made with requirebin
Created
December 13, 2014 15:39
-
-
Save santiagogil/1a04270e1edbea173b6f to your computer and use it in GitHub Desktop.
requirebin sketch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var h = require('virtual-dom/h'); | |
var diff = require('virtual-dom/diff'); | |
var patch = require('virtual-dom/patch'); | |
var createElement = require('virtual-dom/create-element'); | |
var pouchdb = require('pouchdb'); | |
var $ = require('br-jquery'); | |
var bacon = require('baconjs'); | |
var requester = bacon.fromPoll('10000', function(){return bacon.fromPromise($.ajax('https://api.educ.ar/0.9/recursos/juego/316532?key=808509ff7e847aabbb73c4396fbaabe6010cfdd0'));}); | |
//requester.onValue(function(value){console.log(value);}); | |
// 1: Create a function that declares what the DOM should look like | |
function render(count) { | |
return h('div', [h('a', {href: 'blah'}, count), h('a', {href: 'http://google.com'}, 'google')]); | |
} | |
// 2: Initialise the document | |
var count = 'ponele'; // We need some app data. Here we just store a count. | |
var tree = render(count); // We need an initial tree | |
var rootNode = createElement(tree); // Create an initial root DOM node ... | |
document.body.appendChild(rootNode); // ... and it should be in the document | |
// 3: Wire up the update logic | |
var update = function (data) { | |
var newTree = render(data); | |
var patches = diff(tree, newTree); | |
rootNode = patch(rootNode, patches); | |
tree = newTree; | |
}; | |
// Router helpers | |
var filterClicks = function(event){ | |
if(event.target.host == window.location.host && !event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey){ | |
return event; | |
} | |
}; | |
var preventDefault = function(event){ | |
event.preventDefault(); | |
return event; | |
}; | |
// pushState es un colateral | |
var updateUrl = function(event){ | |
window.history.pushState(null, event.target.pathname.slice(1), event.target.pathname); | |
return event; | |
}; | |
// El Router | |
var router = $('a') | |
.asEventStream('click') // Intercepta todos los clicks en links. | |
.filter(filterClicks) // Los filtra para trabajar sólo con links locales sin teclas modificadoras. | |
.map(preventDefault) // Evita el comportamiento habitual del evento, manteniendo el control en la app. | |
.map(updateUrl) // Actualiza la historia de navegación. | |
.flatMapLatest(function(event){return $.ajax('https://api.educ.ar/0.9/recursos/juegos?key=808509ff7e847aabbb73c4396fbaabe6010cfdd0').then(function(data){event.payload = data; return event})}) | |
.mapError("Search fail"); | |
router.onValue(function(value){ value.then(function(data){update(JSON.stringify(data));});}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var isArray=require("x-is-array");var isString=require("x-is-string");var VNode=require("vtree/vnode.js");var VText=require("vtree/vtext.js");var isVNode=require("vtree/is-vnode");var isVText=require("vtree/is-vtext");var isWidget=require("vtree/is-widget");var parseTag=require("./parse-tag");module.exports=h;function h(tagName,properties,children){var tag,props,childNodes,key;if(!children){if(isChildren(properties)){children=properties;properties=undefined}}tag=parseTag(tagName,properties);if(!isString(tag)){props=tag.properties;tag=tag.tagName}else{props=properties}if(isArray(children)){var len=children.length;for(var i=0;i<len;i++){var child=children[i];if(isString(child)){children[i]=new VText(child)}}childNodes=children}else if(isString(children)){childNodes=[new VText(children)]}else if(isChild(children)){childNodes=[children]}if(props&&"key"in props){key=props.key;delete props.key}return new VNode(tag,props,childNodes,key)}function isChild(x){return isVNode(x)||isVText(x)||isWidget(x)}function isChildren(x){return isArray(x)||isString(x)||isChild(x)}},{"./parse-tag":2,"vtree/is-vnode":5,"vtree/is-vtext":6,"vtree/is-widget":7,"vtree/vnode.js":9,"vtree/vtext.js":10,"x-is-array":11,"x-is-string":12}],2:[function(require,module,exports){var split=require("browser-split");var classIdSplit=/([\.#]?[a-zA-Z0-9_:-]+)/;var notClassId=/^\.|#/;module.exports=parseTag;function parseTag(tag,props){if(!tag){return"div"}var noId=!props||!("id"in props);var tagParts=split(tag,classIdSplit);var tagName=null;if(notClassId.test(tagParts[1])){tagName="div"}var id,classes,part,type,i;for(i=0;i<tagParts.length;i++){part=tagParts[i];if(!part){continue}type=part.charAt(0);if(!tagName){tagName=part}else if(type==="."){classes=classes||[];classes.push(part.substring(1,part.length))}else if(type==="#"&&noId){id=part.substring(1,part.length)}}var parsedTags;if(props){if(id!==undefined&&!("id"in props)){props.id=id}if(classes){if(props.className){classes.push(props.className)}props.className=classes.join(" ")}parsedTags=tagName}else if(classes||id!==undefined){var properties={};if(id!==undefined){properties.id=id}if(classes){properties.className=classes.join(" ")}parsedTags={tagName:tagName,properties:properties}}else{parsedTags=tagName}return parsedTags}},{"browser-split":3}],3:[function(require,module,exports){module.exports=function split(undef){var nativeSplit=String.prototype.split,compliantExecNpcg=/()??/.exec("")[1]===undef,self;self=function(str,separator,limit){if(Object.prototype.toString.call(separator)!=="[object RegExp]"){return nativeSplit.call(str,separator,limit)}var output=[],flags=(separator.ignoreCase?"i":"")+(separator.multiline?"m":"")+(separator.extended?"x":"")+(separator.sticky?"y":""),lastLastIndex=0,separator=new RegExp(separator.source,flags+"g"),separator2,match,lastIndex,lastLength;str+="";if(!compliantExecNpcg){separator2=new RegExp("^"+separator.source+"$(?!\\s)",flags)}limit=limit===undef?-1>>>0:limit>>>0;while(match=separator.exec(str)){lastIndex=match.index+match[0].length;if(lastIndex>lastLastIndex){output.push(str.slice(lastLastIndex,match.index));if(!compliantExecNpcg&&match.length>1){match[0].replace(separator2,function(){for(var i=1;i<arguments.length-2;i++){if(arguments[i]===undef){match[i]=undef}}})}if(match.length>1&&match.index<str.length){Array.prototype.push.apply(output,match.slice(1))}lastLength=match[0].length;lastLastIndex=lastIndex;if(output.length>=limit){break}}if(separator.lastIndex===match.index){separator.lastIndex++}}if(lastLastIndex===str.length){if(lastLength||!separator.test("")){output.push("")}}else{output.push(str.slice(lastLastIndex))}return output.length>limit?output.slice(0,limit):output};return self}()},{}],4:[function(require,module,exports){module.exports=isHook;function isHook(hook){return hook&&typeof hook.hook==="function"&&!hook.hasOwnProperty("hook")}},{}],5:[function(require,module,exports){var version=require("./version");module.exports=isVirtualNode;function isVirtualNode(x){return x&&x.type==="VirtualNode"&&x.version===version}},{"./version":8}],6:[function(require,module,exports){var version=require("./version");module.exports=isVirtualText;function isVirtualText(x){return x&&x.type==="VirtualText"&&x.version===version}},{"./version":8}],7:[function(require,module,exports){module.exports=isWidget;function isWidget(w){return w&&w.type==="Widget"}},{}],8:[function(require,module,exports){module.exports="1"},{}],9:[function(require,module,exports){var version=require("./version");var isVNode=require("./is-vnode");var isWidget=require("./is-widget");var isVHook=require("./is-vhook");module.exports=VirtualNode;var noProperties={};var noChildren=[];function VirtualNode(tagName,properties,children,key,namespace){this.tagName=tagName;this.properties=properties||noProperties;this.children=children||noChildren;this.key=key!=null?String(key):undefined;this.namespace=typeof namespace==="string"?namespace:null;var count=children&&children.length||0;var descendants=0;var hasWidgets=false;var descendantHooks=false;var hooks;for(var propName in properties){if(properties.hasOwnProperty(propName)){var property=properties[propName];if(isVHook(property)){if(!hooks){hooks={}}hooks[propName]=property}}}for(var i=0;i<count;i++){var child=children[i];if(isVNode(child)){descendants+=child.count||0;if(!hasWidgets&&child.hasWidgets){hasWidgets=true}if(!descendantHooks&&(child.hooks||child.descendantHooks)){descendantHooks=true}}else if(!hasWidgets&&isWidget(child)){if(typeof child.destroy==="function"){hasWidgets=true}}}this.count=count+descendants;this.hasWidgets=hasWidgets;this.hooks=hooks;this.descendantHooks=descendantHooks}VirtualNode.prototype.version=version;VirtualNode.prototype.type="VirtualNode"},{"./is-vhook":4,"./is-vnode":5,"./is-widget":7,"./version":8}],10:[function(require,module,exports){var version=require("./version");module.exports=VirtualText;function VirtualText(text){this.text=String(text)}VirtualText.prototype.version=version;VirtualText.prototype.type="VirtualText"},{"./version":8}],11:[function(require,module,exports){var nativeIsArray=Array.isArray;var toString=Object.prototype.toString;module.exports=nativeIsArray||isArray;function isArray(obj){return toString.call(obj)==="[object Array]"}},{}],12:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=isString;function isString(obj){return toString.call(obj)==="[object String]"}},{}],"virtual-dom/h":[function(require,module,exports){var h=require("./h/index.js");module.exports=h},{"./h/index.js":1}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);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=isObject;function isObject(x){return typeof x==="object"&&x!==null}},{}],2:[function(require,module,exports){var isArray=require("x-is-array");var isObject=require("is-object");var VPatch=require("./vpatch");var isVNode=require("./is-vnode");var isVText=require("./is-vtext");var isWidget=require("./is-widget");var isThunk=require("./is-thunk");var handleThunk=require("./handle-thunk");module.exports=diff;function diff(a,b){var patch={a:a};walk(a,b,patch,0);return patch}function walk(a,b,patch,index){if(a===b){if(isThunk(a)||isThunk(b)){thunks(a,b,patch,index)}else{hooks(b,patch,index)}return}var apply=patch[index];if(b==null){apply=appendPatch(apply,new VPatch(VPatch.REMOVE,a,b));destroyWidgets(a,patch,index)}else if(isThunk(a)||isThunk(b)){thunks(a,b,patch,index)}else if(isVNode(b)){if(isVNode(a)){if(a.tagName===b.tagName&&a.namespace===b.namespace&&a.key===b.key){var propsPatch=diffProps(a.properties,b.properties,b.hooks);if(propsPatch){apply=appendPatch(apply,new VPatch(VPatch.PROPS,a,propsPatch))}apply=diffChildren(a,b,patch,apply,index)}else{apply=appendPatch(apply,new VPatch(VPatch.VNODE,a,b));destroyWidgets(a,patch,index)}}else{apply=appendPatch(apply,new VPatch(VPatch.VNODE,a,b));destroyWidgets(a,patch,index)}}else if(isVText(b)){if(!isVText(a)){apply=appendPatch(apply,new VPatch(VPatch.VTEXT,a,b));destroyWidgets(a,patch,index)}else if(a.text!==b.text){apply=appendPatch(apply,new VPatch(VPatch.VTEXT,a,b))}}else if(isWidget(b)){apply=appendPatch(apply,new VPatch(VPatch.WIDGET,a,b));if(!isWidget(a)){destroyWidgets(a,patch,index)}}if(apply){patch[index]=apply}}function diffProps(a,b,hooks){var diff;for(var aKey in a){if(!(aKey in b)){diff=diff||{};diff[aKey]=undefined}var aValue=a[aKey];var bValue=b[aKey];if(hooks&&aKey in hooks){diff=diff||{};diff[aKey]=bValue}else{if(isObject(aValue)&&isObject(bValue)){if(getPrototype(bValue)!==getPrototype(aValue)){diff=diff||{};diff[aKey]=bValue}else{var objectDiff=diffProps(aValue,bValue);if(objectDiff){diff=diff||{};diff[aKey]=objectDiff}}}else if(aValue!==bValue){diff=diff||{};diff[aKey]=bValue}}}for(var bKey in b){if(!(bKey in a)){diff=diff||{};diff[bKey]=b[bKey]}}return diff}function getPrototype(value){if(Object.getPrototypeOf){return Object.getPrototypeOf(value)}else if(value.__proto__){return value.__proto__}else if(value.constructor){return value.constructor.prototype}}function diffChildren(a,b,patch,apply,index){var aChildren=a.children;var bChildren=reorder(aChildren,b.children);var aLen=aChildren.length;var bLen=bChildren.length;var len=aLen>bLen?aLen:bLen;for(var i=0;i<len;i++){var leftNode=aChildren[i];var rightNode=bChildren[i];index+=1;if(!leftNode){if(rightNode){apply=appendPatch(apply,new VPatch(VPatch.INSERT,null,rightNode))}}else if(!rightNode){if(leftNode){patch[index]=new VPatch(VPatch.REMOVE,leftNode,null);destroyWidgets(leftNode,patch,index)}}else{walk(leftNode,rightNode,patch,index)}if(isVNode(leftNode)&&leftNode.count){index+=leftNode.count}}if(bChildren.moves){apply=appendPatch(apply,new VPatch(VPatch.ORDER,a,bChildren.moves))}return apply}function destroyWidgets(vNode,patch,index){if(isWidget(vNode)){if(typeof vNode.destroy==="function"){patch[index]=new VPatch(VPatch.REMOVE,vNode,null)}}else if(isVNode(vNode)&&vNode.hasWidgets){var children=vNode.children;var len=children.length;for(var i=0;i<len;i++){var child=children[i];index+=1;destroyWidgets(child,patch,index);if(isVNode(child)&&child.count){index+=child.count}}}}function thunks(a,b,patch,index){var nodes=handleThunk(a,b);var thunkPatch=diff(nodes.a,nodes.b);if(hasPatches(thunkPatch)){patch[index]=new VPatch(VPatch.THUNK,null,thunkPatch)}}function hasPatches(patch){for(var index in patch){if(index!=="a"){return true}}return false}function hooks(vNode,patch,index){if(isVNode(vNode)){if(vNode.hooks){patch[index]=new VPatch(VPatch.PROPS,vNode.hooks,vNode.hooks)}if(vNode.descendantHooks){var children=vNode.children;var len=children.length;for(var i=0;i<len;i++){var child=children[i];index+=1;hooks(child,patch,index);if(isVNode(child)&&child.count){index+=child.count}}}}}function reorder(aChildren,bChildren){var bKeys=keyIndex(bChildren);if(!bKeys){return bChildren}var aKeys=keyIndex(aChildren);if(!aKeys){return bChildren}var bMatch={},aMatch={};for(var key in bKeys){bMatch[bKeys[key]]=aKeys[key]}for(var key in aKeys){aMatch[aKeys[key]]=bKeys[key]}var aLen=aChildren.length;var bLen=bChildren.length;var len=aLen>bLen?aLen:bLen;var shuffle=[];var freeIndex=0;var i=0;var moveIndex=0;var moves={};var removes=moves.removes={};var reverse=moves.reverse={};var hasMoves=false;while(freeIndex<len){var move=aMatch[i];if(move!==undefined){shuffle[i]=bChildren[move];if(move!==moveIndex){moves[move]=moveIndex;reverse[moveIndex]=move;hasMoves=true}moveIndex++}else if(i in aMatch){shuffle[i]=undefined;removes[i]=moveIndex++;hasMoves=true}else{while(bMatch[freeIndex]!==undefined){freeIndex++}if(freeIndex<len){var freeChild=bChildren[freeIndex];if(freeChild){shuffle[i]=freeChild;if(freeIndex!==moveIndex){hasMoves=true;moves[freeIndex]=moveIndex;reverse[moveIndex]=freeIndex}moveIndex++}freeIndex++}}i++}if(hasMoves){shuffle.moves=moves}return shuffle}function keyIndex(children){var i,keys;for(i=0;i<children.length;i++){var child=children[i];if(child.key!==undefined){keys=keys||{};keys[child.key]=i}}return keys}function appendPatch(apply,patch){if(apply){if(isArray(apply)){apply.push(patch)}else{apply=[apply,patch]}return apply}else{return patch}}},{"./handle-thunk":3,"./is-thunk":4,"./is-vnode":5,"./is-vtext":6,"./is-widget":7,"./vpatch":9,"is-object":1,"x-is-array":10}],3:[function(require,module,exports){var isVNode=require("./is-vnode");var isVText=require("./is-vtext");var isWidget=require("./is-widget");var isThunk=require("./is-thunk");module.exports=handleThunk;function handleThunk(a,b){var renderedA=a;var renderedB=b;if(isThunk(b)){renderedB=renderThunk(b,a)}if(isThunk(a)){renderedA=renderThunk(a,null)}return{a:renderedA,b:renderedB}}function renderThunk(thunk,previous){var renderedThunk=thunk.vnode;if(!renderedThunk){renderedThunk=thunk.vnode=thunk.render(previous)}if(!(isVNode(renderedThunk)||isVText(renderedThunk)||isWidget(renderedThunk))){throw new Error("thunk did not return a valid node")}return renderedThunk}},{"./is-thunk":4,"./is-vnode":5,"./is-vtext":6,"./is-widget":7}],4:[function(require,module,exports){module.exports=isThunk;function isThunk(t){return t&&t.type==="Thunk"}},{}],5:[function(require,module,exports){var version=require("./version");module.exports=isVirtualNode;function isVirtualNode(x){return x&&x.type==="VirtualNode"&&x.version===version}},{"./version":8}],6:[function(require,module,exports){var version=require("./version");module.exports=isVirtualText;function isVirtualText(x){return x&&x.type==="VirtualText"&&x.version===version}},{"./version":8}],7:[function(require,module,exports){module.exports=isWidget;function isWidget(w){return w&&w.type==="Widget"}},{}],8:[function(require,module,exports){module.exports="1"},{}],9:[function(require,module,exports){var version=require("./version");VirtualPatch.NONE=0;VirtualPatch.VTEXT=1;VirtualPatch.VNODE=2;VirtualPatch.WIDGET=3;VirtualPatch.PROPS=4;VirtualPatch.ORDER=5;VirtualPatch.INSERT=6;VirtualPatch.REMOVE=7;VirtualPatch.THUNK=8;module.exports=VirtualPatch;function VirtualPatch(type,vNode,patch){this.type=Number(type);this.vNode=vNode;this.patch=patch}VirtualPatch.prototype.version=version;VirtualPatch.prototype.type="VirtualPatch"},{"./version":8}],10:[function(require,module,exports){var nativeIsArray=Array.isArray;var toString=Object.prototype.toString;module.exports=nativeIsArray||isArray;function isArray(obj){return toString.call(obj)==="[object Array]"}},{}],"virtual-dom/diff":[function(require,module,exports){var diff=require("vtree/diff");module.exports=diff},{"vtree/diff":2}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);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){},{}],2:[function(require,module,exports){module.exports=isObject;function isObject(x){return typeof x==="object"&&x!==null}},{}],3:[function(require,module,exports){var isObject=require("is-object");var isHook=require("vtree/is-vhook");module.exports=applyProperties;function applyProperties(node,props,previous){for(var propName in props){var propValue=props[propName];if(propValue===undefined){removeProperty(node,props,previous,propName)}else if(isHook(propValue)){propValue.hook(node,propName,previous?previous[propName]:undefined)}else{if(isObject(propValue)){patchObject(node,props,previous,propName,propValue)}else if(propValue!==undefined){node[propName]=propValue}}}}function removeProperty(node,props,previous,propName){if(previous){var previousValue=previous[propName];if(!isHook(previousValue)){if(propName==="attributes"){for(var attrName in previousValue){node.removeAttribute(attrName)}}else if(propName==="style"){for(var i in previousValue){node.style[i]=""}}else if(typeof previousValue==="string"){node[propName]=""}else{node[propName]=null}}}}function patchObject(node,props,previous,propName,propValue){var previousValue=previous?previous[propName]:undefined;if(propName==="attributes"){for(var attrName in propValue){var attrValue=propValue[attrName];if(attrValue===undefined){node.removeAttribute(attrName)}else{node.setAttribute(attrName,attrValue)}}return}if(previousValue&&isObject(previousValue)&&getPrototype(previousValue)!==getPrototype(propValue)){node[propName]=propValue;return}if(!isObject(node[propName])){node[propName]={}}var replacer=propName==="style"?"":undefined;for(var k in propValue){var value=propValue[k];node[propName][k]=value===undefined?replacer:value}}function getPrototype(value){if(Object.getPrototypeOf){return Object.getPrototypeOf(value)}else if(value.__proto__){return value.__proto__}else if(value.constructor){return value.constructor.prototype}}},{"is-object":2,"vtree/is-vhook":12}],4:[function(require,module,exports){var document=require("global/document");var applyProperties=require("./apply-properties");var isVNode=require("vtree/is-vnode");var isVText=require("vtree/is-vtext");var isWidget=require("vtree/is-widget");var handleThunk=require("vtree/handle-thunk");module.exports=createElement;function createElement(vnode,opts){var doc=opts?opts.document||document:document;var warn=opts?opts.warn:null;vnode=handleThunk(vnode).a;if(isWidget(vnode)){return vnode.init()}else if(isVText(vnode)){return doc.createTextNode(vnode.text)}else if(!isVNode(vnode)){if(warn){warn("Item is not a valid virtual dom node",vnode)}return null}var node=vnode.namespace===null?doc.createElement(vnode.tagName):doc.createElementNS(vnode.namespace,vnode.tagName);var props=vnode.properties;applyProperties(node,props);var children=vnode.children;for(var i=0;i<children.length;i++){var childNode=createElement(children[i],opts);if(childNode){node.appendChild(childNode)}}return node}},{"./apply-properties":3,"global/document":6,"vtree/handle-thunk":10,"vtree/is-vnode":13,"vtree/is-vtext":14,"vtree/is-widget":15}],5:[function(require,module,exports){var noChild={};module.exports=domIndex;function domIndex(rootNode,tree,indices,nodes){if(!indices||indices.length===0){return{}}else{indices.sort(ascending);return recurse(rootNode,tree,indices,nodes,0)}}function recurse(rootNode,tree,indices,nodes,rootIndex){nodes=nodes||{};if(rootNode){if(indexInRange(indices,rootIndex,rootIndex)){nodes[rootIndex]=rootNode}var vChildren=tree.children;if(vChildren){var childNodes=rootNode.childNodes;for(var i=0;i<tree.children.length;i++){rootIndex+=1;var vChild=vChildren[i]||noChild;var nextIndex=rootIndex+(vChild.count||0);if(indexInRange(indices,rootIndex,nextIndex)){recurse(childNodes[i],vChild,indices,nodes,rootIndex)}rootIndex=nextIndex}}}return nodes}function indexInRange(indices,left,right){if(indices.length===0){return false}var minIndex=0;var maxIndex=indices.length-1;var currentIndex;var currentItem;while(minIndex<=maxIndex){currentIndex=(maxIndex+minIndex)/2>>0;currentItem=indices[currentIndex];if(minIndex===maxIndex){return currentItem>=left&¤tItem<=right}else if(currentItem<left){minIndex=currentIndex+1}else if(currentItem>right){maxIndex=currentIndex-1}else{return true}}return false}function ascending(a,b){return a>b?1:-1}},{}],6:[function(require,module,exports){(function(global){var topLevel=typeof global!=="undefined"?global:typeof window!=="undefined"?window:{};var minDoc=require("min-document");if(typeof document!=="undefined"){module.exports=document}else{var doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"];if(!doccy){doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"]=minDoc}module.exports=doccy}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"min-document":1}],7:[function(require,module,exports){var applyProperties=require("./apply-properties");var isWidget=require("vtree/is-widget");var VPatch=require("vtree/vpatch");var render=require("./create-element");var updateWidget=require("./update-widget");module.exports=applyPatch;function applyPatch(vpatch,domNode,renderOptions){var type=vpatch.type;var vNode=vpatch.vNode;var patch=vpatch.patch;switch(type){case VPatch.REMOVE:return removeNode(domNode,vNode);case VPatch.INSERT:return insertNode(domNode,patch,renderOptions);case VPatch.VTEXT:return stringPatch(domNode,vNode,patch,renderOptions);case VPatch.WIDGET:return widgetPatch(domNode,vNode,patch,renderOptions);case VPatch.VNODE:return vNodePatch(domNode,vNode,patch,renderOptions);case VPatch.ORDER:reorderChildren(domNode,patch);return domNode;case VPatch.PROPS:applyProperties(domNode,patch,vNode.properties);return domNode;case VPatch.THUNK:return replaceRoot(domNode,renderOptions.patch(domNode,patch,renderOptions));default:return domNode}}function removeNode(domNode,vNode){var parentNode=domNode.parentNode;if(parentNode){parentNode.removeChild(domNode)}destroyWidget(domNode,vNode);return null}function insertNode(parentNode,vNode,renderOptions){var newNode=render(vNode,renderOptions);if(parentNode){parentNode.appendChild(newNode)}return parentNode}function stringPatch(domNode,leftVNode,vText,renderOptions){var newNode;if(domNode.nodeType===3){domNode.replaceData(0,domNode.length,vText.text);newNode=domNode}else{var parentNode=domNode.parentNode;newNode=render(vText,renderOptions);if(parentNode){parentNode.replaceChild(newNode,domNode)}}destroyWidget(domNode,leftVNode);return newNode}function widgetPatch(domNode,leftVNode,widget,renderOptions){if(updateWidget(leftVNode,widget)){return widget.update(leftVNode,domNode)||domNode}var parentNode=domNode.parentNode;var newWidget=render(widget,renderOptions);if(parentNode){parentNode.replaceChild(newWidget,domNode)}destroyWidget(domNode,leftVNode);return newWidget}function vNodePatch(domNode,leftVNode,vNode,renderOptions){var parentNode=domNode.parentNode;var newNode=render(vNode,renderOptions);if(parentNode){parentNode.replaceChild(newNode,domNode)}destroyWidget(domNode,leftVNode);return newNode}function destroyWidget(domNode,w){if(typeof w.destroy==="function"&&isWidget(w)){w.destroy(domNode)}}function reorderChildren(domNode,bIndex){var children=[];var childNodes=domNode.childNodes;var len=childNodes.length;var i;var reverseIndex=bIndex.reverse;for(i=0;i<len;i++){children.push(domNode.childNodes[i])}var insertOffset=0;var move;var node;var insertNode;for(i=0;i<len;i++){move=bIndex[i];if(move!==undefined&&move!==i){if(reverseIndex[i]>i){insertOffset++}node=children[move];insertNode=childNodes[i+insertOffset]||null;if(node!==insertNode){domNode.insertBefore(node,insertNode)}if(move<i){insertOffset--}}if(i in bIndex.removes){insertOffset++}}}function replaceRoot(oldRoot,newRoot){if(oldRoot&&newRoot&&oldRoot!==newRoot&&oldRoot.parentNode){console.log(oldRoot);oldRoot.parentNode.replaceChild(newRoot,oldRoot)}return newRoot}},{"./apply-properties":3,"./create-element":4,"./update-widget":9,"vtree/is-widget":15,"vtree/vpatch":17}],8:[function(require,module,exports){var document=require("global/document");var isArray=require("x-is-array");var domIndex=require("./dom-index");var patchOp=require("./patch-op");module.exports=patch;function patch(rootNode,patches){return patchRecursive(rootNode,patches)}function patchRecursive(rootNode,patches,renderOptions){var indices=patchIndices(patches);if(indices.length===0){return rootNode}var index=domIndex(rootNode,patches.a,indices);var ownerDocument=rootNode.ownerDocument;if(!renderOptions){renderOptions={patch:patchRecursive};if(ownerDocument!==document){renderOptions.document=ownerDocument}}for(var i=0;i<indices.length;i++){var nodeIndex=indices[i];rootNode=applyPatch(rootNode,index[nodeIndex],patches[nodeIndex],renderOptions)}return rootNode}function applyPatch(rootNode,domNode,patchList,renderOptions){if(!domNode){return rootNode}var newNode;if(isArray(patchList)){for(var i=0;i<patchList.length;i++){newNode=patchOp(patchList[i],domNode,renderOptions);if(domNode===rootNode){rootNode=newNode}}}else{newNode=patchOp(patchList,domNode,renderOptions);if(domNode===rootNode){rootNode=newNode}}return rootNode}function patchIndices(patches){var indices=[];for(var key in patches){if(key!=="a"){indices.push(Number(key))}}return indices}},{"./dom-index":5,"./patch-op":7,"global/document":6,"x-is-array":18}],9:[function(require,module,exports){var isWidget=require("vtree/is-widget");module.exports=updateWidget;function updateWidget(a,b){if(isWidget(a)&&isWidget(b)){if("name"in a&&"name"in b){return a.id===b.id}else{return a.init===b.init}}return false}},{"vtree/is-widget":15}],10:[function(require,module,exports){var isVNode=require("./is-vnode");var isVText=require("./is-vtext");var isWidget=require("./is-widget");var isThunk=require("./is-thunk");module.exports=handleThunk;function handleThunk(a,b){var renderedA=a;var renderedB=b;if(isThunk(b)){renderedB=renderThunk(b,a)}if(isThunk(a)){renderedA=renderThunk(a,null)}return{a:renderedA,b:renderedB}}function renderThunk(thunk,previous){var renderedThunk=thunk.vnode;if(!renderedThunk){renderedThunk=thunk.vnode=thunk.render(previous)}if(!(isVNode(renderedThunk)||isVText(renderedThunk)||isWidget(renderedThunk))){throw new Error("thunk did not return a valid node")}return renderedThunk}},{"./is-thunk":11,"./is-vnode":13,"./is-vtext":14,"./is-widget":15}],11:[function(require,module,exports){module.exports=isThunk;function isThunk(t){return t&&t.type==="Thunk"}},{}],12:[function(require,module,exports){module.exports=isHook;function isHook(hook){return hook&&typeof hook.hook==="function"&&!hook.hasOwnProperty("hook")}},{}],13:[function(require,module,exports){var version=require("./version");module.exports=isVirtualNode;function isVirtualNode(x){return x&&x.type==="VirtualNode"&&x.version===version}},{"./version":16}],14:[function(require,module,exports){var version=require("./version");module.exports=isVirtualText;function isVirtualText(x){return x&&x.type==="VirtualText"&&x.version===version}},{"./version":16}],15:[function(require,module,exports){module.exports=isWidget;function isWidget(w){return w&&w.type==="Widget"}},{}],16:[function(require,module,exports){module.exports="1"},{}],17:[function(require,module,exports){var version=require("./version");VirtualPatch.NONE=0;VirtualPatch.VTEXT=1;VirtualPatch.VNODE=2;VirtualPatch.WIDGET=3;VirtualPatch.PROPS=4;VirtualPatch.ORDER=5;VirtualPatch.INSERT=6;VirtualPatch.REMOVE=7;VirtualPatch.THUNK=8;module.exports=VirtualPatch;function VirtualPatch(type,vNode,patch){this.type=Number(type);this.vNode=vNode;this.patch=patch}VirtualPatch.prototype.version=version;VirtualPatch.prototype.type="VirtualPatch"},{"./version":16}],18:[function(require,module,exports){var nativeIsArray=Array.isArray;var toString=Object.prototype.toString;module.exports=nativeIsArray||isArray;function isArray(obj){return toString.call(obj)==="[object Array]"}},{}],"virtual-dom/patch":[function(require,module,exports){var patch=require("vdom/patch");module.exports=patch},{"vdom/patch":8}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);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){},{}],2:[function(require,module,exports){module.exports=isObject;function isObject(x){return typeof x==="object"&&x!==null}},{}],3:[function(require,module,exports){var isObject=require("is-object");var isHook=require("vtree/is-vhook");module.exports=applyProperties;function applyProperties(node,props,previous){for(var propName in props){var propValue=props[propName];if(propValue===undefined){removeProperty(node,props,previous,propName)}else if(isHook(propValue)){propValue.hook(node,propName,previous?previous[propName]:undefined)}else{if(isObject(propValue)){patchObject(node,props,previous,propName,propValue)}else if(propValue!==undefined){node[propName]=propValue}}}}function removeProperty(node,props,previous,propName){if(previous){var previousValue=previous[propName];if(!isHook(previousValue)){if(propName==="attributes"){for(var attrName in previousValue){node.removeAttribute(attrName)}}else if(propName==="style"){for(var i in previousValue){node.style[i]=""}}else if(typeof previousValue==="string"){node[propName]=""}else{node[propName]=null}}}}function patchObject(node,props,previous,propName,propValue){var previousValue=previous?previous[propName]:undefined;if(propName==="attributes"){for(var attrName in propValue){var attrValue=propValue[attrName];if(attrValue===undefined){node.removeAttribute(attrName)}else{node.setAttribute(attrName,attrValue)}}return}if(previousValue&&isObject(previousValue)&&getPrototype(previousValue)!==getPrototype(propValue)){node[propName]=propValue;return}if(!isObject(node[propName])){node[propName]={}}var replacer=propName==="style"?"":undefined;for(var k in propValue){var value=propValue[k];node[propName][k]=value===undefined?replacer:value}}function getPrototype(value){if(Object.getPrototypeOf){return Object.getPrototypeOf(value)}else if(value.__proto__){return value.__proto__}else if(value.constructor){return value.constructor.prototype}}},{"is-object":2,"vtree/is-vhook":8}],4:[function(require,module,exports){var document=require("global/document");var applyProperties=require("./apply-properties");var isVNode=require("vtree/is-vnode");var isVText=require("vtree/is-vtext");var isWidget=require("vtree/is-widget");var handleThunk=require("vtree/handle-thunk");module.exports=createElement;function createElement(vnode,opts){var doc=opts?opts.document||document:document;var warn=opts?opts.warn:null;vnode=handleThunk(vnode).a;if(isWidget(vnode)){return vnode.init()}else if(isVText(vnode)){return doc.createTextNode(vnode.text)}else if(!isVNode(vnode)){if(warn){warn("Item is not a valid virtual dom node",vnode)}return null}var node=vnode.namespace===null?doc.createElement(vnode.tagName):doc.createElementNS(vnode.namespace,vnode.tagName);var props=vnode.properties;applyProperties(node,props);var children=vnode.children;for(var i=0;i<children.length;i++){var childNode=createElement(children[i],opts);if(childNode){node.appendChild(childNode)}}return node}},{"./apply-properties":3,"global/document":5,"vtree/handle-thunk":6,"vtree/is-vnode":9,"vtree/is-vtext":10,"vtree/is-widget":11}],5:[function(require,module,exports){(function(global){var topLevel=typeof global!=="undefined"?global:typeof window!=="undefined"?window:{};var minDoc=require("min-document");if(typeof document!=="undefined"){module.exports=document}else{var doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"];if(!doccy){doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"]=minDoc}module.exports=doccy}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"min-document":1}],6:[function(require,module,exports){var isVNode=require("./is-vnode"); | |
var isVText=require("./is-vtext");var isWidget=require("./is-widget");var isThunk=require("./is-thunk");module.exports=handleThunk;function handleThunk(a,b){var renderedA=a;var renderedB=b;if(isThunk(b)){renderedB=renderThunk(b,a)}if(isThunk(a)){renderedA=renderThunk(a,null)}return{a:renderedA,b:renderedB}}function renderThunk(thunk,previous){var renderedThunk=thunk.vnode;if(!renderedThunk){renderedThunk=thunk.vnode=thunk.render(previous)}if(!(isVNode(renderedThunk)||isVText(renderedThunk)||isWidget(renderedThunk))){throw new Error("thunk did not return a valid node")}return renderedThunk}},{"./is-thunk":7,"./is-vnode":9,"./is-vtext":10,"./is-widget":11}],7:[function(require,module,exports){module.exports=isThunk;function isThunk(t){return t&&t.type==="Thunk"}},{}],8:[function(require,module,exports){module.exports=isHook;function isHook(hook){return hook&&typeof hook.hook==="function"&&!hook.hasOwnProperty("hook")}},{}],9:[function(require,module,exports){var version=require("./version");module.exports=isVirtualNode;function isVirtualNode(x){return x&&x.type==="VirtualNode"&&x.version===version}},{"./version":12}],10:[function(require,module,exports){var version=require("./version");module.exports=isVirtualText;function isVirtualText(x){return x&&x.type==="VirtualText"&&x.version===version}},{"./version":12}],11:[function(require,module,exports){module.exports=isWidget;function isWidget(w){return w&&w.type==="Widget"}},{}],12:[function(require,module,exports){module.exports="1"},{}],"virtual-dom/create-element":[function(require,module,exports){var createElement=require("vdom/create-element");module.exports=createElement},{"vdom/create-element":4}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);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){},{}],2:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;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(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}else{throw TypeError('Uncaught, unspecified "error" event.')}return false}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];handler.apply(this,args)}}else if(isObject(handler)){len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];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={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){var m;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"){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};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;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}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{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.listenerCount=function(emitter,type){var ret;if(!emitter._events||!emitter._events[type])ret=0;else if(isFunction(emitter._events[type]))ret=1;else ret=emitter._events[type].length;return ret};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}},{}],3:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}if(canPost){var queue=[];window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],4:[function(require,module,exports){"use strict";var utils=require("./utils");var merge=require("./merge");var errors=require("./deps/errors");var EventEmitter=require("events").EventEmitter;var upsert=require("./deps/upsert");var Changes=require("./changes");var Promise=utils.Promise;function arrayFirst(arr,callback){for(var i=0;i<arr.length;i++){if(callback(arr[i],i)===true){return arr[i]}}return false}function yankError(callback){return function(err,results){if(err||results[0]&&results[0].error){callback(err||results[0])}else{callback(null,results.length?results[0]:results)}}}function computeHeight(revs){var height={};var edges=[];merge.traverseRevTree(revs,function(isLeaf,pos,id,prnt){var rev=pos+"-"+id;if(isLeaf){height[rev]=0}if(prnt!==undefined){edges.push({from:prnt,to:rev})}return rev});edges.reverse();edges.forEach(function(edge){if(height[edge.from]===undefined){height[edge.from]=1+height[edge.to]}else{height[edge.from]=Math.min(height[edge.from],1+height[edge.to])}});return height}function allDocsKeysQuery(api,opts,callback){var keys="limit"in opts?opts.keys.slice(opts.skip,opts.limit+opts.skip):opts.skip>0?opts.keys.slice(opts.skip):opts.keys;if(opts.descending){keys.reverse()}if(!keys.length){return api._allDocs({limit:0},callback)}var finalResults={offset:opts.skip};return Promise.all(keys.map(function(key,i){var subOpts=utils.extend(true,{key:key,deleted:"ok"},opts);["limit","skip","keys"].forEach(function(optKey){delete subOpts[optKey]});return new Promise(function(resolve,reject){api._allDocs(subOpts,function(err,res){if(err){return reject(err)}finalResults.total_rows=res.total_rows;resolve(res.rows[0]||{key:key,error:"not_found"})})})})).then(function(results){finalResults.rows=results;return finalResults})}utils.inherits(AbstractPouchDB,EventEmitter);module.exports=AbstractPouchDB;function AbstractPouchDB(){var self=this;EventEmitter.call(this);self.autoCompact=function(callback){if(!self.auto_compaction||self.type()==="http"){return callback}return function(err,res){if(err){callback(err)}else{var count=res.length;var decCount=function(){count--;if(!count){callback(null,res)}};if(!res.length){return callback(null,res)}res.forEach(function(doc){if(doc.ok&&doc.id){self.compactDocument(doc.id,0,decCount)}else{decCount()}})}}};var listeners=0,changes;var eventNames=["change","delete","create","update"];this.on("newListener",function(eventName){if(~eventNames.indexOf(eventName)){if(listeners){listeners++;return}else{listeners++}}else{return}var lastChange=0;changes=this.changes({conflicts:true,include_docs:true,continuous:true,since:"now",onChange:function(change){if(change.seq<=lastChange){return}lastChange=change.seq;self.emit("change",change);if(change.doc._deleted){self.emit("delete",change)}else if(change.doc._rev.split("-")[0]==="1"){self.emit("create",change)}else{self.emit("update",change)}}})});this.on("removeListener",function(eventName){if(~eventNames.indexOf(eventName)){listeners--;if(listeners){return}}else{return}changes.cancel()})}AbstractPouchDB.prototype.post=utils.adapterFun("post",function(doc,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}if(typeof doc!=="object"||Array.isArray(doc)){return callback(errors.NOT_AN_OBJECT)}this.bulkDocs({docs:[doc]},opts,this.autoCompact(yankError(callback)))});AbstractPouchDB.prototype.put=utils.adapterFun("put",utils.getArguments(function(args){var temp,temptype,opts,callback;var doc=args.shift();var id="_id"in doc;if(typeof doc!=="object"||Array.isArray(doc)){callback=args.pop();return callback(errors.NOT_AN_OBJECT)}doc=utils.clone(doc);while(true){temp=args.shift();temptype=typeof temp;if(temptype==="string"&&!id){doc._id=temp;id=true}else if(temptype==="string"&&id&&!("_rev"in doc)){doc._rev=temp}else if(temptype==="object"){opts=temp}else if(temptype==="function"){callback=temp}if(!args.length){break}}opts=opts||{};var error=utils.invalidIdError(doc._id);if(error){return callback(error)}if(utils.isLocalId(doc._id)&&typeof this._putLocal==="function"){if(doc._deleted){return this._removeLocal(doc,callback)}else{return this._putLocal(doc,callback)}}this.bulkDocs({docs:[doc]},opts,this.autoCompact(yankError(callback)))}));AbstractPouchDB.prototype.putAttachment=utils.adapterFun("putAttachment",function(docId,attachmentId,rev,blob,type,callback){var api=this;if(typeof type==="function"){callback=type;type=blob;blob=rev;rev=null}if(typeof type==="undefined"){type=blob;blob=rev;rev=null}function createAttachment(doc){doc._attachments=doc._attachments||{};doc._attachments[attachmentId]={content_type:type,data:blob};return api.put(doc)}return api.get(docId).then(function(doc){if(doc._rev!==rev){throw errors.REV_CONFLICT}return createAttachment(doc)},function(err){if(err.error===errors.MISSING_DOC.error){return createAttachment({_id:docId})}else{throw err}})});AbstractPouchDB.prototype.removeAttachment=utils.adapterFun("removeAttachment",function(docId,attachmentId,rev,callback){var self=this;self.get(docId,function(err,obj){if(err){callback(err);return}if(obj._rev!==rev){callback(errors.REV_CONFLICT);return}if(!obj._attachments){return callback()}delete obj._attachments[attachmentId];if(Object.keys(obj._attachments).length===0){delete obj._attachments}self.put(obj,callback)})});AbstractPouchDB.prototype.remove=utils.adapterFun("remove",function(docOrId,optsOrRev,opts,callback){var doc;if(typeof optsOrRev==="string"){doc={_id:docOrId,_rev:optsOrRev};if(typeof opts==="function"){callback=opts;opts={}}}else{doc=docOrId;if(typeof optsOrRev==="function"){callback=optsOrRev;opts={}}else{callback=opts;opts=optsOrRev}}opts=utils.clone(opts||{});opts.was_delete=true;var newDoc={_id:doc._id,_rev:doc._rev||opts.rev};newDoc._deleted=true;if(utils.isLocalId(newDoc._id)&&typeof this._removeLocal==="function"){return this._removeLocal(doc,callback)}this.bulkDocs({docs:[newDoc]},opts,yankError(callback))});AbstractPouchDB.prototype.revsDiff=utils.adapterFun("revsDiff",function(req,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}opts=utils.clone(opts);var ids=Object.keys(req);if(!ids.length){return callback(null,{})}var count=0;var missing=new utils.Map;function addToMissing(id,revId){if(!missing.has(id)){missing.set(id,{missing:[]})}missing.get(id).missing.push(revId)}function processDoc(id,rev_tree){var missingForId=req[id].slice(0);merge.traverseRevTree(rev_tree,function(isLeaf,pos,revHash,ctx,opts){var rev=pos+"-"+revHash;var idx=missingForId.indexOf(rev);if(idx===-1){return}missingForId.splice(idx,1);if(opts.status!=="available"){addToMissing(id,rev)}});missingForId.forEach(function(rev){addToMissing(id,rev)})}ids.map(function(id){this._getRevisionTree(id,function(err,rev_tree){if(err&&err.status===404&&err.message==="missing"){missing.set(id,{missing:req[id]})}else if(err){return callback(err)}else{processDoc(id,rev_tree)}if(++count===ids.length){var missingObj={};missing.forEach(function(value,key){missingObj[key]=value});return callback(null,missingObj)}})},this)});AbstractPouchDB.prototype.compactDocument=utils.adapterFun("compactDocument",function(docId,maxHeight,callback){var self=this;this._getRevisionTree(docId,function(err,revTree){if(err){return callback(err)}var height=computeHeight(revTree);var candidates=[];var revs=[];Object.keys(height).forEach(function(rev){if(height[rev]>maxHeight){candidates.push(rev)}});merge.traverseRevTree(revTree,function(isLeaf,pos,revHash,ctx,opts){var rev=pos+"-"+revHash;if(opts.status==="available"&&candidates.indexOf(rev)!==-1){revs.push(rev)}});self._doCompaction(docId,revs,callback)})});AbstractPouchDB.prototype.compact=utils.adapterFun("compact",function(opts,callback){if(typeof opts==="function"){callback=opts;opts={}}var self=this;opts=utils.clone(opts||{});self.get("_local/compaction")["catch"](function(){return false}).then(function(doc){if(typeof self._compact==="function"){if(doc&&doc.last_seq){opts.last_seq=doc.last_seq}return self._compact(opts,callback)}})});AbstractPouchDB.prototype._compact=function(opts,callback){var done=false;var started=0;var copts={returnDocs:false};var self=this;var lastSeq;function finish(){upsert(self,"_local/compaction",function(doc){if(!doc.last_seq||doc.last_seq<lastSeq){doc.last_seq=lastSeq;return doc}return false},callback)}if(opts.last_seq){copts.since=opts.last_seq}function afterCompact(){started--;if(!started&&done){finish()}}function onChange(row){started++;self.compactDocument(row.id,0).then(afterCompact,callback)}self.changes(copts).on("change",onChange).on("complete",function(resp){done=true;lastSeq=resp.last_seq;if(!started){finish()}}).on("error",callback)};AbstractPouchDB.prototype.get=utils.adapterFun("get",function(id,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}if(typeof id!=="string"){return callback(errors.INVALID_ID)}if(utils.isLocalId(id)&&typeof this._getLocal==="function"){return this._getLocal(id,callback)}var leaves=[],self=this;function finishOpenRevs(){var result=[];var count=leaves.length;if(!count){return callback(null,result)}leaves.forEach(function(leaf){self.get(id,{rev:leaf,revs:opts.revs,attachments:opts.attachments},function(err,doc){if(!err){result.push({ok:doc})}else{result.push({missing:leaf})}count--;if(!count){callback(null,result)}})})}if(opts.open_revs){if(opts.open_revs==="all"){this._getRevisionTree(id,function(err,rev_tree){if(err){rev_tree=[]}leaves=merge.collectLeaves(rev_tree).map(function(leaf){return leaf.rev});finishOpenRevs()})}else{if(Array.isArray(opts.open_revs)){leaves=opts.open_revs;for(var i=0;i<leaves.length;i++){var l=leaves[i];if(!(typeof l==="string"&&/^\d+-/.test(l))){return callback(errors.error(errors.BAD_REQUEST,"Invalid rev format"))}}finishOpenRevs()}else{return callback(errors.error(errors.UNKNOWN_ERROR,"function_clause"))}}return}return this._get(id,opts,function(err,result){opts=utils.clone(opts);if(err){return callback(err)}var doc=result.doc;if(!doc){return callback(new Error("no doc!"))}var metadata=result.metadata;var ctx=result.ctx;if(opts.conflicts){var conflicts=merge.collectConflicts(metadata);if(conflicts.length){doc._conflicts=conflicts}}if(opts.revs||opts.revs_info){var paths=merge.rootToLeaf(metadata.rev_tree);var path=arrayFirst(paths,function(arr){return arr.ids.map(function(x){return x.id}).indexOf(doc._rev.split("-")[1])!==-1});var indexOfRev=path.ids.map(function(x){return x.id}).indexOf(doc._rev.split("-")[1])+1;var howMany=path.ids.length-indexOfRev;path.ids.splice(indexOfRev,howMany);path.ids.reverse();if(opts.revs){doc._revisions={start:path.pos+path.ids.length-1,ids:path.ids.map(function(rev){return rev.id})}}if(opts.revs_info){var pos=path.pos+path.ids.length;doc._revs_info=path.ids.map(function(rev){pos--;return{rev:pos+"-"+rev.id,status:rev.opts.status}})}}if(opts.local_seq){doc._local_seq=result.metadata.seq}if(opts.attachments&&doc._attachments){var attachments=doc._attachments;var count=Object.keys(attachments).length;if(count===0){return callback(null,doc)}Object.keys(attachments).forEach(function(key){this._getAttachment(attachments[key],{encode:true,ctx:ctx},function(err,data){var att=doc._attachments[key];att.data=data;delete att.stub;delete att.length;if(!--count){callback(null,doc)}})},self)}else{if(doc._attachments){for(var key in doc._attachments){if(doc._attachments.hasOwnProperty(key)){doc._attachments[key].stub=true}}}callback(null,doc)}})});AbstractPouchDB.prototype.getAttachment=utils.adapterFun("getAttachment",function(docId,attachmentId,opts,callback){var self=this;if(opts instanceof Function){callback=opts;opts={}}opts=utils.clone(opts);this._get(docId,opts,function(err,res){if(err){return callback(err)}if(res.doc._attachments&&res.doc._attachments[attachmentId]){opts.ctx=res.ctx;self._getAttachment(res.doc._attachments[attachmentId],opts,callback)}else{return callback(errors.MISSING_DOC)}})});AbstractPouchDB.prototype.allDocs=utils.adapterFun("allDocs",function(opts,callback){if(typeof opts==="function"){callback=opts;opts={}}opts=utils.clone(opts);opts.skip=typeof opts.skip!=="undefined"?opts.skip:0;if("keys"in opts){if(!Array.isArray(opts.keys)){return callback(new TypeError("options.keys must be an array"))}var incompatibleOpt=["startkey","endkey","key"].filter(function(incompatibleOpt){return incompatibleOpt in opts})[0];if(incompatibleOpt){callback(errors.error(errors.QUERY_PARSE_ERROR,"Query parameter `"+incompatibleOpt+"` is not compatible with multi-get"));return}if(this.type()!=="http"){return allDocsKeysQuery(this,opts,callback)}}return this._allDocs(opts,callback)});AbstractPouchDB.prototype.changes=function(opts,callback){if(typeof opts==="function"){callback=opts;opts={}}return new Changes(this,opts,callback)};AbstractPouchDB.prototype.close=utils.adapterFun("close",function(callback){this._closed=true;return this._close(callback)});AbstractPouchDB.prototype.info=utils.adapterFun("info",function(callback){var self=this;this._info(function(err,info){if(err){return callback(err)}info.db_name=info.db_name||self._db_name;info.auto_compaction=!!(self._auto_compaction&&self.type()!=="http");callback(null,info)})});AbstractPouchDB.prototype.id=utils.adapterFun("id",function(callback){return this._id(callback)});AbstractPouchDB.prototype.type=function(){return typeof this._type==="function"?this._type():this.adapter};AbstractPouchDB.prototype.bulkDocs=utils.adapterFun("bulkDocs",function(req,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}opts=utils.clone(opts);if(Array.isArray(req)){req={docs:req}}if(!req||!req.docs||!Array.isArray(req.docs)){return callback(errors.MISSING_BULK_DOCS)}for(var i=0;i<req.docs.length;++i){if(typeof req.docs[i]!=="object"||Array.isArray(req.docs[i])){return callback(errors.NOT_AN_OBJECT)}}req=utils.clone(req);if(!("new_edits"in opts)){if("new_edits"in req){opts.new_edits=req.new_edits}else{opts.new_edits=true}}if(!opts.new_edits&&this.type()!=="http"){req.docs.sort(function(a,b){var idCompare=utils.compare(a._id,b._id);if(idCompare!==0){return idCompare}var aStart=a._revisions?a._revisions.start:0;var bStart=b._revisions?b._revisions.start:0;return utils.compare(aStart,bStart)})}return this._bulkDocs(req,opts,this.autoCompact(function(err,res){if(err){return callback(err)}if(!opts.new_edits){res=res.filter(function(x){return x.error})}callback(null,res)}))});AbstractPouchDB.prototype.registerDependentDatabase=utils.adapterFun("registerDependentDatabase",function(dependentDb,callback){var opts={};if(this.__opts.db){opts.db=this.__opts.db}if(this._adapter){opts.adapter=this._adapter}var depDB=new this.constructor(dependentDb,opts);function diffFun(doc){doc.dependentDbs=doc.dependentDbs||{};if(doc.dependentDbs[dependentDb]){return false}doc.dependentDbs[dependentDb]=true;return doc}upsert(this,"_local/_pouch_dependentDbs",diffFun,function(err){if(err){return callback(err)}return callback(null,{db:depDB})})})},{"./changes":9,"./deps/errors":15,"./deps/upsert":19,"./merge":23,"./utils":28,events:2}],5:[function(require,module,exports){(function(process){"use strict";var CHANGES_BATCH_SIZE=25;var utils=require("../utils");var errors=require("../deps/errors");function encodeDocId(id){if(/^_(design|local)/.test(id)){return id}return encodeURIComponent(id)}function preprocessAttachments(doc){if(!doc._attachments||!Object.keys(doc._attachments)){return utils.Promise.resolve()}return utils.Promise.all(Object.keys(doc._attachments).map(function(key){var attachment=doc._attachments[key];if(attachment.data&&typeof attachment.data!=="string"){if(typeof process===undefined||process.browser){return new utils.Promise(function(resolve){utils.readAsBinaryString(attachment.data,function(binary){attachment.data=utils.btoa(binary);resolve()})})}else{attachment.data=attachment.data.toString("base64")}}}))}function getHost(name,opts){if(/http(s?):/.test(name)){var uri=utils.parseUri(name);uri.remote=true;if(uri.user||uri.password){uri.auth={username:uri.user,password:uri.password}}var parts=uri.path.replace(/(^\/|\/$)/g,"").split("/");uri.db=parts.pop();uri.path=parts.join("/");opts=opts||{};opts=utils.clone(opts);uri.headers=opts.headers||{};if(opts.auth||uri.auth){var nAuth=opts.auth||uri.auth;var token=utils.btoa(nAuth.username+":"+nAuth.password);uri.headers.Authorization="Basic "+token}if(opts.headers){uri.headers=opts.headers}return uri}return{host:"",path:"/",db:name,auth:false}}function genDBUrl(opts,path){return genUrl(opts,opts.db+"/"+path)}function genUrl(opts,path){if(opts.remote){var pathDel=!opts.path?"":"/";return opts.protocol+"://"+opts.host+":"+opts.port+"/"+opts.path+pathDel+path}return"/"+path}function HttpPouch(opts,callback){var api=this;api.getHost=opts.getHost?opts.getHost:getHost;var host=api.getHost(opts.name,opts);var dbUrl=genDBUrl(host,"");api.getUrl=function(){return dbUrl};api.getHeaders=function(){return utils.clone(host.headers)};var ajaxOpts=opts.ajax||{};opts=utils.clone(opts);function ajax(options,callback){return utils.ajax(utils.extend({},ajaxOpts,options),callback)}var createDB=function(){ajax({headers:host.headers,method:"PUT",url:dbUrl},function(err,ret){if(err&&err.status===401){ajax({headers:host.headers,method:"HEAD",url:dbUrl},function(err,ret){if(err){callback(err)}else{callback(null,api)}})}else if(!err||err.status===412){callback(null,api)}else{callback(err)}})};if(!opts.skipSetup){ajax({headers:host.headers,method:"GET",url:dbUrl},function(err,ret){if(err){if(err.status===404){utils.explain404("PouchDB is just detecting if the remote DB exists.");createDB()}else{callback(err)}}else{callback(null,api)}})}api.type=function(){return"http"};api.id=utils.adapterFun("id",function(callback){ajax({headers:host.headers,method:"GET",url:genUrl(host,"")},function(err,result){var uuid=result&&result.uuid?result.uuid+host.db:genDBUrl(host,"");callback(null,uuid)})});api.request=utils.adapterFun("request",function(options,callback){options.headers=host.headers;options.url=genDBUrl(host,options.url);ajax(options,callback)});api.compact=utils.adapterFun("compact",function(opts,callback){if(typeof opts==="function"){callback=opts;opts={}}opts=utils.clone(opts);ajax({headers:host.headers,url:genDBUrl(host,"_compact"),method:"POST"},function(){function ping(){api.info(function(err,res){if(!res.compact_running){callback()}else{setTimeout(ping,opts.interval||200)}})}if(typeof callback==="function"){ping()}})});api._info=function(callback){ajax({headers:host.headers,method:"GET",url:genDBUrl(host,"")},function(err,res){if(err){callback(err)}else{res.host=genDBUrl(host,"");callback(null,res)}})};api.get=utils.adapterFun("get",function(id,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}opts=utils.clone(opts);if(opts.auto_encode===undefined){opts.auto_encode=true}var params=[];if(opts.revs){params.push("revs=true")}if(opts.revs_info){params.push("revs_info=true")}if(opts.local_seq){params.push("local_seq=true")}if(opts.open_revs){if(opts.open_revs!=="all"){opts.open_revs=JSON.stringify(opts.open_revs)}params.push("open_revs="+opts.open_revs)}if(opts.attachments){params.push("attachments=true")}if(opts.rev){params.push("rev="+opts.rev)}if(opts.conflicts){params.push("conflicts="+opts.conflicts)}params=params.join("&");params=params===""?"":"?"+params;if(opts.auto_encode){id=encodeDocId(id)}var options={headers:host.headers,method:"GET",url:genDBUrl(host,id+params)};var parts=id.split("/");if(parts.length>1&&parts[0]!=="_design"&&parts[0]!=="_local"||parts.length>2&&parts[0]==="_design"&&parts[0]!=="_local"){options.binary=true}ajax(options,function(err,doc,xhr){if(err){return callback(err)}callback(null,doc,xhr)})});api.remove=utils.adapterFun("remove",function(docOrId,optsOrRev,opts,callback){var doc;if(typeof optsOrRev==="string"){doc={_id:docOrId,_rev:optsOrRev};if(typeof opts==="function"){callback=opts;opts={}}}else{doc=docOrId;if(typeof optsOrRev==="function"){callback=optsOrRev;opts={}}else{callback=opts;opts=optsOrRev}}var rev=doc._rev||opts.rev;ajax({headers:host.headers,method:"DELETE",url:genDBUrl(host,encodeDocId(doc._id))+"?rev="+rev},callback)});function encodeAttachmentId(attachmentId){return attachmentId.split("/").map(encodeURIComponent).join("/")}api.getAttachment=utils.adapterFun("getAttachment",function(docId,attachmentId,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}opts=utils.clone(opts);if(opts.auto_encode===undefined){opts.auto_encode=true}if(opts.auto_encode){docId=encodeDocId(docId)}opts.auto_encode=false;api.get(docId+"/"+encodeAttachmentId(attachmentId),opts,callback)});api.removeAttachment=utils.adapterFun("removeAttachment",function(docId,attachmentId,rev,callback){var url=genDBUrl(host,encodeDocId(docId)+"/"+encodeAttachmentId(attachmentId))+"?rev="+rev;ajax({headers:host.headers,method:"DELETE",url:url},callback)});api.putAttachment=utils.adapterFun("putAttachment",function(docId,attachmentId,rev,blob,type,callback){if(typeof type==="function"){callback=type;type=blob;blob=rev;rev=null}if(typeof type==="undefined"){type=blob;blob=rev;rev=null}var id=encodeDocId(docId)+"/"+encodeAttachmentId(attachmentId);var url=genDBUrl(host,id);if(rev){url+="?rev="+rev}if(typeof blob==="string"){try{blob=utils.atob(blob)}catch(err){return callback(utils.extend({},errors.BAD_ARG,{reason:"Attachments need to be base64 encoded"}))}}var opts={headers:utils.clone(host.headers),method:"PUT",url:url,processData:false,body:blob,timeout:6e4};opts.headers["Content-Type"]=type;ajax(opts,callback)});api.put=utils.adapterFun("put",utils.getArguments(function(args){var temp,temptype,opts;var doc=args.shift();var id="_id"in doc;var callback=args.pop();if(typeof doc!=="object"||Array.isArray(doc)){return callback(errors.NOT_AN_OBJECT)}doc=utils.clone(doc);preprocessAttachments(doc).then(function(){while(true){temp=args.shift();temptype=typeof temp;if(temptype==="string"&&!id){doc._id=temp;id=true}else if(temptype==="string"&&id&&!("_rev"in doc)){doc._rev=temp}else if(temptype==="object"){opts=utils.clone(temp)}if(!args.length){break}}opts=opts||{};var error=utils.invalidIdError(doc._id);if(error){throw error}var params=[];if(opts&&typeof opts.new_edits!=="undefined"){params.push("new_edits="+opts.new_edits)}params=params.join("&");if(params!==""){params="?"+params}ajax({headers:host.headers,method:"PUT",url:genDBUrl(host,encodeDocId(doc._id))+params,body:doc},function(err,res){if(err){return callback(err)}res.ok=true;callback(null,res)})})["catch"](callback)}));api.post=utils.adapterFun("post",function(doc,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}opts=utils.clone(opts);if(typeof doc!=="object"){return callback(errors.NOT_AN_OBJECT)}if(!("_id"in doc)){doc._id=utils.uuid()}api.put(doc,opts,function(err,res){if(err){return callback(err)}res.ok=true;callback(null,res)})});api._bulkDocs=function(req,opts,callback){if(typeof opts.new_edits!=="undefined"){req.new_edits=opts.new_edits}utils.Promise.all(req.docs.map(preprocessAttachments)).then(function(){ajax({headers:host.headers,method:"POST",url:genDBUrl(host,"_bulk_docs"),body:req},function(err,results){if(err){return callback(err)}results.forEach(function(result){result.ok=true});callback(null,results)})})["catch"](callback)};api.allDocs=utils.adapterFun("allDocs",function(opts,callback){if(typeof opts==="function"){callback=opts;opts={}}opts=utils.clone(opts);var params=[];var body;var method="GET";if(opts.conflicts){params.push("conflicts=true")}if(opts.descending){params.push("descending=true")}if(opts.include_docs){params.push("include_docs=true")}if(opts.key){params.push("key="+encodeURIComponent(JSON.stringify(opts.key)))}if(opts.startkey){params.push("startkey="+encodeURIComponent(JSON.stringify(opts.startkey)))}if(opts.endkey){params.push("endkey="+encodeURIComponent(JSON.stringify(opts.endkey)))}if(typeof opts.inclusive_end!=="undefined"){params.push("inclusive_end="+!!opts.inclusive_end)}if(typeof opts.limit!=="undefined"){params.push("limit="+opts.limit)}if(typeof opts.skip!=="undefined"){params.push("skip="+opts.skip) | |
}params=params.join("&");if(params!==""){params="?"+params}if(typeof opts.keys!=="undefined"){var MAX_URL_LENGTH=2e3;var keysAsString="keys="+encodeURIComponent(JSON.stringify(opts.keys));if(keysAsString.length+params.length+1<=MAX_URL_LENGTH){params+=(params.indexOf("?")!==-1?"&":"?")+keysAsString}else{method="POST";body=JSON.stringify({keys:opts.keys})}}ajax({headers:host.headers,method:method,url:genDBUrl(host,"_all_docs"+params),body:body},callback)});api._changes=function(opts){var batchSize="batch_size"in opts?opts.batch_size:CHANGES_BATCH_SIZE;opts=utils.clone(opts);opts.timeout=opts.timeout||30*1e3;var params={timeout:opts.timeout-5*1e3};var limit=typeof opts.limit!=="undefined"?opts.limit:false;if(limit===0){limit=1}var returnDocs;if("returnDocs"in opts){returnDocs=opts.returnDocs}else{returnDocs=true}var leftToFetch=limit;if(opts.style){params.style=opts.style}if(opts.include_docs||opts.filter&&typeof opts.filter==="function"){params.include_docs=true}if(opts.continuous){params.feed="longpoll"}if(opts.conflicts){params.conflicts=true}if(opts.descending){params.descending=true}if(opts.filter&&typeof opts.filter==="string"){params.filter=opts.filter;if(opts.filter==="_view"&&opts.view&&typeof opts.view==="string"){params.view=opts.view}}if(opts.query_params&&typeof opts.query_params==="object"){for(var param_name in opts.query_params){if(opts.query_params.hasOwnProperty(param_name)){params[param_name]=opts.query_params[param_name]}}}if(opts.continuous&&api._useSSE){return api.sse(opts,params,returnDocs)}var xhr;var lastFetchedSeq;var fetch=function(since,callback){if(opts.aborted){return}params.since=since;if(opts.descending){if(limit){params.limit=leftToFetch}}else{params.limit=!limit||leftToFetch>batchSize?batchSize:leftToFetch}var paramStr="?"+Object.keys(params).map(function(k){return k+"="+params[k]}).join("&");var xhrOpts={headers:host.headers,method:"GET",url:genDBUrl(host,"_changes"+paramStr),timeout:opts.timeout};lastFetchedSeq=since;if(opts.aborted){return}xhr=ajax(xhrOpts,callback)};var fetchTimeout=10;var fetchRetryCount=0;var results={results:[]};var fetched=function(err,res){if(opts.aborted){return}var raw_results_length=0;if(res&&res.results){raw_results_length=res.results.length;results.last_seq=res.last_seq;var req={};req.query=opts.query_params;res.results=res.results.filter(function(c){leftToFetch--;var ret=utils.filterChange(opts)(c);if(ret){if(returnDocs){results.results.push(c)}utils.call(opts.onChange,c)}return ret})}else if(err){opts.aborted=true;utils.call(opts.complete,err);return}if(res&&res.last_seq){lastFetchedSeq=res.last_seq}var finished=limit&&leftToFetch<=0||res&&raw_results_length<batchSize||opts.descending;if(opts.continuous&&!(limit&&leftToFetch<=0)||!finished){if(err){fetchRetryCount+=1}else{fetchRetryCount=0}var timeoutMultiplier=1<<fetchRetryCount;var retryWait=fetchTimeout*timeoutMultiplier;var maximumWait=opts.maximumWait||3e4;if(retryWait>maximumWait){utils.call(opts.complete,err||errors.UNKNOWN_ERROR);return}setTimeout(function(){fetch(lastFetchedSeq,fetched)},retryWait)}else{utils.call(opts.complete,null,results)}};fetch(opts.since||0,fetched);return{cancel:function(){opts.aborted=true;if(xhr){xhr.abort()}}}};api.sse=function(opts,params,returnDocs){params.feed="eventsource";params.since=opts.since||0;params.limit=opts.limit;delete params.timeout;var paramStr="?"+Object.keys(params).map(function(k){return k+"="+params[k]}).join("&");var url=genDBUrl(host,"_changes"+paramStr);var source=new EventSource(url);var results={results:[],last_seq:false};var dispatched=false;var open=false;source.addEventListener("message",msgHandler,false);source.onopen=function(){open=true};source.onerror=errHandler;return{cancel:function(){if(dispatched){return dispatched.cancel()}source.removeEventListener("message",msgHandler,false);source.close()}};function msgHandler(e){var data=JSON.parse(e.data);if(returnDocs){results.results.push(data)}results.last_seq=data.seq;utils.call(opts.onChange,data)}function errHandler(err){source.removeEventListener("message",msgHandler,false);if(open===false){api._useSSE=false;dispatched=api._changes(opts);return}source.close();utils.call(opts.complete,err)}};api._useSSE=false;api.revsDiff=utils.adapterFun("revsDiff",function(req,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}ajax({headers:host.headers,method:"POST",url:genDBUrl(host,"_revs_diff"),body:JSON.stringify(req)},callback)});api._close=function(callback){callback()};api.destroy=utils.adapterFun("destroy",function(callback){ajax({url:genDBUrl(host,""),method:"DELETE",headers:host.headers},function(err,resp){if(err){api.emit("error",err);callback(err)}else{api.emit("destroyed");callback(null,resp)}})})}HttpPouch.destroy=utils.toPromise(function(name,opts,callback){var host=getHost(name,opts);opts=opts||{};if(typeof opts==="function"){callback=opts;opts={}}opts=utils.clone(opts);opts.headers=host.headers;opts.method="DELETE";opts.url=genDBUrl(host,"");var ajaxOpts=opts.ajax||{};opts=utils.extend({},opts,ajaxOpts);utils.ajax(opts,callback)});HttpPouch.valid=function(){return true};module.exports=HttpPouch}).call(this,require("_process"))},{"../deps/errors":15,"../utils":28,_process:3}],6:[function(require,module,exports){(function(process,global){"use strict";var utils=require("../utils");var merge=require("../merge");var errors=require("../deps/errors");var vuvuzela=require("vuvuzela");var cachedDBs={};var taskQueue={running:false,queue:[]};function tryCode(fun,that,args){try{fun.apply(that,args)}catch(err){if(window.PouchDB){window.PouchDB.emit("error",err)}}}function applyNext(){if(taskQueue.running||!taskQueue.queue.length){return}taskQueue.running=true;var item=taskQueue.queue.shift();item.action(function(err,res){tryCode(item.callback,this,[err,res]);taskQueue.running=false;process.nextTick(applyNext)})}function idbError(callback){return function(event){var message=event.target&&event.target.error&&event.target.error.name||event.target;callback(errors.error(errors.IDB_ERROR,message,event.type))}}function encodeMetadata(metadata,winningRev,deleted){var storedObject={data:vuvuzela.stringify(metadata)};storedObject.winningRev=winningRev;storedObject.deletedOrLocal=deleted?"1":"0";storedObject.id=metadata.id;return storedObject}function decodeMetadata(storedObject){if(!storedObject){return null}if(!storedObject.data){return storedObject}var metadata=vuvuzela.parse(storedObject.data);metadata.winningRev=storedObject.winningRev;metadata.deletedOrLocal=storedObject.deletedOrLocal==="1";return metadata}function IdbPouch(opts,callback){var api=this;taskQueue.queue.push({action:function(thisCallback){init(api,opts,thisCallback)},callback:callback});applyNext()}function init(api,opts,callback){var ADAPTER_VERSION=4;var DOC_STORE="document-store";var BY_SEQ_STORE="by-sequence";var ATTACH_STORE="attach-store";var ATTACH_AND_SEQ_STORE="attach-seq-store";var META_STORE="meta-store";var LOCAL_STORE="local-store";var DETECT_BLOB_SUPPORT_STORE="detect-blob-support";var name=opts.name;var blobSupport=null;var instanceId=null;var idStored=false;var idb=null;var docCount=-1;function createSchema(db){var docStore=db.createObjectStore(DOC_STORE,{keyPath:"id"});docStore.createIndex("seq","seq",{unique:true});db.createObjectStore(BY_SEQ_STORE,{autoIncrement:true}).createIndex("_doc_id_rev","_doc_id_rev",{unique:true});db.createObjectStore(ATTACH_STORE,{keyPath:"digest"});db.createObjectStore(META_STORE,{keyPath:"id",autoIncrement:false});db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);docStore.createIndex("deletedOrLocal","deletedOrLocal",{unique:false});db.createObjectStore(LOCAL_STORE,{keyPath:"_id"}).createIndex("_doc_id_rev","_doc_id_rev",{unique:true});var attAndSeqStore=db.createObjectStore(ATTACH_AND_SEQ_STORE,{autoIncrement:true});attAndSeqStore.createIndex("seq","seq");attAndSeqStore.createIndex("digestSeq","digestSeq",{unique:true})}function addDeletedOrLocalIndex(txn,callback){var docStore=txn.objectStore(DOC_STORE);docStore.createIndex("deletedOrLocal","deletedOrLocal",{unique:false});docStore.openCursor().onsuccess=function(event){var cursor=event.target.result;if(cursor){var metadata=cursor.value;var deleted=utils.isDeleted(metadata);metadata.deletedOrLocal=deleted?"1":"0";docStore.put(metadata);cursor["continue"]()}else{callback()}}}function createLocalStoreSchema(db){db.createObjectStore(LOCAL_STORE,{keyPath:"_id"}).createIndex("_doc_id_rev","_doc_id_rev",{unique:true})}function migrateLocalStore(txn,cb){var localStore=txn.objectStore(LOCAL_STORE);var docStore=txn.objectStore(DOC_STORE);var seqStore=txn.objectStore(BY_SEQ_STORE);var cursor=docStore.openCursor();cursor.onsuccess=function(event){var cursor=event.target.result;if(cursor){var metadata=cursor.value;var docId=metadata.id;var local=utils.isLocalId(docId);var rev=merge.winningRev(metadata);if(local){var docIdRev=docId+"::"+rev;var start=docId+"::";var end=docId+"::~";var index=seqStore.index("_doc_id_rev");var range=global.IDBKeyRange.bound(start,end,false,false);var seqCursor=index.openCursor(range);seqCursor.onsuccess=function(e){seqCursor=e.target.result;if(!seqCursor){docStore["delete"](cursor.primaryKey);cursor["continue"]()}else{var data=seqCursor.value;if(data._doc_id_rev===docIdRev){localStore.put(data)}seqStore["delete"](seqCursor.primaryKey);seqCursor["continue"]()}}}else{cursor["continue"]()}}else if(cb){cb()}}}function addAttachAndSeqStore(db){var attAndSeqStore=db.createObjectStore(ATTACH_AND_SEQ_STORE,{autoIncrement:true});attAndSeqStore.createIndex("seq","seq");attAndSeqStore.createIndex("digestSeq","digestSeq",{unique:true})}function migrateAttsAndSeqs(txn){var seqStore=txn.objectStore(BY_SEQ_STORE);var attStore=txn.objectStore(ATTACH_STORE);var attAndSeqStore=txn.objectStore(ATTACH_AND_SEQ_STORE);var req=attStore.count();req.onsuccess=function(e){var count=e.target.result;if(!count){return}seqStore.openCursor().onsuccess=function(e){var cursor=e.target.result;if(!cursor){return}var doc=cursor.value;var seq=cursor.primaryKey;var atts=Object.keys(doc._attachments||{});var digestMap={};for(var j=0;j<atts.length;j++){var att=doc._attachments[atts[j]];digestMap[att.digest]=true}var digests=Object.keys(digestMap);for(j=0;j<digests.length;j++){var digest=digests[j];attAndSeqStore.put({seq:seq,digestSeq:digest+"::"+seq})}cursor["continue"]()}}}api.type=function(){return"idb"};api._id=utils.toPromise(function(callback){callback(null,instanceId)});api._bulkDocs=function idb_bulkDocs(req,opts,callback){var newEdits=opts.new_edits;var userDocs=req.docs;var docInfos=userDocs.map(function(doc,i){if(doc._id&&utils.isLocalId(doc._id)){return doc}var newDoc=utils.parseDoc(doc,newEdits);newDoc._bulk_seq=i;return newDoc});var docInfoErrors=docInfos.filter(function(docInfo){return docInfo.error});if(docInfoErrors.length){return callback(docInfoErrors[0])}var results=new Array(docInfos.length);var fetchedDocs=new utils.Map;var preconditionErrored=false;function processDocs(){if(!docInfos.length){return}var idsToDocs=new utils.Map;docInfos.forEach(function(currentDoc,resultsIdx){if(currentDoc._id&&utils.isLocalId(currentDoc._id)){api[currentDoc._deleted?"_removeLocal":"_putLocal"](currentDoc,{ctx:txn},function(err,resp){if(err){results[resultsIdx]=err}else{results[resultsIdx]={}}});return}var id=currentDoc.metadata.id;if(idsToDocs.has(id)){idsToDocs.get(id).push([currentDoc,resultsIdx])}else{idsToDocs.set(id,[[currentDoc,resultsIdx]])}});idsToDocs.forEach(function(docs,id){var numDone=0;function docWritten(){if(++numDone<docs.length){nextDoc()}}function nextDoc(){var value=docs[numDone];var currentDoc=value[0];var resultsIdx=value[1];if(fetchedDocs.has(id)){updateDoc(fetchedDocs.get(id),currentDoc,resultsIdx,docWritten)}else{insertDoc(currentDoc,resultsIdx,docWritten)}}nextDoc()})}function fetchExistingDocs(callback){if(!docInfos.length){return callback()}var numFetched=0;function checkDone(){if(++numFetched===docInfos.length){callback()}}docInfos.forEach(function(docInfo){if(docInfo._id&&utils.isLocalId(docInfo._id)){return checkDone()}var id=docInfo.metadata.id;var req=txn.objectStore(DOC_STORE).get(id);req.onsuccess=function process_docRead(event){var metadata=decodeMetadata(event.target.result);if(metadata){fetchedDocs.set(id,metadata)}checkDone()}})}function complete(){if(preconditionErrored){return}var aresults=results.map(function(result){if(result._bulk_seq){delete result._bulk_seq}else if(!Object.keys(result).length){return{ok:true}}if(result.error){return result}var metadata=result.metadata;var rev=merge.winningRev(metadata);return{ok:true,id:metadata.id,rev:rev}});IdbPouch.Changes.notify(name);docCount=-1;callback(null,aresults)}function preprocessAttachment(att,finish){if(att.stub){return finish()}if(typeof att.data==="string"){var data;try{data=atob(att.data)}catch(e){var err=errors.error(errors.BAD_ARG,"Attachments need to be base64 encoded");return callback(err)}var length;if(blobSupport){var type=att.content_type;data=utils.fixBinary(data);length=data.byteLength;att.data=utils.createBlob([data],{type:type})}else{length=data.length}utils.MD5(data).then(function(result){att.digest="md5-"+result;att.length=length;finish()});return}utils.readAsBinaryString(att.data,function(binary){if(!blobSupport){att.data=btoa(binary)}utils.MD5(binary).then(function(result){att.digest="md5-"+result;att.length=binary.length;finish()})})}function verifyAttachment(digest,callback){var req=txn.objectStore([ATTACH_STORE]).get(digest);req.onsuccess=function(e){if(!e.target.result){var err=new Error("unknown stub attachment with digest "+digest);err.status=412;callback(err)}else{callback()}}}function verifyAttachments(finish){var digests=[];docInfos.forEach(function(docInfo){if(docInfo.data&&docInfo.data._attachments){Object.keys(docInfo.data._attachments).forEach(function(filename){var att=docInfo.data._attachments[filename];if(att.stub){digests.push(att.digest)}})}});if(!digests.length){return finish()}var numDone=0;var err;function checkDone(){if(++numDone===digests.length){finish(err)}}digests.forEach(function(digest){verifyAttachment(digest,function(attErr){if(attErr&&!err){err=attErr}checkDone()})})}function preprocessAttachments(callback){if(!docInfos.length){return callback()}var docv=0;docInfos.forEach(function(docInfo){var attachments=docInfo.data&&docInfo.data._attachments?Object.keys(docInfo.data._attachments):[];if(!attachments.length){return done()}var recv=0;function attachmentProcessed(){recv++;if(recv===attachments.length){done()}}for(var key in docInfo.data._attachments){if(docInfo.data._attachments.hasOwnProperty(key)){preprocessAttachment(docInfo.data._attachments[key],attachmentProcessed)}}});function done(){docv++;if(docInfos.length===docv){callback()}}}function writeDoc(docInfo,winningRev,deleted,callback,resultsIdx){var err=null;var recv=0;var id=docInfo.data._id=docInfo.metadata.id;var rev=docInfo.data._rev=docInfo.metadata.rev;var docIdRev=id+"::"+rev;if(deleted){docInfo.data._deleted=true}var attachments=docInfo.data._attachments?Object.keys(docInfo.data._attachments):[];function collectResults(attachmentErr){if(!err){if(attachmentErr){err=attachmentErr;callback(err)}else if(recv===attachments.length){finish()}}}function attachmentSaved(err){recv++;collectResults(err)}for(var key in docInfo.data._attachments){if(!docInfo.data._attachments[key].stub){var data=docInfo.data._attachments[key].data;delete docInfo.data._attachments[key].data;var digest=docInfo.data._attachments[key].digest;saveAttachment(digest,data,attachmentSaved)}else{recv++;collectResults()}}function insertAttachmentMappings(seq,callback){var attsAdded=0;var attsToAdd=Object.keys(docInfo.data._attachments||{});if(!attsToAdd.length){return callback()}function checkDone(){if(++attsAdded===attsToAdd.length){callback()}}function add(att){var digest=docInfo.data._attachments[att].digest;var req=txn.objectStore(ATTACH_AND_SEQ_STORE).put({seq:seq,digestSeq:digest+"::"+seq});req.onsuccess=checkDone;req.onerror=function(e){e.preventDefault();e.stopPropagation();checkDone()}}for(var i=0;i<attsToAdd.length;i++){add(attsToAdd[i])}}function finish(){docInfo.data._doc_id_rev=docIdRev;var seqStore=txn.objectStore(BY_SEQ_STORE);var index=seqStore.index("_doc_id_rev");function afterPut(e){var metadata=docInfo.metadata;var seq=e.target.result;metadata.seq=seq;delete metadata.rev;var metadataToStore=encodeMetadata(metadata,winningRev,deleted);var metaDataReq=txn.objectStore(DOC_STORE).put(metadataToStore);metaDataReq.onsuccess=function(){delete metadata.deletedOrLocal;delete metadata.winningRev;results[resultsIdx]=docInfo;fetchedDocs.set(docInfo.metadata.id,docInfo.metadata);insertAttachmentMappings(seq,function(){utils.call(callback)})}}var putReq=seqStore.put(docInfo.data);putReq.onsuccess=afterPut;putReq.onerror=function(e){e.preventDefault();e.stopPropagation();var getKeyReq=index.getKey(docInfo.data._doc_id_rev);getKeyReq.onsuccess=function(e){var putReq=seqStore.put(docInfo.data,e.target.result);putReq.onsuccess=afterPut}}}if(!attachments.length){finish()}}function updateDoc(oldDoc,docInfo,resultsIdx,callback){if(utils.revExists(oldDoc,docInfo.metadata.rev)){results[resultsIdx]=docInfo;callback();return}var merged=merge.merge(oldDoc.rev_tree,docInfo.metadata.rev_tree[0],1e3);var previouslyDeleted=utils.isDeleted(oldDoc);var deleted=utils.isDeleted(docInfo.metadata);var inConflict=previouslyDeleted&&deleted&&newEdits||!previouslyDeleted&&newEdits&&merged.conflicts!=="new_leaf"||previouslyDeleted&&!deleted&&merged.conflicts==="new_branch";if(inConflict){results[resultsIdx]=makeErr(errors.REV_CONFLICT,docInfo._bulk_seq);return callback()}docInfo.metadata.rev_tree=merged.tree;var winningRev=merge.winningRev(docInfo.metadata);deleted=utils.isDeleted(docInfo.metadata,winningRev);writeDoc(docInfo,winningRev,deleted,callback,resultsIdx)}function insertDoc(docInfo,resultsIdx,callback){var winningRev=merge.winningRev(docInfo.metadata);var deleted=utils.isDeleted(docInfo.metadata,winningRev);if("was_delete"in opts&&deleted){results[resultsIdx]=errors.MISSING_DOC;return callback()}writeDoc(docInfo,winningRev,deleted,callback,resultsIdx)}function makeErr(err,seq){err._bulk_seq=seq;return err}function saveAttachment(digest,data,callback){var objectStore=txn.objectStore(ATTACH_STORE);objectStore.get(digest).onsuccess=function(e){var exists=e.target.result;if(exists){return utils.call(callback)}var newAtt={digest:digest,body:data};objectStore.put(newAtt).onsuccess=function(){utils.call(callback)}}}var txn;preprocessAttachments(function(){var stores=[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE,META_STORE,LOCAL_STORE,ATTACH_AND_SEQ_STORE];txn=idb.transaction(stores,"readwrite");txn.onerror=idbError(callback);txn.ontimeout=idbError(callback);txn.oncomplete=complete;verifyAttachments(function(err){if(err){preconditionErrored=true;return callback(err)}fetchExistingDocs(processDocs)})})};api._get=function idb_get(id,opts,callback){var doc;var metadata;var err;var txn;opts=utils.clone(opts);if(opts.ctx){txn=opts.ctx}else{txn=idb.transaction([DOC_STORE,BY_SEQ_STORE,ATTACH_STORE],"readonly")}function finish(){callback(err,{doc:doc,metadata:metadata,ctx:txn})}txn.objectStore(DOC_STORE).get(id).onsuccess=function(e){metadata=decodeMetadata(e.target.result);if(!metadata){err=errors.MISSING_DOC;return finish()}if(utils.isDeleted(metadata)&&!opts.rev){err=errors.error(errors.MISSING_DOC,"deleted");return finish()}var objectStore=txn.objectStore(BY_SEQ_STORE);var rev=opts.rev||metadata.winningRev||merge.winningRev(metadata);var key=metadata.id+"::"+rev;objectStore.index("_doc_id_rev").get(key).onsuccess=function(e){doc=e.target.result;if(doc&&doc._doc_id_rev){delete doc._doc_id_rev}if(!doc){err=errors.MISSING_DOC;return finish()}finish()}}};api._getAttachment=function(attachment,opts,callback){var txn;opts=utils.clone(opts);if(opts.ctx){txn=opts.ctx}else{txn=idb.transaction([DOC_STORE,BY_SEQ_STORE,ATTACH_STORE],"readonly")}var digest=attachment.digest;var type=attachment.content_type;txn.objectStore(ATTACH_STORE).get(digest).onsuccess=function(e){var data=e.target.result.body;if(opts.encode){if(!data){callback(null,"")}else if(typeof data!=="string"){utils.readAsBinaryString(data,function(binary){callback(null,btoa(binary))})}else{callback(null,data)}}else{if(!data){callback(null,utils.createBlob([""],{type:type}))}else if(typeof data!=="string"){callback(null,data)}else{data=utils.fixBinary(atob(data));callback(null,utils.createBlob([data],{type:type}))}}}};function allDocsQuery(totalRows,opts,callback){var start="startkey"in opts?opts.startkey:false;var end="endkey"in opts?opts.endkey:false;var key="key"in opts?opts.key:false;var skip=opts.skip||0;var limit=typeof opts.limit==="number"?opts.limit:-1;var inclusiveEnd=opts.inclusive_end!==false;var descending="descending"in opts&&opts.descending?"prev":null;var manualDescEnd=false;if(descending&&start&&end){manualDescEnd=end;end=false}var keyRange=null;try{if(start&&end){keyRange=global.IDBKeyRange.bound(start,end,false,!inclusiveEnd)}else if(start){if(descending){keyRange=global.IDBKeyRange.upperBound(start)}else{keyRange=global.IDBKeyRange.lowerBound(start)}}else if(end){if(descending){keyRange=global.IDBKeyRange.lowerBound(end,!inclusiveEnd)}else{keyRange=global.IDBKeyRange.upperBound(end,!inclusiveEnd)}}else if(key){keyRange=global.IDBKeyRange.only(key)}}catch(e){if(e.name==="DataError"&&e.code===0){return callback(null,{total_rows:totalRows,offset:opts.skip,rows:[]})}else{return callback(errors.error(errors.IDB_ERROR,e.name,e.message))}}var transaction=idb.transaction([DOC_STORE,BY_SEQ_STORE],"readonly");transaction.oncomplete=function(){callback(null,{total_rows:totalRows,offset:opts.skip,rows:results})};var oStore=transaction.objectStore(DOC_STORE);var oCursor=descending?oStore.openCursor(keyRange,descending):oStore.openCursor(keyRange);var results=[];oCursor.onsuccess=function(e){if(!e.target.result){return}var cursor=e.target.result;var metadata=decodeMetadata(cursor.value);var winningRev=metadata.winningRev||merge.winningRev(metadata);function allDocsInner(metadata,data){var doc={id:metadata.id,key:metadata.id,value:{rev:winningRev}};if(opts.include_docs){doc.doc=data;doc.doc._rev=winningRev;if(doc.doc._doc_id_rev){delete doc.doc._doc_id_rev}if(opts.conflicts){doc.doc._conflicts=merge.collectConflicts(metadata)}for(var att in doc.doc._attachments){if(doc.doc._attachments.hasOwnProperty(att)){doc.doc._attachments[att].stub=true}}}var deleted=utils.isDeleted(metadata,winningRev);if(opts.deleted==="ok"){if(deleted){doc.value.deleted=true;doc.doc=null}results.push(doc)}else if(!deleted&&skip--<=0){if(manualDescEnd){if(inclusiveEnd&&doc.key<manualDescEnd){return}else if(!inclusiveEnd&&doc.key<=manualDescEnd){return}}results.push(doc);if(--limit===0){return}}cursor["continue"]()}if(!opts.include_docs){allDocsInner(metadata)}else{var index=transaction.objectStore(BY_SEQ_STORE).index("_doc_id_rev");var key=metadata.id+"::"+winningRev;index.get(key).onsuccess=function(event){allDocsInner(decodeMetadata(cursor.value),event.target.result)}}}}function countDocs(callback){if(docCount!==-1){return callback(null,docCount)}var count;var txn=idb.transaction([DOC_STORE],"readonly");var index=txn.objectStore(DOC_STORE).index("deletedOrLocal");index.count(global.IDBKeyRange.only("0")).onsuccess=function(e){count=e.target.result};txn.onerror=idbError(callback);txn.oncomplete=function(){docCount=count;callback(null,docCount)}}api._allDocs=function idb_allDocs(opts,callback){countDocs(function(err,totalRows){if(err){return callback(err)}if(opts.limit===0){return callback(null,{total_rows:totalRows,offset:opts.skip,rows:[]})}allDocsQuery(totalRows,opts,callback)})};api._info=function idb_info(callback){countDocs(function(err,count){if(err){return callback(err)}if(idb===null){var error=new Error("db isn't open");error.id="idbNull";return callback(error)}var updateSeq=0;var txn=idb.transaction([BY_SEQ_STORE],"readonly");txn.objectStore(BY_SEQ_STORE).openCursor(null,"prev").onsuccess=function(event){var cursor=event.target.result;if(cursor){updateSeq=cursor.key}else{updateSeq=0}};txn.oncomplete=function(){callback(null,{doc_count:count,update_seq:updateSeq})}})};api._changes=function(opts){opts=utils.clone(opts);if(opts.continuous){var id=name+":"+utils.uuid();IdbPouch.Changes.addListener(name,id,api,opts);IdbPouch.Changes.notify(name);return{cancel:function(){IdbPouch.Changes.removeListener(name,id)}}}var descending=opts.descending?"prev":null;var lastSeq=0;opts.since=opts.since&&!descending?opts.since:0;var limit="limit"in opts?opts.limit:-1;if(limit===0){limit=1}var returnDocs;if("returnDocs"in opts){returnDocs=opts.returnDocs}else{returnDocs=true}var results=[];var numResults=0;var filter=utils.filterChange(opts);var txn;function fetchChanges(){txn=idb.transaction([DOC_STORE,BY_SEQ_STORE],"readonly");txn.oncomplete=onTxnComplete;var req;if(descending){req=txn.objectStore(BY_SEQ_STORE).openCursor(global.IDBKeyRange.lowerBound(opts.since,true),descending)}else{req=txn.objectStore(BY_SEQ_STORE).openCursor(global.IDBKeyRange.lowerBound(opts.since,true))}req.onsuccess=onsuccess;req.onerror=onerror}fetchChanges();function onsuccess(event){var cursor=event.target.result;if(!cursor){return}var doc=cursor.value;if(opts.doc_ids&&opts.doc_ids.indexOf(doc._id)===-1){return cursor["continue"]()}var index=txn.objectStore(DOC_STORE);index.get(doc._id).onsuccess=function(event){var metadata=decodeMetadata(event.target.result);if(lastSeq<metadata.seq){lastSeq=metadata.seq}var winningRev=metadata.winningRev||merge.winningRev(metadata);if(doc._rev!==winningRev){return cursor["continue"]()}delete doc["_doc_id_rev"];var change=opts.processChange(doc,metadata,opts);change.seq=cursor.key;if(filter(change)){numResults++;if(returnDocs){results.push(change)}opts.onChange(change)}if(numResults!==limit){cursor["continue"]()}}}function onTxnComplete(){if(!opts.continuous){opts.complete(null,{results:results,last_seq:lastSeq})}}};api._close=function(callback){if(idb===null){return callback(errors.NOT_OPEN)}idb.close();delete cachedDBs[name];idb=null;callback()};api._getRevisionTree=function(docId,callback){var txn=idb.transaction([DOC_STORE],"readonly");var req=txn.objectStore(DOC_STORE).get(docId);req.onsuccess=function(event){var doc=decodeMetadata(event.target.result);if(!doc){callback(errors.MISSING_DOC)}else{callback(null,doc.rev_tree)}}};api._doCompaction=function(docId,revs,callback){var txn=idb.transaction([DOC_STORE,BY_SEQ_STORE,ATTACH_STORE,ATTACH_AND_SEQ_STORE],"readwrite");var docStore=txn.objectStore(DOC_STORE);var seqStore=txn.objectStore(BY_SEQ_STORE);var attStore=txn.objectStore(ATTACH_STORE);var attAndSeqStore=txn.objectStore(ATTACH_AND_SEQ_STORE);var possiblyOrphanedDigests=[];function deleteOrphanedAttachments(){if(!possiblyOrphanedDigests.length){return}possiblyOrphanedDigests.forEach(function(digest){var countReq=attAndSeqStore.index("digestSeq").count(global.IDBKeyRange.bound(digest+"::",digest+"::",false,false));countReq.onsuccess=function(e){var count=e.target.result;if(!count){attStore["delete"](digest)}}})}docStore.get(docId).onsuccess=function(event){var metadata=decodeMetadata(event.target.result);merge.traverseRevTree(metadata.rev_tree,function(isLeaf,pos,revHash,ctx,opts){var rev=pos+"-"+revHash;if(revs.indexOf(rev)!==-1){opts.status="missing"}});var count=revs.length;revs.forEach(function(rev){var index=seqStore.index("_doc_id_rev");var key=docId+"::"+rev;index.getKey(key).onsuccess=function(e){var seq=e.target.result;if(typeof seq!=="number"){return}seqStore["delete"](seq);var cursor=attAndSeqStore.index("seq").openCursor(global.IDBKeyRange.only(seq));cursor.onsuccess=function(event){var cursor=event.target.result;if(cursor){var digest=cursor.value.digestSeq.split("::")[0];possiblyOrphanedDigests.push(digest);attAndSeqStore["delete"](cursor.primaryKey);cursor["continue"]()}else{count--;if(!count){var winningRev=metadata.winningRev||merge.winningRev(metadata);var deleted=metadata.deletedOrLocal;txn.objectStore(DOC_STORE).put(encodeMetadata(metadata,winningRev,deleted));deleteOrphanedAttachments()}}}}})};txn.onerror=idbError(callback);txn.oncomplete=function(){utils.call(callback)}};api._getLocal=function(id,callback){var tx=idb.transaction([LOCAL_STORE],"readonly");var req=tx.objectStore(LOCAL_STORE).get(id);req.onerror=idbError(callback);req.onsuccess=function(e){var doc=e.target.result;if(!doc){callback(errors.MISSING_DOC)}else{delete doc["_doc_id_rev"];callback(null,doc)}}};api._putLocal=function(doc,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}delete doc._revisions;var oldRev=doc._rev;var id=doc._id;if(!oldRev){doc._rev="0-1"}else{doc._rev="0-"+(parseInt(oldRev.split("-")[1],10)+1)}doc._doc_id_rev=id+"::"+doc._rev;var tx=opts.ctx;var ret;if(!tx){tx=idb.transaction([LOCAL_STORE],"readwrite");tx.onerror=idbError(callback);tx.oncomplete=function(){if(ret){callback(null,ret)}}}var oStore=tx.objectStore(LOCAL_STORE);var req;if(oldRev){var index=oStore.index("_doc_id_rev");var docIdRev=id+"::"+oldRev;req=index.get(docIdRev);req.onsuccess=function(e){if(!e.target.result){callback(errors.REV_CONFLICT)}else{var req=oStore.put(doc);req.onsuccess=function(){ret={ok:true,id:doc._id,rev:doc._rev};if(opts.ctx){callback(null,ret)}}}}}else{req=oStore.get(id);req.onsuccess=function(e){if(e.target.result){callback(errors.REV_CONFLICT)}else{var req=oStore.put(doc);req.onsuccess=function(){ret={ok:true,id:doc._id,rev:doc._rev};if(opts.ctx){callback(null,ret)}}}}}};api._removeLocal=function(doc,callback){var tx=idb.transaction([LOCAL_STORE],"readwrite");var ret;tx.oncomplete=function(){if(ret){callback(null,ret)}};var docIdRev=doc._id+"::"+doc._rev;var oStore=tx.objectStore(LOCAL_STORE);var index=oStore.index("_doc_id_rev");var req=index.get(docIdRev);req.onerror=idbError(callback);req.onsuccess=function(e){var doc=e.target.result;if(!doc){callback(errors.MISSING_DOC)}else{var req=index.getKey(docIdRev);req.onsuccess=function(e){var key=e.target.result;oStore["delete"](key);ret={ok:true,id:doc._id,rev:"0-0"}}}}};var cached=cachedDBs[name];if(cached){idb=cached.idb;blobSupport=cached.blobSupport;instanceId=cached.instanceId;idStored=cached.idStored;process.nextTick(function(){callback(null,api)});return}var req=global.indexedDB.open(name,ADAPTER_VERSION);if(!("openReqList"in IdbPouch)){IdbPouch.openReqList={}}IdbPouch.openReqList[name]=req;req.onupgradeneeded=function(e){var db=e.target.result;if(e.oldVersion<1){createSchema(db);return}var txn=e.currentTarget.transaction;if(e.oldVersion<4){addAttachAndSeqStore(db);if(e.oldVersion<3){createLocalStoreSchema(db);if(e.oldVersion<2){addDeletedOrLocalIndex(txn,function(){migrateLocalStore(txn,function(){migrateAttsAndSeqs(txn)})})}else{migrateLocalStore(txn,function(){migrateAttsAndSeqs(txn)})}}else{migrateAttsAndSeqs(txn)}}};req.onsuccess=function(e){idb=e.target.result;idb.onversionchange=function(){idb.close();delete cachedDBs[name]};idb.onabort=function(){idb.close();delete cachedDBs[name]};var txn=idb.transaction([META_STORE,DETECT_BLOB_SUPPORT_STORE],"readwrite");var req=txn.objectStore(META_STORE).get(META_STORE);req.onsuccess=function(e){var checkSetupComplete=function(){if(blobSupport===null||!idStored){return}else{cachedDBs[name]={idb:idb,blobSupport:blobSupport,instanceId:instanceId,idStored:idStored,loaded:true};callback(null,api)}};var meta=e.target.result||{id:META_STORE};if(name+"_id"in meta){instanceId=meta[name+"_id"];idStored=true;checkSetupComplete()}else{instanceId=utils.uuid();meta[name+"_id"]=instanceId;txn.objectStore(META_STORE).put(meta).onsuccess=function(){idStored=true;checkSetupComplete()}}try{var blob=utils.createBlob([""],{type:"image/png"});txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob,"key");txn.oncomplete=function(){txn=idb.transaction([META_STORE,DETECT_BLOB_SUPPORT_STORE],"readwrite");var getBlobReq=txn.objectStore(DETECT_BLOB_SUPPORT_STORE).get("key");getBlobReq.onsuccess=function(e){var storedBlob=e.target.result;var url=URL.createObjectURL(storedBlob); | |
utils.ajax({url:url,cache:true,binary:true},function(err,res){if(err&&err.status===405){blobSupport=true}else{blobSupport=!!(res&&res.type==="image/png");if(err&&err.status===404){utils.explain404("PouchDB is just detecting blob URL support.")}}URL.revokeObjectURL(url);checkSetupComplete()})}}}catch(err){blobSupport=false;checkSetupComplete()}}};req.onerror=idbError(callback)}IdbPouch.valid=function(){var isSafari=typeof openDatabase!=="undefined"&&/Safari/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent);return!isSafari&&global.indexedDB&&global.IDBKeyRange};function destroy(name,opts,callback){if(!("openReqList"in IdbPouch)){IdbPouch.openReqList={}}IdbPouch.Changes.removeAllListeners(name);if(IdbPouch.openReqList[name]&&IdbPouch.openReqList[name].result){IdbPouch.openReqList[name].result.close()}var req=global.indexedDB.deleteDatabase(name);req.onsuccess=function(){if(IdbPouch.openReqList[name]){IdbPouch.openReqList[name]=null}if(utils.hasLocalStorage()&&name in global.localStorage){delete global.localStorage[name]}delete cachedDBs[name];callback(null,{ok:true})};req.onerror=idbError(callback)}IdbPouch.destroy=utils.toPromise(function(name,opts,callback){taskQueue.queue.push({action:function(thisCallback){destroy(name,opts,thisCallback)},callback:callback});applyNext()});IdbPouch.Changes=new utils.Changes;module.exports=IdbPouch}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../deps/errors":15,"../merge":23,"../utils":28,_process:3,vuvuzela:60}],7:[function(require,module,exports){module.exports=["idb","websql"]},{}],8:[function(require,module,exports){(function(global){"use strict";var utils=require("../utils");var merge=require("../merge");var errors=require("../deps/errors");var vuvuzela=require("vuvuzela");var parseHexString=require("../deps/parse-hex");function quote(str){return"'"+str+"'"}function escapeBlob(str){return str.replace(/\u0002/g,"").replace(/\u0001/g,"").replace(/\u0000/g,"")}function unescapeBlob(str){return str.replace(/\u0001\u0001/g,"\x00").replace(/\u0001\u0002/g,"").replace(/\u0002\u0002/g,"")}var cachedDatabases={};var openDB=utils.getArguments(function(args){if(typeof global!=="undefined"){if(global.navigator&&global.navigator.sqlitePlugin&&global.navigator.sqlitePlugin.openDatabase){return navigator.sqlitePlugin.openDatabase.apply(navigator.sqlitePlugin,args)}else if(global.sqlitePlugin&&global.sqlitePlugin.openDatabase){return global.sqlitePlugin.openDatabase.apply(global.sqlitePlugin,args)}else{var db=cachedDatabases[args[0]];if(!db){db=cachedDatabases[args[0]]=global.openDatabase.apply(global,args)}return db}}});var POUCH_VERSION=1;var ADAPTER_VERSION=6;var DOC_STORE=quote("document-store");var BY_SEQ_STORE=quote("by-sequence");var ATTACH_STORE=quote("attach-store");var LOCAL_STORE=quote("local-store");var META_STORE=quote("metadata-store");var ATTACH_AND_SEQ_STORE=quote("attach-seq-store");var BY_SEQ_STORE_DELETED_INDEX_SQL="CREATE INDEX IF NOT EXISTS 'by-seq-deleted-idx' ON "+BY_SEQ_STORE+" (seq, deleted)";var BY_SEQ_STORE_DOC_ID_REV_INDEX_SQL="CREATE UNIQUE INDEX IF NOT EXISTS 'by-seq-doc-id-rev' ON "+BY_SEQ_STORE+" (doc_id, rev)";var DOC_STORE_WINNINGSEQ_INDEX_SQL="CREATE INDEX IF NOT EXISTS 'doc-winningseq-idx' ON "+DOC_STORE+" (winningseq)";var ATTACH_AND_SEQ_STORE_SEQ_INDEX_SQL="CREATE INDEX IF NOT EXISTS 'attach-seq-seq-idx' ON "+ATTACH_AND_SEQ_STORE+" (seq)";var ATTACH_AND_SEQ_STORE_ATTACH_INDEX_SQL="CREATE UNIQUE INDEX IF NOT EXISTS 'attach-seq-digest-idx' ON "+ATTACH_AND_SEQ_STORE+" (digest, seq)";var DOC_STORE_AND_BY_SEQ_JOINER=BY_SEQ_STORE+".seq = "+DOC_STORE+".winningseq";var SELECT_DOCS=BY_SEQ_STORE+".seq AS seq, "+BY_SEQ_STORE+".deleted AS deleted, "+BY_SEQ_STORE+".json AS data, "+BY_SEQ_STORE+".rev AS rev, "+DOC_STORE+".json AS metadata";function select(selector,table,joiner,where,orderBy){return"SELECT "+selector+" FROM "+(typeof table==="string"?table:table.join(" JOIN "))+(joiner?" ON "+joiner:"")+(where?" WHERE "+(typeof where==="string"?where:where.join(" AND ")):"")+(orderBy?" ORDER BY "+orderBy:"")}function unknownError(callback){return function(event){var errorNameMatch=event&&event.constructor.toString().match(/function ([^\(]+)/);var errorName=errorNameMatch&&errorNameMatch[1]||event.type;var errorReason=event.target||event.message;callback(errors.error(errors.WSQ_ERROR,errorReason,errorName))}}function stringifyDoc(doc){delete doc._id;delete doc._rev;return JSON.stringify(doc)}function unstringifyDoc(doc,id,rev){doc=JSON.parse(doc);doc._id=id;doc._rev=rev;return doc}function getSize(opts){if("size"in opts){return opts.size*1e6}var isAndroid=/Android/.test(window.navigator.userAgent);return isAndroid?5e6:1}function WebSqlPouch(opts,callback){var api=this;var instanceId=null;var name=opts.name;var size=getSize(opts);var idRequests=[];var docCount=-1;var encoding;var db=openDB(name,POUCH_VERSION,name,size);if(!db){return callback(errors.UNKNOWN_ERROR)}else if(typeof db.readTransaction!=="function"){db.readTransaction=db.transaction}function dbCreated(){if(utils.hasLocalStorage()){global.localStorage["_pouch__websqldb_"+name]=true}callback(null,api)}function runMigration2(tx,callback){tx.executeSql(DOC_STORE_WINNINGSEQ_INDEX_SQL);tx.executeSql("ALTER TABLE "+BY_SEQ_STORE+" ADD COLUMN deleted TINYINT(1) DEFAULT 0",[],function(){tx.executeSql(BY_SEQ_STORE_DELETED_INDEX_SQL);tx.executeSql("ALTER TABLE "+DOC_STORE+" ADD COLUMN local TINYINT(1) DEFAULT 0",[],function(){tx.executeSql("CREATE INDEX IF NOT EXISTS 'doc-store-local-idx' ON "+DOC_STORE+" (local, id)");var sql="SELECT "+DOC_STORE+".winningseq AS seq, "+DOC_STORE+".json AS metadata FROM "+BY_SEQ_STORE+" JOIN "+DOC_STORE+" ON "+BY_SEQ_STORE+".seq = "+DOC_STORE+".winningseq";tx.executeSql(sql,[],function(tx,result){var deleted=[];var local=[];for(var i=0;i<result.rows.length;i++){var item=result.rows.item(i);var seq=item.seq;var metadata=JSON.parse(item.metadata);if(utils.isDeleted(metadata)){deleted.push(seq)}if(utils.isLocalId(metadata.id)){local.push(metadata.id)}}tx.executeSql("UPDATE "+DOC_STORE+"SET local = 1 WHERE id IN ("+local.map(function(){return"?"}).join(",")+")",local,function(){tx.executeSql("UPDATE "+BY_SEQ_STORE+" SET deleted = 1 WHERE seq IN ("+deleted.map(function(){return"?"}).join(",")+")",deleted,callback)})})})})}function runMigration3(tx,callback){var local="CREATE TABLE IF NOT EXISTS "+LOCAL_STORE+" (id UNIQUE, rev, json)";tx.executeSql(local,[],function(){var sql="SELECT "+DOC_STORE+".id AS id, "+BY_SEQ_STORE+".json AS data "+"FROM "+BY_SEQ_STORE+" JOIN "+DOC_STORE+" ON "+BY_SEQ_STORE+".seq = "+DOC_STORE+".winningseq WHERE local = 1";tx.executeSql(sql,[],function(tx,res){var rows=[];for(var i=0;i<res.rows.length;i++){rows.push(res.rows.item(i))}function doNext(){if(!rows.length){return callback(tx)}var row=rows.shift();var rev=JSON.parse(row.data)._rev;tx.executeSql("INSERT INTO "+LOCAL_STORE+" (id, rev, json) VALUES (?,?,?)",[row.id,rev,row.data],function(tx){tx.executeSql("DELETE FROM "+DOC_STORE+" WHERE id=?",[row.id],function(tx){tx.executeSql("DELETE FROM "+BY_SEQ_STORE+" WHERE seq=?",[row.seq],function(){doNext()})})})}doNext()})})}function runMigration4(tx,callback){function updateRows(rows){function doNext(){if(!rows.length){return callback(tx)}var row=rows.shift();var doc_id_rev=parseHexString(row.hex,encoding);var idx=doc_id_rev.lastIndexOf("::");var doc_id=doc_id_rev.substring(0,idx);var rev=doc_id_rev.substring(idx+2);var sql="UPDATE "+BY_SEQ_STORE+" SET doc_id=?, rev=? WHERE doc_id_rev=?";tx.executeSql(sql,[doc_id,rev,doc_id_rev],function(){doNext()})}doNext()}var sql="ALTER TABLE "+BY_SEQ_STORE+" ADD COLUMN doc_id";tx.executeSql(sql,[],function(tx){var sql="ALTER TABLE "+BY_SEQ_STORE+" ADD COLUMN rev";tx.executeSql(sql,[],function(tx){tx.executeSql(BY_SEQ_STORE_DOC_ID_REV_INDEX_SQL,[],function(tx){var sql="SELECT hex(doc_id_rev) as hex FROM "+BY_SEQ_STORE;tx.executeSql(sql,[],function(tx,res){var rows=[];for(var i=0;i<res.rows.length;i++){rows.push(res.rows.item(i))}updateRows(rows)})})})})}function runMigration5(tx,callback){function migrateAttsAndSeqs(tx){var sql="SELECT COUNT(*) AS cnt FROM "+ATTACH_STORE;tx.executeSql(sql,[],function(tx,res){var count=res.rows.item(0).cnt;if(!count){return callback(tx)}var offset=0;var pageSize=10;function nextPage(){var sql=select(SELECT_DOCS+", "+DOC_STORE+".id AS id",[DOC_STORE,BY_SEQ_STORE],DOC_STORE_AND_BY_SEQ_JOINER,null,DOC_STORE+".id ");sql+=" LIMIT "+pageSize+" OFFSET "+offset;offset+=pageSize;tx.executeSql(sql,[],function(tx,res){if(!res.rows.length){return callback(tx)}var digestSeqs={};function addDigestSeq(digest,seq){var seqs=digestSeqs[digest]=digestSeqs[digest]||[];if(seqs.indexOf(seq)===-1){seqs.push(seq)}}for(var i=0;i<res.rows.length;i++){var row=res.rows.item(i);var doc=unstringifyDoc(row.data,row.id,row.rev);var atts=Object.keys(doc._attachments||{});for(var j=0;j<atts.length;j++){var att=doc._attachments[atts[j]];addDigestSeq(att.digest,row.seq)}}var digestSeqPairs=[];Object.keys(digestSeqs).forEach(function(digest){var seqs=digestSeqs[digest];seqs.forEach(function(seq){digestSeqPairs.push([digest,seq])})});if(!digestSeqPairs.length){return nextPage()}var numDone=0;digestSeqPairs.forEach(function(pair){var sql="INSERT INTO "+ATTACH_AND_SEQ_STORE+" (digest, seq) VALUES (?,?)";tx.executeSql(sql,pair,function(){if(++numDone===digestSeqPairs.length){nextPage()}})})})}nextPage()})}var attachAndRev="CREATE TABLE IF NOT EXISTS "+ATTACH_AND_SEQ_STORE+" (digest, seq INTEGER)";tx.executeSql(attachAndRev,[],function(tx){tx.executeSql(ATTACH_AND_SEQ_STORE_ATTACH_INDEX_SQL,[],function(tx){tx.executeSql(ATTACH_AND_SEQ_STORE_SEQ_INDEX_SQL,[],migrateAttsAndSeqs)})})}function runMigration6(tx,callback){var sql="ALTER TABLE "+ATTACH_STORE+" ADD COLUMN escaped TINYINT(1) DEFAULT 0";tx.executeSql(sql,[],callback)}function checkEncoding(tx,cb){tx.executeSql('SELECT HEX("a") AS hex',[],function(tx,res){var hex=res.rows.item(0).hex;encoding=hex.length===2?"UTF-8":"UTF-16";cb()})}function onGetInstanceId(){while(idRequests.length>0){var idCallback=idRequests.pop();idCallback(null,instanceId)}}function onGetVersion(tx,dbVersion){if(dbVersion===0){var meta="CREATE TABLE IF NOT EXISTS "+META_STORE+" (dbid, db_version INTEGER)";var attach="CREATE TABLE IF NOT EXISTS "+ATTACH_STORE+" (digest UNIQUE, escaped TINYINT(1), body BLOB)";var attachAndRev="CREATE TABLE IF NOT EXISTS "+ATTACH_AND_SEQ_STORE+" (digest, seq INTEGER)";var doc="CREATE TABLE IF NOT EXISTS "+DOC_STORE+" (id unique, json, winningseq)";var seq="CREATE TABLE IF NOT EXISTS "+BY_SEQ_STORE+" (seq INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "+"json, deleted TINYINT(1), doc_id, rev)";var local="CREATE TABLE IF NOT EXISTS "+LOCAL_STORE+" (id UNIQUE, rev, json)";tx.executeSql(attach);tx.executeSql(local);tx.executeSql(attachAndRev,[],function(){tx.executeSql(ATTACH_AND_SEQ_STORE_SEQ_INDEX_SQL);tx.executeSql(ATTACH_AND_SEQ_STORE_ATTACH_INDEX_SQL)});tx.executeSql(doc,[],function(){tx.executeSql(DOC_STORE_WINNINGSEQ_INDEX_SQL);tx.executeSql(seq,[],function(){tx.executeSql(BY_SEQ_STORE_DELETED_INDEX_SQL);tx.executeSql(BY_SEQ_STORE_DOC_ID_REV_INDEX_SQL);tx.executeSql(meta,[],function(){var initSeq="INSERT INTO "+META_STORE+" (db_version, dbid) VALUES (?,?)";instanceId=utils.uuid();var initSeqArgs=[ADAPTER_VERSION,instanceId];tx.executeSql(initSeq,initSeqArgs,function(tx){onGetInstanceId()})})})})}else{var setupDone=function(){var migrated=dbVersion<ADAPTER_VERSION;if(migrated){tx.executeSql("UPDATE "+META_STORE+" SET db_version = "+ADAPTER_VERSION)}var sql="SELECT dbid FROM "+META_STORE;tx.executeSql(sql,[],function(tx,result){instanceId=result.rows.item(0).dbid;onGetInstanceId()})};var tasks=[runMigration2,runMigration3,runMigration4,runMigration5,runMigration6,setupDone];var i=dbVersion;var nextMigration=function(tx){tasks[i-1](tx,nextMigration);i++};nextMigration(tx)}}function setup(){db.transaction(function(tx){checkEncoding(tx,function(){fetchVersion(tx)})},unknownError(callback),dbCreated)}function fetchVersion(tx){var sql="SELECT sql FROM sqlite_master WHERE tbl_name = "+META_STORE;tx.executeSql(sql,[],function(tx,result){if(!result.rows.length){onGetVersion(tx,0)}else if(!/db_version/.test(result.rows.item(0).sql)){tx.executeSql("ALTER TABLE "+META_STORE+" ADD COLUMN db_version INTEGER",[],function(){onGetVersion(tx,1)})}else{tx.executeSql("SELECT db_version FROM "+META_STORE,[],function(tx,result){var dbVersion=result.rows.item(0).db_version;onGetVersion(tx,dbVersion)})}})}if(utils.isCordova()&&typeof global!=="undefined"){global.addEventListener(name+"_pouch",function cordova_init(){global.removeEventListener(name+"_pouch",cordova_init,false);setup()},false)}else{setup()}api.type=function(){return"websql"};api._id=utils.toPromise(function(callback){callback(null,instanceId)});api._info=function(callback){db.readTransaction(function(tx){countDocs(tx,function(docCount){var sql="SELECT MAX(seq) AS seq FROM "+BY_SEQ_STORE;tx.executeSql(sql,[],function(tx,res){var updateSeq=res.rows.item(0).seq||0;callback(null,{doc_count:docCount,update_seq:updateSeq})})})},unknownError(callback))};api._bulkDocs=function(req,opts,callback){var newEdits=opts.new_edits;var userDocs=req.docs;var docInfos=userDocs.map(function(doc,i){if(doc._id&&utils.isLocalId(doc._id)){return doc}var newDoc=utils.parseDoc(doc,newEdits);newDoc._bulk_seq=i;return newDoc});var docInfoErrors=docInfos.filter(function(docInfo){return docInfo.error});if(docInfoErrors.length){return callback(docInfoErrors[0])}var tx;var results=new Array(docInfos.length);var fetchedDocs=new utils.Map;var numDocsWritten=0;function complete(){var aresults=results.map(function(result){if(result._bulk_seq){delete result._bulk_seq}else if(!Object.keys(result).length){return{ok:true}}if(result.error){return result}var metadata=result.metadata;var rev=merge.winningRev(metadata);return{ok:true,id:metadata.id,rev:rev}});WebSqlPouch.Changes.notify(name);callback(null,aresults)}function verifyAttachment(digest,callback){var sql="SELECT count(*) as cnt FROM "+ATTACH_STORE+" WHERE digest=?";tx.executeSql(sql,[digest],function(tx,result){if(result.rows.item(0).cnt===0){var err=new Error("unknown stub attachment with digest "+digest);err.status=412;callback(err)}else{callback()}})}function verifyAttachments(finish){var digests=[];docInfos.forEach(function(docInfo){if(docInfo.data&&docInfo.data._attachments){Object.keys(docInfo.data._attachments).forEach(function(filename){var att=docInfo.data._attachments[filename];if(att.stub){digests.push(att.digest)}})}});if(!digests.length){return finish()}var numDone=0;var err;function checkDone(){if(++numDone===digests.length){finish(err)}}digests.forEach(function(digest){verifyAttachment(digest,function(attErr){if(attErr&&!err){err=attErr}checkDone()})})}function preprocessAttachment(att,finish){if(att.stub){return finish()}if(typeof att.data==="string"){try{att.data=atob(att.data)}catch(e){var err=errors.error(errors.BAD_ARG,"Attachments need to be base64 encoded");return callback(err)}var data=utils.fixBinary(att.data);att.data=utils.createBlob([data],{type:att.content_type})}utils.readAsBinaryString(att.data,function(binary){att.data=binary;utils.MD5(binary).then(function(result){att.digest="md5-"+result;att.length=binary.length;finish()})})}function preprocessAttachments(callback){if(!docInfos.length){return callback()}var docv=0;docInfos.forEach(function(docInfo){var attachments=docInfo.data&&docInfo.data._attachments?Object.keys(docInfo.data._attachments):[];var recv=0;if(!attachments.length){return done()}function processedAttachment(){recv++;if(recv===attachments.length){done()}}for(var key in docInfo.data._attachments){if(docInfo.data._attachments.hasOwnProperty(key)){preprocessAttachment(docInfo.data._attachments[key],processedAttachment)}}});function done(){docv++;if(docInfos.length===docv){callback()}}}function writeDoc(docInfo,winningRev,deleted,callback,isUpdate,resultsIdx){function finish(){var data=docInfo.data;var deletedInt=deleted?1:0;var id=data._id;var rev=data._rev;var json=stringifyDoc(data);var sql="INSERT INTO "+BY_SEQ_STORE+" (doc_id, rev, json, deleted) VALUES (?, ?, ?, ?);";var sqlArgs=[id,rev,json,deletedInt];function insertAttachmentMappings(seq,callback){var attsAdded=0;var attsToAdd=Object.keys(data._attachments||{});if(!attsToAdd.length){return callback()}function checkDone(){if(++attsAdded===attsToAdd.length){callback()}return false}function add(att){var sql="INSERT INTO "+ATTACH_AND_SEQ_STORE+" (digest, seq) VALUES (?,?)";var sqlArgs=[data._attachments[att].digest,seq];tx.executeSql(sql,sqlArgs,checkDone,checkDone)}for(var i=0;i<attsToAdd.length;i++){add(attsToAdd[i])}}tx.executeSql(sql,sqlArgs,function(tx,result){var seq=result.insertId;insertAttachmentMappings(seq,function(){dataWritten(tx,seq)})},function(){var fetchSql=select("seq",BY_SEQ_STORE,null,"doc_id=? AND rev=?");tx.executeSql(fetchSql,[id,rev],function(tx,res){var seq=res.rows.item(0).seq;var sql="UPDATE "+BY_SEQ_STORE+" SET json=?, deleted=? WHERE doc_id=? AND rev=?;";var sqlArgs=[json,deletedInt,id,rev];tx.executeSql(sql,sqlArgs,function(tx){insertAttachmentMappings(seq,function(){dataWritten(tx,seq)})})});return false})}function collectResults(attachmentErr){if(!err){if(attachmentErr){err=attachmentErr;callback(err)}else if(recv===attachments.length){finish()}}}var err=null;var recv=0;docInfo.data._id=docInfo.metadata.id;docInfo.data._rev=docInfo.metadata.rev;if(deleted){docInfo.data._deleted=true}var attachments=docInfo.data._attachments?Object.keys(docInfo.data._attachments):[];function attachmentSaved(err){recv++;collectResults(err)}for(var key in docInfo.data._attachments){if(!docInfo.data._attachments[key].stub){var data=docInfo.data._attachments[key].data;delete docInfo.data._attachments[key].data;var digest=docInfo.data._attachments[key].digest;saveAttachment(digest,data,attachmentSaved)}else{recv++;collectResults()}}if(!attachments.length){finish()}function dataWritten(tx,seq){docInfo.metadata.seq=seq;delete docInfo.metadata.rev;var sql=isUpdate?"UPDATE "+DOC_STORE+" SET json=?, winningseq=(SELECT seq FROM "+BY_SEQ_STORE+" WHERE doc_id="+DOC_STORE+".id AND rev=?) WHERE id=?":"INSERT INTO "+DOC_STORE+" (id, winningseq, json) VALUES (?, ?, ?);";var metadataStr=vuvuzela.stringify(docInfo.metadata);var id=docInfo.metadata.id;var params=isUpdate?[metadataStr,winningRev,id]:[id,seq,metadataStr];tx.executeSql(sql,params,function(){results[resultsIdx]=docInfo;fetchedDocs.set(id,docInfo.metadata);callback()})}}function updateDoc(oldDoc,docInfo,resultsIdx,callback){if(utils.revExists(oldDoc,docInfo.metadata.rev)){results[resultsIdx]=docInfo;callback();return}var merged=merge.merge(oldDoc.rev_tree,docInfo.metadata.rev_tree[0],1e3);var previouslyDeleted=utils.isDeleted(oldDoc);var deleted=utils.isDeleted(docInfo.metadata);var inConflict=previouslyDeleted&&deleted&&newEdits||!previouslyDeleted&&newEdits&&merged.conflicts!=="new_leaf"||previouslyDeleted&&!deleted&&merged.conflicts==="new_branch";if(inConflict){results[resultsIdx]=makeErr(errors.REV_CONFLICT,docInfo._bulk_seq);return callback()}docInfo.metadata.rev_tree=merged.tree;var winningRev=merge.winningRev(docInfo.metadata);deleted=utils.isDeleted(docInfo.metadata,winningRev);writeDoc(docInfo,winningRev,deleted,callback,true,resultsIdx)}function insertDoc(docInfo,resultsIdx,callback){var winningRev=merge.winningRev(docInfo.metadata);var deleted=utils.isDeleted(docInfo.metadata,winningRev);if("was_delete"in opts&&deleted){results[resultsIdx]=errors.MISSING_DOC;return callback()}writeDoc(docInfo,winningRev,deleted,callback,false,resultsIdx)}function checkDoneWritingDocs(){if(++numDocsWritten===docInfos.length){complete()}}function processDocs(){if(!docInfos.length){return complete()}var idsToDocs=new utils.Map;docInfos.forEach(function(currentDoc,resultsIdx){if(currentDoc._id&&utils.isLocalId(currentDoc._id)){api[currentDoc._deleted?"_removeLocal":"_putLocal"](currentDoc,{ctx:tx},function(err,resp){if(err){results[resultsIdx]=err}else{results[resultsIdx]={}}checkDoneWritingDocs()});return}var id=currentDoc.metadata.id;if(idsToDocs.has(id)){idsToDocs.get(id).push([currentDoc,resultsIdx])}else{idsToDocs.set(id,[[currentDoc,resultsIdx]])}});idsToDocs.forEach(function(docs,id){var numDone=0;function docWritten(){checkDoneWritingDocs();if(++numDone<docs.length){nextDoc()}}function nextDoc(){var value=docs[numDone];var currentDoc=value[0];var resultsIdx=value[1];if(fetchedDocs.has(id)){updateDoc(fetchedDocs.get(id),currentDoc,resultsIdx,docWritten)}else{insertDoc(currentDoc,resultsIdx,docWritten)}}nextDoc()})}function fetchExistingDocs(callback){if(!docInfos.length){return callback()}var numFetched=0;function checkDone(){if(++numFetched===docInfos.length){callback()}}docInfos.forEach(function(docInfo){if(docInfo._id&&utils.isLocalId(docInfo._id)){return checkDone()}var id=docInfo.metadata.id;tx.executeSql("SELECT json FROM "+DOC_STORE+" WHERE id = ?",[id],function(tx,result){if(result.rows.length){var metadata=vuvuzela.parse(result.rows.item(0).json);fetchedDocs.set(id,metadata)}checkDone()})})}function makeErr(err,seq){err._bulk_seq=seq;return err}function saveAttachment(digest,data,callback){var sql="SELECT digest FROM "+ATTACH_STORE+" WHERE digest=?";tx.executeSql(sql,[digest],function(tx,result){if(result.rows.length){return callback()}sql="INSERT INTO "+ATTACH_STORE+" (digest, body, escaped) VALUES (?,?,1)";tx.executeSql(sql,[digest,escapeBlob(data)],function(){callback()},function(){callback();return false})})}preprocessAttachments(function(){db.transaction(function(txn){tx=txn;verifyAttachments(function(err){if(err){return callback(err)}fetchExistingDocs(processDocs)})},unknownError(callback),function(){docCount=-1})})};api._get=function(id,opts,callback){opts=utils.clone(opts);var doc;var metadata;var err;if(!opts.ctx){db.readTransaction(function(txn){opts.ctx=txn;api._get(id,opts,callback)});return}var tx=opts.ctx;function finish(){callback(err,{doc:doc,metadata:metadata,ctx:tx})}var sql;var sqlArgs;if(opts.rev){sql=select(SELECT_DOCS,[DOC_STORE,BY_SEQ_STORE],DOC_STORE+".id="+BY_SEQ_STORE+".doc_id",[BY_SEQ_STORE+".doc_id=?",BY_SEQ_STORE+".rev=?"]);sqlArgs=[id,opts.rev]}else{sql=select(SELECT_DOCS,[DOC_STORE,BY_SEQ_STORE],DOC_STORE_AND_BY_SEQ_JOINER,DOC_STORE+".id=?");sqlArgs=[id]}tx.executeSql(sql,sqlArgs,function(a,results){if(!results.rows.length){err=errors.MISSING_DOC;return finish()}var item=results.rows.item(0);metadata=vuvuzela.parse(item.metadata);if(item.deleted&&!opts.rev){err=errors.error(errors.MISSING_DOC,"deleted");return finish()}doc=unstringifyDoc(item.data,metadata.id,item.rev);finish()})};function countDocs(tx,callback){if(docCount!==-1){return callback(docCount)}var sql=select("COUNT("+DOC_STORE+".id) AS 'num'",[DOC_STORE,BY_SEQ_STORE],DOC_STORE_AND_BY_SEQ_JOINER,BY_SEQ_STORE+".deleted=0");tx.executeSql(sql,[],function(tx,result){docCount=result.rows.item(0).num;callback(docCount)})}api._allDocs=function(opts,callback){var results=[];var totalRows;var start="startkey"in opts?opts.startkey:false;var end="endkey"in opts?opts.endkey:false;var key="key"in opts?opts.key:false;var descending="descending"in opts?opts.descending:false;var limit="limit"in opts?opts.limit:-1;var offset="skip"in opts?opts.skip:0;var inclusiveEnd=opts.inclusive_end!==false;var sqlArgs=[];var criteria=[];if(key!==false){criteria.push(DOC_STORE+".id = ?");sqlArgs.push(key)}else if(start!==false||end!==false){if(start!==false){criteria.push(DOC_STORE+".id "+(descending?"<=":">=")+" ?");sqlArgs.push(start)}if(end!==false){var comparator=descending?">":"<";if(inclusiveEnd){comparator+="="}criteria.push(DOC_STORE+".id "+comparator+" ?");sqlArgs.push(end)}if(key!==false){criteria.push(DOC_STORE+".id = ?");sqlArgs.push(key)}}if(opts.deleted!=="ok"){criteria.push(BY_SEQ_STORE+".deleted = 0")}db.readTransaction(function(tx){countDocs(tx,function(count){totalRows=count;if(limit===0){return}var sql=select(SELECT_DOCS,[DOC_STORE,BY_SEQ_STORE],DOC_STORE_AND_BY_SEQ_JOINER,criteria,DOC_STORE+".id "+(descending?"DESC":"ASC"));sql+=" LIMIT "+limit+" OFFSET "+offset;tx.executeSql(sql,sqlArgs,function(tx,result){for(var i=0,l=result.rows.length;i<l;i++){var item=result.rows.item(i);var metadata=vuvuzela.parse(item.metadata);var data=unstringifyDoc(item.data,metadata.id,item.rev);var winningRev=data._rev;var doc={id:metadata.id,key:metadata.id,value:{rev:winningRev}};if(opts.include_docs){doc.doc=data;doc.doc._rev=winningRev;if(opts.conflicts){doc.doc._conflicts=merge.collectConflicts(metadata)}for(var att in doc.doc._attachments){if(doc.doc._attachments.hasOwnProperty(att)){doc.doc._attachments[att].stub=true}}}if(item.deleted){if(opts.deleted==="ok"){doc.value.deleted=true;doc.doc=null}else{continue}}results.push(doc)}})})},unknownError(callback),function(){callback(null,{total_rows:totalRows,offset:opts.skip,rows:results})})};api._changes=function(opts){opts=utils.clone(opts);if(opts.continuous){var id=name+":"+utils.uuid();WebSqlPouch.Changes.addListener(name,id,api,opts);WebSqlPouch.Changes.notify(name);return{cancel:function(){WebSqlPouch.Changes.removeListener(name,id)}}}var descending=opts.descending;opts.since=opts.since&&!descending?opts.since:0;var limit="limit"in opts?opts.limit:-1;if(limit===0){limit=1}var returnDocs;if("returnDocs"in opts){returnDocs=opts.returnDocs}else{returnDocs=true}var results=[];var numResults=0;function fetchChanges(){var criteria=[DOC_STORE+".winningseq > "+opts.since];var sqlArgs=[];if(opts.doc_ids){criteria.push(DOC_STORE+".id IN ("+opts.doc_ids.map(function(){return"?"}).join(",")+")");sqlArgs=opts.doc_ids}var sql=select(SELECT_DOCS,[DOC_STORE,BY_SEQ_STORE],DOC_STORE_AND_BY_SEQ_JOINER,criteria,DOC_STORE+".winningseq "+(descending?"DESC":"ASC"));var filter=utils.filterChange(opts);if(!opts.view&&!opts.filter){sql+=" LIMIT "+limit}db.readTransaction(function(tx){tx.executeSql(sql,sqlArgs,function(tx,result){var lastSeq=0;for(var i=0,l=result.rows.length;i<l;i++){var res=result.rows.item(i);var metadata=vuvuzela.parse(res.metadata);if(lastSeq<res.seq){lastSeq=res.seq}var doc=unstringifyDoc(res.data,metadata.id,res.rev);var change=opts.processChange(doc,metadata,opts);change.seq=res.seq;if(filter(change)){numResults++;if(returnDocs){results.push(change)}opts.onChange(change)}if(numResults===limit){break}}if(!opts.continuous){opts.complete(null,{results:results,last_seq:lastSeq})}})})}fetchChanges()};api._close=function(callback){callback()};api._getAttachment=function(attachment,opts,callback){var res;var tx=opts.ctx;var digest=attachment.digest;var type=attachment.content_type;var sql="SELECT escaped, "+"CASE WHEN escaped = 1 THEN body ELSE HEX(body) END AS body FROM "+ATTACH_STORE+" WHERE digest=?";tx.executeSql(sql,[digest],function(tx,result){var item=result.rows.item(0);var data=item.escaped?unescapeBlob(item.body):parseHexString(item.body,encoding);if(opts.encode){res=btoa(data)}else{data=utils.fixBinary(data);res=utils.createBlob([data],{type:type})}callback(null,res)})};api._getRevisionTree=function(docId,callback){db.readTransaction(function(tx){var sql="SELECT json AS metadata FROM "+DOC_STORE+" WHERE id = ?";tx.executeSql(sql,[docId],function(tx,result){if(!result.rows.length){callback(errors.MISSING_DOC)}else{var data=vuvuzela.parse(result.rows.item(0).metadata);callback(null,data.rev_tree)}})})};api._doCompaction=function(docId,revs,callback){if(!revs.length){return callback()}db.transaction(function(tx){var sql="SELECT json AS metadata FROM "+DOC_STORE+" WHERE id = ?";tx.executeSql(sql,[docId],function(tx,result){var metadata=vuvuzela.parse(result.rows.item(0).metadata);merge.traverseRevTree(metadata.rev_tree,function(isLeaf,pos,revHash,ctx,opts){var rev=pos+"-"+revHash;if(revs.indexOf(rev)!==-1){opts.status="missing"}});var sql="UPDATE "+DOC_STORE+" SET json = ? WHERE id = ?";tx.executeSql(sql,[vuvuzela.stringify(metadata),docId])});revs.forEach(function(rev){var sql="SELECT seq FROM "+BY_SEQ_STORE+" WHERE doc_id=? AND rev=?";tx.executeSql(sql,[docId,rev],function(tx,res){if(!res.rows.length){return}var seq=res.rows.item(0).seq;var sql="SELECT a1.digest AS digest "+"FROM "+ATTACH_AND_SEQ_STORE+" a1 JOIN "+ATTACH_AND_SEQ_STORE+" a2 ON a1.digest=a2.digest "+"WHERE a1.seq=? "+"GROUP BY a1.digest HAVING COUNT(*) = 1";tx.executeSql(sql,[seq],function(tx,res){var orphanedAttachments=[];for(var i=0;i<res.rows.length;i++){orphanedAttachments.push(res.rows.item(i).digest)}tx.executeSql("DELETE FROM "+BY_SEQ_STORE+" WHERE seq=?",[seq]);tx.executeSql("DELETE FROM "+ATTACH_AND_SEQ_STORE+" WHERE seq=?",[seq]);orphanedAttachments.forEach(function(digest){tx.executeSql("DELETE FROM "+ATTACH_AND_SEQ_STORE+" WHERE digest=?",[digest]);tx.executeSql("DELETE FROM "+ATTACH_STORE+" WHERE digest=?",[digest])})})})})},unknownError(callback),function(){callback()})};api._getLocal=function(id,callback){db.readTransaction(function(tx){var sql="SELECT json, rev FROM "+LOCAL_STORE+" WHERE id=?";tx.executeSql(sql,[id],function(tx,res){if(res.rows.length){var item=res.rows.item(0);var doc=unstringifyDoc(item.json,id,item.rev);callback(null,doc)}else{callback(errors.MISSING_DOC)}})})};api._putLocal=function(doc,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}delete doc._revisions;var oldRev=doc._rev;var id=doc._id;var newRev;if(!oldRev){newRev=doc._rev="0-1"}else{newRev=doc._rev="0-"+(parseInt(oldRev.split("-")[1],10)+1)}var json=stringifyDoc(doc);var ret;function putLocal(tx){var sql;var values;if(oldRev){sql="UPDATE "+LOCAL_STORE+" SET rev=?, json=? "+"WHERE id=? AND rev=?";values=[newRev,json,id,oldRev]}else{sql="INSERT INTO "+LOCAL_STORE+" (id, rev, json) VALUES (?,?,?)";values=[id,newRev,json]}tx.executeSql(sql,values,function(tx,res){if(res.rowsAffected){ret={ok:true,id:id,rev:newRev};if(opts.ctx){callback(null,ret)}}else{callback(errors.REV_CONFLICT)}},function(){callback(errors.REV_CONFLICT);return false})}if(opts.ctx){putLocal(opts.ctx)}else{db.transaction(function(tx){putLocal(tx)},unknownError(callback),function(){if(ret){callback(null,ret)}})}};api._removeLocal=function(doc,callback){var ret;db.transaction(function(tx){var sql="DELETE FROM "+LOCAL_STORE+" WHERE id=? AND rev=?";var params=[doc._id,doc._rev];tx.executeSql(sql,params,function(tx,res){if(!res.rowsAffected){return callback(errors.REV_CONFLICT)}ret={ok:true,id:doc._id,rev:"0-0"}})},unknownError(callback),function(){callback(null,ret)})}}WebSqlPouch.valid=function(){if(typeof global!=="undefined"){if(global.navigator&&global.navigator.sqlitePlugin&&global.navigator.sqlitePlugin.openDatabase){return true}else if(global.sqlitePlugin&&global.sqlitePlugin.openDatabase){return true}else if(global.openDatabase){return true}}return false};WebSqlPouch.destroy=utils.toPromise(function(name,opts,callback){WebSqlPouch.Changes.removeAllListeners(name);var size=getSize(opts);var db=openDB(name,POUCH_VERSION,name,size);db.transaction(function(tx){var stores=[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE,META_STORE,LOCAL_STORE,ATTACH_AND_SEQ_STORE];stores.forEach(function(store){tx.executeSql("DROP TABLE IF EXISTS "+store,[])})},unknownError(callback),function(){if(utils.hasLocalStorage()){delete global.localStorage["_pouch__websqldb_"+name];delete global.localStorage[name]}callback(null,{ok:true})})});WebSqlPouch.Changes=new utils.Changes;module.exports=WebSqlPouch}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../deps/errors":15,"../deps/parse-hex":17,"../merge":23,"../utils":28,vuvuzela:60}],9:[function(require,module,exports){"use strict";var utils=require("./utils");var merge=require("./merge");var errors=require("./deps/errors");var EE=require("events").EventEmitter;var evalFilter=require("./evalFilter");var evalView=require("./evalView");module.exports=Changes;utils.inherits(Changes,EE);function Changes(db,opts,callback){EE.call(this);var self=this;this.db=db;opts=opts?utils.clone(opts):{}; | |
var oldComplete=callback||opts.complete||function(){};var complete=opts.complete=utils.once(function(err,resp){if(err){self.emit("error",err)}else{self.emit("complete",resp)}self.removeAllListeners();db.removeListener("destroyed",onDestroy)});if(oldComplete){self.on("complete",function(resp){oldComplete(null,resp)});self.on("error",function(err){oldComplete(err)})}var oldOnChange=opts.onChange;if(oldOnChange){self.on("change",oldOnChange)}function onDestroy(){self.cancel()}db.once("destroyed",onDestroy);opts.onChange=function(change){if(opts.isCancelled){return}self.emit("change",change);if(self.startSeq&&self.startSeq<=change.seq){self.emit("uptodate");self.startSeq=false}if(change.deleted){self.emit("delete",change)}else if(change.changes.length===1&&change.changes[0].rev.slice(0,2)==="1-"){self.emit("create",change)}else{self.emit("update",change)}};var promise=new utils.Promise(function(fulfill,reject){opts.complete=function(err,res){if(err){reject(err)}else{fulfill(res)}}});self.once("cancel",function(){if(oldOnChange){self.removeListener("change",oldOnChange)}opts.complete(null,{status:"cancelled"})});this.then=promise.then.bind(promise);this["catch"]=promise["catch"].bind(promise);this.then(function(result){complete(null,result)},complete);if(!db.taskqueue.isReady){db.taskqueue.addTask(function(){if(self.isCancelled){self.emit("cancel")}else{self.doChanges(opts)}})}else{self.doChanges(opts)}}Changes.prototype.cancel=function(){this.isCancelled=true;if(this.db.taskqueue.isReady){this.emit("cancel")}};function processChange(doc,metadata,opts){var changeList=[{rev:doc._rev}];if(opts.style==="all_docs"){changeList=merge.collectLeaves(metadata.rev_tree).map(function(x){return{rev:x.rev}})}var change={id:metadata.id,changes:changeList,doc:doc};if(utils.isDeleted(metadata,doc._rev)){change.deleted=true}if(opts.conflicts){change.doc._conflicts=merge.collectConflicts(metadata);if(!change.doc._conflicts.length){delete change.doc._conflicts}}return change}Changes.prototype.doChanges=function(opts){var self=this;var callback=opts.complete;opts=utils.clone(opts);if("live"in opts&&!("continuous"in opts)){opts.continuous=opts.live}opts.processChange=processChange;if(opts.since==="latest"){opts.since="now"}if(!opts.since){opts.since=0}if(opts.since==="now"){this.db.info().then(function(info){if(self.isCancelled){callback(null,{status:"cancelled"});return}opts.since=info.update_seq-1;self.doChanges(opts)},callback);return}if(opts.continuous&&opts.since!=="now"){this.db.info().then(function(info){self.startSeq=info.update_seq-1},function(err){if(err.id==="idbNull"){return}throw err})}if(this.db.type()!=="http"&&opts.filter&&typeof opts.filter==="string"){return this.filterChanges(opts)}if(!("descending"in opts)){opts.descending=false}opts.limit=opts.limit===0?1:opts.limit;opts.complete=callback;var newPromise=this.db._changes(opts);if(newPromise&&typeof newPromise.cancel==="function"){var cancel=self.cancel;self.cancel=utils.getArguments(function(args){newPromise.cancel();cancel.apply(this,args)})}};Changes.prototype.filterChanges=function(opts){var self=this;var callback=opts.complete;if(opts.filter==="_view"){if(!opts.view||typeof opts.view!=="string"){var err=new Error("`view` filter parameter is not provided.");err.status=errors.BAD_REQUEST.status;err.name=errors.BAD_REQUEST.name;err.error=true;callback(err);return}var viewName=opts.view.split("/");this.db.get("_design/"+viewName[0],function(err,ddoc){if(self.isCancelled){callback(null,{status:"cancelled"});return}if(err){callback(err);return}if(ddoc&&ddoc.views&&ddoc.views[viewName[1]]){var filter=evalView(ddoc.views[viewName[1]].map);opts.filter=filter;self.doChanges(opts);return}var msg=ddoc.views?"missing json key: "+viewName[1]:"missing json key: views";if(!err){err=new Error(msg);err.status=errors.MISSING_DOC.status;err.name=errors.MISSING_DOC.name;err.error=true}callback(err);return})}else{var filterName=opts.filter.split("/");this.db.get("_design/"+filterName[0],function(err,ddoc){if(self.isCancelled){callback(null,{status:"cancelled"});return}if(err){callback(err);return}if(ddoc&&ddoc.filters&&ddoc.filters[filterName[1]]){var filter=evalFilter(ddoc.filters[filterName[1]]);opts.filter=filter;self.doChanges(opts);return}else{var msg=ddoc&&ddoc.filters?"missing json key: "+filterName[1]:"missing json key: filters";if(!err){err=new Error(msg);err.status=errors.MISSING_DOC.status;err.name=errors.MISSING_DOC.name;err.error=true}callback(err);return}})}}},{"./deps/errors":15,"./evalFilter":21,"./evalView":22,"./merge":23,"./utils":28,events:2}],10:[function(require,module,exports){"use strict";var utils=require("./utils");function updateCheckpoint(db,id,checkpoint,returnValue){return db.get(id)["catch"](function(err){if(err.status===404){if(db.type()==="http"){utils.explain404("PouchDB is just checking if a remote checkpoint exists.")}return{_id:id}}throw err}).then(function(doc){if(returnValue.cancelled){return}doc.last_seq=checkpoint;return db.put(doc)})}function Checkpointer(src,target,id,returnValue){this.src=src;this.target=target;this.id=id;this.returnValue=returnValue}Checkpointer.prototype.writeCheckpoint=function(checkpoint){var self=this;return this.updateTarget(checkpoint).then(function(){return self.updateSource(checkpoint)})};Checkpointer.prototype.updateTarget=function(checkpoint){return updateCheckpoint(this.target,this.id,checkpoint,this.returnValue)};Checkpointer.prototype.updateSource=function(checkpoint){var self=this;if(this.readOnlySource){return utils.Promise.resolve(true)}return updateCheckpoint(this.src,this.id,checkpoint,this.returnValue)["catch"](function(err){var isForbidden=typeof err.status==="number"&&Math.floor(err.status/100)===4;if(isForbidden){self.readOnlySource=true;return true}throw err})};Checkpointer.prototype.getCheckpoint=function(){var self=this;return self.target.get(self.id).then(function(targetDoc){return self.src.get(self.id).then(function(sourceDoc){if(targetDoc.last_seq===sourceDoc.last_seq){return sourceDoc.last_seq}return 0},function(err){if(err.status===404&&targetDoc.last_seq){return self.src.put({_id:self.id,last_seq:0}).then(function(){return 0},function(err){if(err.status===401){self.readOnlySource=true;return targetDoc.last_seq}return 0})}throw err})})["catch"](function(err){if(err.status!==404){throw err}return 0})};module.exports=Checkpointer},{"./utils":28}],11:[function(require,module,exports){(function(global){"use strict";var Adapter=require("./adapter");var utils=require("./utils");var TaskQueue=require("./taskqueue");var Promise=utils.Promise;function defaultCallback(err){if(err&&global.debug){console.error(err)}}utils.inherits(PouchDB,Adapter);function PouchDB(name,opts,callback){if(!(this instanceof PouchDB)){return new PouchDB(name,opts,callback)}var self=this;if(typeof opts==="function"||typeof opts==="undefined"){callback=opts;opts={}}if(name&&typeof name==="object"){opts=name;name=undefined}if(typeof callback==="undefined"){callback=defaultCallback}opts=opts||{};this.__opts=opts;var oldCB=callback;self.auto_compaction=opts.auto_compaction;self.prefix=PouchDB.prefix;Adapter.call(self);self.taskqueue=new TaskQueue;var promise=new Promise(function(fulfill,reject){callback=function(err,resp){if(err){return reject(err)}delete resp.then;fulfill(resp)};opts=utils.clone(opts);var originalName=opts.name||name;var backend,error;(function(){try{if(typeof originalName!=="string"){error=new Error("Missing/invalid DB name");error.code=400;throw error}backend=PouchDB.parseAdapter(originalName,opts);opts.originalName=originalName;opts.name=backend.name;if(opts.prefix&&backend.adapter!=="http"&&backend.adapter!=="https"){opts.name=opts.prefix+opts.name}opts.adapter=opts.adapter||backend.adapter;self._adapter=opts.adapter;self._db_name=originalName;if(!PouchDB.adapters[opts.adapter]){error=new Error("Adapter is missing");error.code=404;throw error}if(!PouchDB.adapters[opts.adapter].valid()){error=new Error("Invalid Adapter");error.code=404;throw error}}catch(err){self.taskqueue.fail(err);self.changes=utils.toPromise(function(opts){if(opts.complete){opts.complete(err)}})}})();if(error){return reject(error)}self.adapter=opts.adapter;self.replicate={};self.replicate.from=function(url,opts,callback){return self.constructor.replicate(url,self,opts,callback)};self.replicate.to=function(url,opts,callback){return self.constructor.replicate(self,url,opts,callback)};self.sync=function(dbName,opts,callback){return self.constructor.sync(self,dbName,opts,callback)};self.replicate.sync=self.sync;self.destroy=utils.adapterFun("destroy",function(callback){var self=this;self.info(function(err,info){if(err){return callback(err)}self.constructor.destroy(info.db_name,callback)})});PouchDB.adapters[opts.adapter].call(self,opts,function(err,db){if(err){if(callback){self.taskqueue.fail(err);callback(err)}return}function destructionListener(event){if(event==="destroyed"){self.emit("destroyed");PouchDB.removeListener(originalName,destructionListener)}}PouchDB.on(originalName,destructionListener);self.emit("created",self);PouchDB.emit("created",opts.originalName);self.taskqueue.ready(self);callback(null,self)});if(opts.skipSetup){self.taskqueue.ready(self)}if(utils.isCordova()){cordova.fireWindowEvent(opts.name+"_pouch",{})}});promise.then(function(resp){oldCB(null,resp)},oldCB);self.then=promise.then.bind(promise);self["catch"]=promise["catch"].bind(promise)}module.exports=PouchDB}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./adapter":4,"./taskqueue":27,"./utils":28}],12:[function(require,module,exports){"use strict";var createBlob=require("./blob.js");var errors=require("./errors");var utils=require("../utils");var hasUpload;function ajax(options,adapterCallback){var requestCompleted=false;var callback=utils.getArguments(function(args){if(requestCompleted){return}adapterCallback.apply(this,args);requestCompleted=true});if(typeof options==="function"){callback=options;options={}}options=utils.clone(options);var defaultOptions={method:"GET",headers:{},json:true,processData:true,timeout:1e4,cache:false};options=utils.extend(true,defaultOptions,options);if(options.method==="GET"&&!options.cache){var hasArgs=options.url.indexOf("?")!==-1;options.url+=(hasArgs?"&":"?")+"_nonce="+utils.uuid(16)}function onSuccess(obj,resp,cb){if(!options.binary&&!options.json&&options.processData&&typeof obj!=="string"){obj=JSON.stringify(obj)}else if(!options.binary&&options.json&&typeof obj==="string"){try{obj=JSON.parse(obj)}catch(e){return cb(e)}}if(Array.isArray(obj)){obj=obj.map(function(v){var obj;if(v.ok){return v}else if(v.error&&v.error==="conflict"){obj=errors.REV_CONFLICT;obj.id=v.id;return obj}else if(v.error&&v.error==="forbidden"){obj=errors.FORBIDDEN;obj.id=v.id;obj.reason=v.reason;return obj}else if(v.missing){obj=errors.MISSING_DOC;obj.missing=v.missing;return obj}else{return v}})}cb(null,obj,resp)}function onError(err,cb){var errParsed,errObj,errType,key;try{errParsed=JSON.parse(err.responseText);for(key in errors){if(errors.hasOwnProperty(key)&&errors[key].name===errParsed.error){errType=errors[key];break}}if(!errType){errType=errors.UNKNOWN_ERROR;if(err.status){errType.status=err.status}if(err.statusText){err.name=err.statusText}}errObj=errors.error(errType,errParsed.reason)}catch(e){for(var key in errors){if(errors.hasOwnProperty(key)&&errors[key].status===err.status){errType=errors[key];break}}if(!errType){errType=errors.UNKNOWN_ERROR;if(err.status){errType.status=err.status}if(err.statusText){err.name=err.statusText}}errObj=errors.error(errType)}if(err.withCredentials&&err.status===0){errObj.status=405;errObj.statusText="Method Not Allowed"}cb(errObj)}var timer;var xhr;if(options.xhr){xhr=new options.xhr}else{xhr=new XMLHttpRequest}xhr.open(options.method,options.url);xhr.withCredentials=true;if(options.json){options.headers.Accept="application/json";options.headers["Content-Type"]=options.headers["Content-Type"]||"application/json";if(options.body&&options.processData&&typeof options.body!=="string"){options.body=JSON.stringify(options.body)}}if(options.binary){xhr.responseType="arraybuffer"}var createCookie=function(name,value,days){var expires="";if(days){var date=new Date;date.setTime(date.getTime()+days*24*60*60*1e3);expires="; expires="+date.toGMTString()}document.cookie=name+"="+value+expires+"; path=/"};for(var key in options.headers){if(key==="Cookie"){var cookie=options.headers[key].split("=");createCookie(cookie[0],cookie[1],10)}else{xhr.setRequestHeader(key,options.headers[key])}}if(!("body"in options)){options.body=null}var abortReq=function(){if(requestCompleted){return}xhr.abort();onError(xhr,callback)};xhr.onreadystatechange=function(){if(xhr.readyState!==4||requestCompleted){return}clearTimeout(timer);if(xhr.status>=200&&xhr.status<300){var data;if(options.binary){data=createBlob([xhr.response||""],{type:xhr.getResponseHeader("Content-Type")})}else{data=xhr.responseText}onSuccess(data,xhr,callback)}else{onError(xhr,callback)}};if(options.timeout>0){timer=setTimeout(abortReq,options.timeout);xhr.onprogress=function(){clearTimeout(timer);timer=setTimeout(abortReq,options.timeout)};if(typeof hasUpload==="undefined"){hasUpload=Object.keys(xhr).indexOf("upload")!==-1}if(hasUpload){xhr.upload.onprogress=xhr.onprogress}}if(options.body&&options.body instanceof Blob){utils.readAsBinaryString(options.body,function(binary){xhr.send(utils.fixBinary(binary))})}else{xhr.send(options.body)}return{abort:abortReq}}module.exports=ajax},{"../utils":28,"./blob.js":13,"./errors":15}],13:[function(require,module,exports){(function(global){"use strict";function createBlob(parts,properties){parts=parts||[];properties=properties||{};try{return new Blob(parts,properties)}catch(e){if(e.name!=="TypeError"){throw e}var BlobBuilder=global.BlobBuilder||global.MSBlobBuilder||global.MozBlobBuilder||global.WebKitBlobBuilder;var builder=new BlobBuilder;for(var i=0;i<parts.length;i+=1){builder.append(parts[i])}return builder.getBlob(properties.type)}}module.exports=createBlob}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],14:[function(require,module,exports){"use strict";exports.Map=LazyMap;exports.Set=LazySet;function LazyMap(){this.store={}}LazyMap.prototype.mangle=function(key){if(typeof key!=="string"){throw new TypeError("key must be a string but Got "+key)}return"$"+key};LazyMap.prototype.unmangle=function(key){return key.substring(1)};LazyMap.prototype.get=function(key){var mangled=this.mangle(key);if(mangled in this.store){return this.store[mangled]}else{return void 0}};LazyMap.prototype.set=function(key,value){var mangled=this.mangle(key);this.store[mangled]=value;return true};LazyMap.prototype.has=function(key){var mangled=this.mangle(key);return mangled in this.store};LazyMap.prototype["delete"]=function(key){var mangled=this.mangle(key);if(mangled in this.store){delete this.store[mangled];return true}return false};LazyMap.prototype.forEach=function(cb){var self=this;var keys=Object.keys(self.store);keys.forEach(function(key){var value=self.store[key];key=self.unmangle(key);cb(value,key)})};function LazySet(){this.store=new LazyMap}LazySet.prototype.add=function(key){return this.store.set(key,true)};LazySet.prototype.has=function(key){return this.store.has(key)};LazySet.prototype["delete"]=function(key){return this.store["delete"](key)}},{}],15:[function(require,module,exports){"use strict";function PouchError(opts){this.status=opts.status;this.name=opts.error;this.message=opts.reason;this.error=true}PouchError.prototype__proto__=Error.prototype;PouchError.prototype.toString=function(){return JSON.stringify({status:this.status,name:this.name,message:this.message})};exports.UNAUTHORIZED=new PouchError({status:401,error:"unauthorized",reason:"Name or password is incorrect."});exports.MISSING_BULK_DOCS=new PouchError({status:400,error:"bad_request",reason:"Missing JSON list of 'docs'"});exports.MISSING_DOC=new PouchError({status:404,error:"not_found",reason:"missing"});exports.REV_CONFLICT=new PouchError({status:409,error:"conflict",reason:"Document update conflict"});exports.INVALID_ID=new PouchError({status:400,error:"invalid_id",reason:"_id field must contain a string"});exports.MISSING_ID=new PouchError({status:412,error:"missing_id",reason:"_id is required for puts"});exports.RESERVED_ID=new PouchError({status:400,error:"bad_request",reason:"Only reserved document ids may start with underscore."});exports.NOT_OPEN=new PouchError({status:412,error:"precondition_failed",reason:"Database not open"});exports.UNKNOWN_ERROR=new PouchError({status:500,error:"unknown_error",reason:"Database encountered an unknown error"});exports.BAD_ARG=new PouchError({status:500,error:"badarg",reason:"Some query argument is invalid"});exports.INVALID_REQUEST=new PouchError({status:400,error:"invalid_request",reason:"Request was invalid"});exports.QUERY_PARSE_ERROR=new PouchError({status:400,error:"query_parse_error",reason:"Some query parameter is invalid"});exports.DOC_VALIDATION=new PouchError({status:500,error:"doc_validation",reason:"Bad special document member"});exports.BAD_REQUEST=new PouchError({status:400,error:"bad_request",reason:"Something wrong with the request"});exports.NOT_AN_OBJECT=new PouchError({status:400,error:"bad_request",reason:"Document must be a JSON object"});exports.DB_MISSING=new PouchError({status:404,error:"not_found",reason:"Database not found"});exports.IDB_ERROR=new PouchError({status:500,error:"indexed_db_went_bad",reason:"unknown"});exports.WSQ_ERROR=new PouchError({status:500,error:"web_sql_went_bad",reason:"unknown"});exports.LDB_ERROR=new PouchError({status:500,error:"levelDB_went_went_bad",reason:"unknown"});exports.FORBIDDEN=new PouchError({status:403,error:"forbidden",reason:"Forbidden by design doc validate_doc_update function"});exports.error=function(error,reason,name){function CustomPouchError(msg){this.message=reason;if(name){this.name=name}}CustomPouchError.prototype=error;return new CustomPouchError(reason)}},{}],16:[function(require,module,exports){(function(process,global){"use strict";var crypto=require("crypto");var Md5=require("spark-md5");var setImmediateShim=global.setImmediate||global.setTimeout;var MD5_CHUNK_SIZE=32768;function sliceShim(arrayBuffer,begin,end){if(typeof arrayBuffer.slice==="function"){if(!begin){return arrayBuffer.slice()}else if(!end){return arrayBuffer.slice(begin)}else{return arrayBuffer.slice(begin,end)}}begin=Math.floor(begin||0);end=Math.floor(end||0);var len=arrayBuffer.byteLength;begin=begin<0?Math.max(begin+len,0):Math.min(len,begin);end=end<0?Math.max(end+len,0):Math.min(len,end);if(end-begin<=0){return new ArrayBuffer(0)}var result=new ArrayBuffer(end-begin);var resultBytes=new Uint8Array(result);var sourceBytes=new Uint8Array(arrayBuffer,begin,end-begin);resultBytes.set(sourceBytes);return result}function intToString(int){var bytes=[int&255,int>>>8&255,int>>>16&255,int>>>24&255];return bytes.map(function(byte){return String.fromCharCode(byte)}).join("")}function rawToBase64(raw){var res="";for(var i=0;i<raw.length;i++){res+=intToString(raw[i])}return global.btoa(res)}module.exports=function(data,callback){if(!process.browser){var base64=crypto.createHash("md5").update(data).digest("base64");callback(null,base64);return}var inputIsString=typeof data==="string";var len=inputIsString?data.length:data.byteLength;var chunkSize=Math.min(MD5_CHUNK_SIZE,len);var chunks=Math.ceil(len/chunkSize);var currentChunk=0;var buffer=inputIsString?new Md5:new Md5.ArrayBuffer;function append(buffer,data,start,end){if(inputIsString){buffer.appendBinary(data.substring(start,end))}else{buffer.append(sliceShim(data,start,end))}}function loadNextChunk(){var start=currentChunk*chunkSize;var end=start+chunkSize;if(start+chunkSize>=data.size){end=data.size}currentChunk++;if(currentChunk<chunks){append(buffer,data,start,end);setImmediateShim(loadNextChunk)}else{append(buffer,data,start,end);var raw=buffer.end(true);var base64=rawToBase64(raw);callback(null,base64);buffer.destroy()}}loadNextChunk()}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{_process:3,crypto:1,"spark-md5":59}],17:[function(require,module,exports){"use strict";function decodeUtf8(str){return decodeURIComponent(window.escape(str))}function hexToInt(charCode){return charCode<65?charCode-48:charCode-55}function parseHexUtf8(str,start,end){var result="";while(start<end){result+=String.fromCharCode(hexToInt(str.charCodeAt(start++))<<4|hexToInt(str.charCodeAt(start++)))}return result}function parseHexUtf16(str,start,end){var result="";while(start<end){result+=String.fromCharCode(hexToInt(str.charCodeAt(start+2))<<12|hexToInt(str.charCodeAt(start+3))<<8|hexToInt(str.charCodeAt(start))<<4|hexToInt(str.charCodeAt(start+1)));start+=4}return result}function parseHexString(str,encoding){if(encoding==="UTF-8"){return decodeUtf8(parseHexUtf8(str,0,str.length))}else{return parseHexUtf16(str,0,str.length)}}module.exports=parseHexString},{}],18:[function(require,module,exports){"use strict";var options={strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};function parseUri(str){var o=options;var m=o.parser[o.strictMode?"strict":"loose"].exec(str);var uri={};var i=14;while(i--){var key=o.key[i];var value=m[i]||"";var encoded=["user","password"].indexOf(key)!==-1;uri[key]=encoded?decodeURIComponent(value):value}uri[o.q.name]={};uri[o.key[12]].replace(o.q.parser,function($0,$1,$2){if($1){uri[o.q.name][$1]=$2}});return uri}module.exports=parseUri},{}],19:[function(require,module,exports){"use strict";var Promise=require("../utils").Promise;function upsert(db,docId,diffFun){return new Promise(function(fulfill,reject){if(docId&&typeof docId==="object"){docId=docId._id}if(typeof docId!=="string"){return reject(new Error("doc id is required"))}db.get(docId,function(err,doc){if(err){if(err.status!==404){return reject(err)}return fulfill(tryAndPut(db,diffFun({_id:docId}),diffFun))}var newDoc=diffFun(doc);if(!newDoc){return fulfill(doc)}fulfill(tryAndPut(db,newDoc,diffFun))})})}function tryAndPut(db,doc,diffFun){return db.put(doc)["catch"](function(err){if(err.status!==409){throw err}return upsert(db,doc,diffFun)})}module.exports=function(db,docId,diffFun,cb){if(typeof cb==="function"){upsert(db,docId,diffFun).then(function(resp){cb(null,resp)},cb)}else{return upsert(db,docId,diffFun)}}},{"../utils":28}],20:[function(require,module,exports){"use strict";var chars=("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"+"abcdefghijklmnopqrstuvwxyz").split("");function getValue(radix){return 0|Math.random()*radix}function uuid(len,radix){radix=radix||chars.length;var out="";var i=-1;if(len){while(++i<len){out+=chars[getValue(radix)]}return out}while(++i<36){switch(i){case 8:case 13:case 18:case 23:out+="-";break;case 19:out+=chars[getValue(16)&3|8];break;default:out+=chars[getValue(16)]}}return out}module.exports=uuid},{}],21:[function(require,module,exports){"use strict";module.exports=evalFilter;function evalFilter(input){return eval(["(function () { return ",input," })()"].join(""))}},{}],22:[function(require,module,exports){"use strict";module.exports=evalView;function evalView(input){return eval(["(function () {"," return function (doc) {"," var emitted = false;"," var emit = function (a, b) {"," emitted = true;"," };"," var view = "+input+";"," view(doc);"," if (emitted) {"," return true;"," }"," }","})()"].join("\n"))}},{}],23:[function(require,module,exports){"use strict";var extend=require("pouchdb-extend");function pathToTree(path){var doc=path.shift();var root=[doc.id,doc.opts,[]];var leaf=root;var nleaf;while(path.length){doc=path.shift();nleaf=[doc.id,doc.opts,[]];leaf[2].push(nleaf);leaf=nleaf}return root}function mergeTree(in_tree1,in_tree2){var queue=[{tree1:in_tree1,tree2:in_tree2}];var conflicts=false;while(queue.length>0){var item=queue.pop();var tree1=item.tree1;var tree2=item.tree2;if(tree1[1].status||tree2[1].status){tree1[1].status=tree1[1].status==="available"||tree2[1].status==="available"?"available":"missing"}for(var i=0;i<tree2[2].length;i++){if(!tree1[2][0]){conflicts="new_leaf";tree1[2][0]=tree2[2][i];continue}var merged=false;for(var j=0;j<tree1[2].length;j++){if(tree1[2][j][0]===tree2[2][i][0]){queue.push({tree1:tree1[2][j],tree2:tree2[2][i]});merged=true}}if(!merged){conflicts="new_branch";tree1[2].push(tree2[2][i]);tree1[2].sort()}}}return{conflicts:conflicts,tree:in_tree1}}function doMerge(tree,path,dontExpand){var restree=[];var conflicts=false;var merged=false;var res;if(!tree.length){return{tree:[path],conflicts:"new_leaf"}}tree.forEach(function(branch){if(branch.pos===path.pos&&branch.ids[0]===path.ids[0]){res=mergeTree(branch.ids,path.ids);restree.push({pos:branch.pos,ids:res.tree});conflicts=conflicts||res.conflicts;merged=true}else if(dontExpand!==true){var t1=branch.pos<path.pos?branch:path;var t2=branch.pos<path.pos?path:branch;var diff=t2.pos-t1.pos;var candidateParents=[];var trees=[];trees.push({ids:t1.ids,diff:diff,parent:null,parentIdx:null});while(trees.length>0){var item=trees.pop();if(item.diff===0){if(item.ids[0]===t2.ids[0]){candidateParents.push(item)}continue}if(!item.ids){continue}item.ids[2].forEach(function(el,idx){trees.push({ids:el,diff:item.diff-1,parent:item.ids,parentIdx:idx})})}var el=candidateParents[0];if(!el){restree.push(branch)}else{res=mergeTree(el.ids,t2.ids);el.parent[2][el.parentIdx]=res.tree;restree.push({pos:t1.pos,ids:t1.ids});conflicts=conflicts||res.conflicts;merged=true}}else{restree.push(branch)}});if(!merged){restree.push(path)}restree.sort(function(a,b){return a.pos-b.pos});return{tree:restree,conflicts:conflicts||"internal_node"}}function stem(tree,depth){var stemmedPaths=PouchMerge.rootToLeaf(tree).map(function(path){var stemmed=path.ids.slice(-depth);return{pos:path.pos+(path.ids.length-stemmed.length),ids:pathToTree(stemmed)}});return stemmedPaths.reduce(function(prev,current,i,arr){return doMerge(prev,current,true).tree},[stemmedPaths.shift()])}var PouchMerge={};PouchMerge.merge=function(tree,path,depth){tree=extend(true,[],tree);path=extend(true,{},path);var newTree=doMerge(tree,path);return{tree:stem(newTree.tree,depth),conflicts:newTree.conflicts}};PouchMerge.winningRev=function(metadata){var leafs=[];PouchMerge.traverseRevTree(metadata.rev_tree,function(isLeaf,pos,id,something,opts){if(isLeaf){leafs.push({pos:pos,id:id,deleted:!!opts.deleted})}});leafs.sort(function(a,b){if(a.deleted!==b.deleted){return a.deleted>b.deleted?1:-1}if(a.pos!==b.pos){return b.pos-a.pos}return a.id<b.id?1:-1});return leafs[0].pos+"-"+leafs[0].id};PouchMerge.traverseRevTree=function(revs,callback){var toVisit=revs.slice();var node;while(node=toVisit.pop()){var pos=node.pos;var tree=node.ids;var branches=tree[2];var newCtx=callback(branches.length===0,pos,tree[0],node.ctx,tree[1]);for(var i=0,len=branches.length;i<len;i++){toVisit.push({pos:pos+1,ids:branches[i],ctx:newCtx})}}};PouchMerge.collectLeaves=function(revs){var leaves=[];PouchMerge.traverseRevTree(revs,function(isLeaf,pos,id,acc,opts){if(isLeaf){leaves.unshift({rev:pos+"-"+id,pos:pos,opts:opts})}});leaves.sort(function(a,b){return b.pos-a.pos});leaves.map(function(leaf){delete leaf.pos});return leaves};PouchMerge.collectConflicts=function(metadata){var win=PouchMerge.winningRev(metadata);var leaves=PouchMerge.collectLeaves(metadata.rev_tree);var conflicts=[];leaves.forEach(function(leaf){if(leaf.rev!==win&&!leaf.opts.deleted){conflicts.push(leaf.rev)}});return conflicts};PouchMerge.rootToLeaf=function(tree){var paths=[];PouchMerge.traverseRevTree(tree,function(isLeaf,pos,id,history,opts){history=history?history.slice(0):[];history.push({id:id,opts:opts});if(isLeaf){var rootPos=pos+1-history.length;paths.unshift({pos:rootPos,ids:history})}return history});return paths};module.exports=PouchMerge},{"pouchdb-extend":50}],24:[function(require,module,exports){"use strict";var utils=require("./utils");var EE=require("events").EventEmitter;var Checkpointer=require("./checkpointer");var MAX_SIMULTANEOUS_REVS=50;function randomNumber(min,max){min=parseInt(min,10);max=parseInt(max,10);if(min!==min){min=0}if(max!==max||max<=min){max=(min||1)<<1}else{max=max+1}var ratio=Math.random();var range=max-min;return~~(range*ratio+min)}function defaultBackOff(min){var max=0;if(!min){max=2e3}return randomNumber(min,max)}function backOff(repId,src,target,opts,returnValue,result,error){if(opts.retry===false){returnValue.emit("error",error);returnValue.removeAllListeners();return}opts.default_back_off=opts.default_back_off||0;opts.retries=opts.retries||0;if(typeof opts.back_off_function!=="function"){opts.back_off_function=defaultBackOff}opts.retries++;if(opts.max_retries&&opts.retries>opts.max_retries){returnValue.emit("error",new Error("tried "+opts.retries+" times but replication failed"));returnValue.removeAllListeners();return}returnValue.emit("requestError",error);if(returnValue.state==="active"){returnValue.emit("syncStopped");returnValue.state="stopped";returnValue.once("syncRestarted",function(){opts.current_back_off=opts.default_back_off})}opts.current_back_off=opts.current_back_off||opts.default_back_off;opts.current_back_off=opts.back_off_function(opts.current_back_off);setTimeout(function(){replicate(repId,src,target,opts,returnValue)},opts.current_back_off)}utils.inherits(Replication,EE);function Replication(opts){EE.call(this);this.cancelled=false;this.state="pending";var self=this;var promise=new utils.Promise(function(fulfill,reject){self.once("complete",fulfill);self.once("error",reject)});self.then=function(resolve,reject){return promise.then(resolve,reject)};self["catch"]=function(reject){return promise["catch"](reject)};self["catch"](function(err){})}Replication.prototype.cancel=function(){this.cancelled=true;this.state="cancelled";this.emit("cancel")};Replication.prototype.ready=function(src,target){var self=this;this.once("change",function(){if(this.state==="pending"){self.state="active";self.emit("syncStarted")}else if(self.state==="stopped"){self.state="active";self.emit("syncRestarted")}});function onDestroy(){self.cancel()}src.once("destroyed",onDestroy);target.once("destroyed",onDestroy);function cleanup(){src.removeListener("destroyed",onDestroy);target.removeListener("destroyed",onDestroy)}this.then(cleanup,cleanup)};function genReplicationId(src,target,opts){var filterFun=opts.filter?opts.filter.toString():"";return src.id().then(function(src_id){return target.id().then(function(target_id){var queryData=src_id+target_id+filterFun+JSON.stringify(opts.query_params)+opts.doc_ids;return utils.MD5(queryData).then(function(md5){md5=md5.replace(/\//g,".").replace(/\+/g,"_");return"_local/"+md5})})})}function replicate(repId,src,target,opts,returnValue,result){var batches=[];var currentBatch;var pendingBatch={seq:0,changes:[],docs:[]};var writingCheckpoint=false;var changesCompleted=false;var replicationCompleted=false;var last_seq=0;var continuous=opts.continuous||opts.live||false;var batch_size=opts.batch_size||100;var batches_limit=opts.batches_limit||10;var changesPending=false;var doc_ids=opts.doc_ids;var state={cancelled:false};var checkpointer=new Checkpointer(src,target,repId,state);result=result||{ok:true,start_time:new Date,docs_read:0,docs_written:0,doc_write_failures:0,errors:[]};var changesOpts={};returnValue.ready(src,target);function writeDocs(){if(currentBatch.docs.length===0){return | |
}var docs=currentBatch.docs;return target.bulkDocs({docs:docs},{new_edits:false}).then(function(res){if(state.cancelled){completeReplication();throw new Error("cancelled")}var errors=[];res.forEach(function(res){if(res.error){result.doc_write_failures++;var error=new Error(res.reason||res.message||"Unknown reason");error.name=res.name||res.error;errors.push(error)}});result.errors=result.errors.concat(errors);result.docs_written+=currentBatch.docs.length-errors.length;var non403s=errors.filter(function(error){return error.name!=="unauthorized"&&error.name!=="forbidden"});if(non403s.length>0){var error=new Error("bulkDocs error");error.other_errors=errors;abortReplication("target.bulkDocs failed to write docs",error);throw new Error("bulkWrite partial failure")}},function(err){result.doc_write_failures+=docs.length;throw err})}function getNextDoc(){var diffs=currentBatch.diffs;var id=Object.keys(diffs)[0];var allMissing=diffs[id].missing;var missingBatches=[];for(var i=0;i<allMissing.length;i+=MAX_SIMULTANEOUS_REVS){missingBatches.push(allMissing.slice(i,Math.min(allMissing.length,i+MAX_SIMULTANEOUS_REVS)))}return utils.Promise.all(missingBatches.map(function(missing){return src.get(id,{revs:true,open_revs:missing,attachments:true}).then(function(docs){docs.forEach(function(doc){if(state.cancelled){return completeReplication()}if(doc.ok){result.docs_read++;currentBatch.pendingRevs++;currentBatch.docs.push(doc.ok)}});delete diffs[id]})}))}function getAllDocs(){if(Object.keys(currentBatch.diffs).length>0){return getNextDoc().then(getAllDocs)}else{return utils.Promise.resolve()}}function getRevisionOneDocs(){var ids=Object.keys(currentBatch.diffs).filter(function(id){var missing=currentBatch.diffs[id].missing;return missing.length===1&&missing[0].slice(0,2)==="1-"});return src.allDocs({keys:ids,include_docs:true}).then(function(res){if(state.cancelled){completeReplication();throw new Error("cancelled")}res.rows.forEach(function(row){if(row.doc&&!row.deleted&&row.value.rev.slice(0,2)==="1-"&&(!row.doc._attachments||Object.keys(row.doc._attachments).length===0)){result.docs_read++;currentBatch.pendingRevs++;currentBatch.docs.push(row.doc);delete currentBatch.diffs[row.id]}})})}function getDocs(){return getRevisionOneDocs().then(getAllDocs)}function finishBatch(){writingCheckpoint=true;return checkpointer.writeCheckpoint(currentBatch.seq).then(function(res){writingCheckpoint=false;if(state.cancelled){completeReplication();throw new Error("cancelled")}result.last_seq=last_seq=currentBatch.seq;returnValue.emit("change",utils.clone(result));currentBatch=undefined;getChanges()})["catch"](function(err){writingCheckpoint=false;abortReplication("writeCheckpoint completed with error",err);throw err})}function getDiffs(){var diff={};currentBatch.changes.forEach(function(change){diff[change.id]=change.changes.map(function(x){return x.rev})});return target.revsDiff(diff).then(function(diffs){if(state.cancelled){completeReplication();throw new Error("cancelled")}currentBatch.diffs=diffs;currentBatch.pendingRevs=0})}function startNextBatch(){if(state.cancelled||currentBatch){return}if(batches.length===0){processPendingBatch(true);return}currentBatch=batches.shift();getDiffs().then(getDocs).then(writeDocs).then(finishBatch).then(startNextBatch)["catch"](function(err){abortReplication("batch processing terminated with error",err)})}function processPendingBatch(immediate){if(pendingBatch.changes.length===0){if(batches.length===0&&!currentBatch){if(continuous&&changesOpts.live||changesCompleted){returnValue.emit("uptodate",utils.clone(result))}if(changesCompleted){completeReplication()}}return}if(immediate||changesCompleted||pendingBatch.changes.length>=batch_size){batches.push(pendingBatch);pendingBatch={seq:0,changes:[],docs:[]};startNextBatch()}}function abortReplication(reason,err){if(replicationCompleted){return}result.ok=false;result.status="aborting";result.errors.push(err);batches=[];pendingBatch={seq:0,changes:[],docs:[]};completeReplication()}function completeReplication(){if(replicationCompleted){return}if(state.cancelled){result.status="cancelled";if(writingCheckpoint){return}}result.status=result.status||"complete";result.end_time=new Date;result.last_seq=last_seq;replicationCompleted=state.cancelled=true;var non403s=result.errors.filter(function(error){return error.name!=="unauthorized"&&error.name!=="forbidden"});if(non403s.length>0){var error=result.errors.pop();if(result.errors.length>0){error.other_errors=result.errors}error.result=result;backOff(repId,src,target,opts,returnValue,result,error)}else{returnValue.emit("complete",result);returnValue.removeAllListeners()}}function onChange(change){if(state.cancelled){return completeReplication()}if(pendingBatch.changes.length===0&&batches.length===0&&!currentBatch){returnValue.emit("outofdate",utils.clone(result))}pendingBatch.seq=change.seq;pendingBatch.changes.push(change);processPendingBatch(batches.length===0)}function onChangesComplete(changes){changesPending=false;if(state.cancelled){return completeReplication()}if(changesOpts.since<changes.last_seq){changesOpts.since=changes.last_seq;getChanges()}else{if(continuous){changesOpts.live=true;getChanges()}else{changesCompleted=true}}processPendingBatch(true)}function onChangesError(err){changesPending=false;if(state.cancelled){return completeReplication()}abortReplication("changes rejected",err)}function getChanges(){if(!(!changesPending&&!changesCompleted&&batches.length<batches_limit)){return}changesPending=true;function abortChanges(){changes.cancel()}function removeListener(){returnValue.removeListener("cancel",abortChanges)}returnValue.once("cancel",abortChanges);var changes=src.changes(changesOpts).on("change",onChange);changes.then(removeListener,removeListener);changes.then(onChangesComplete)["catch"](onChangesError)}function startChanges(){checkpointer.getCheckpoint().then(function(checkpoint){last_seq=checkpoint;changesOpts={since:last_seq,limit:batch_size,batch_size:batch_size,style:"all_docs",doc_ids:doc_ids,returnDocs:false};if(opts.filter){changesOpts.filter=opts.filter}if(opts.query_params){changesOpts.query_params=opts.query_params}getChanges()})["catch"](function(err){abortReplication("getCheckpoint rejected with ",err)})}returnValue.once("cancel",completeReplication);if(typeof opts.onChange==="function"){returnValue.on("change",opts.onChange)}if(typeof opts.complete==="function"){returnValue.once("error",opts.complete);returnValue.once("complete",function(result){opts.complete(null,result)})}if(typeof opts.since==="undefined"){startChanges()}else{writingCheckpoint=true;checkpointer.writeCheckpoint(opts.since).then(function(res){writingCheckpoint=false;if(state.cancelled){completeReplication();return}last_seq=opts.since;startChanges()})["catch"](function(err){writingCheckpoint=false;abortReplication("writeCheckpoint completed with error",err);throw err})}}exports.toPouch=toPouch;function toPouch(db,opts){var PouchConstructor=opts.PouchConstructor;if(typeof db==="string"){return new PouchConstructor(db)}else if(db.then){return db}else{return utils.Promise.resolve(db)}}exports.replicate=replicateWrapper;function replicateWrapper(src,target,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}if(typeof opts==="undefined"){opts={}}if(!opts.complete){opts.complete=callback||function(){}}opts=utils.clone(opts);opts.continuous=opts.continuous||opts.live;opts.retry=opts.retry||false;opts.PouchConstructor=opts.PouchConstructor||this;var replicateRet=new Replication(opts);toPouch(src,opts).then(function(src){return toPouch(target,opts).then(function(target){return genReplicationId(src,target,opts).then(function(repId){replicate(repId,src,target,opts,replicateRet)})})})["catch"](function(err){replicateRet.emit("error",err);opts.complete(err)});return replicateRet}},{"./checkpointer":10,"./utils":28,events:2}],25:[function(require,module,exports){(function(global){"use strict";var PouchDB=require("./constructor");var utils=require("./utils");var Promise=utils.Promise;var EventEmitter=require("events").EventEmitter;PouchDB.adapters={};PouchDB.preferredAdapters=require("./adapters/preferredAdapters.js");PouchDB.prefix="_pouch_";var eventEmitter=new EventEmitter;var eventEmitterMethods=["on","addListener","emit","listeners","once","removeAllListeners","removeListener","setMaxListeners"];eventEmitterMethods.forEach(function(method){PouchDB[method]=eventEmitter[method].bind(eventEmitter)});PouchDB.setMaxListeners(0);PouchDB.parseAdapter=function(name,opts){var match=name.match(/([a-z\-]*):\/\/(.*)/);var adapter,adapterName;if(match){name=/http(s?)/.test(match[1])?match[1]+"://"+match[2]:match[2];adapter=match[1];if(!PouchDB.adapters[adapter].valid()){throw"Invalid adapter"}return{name:name,adapter:match[1]}}var skipIdb="idb"in PouchDB.adapters&&"websql"in PouchDB.adapters&&utils.hasLocalStorage()&&global.localStorage["_pouch__websqldb_"+PouchDB.prefix+name];if(typeof opts!=="undefined"&&opts.db){adapterName="leveldb"}else{for(var i=0;i<PouchDB.preferredAdapters.length;++i){adapterName=PouchDB.preferredAdapters[i];if(adapterName in PouchDB.adapters){if(skipIdb&&adapterName==="idb"){continue}break}}}adapter=PouchDB.adapters[adapterName];if(adapterName&&adapter){var use_prefix="use_prefix"in adapter?adapter.use_prefix:true;return{name:use_prefix?PouchDB.prefix+name:name,adapter:adapterName}}throw"No valid adapter found"};PouchDB.destroy=utils.toPromise(function(name,opts,callback){if(typeof opts==="function"||typeof opts==="undefined"){callback=opts;opts={}}if(name&&typeof name==="object"){opts=name;name=undefined}var backend=PouchDB.parseAdapter(opts.name||name,opts);var dbName=backend.name;var adapter=PouchDB.adapters[backend.adapter];var usePrefix="use_prefix"in adapter?adapter.use_prefix:true;var baseName=usePrefix?dbName.replace(new RegExp("^"+PouchDB.prefix),""):dbName;var fullName=(backend.adapter==="http"||backend.adapter==="https"?"":opts.prefix||"")+dbName;function destroyDb(){adapter.destroy(fullName,opts,function(err,resp){if(err){callback(err)}else{PouchDB.emit("destroyed",name);PouchDB.emit(name,"destroyed");callback(null,resp||{ok:true})}})}var createOpts=utils.extend(true,{},opts,{adapter:backend.adapter});new PouchDB(baseName,createOpts,function(err,db){if(err){return callback(err)}db.get("_local/_pouch_dependentDbs",function(err,localDoc){if(err){if(err.status!==404){return callback(err)}else{return destroyDb()}}var dependentDbs=localDoc.dependentDbs;var deletedMap=Object.keys(dependentDbs).map(function(name){var trueName=usePrefix?name.replace(new RegExp("^"+PouchDB.prefix),""):name;var subOpts=utils.extend(true,opts,{adapter:backend.adapter});return PouchDB.destroy(trueName,subOpts)});Promise.all(deletedMap).then(destroyDb,function(error){callback(error)})})})});PouchDB.allDbs=utils.toPromise(function(callback){var err=new Error("allDbs method removed");err.stats="400";callback(err)});PouchDB.adapter=function(id,obj){if(obj.valid()){PouchDB.adapters[id]=obj}};PouchDB.plugin=function(obj){Object.keys(obj).forEach(function(id){PouchDB.prototype[id]=obj[id]})};PouchDB.defaults=function(defaultOpts){function PouchAlt(name,opts,callback){if(typeof opts==="function"||typeof opts==="undefined"){callback=opts;opts={}}if(name&&typeof name==="object"){opts=name;name=undefined}opts=utils.extend(true,{},defaultOpts,opts);PouchDB.call(this,name,opts,callback)}utils.inherits(PouchAlt,PouchDB);PouchAlt.destroy=utils.toPromise(function(name,opts,callback){if(typeof opts==="function"||typeof opts==="undefined"){callback=opts;opts={}}if(name&&typeof name==="object"){opts=name;name=undefined}opts=utils.extend(true,{},defaultOpts,opts);return PouchDB.destroy(name,opts,callback)});eventEmitterMethods.forEach(function(method){PouchAlt[method]=eventEmitter[method].bind(eventEmitter)});PouchAlt.setMaxListeners(0);PouchAlt.preferredAdapters=PouchDB.preferredAdapters.slice();Object.keys(PouchDB).forEach(function(key){if(!(key in PouchAlt)){PouchAlt[key]=PouchDB[key]}});return PouchAlt};module.exports=PouchDB}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./adapters/preferredAdapters.js":7,"./constructor":11,"./utils":28,events:2}],26:[function(require,module,exports){"use strict";var utils=require("./utils");var replication=require("./replicate");var replicate=replication.replicate;var EE=require("events").EventEmitter;utils.inherits(Sync,EE);module.exports=sync;function sync(src,target,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}if(typeof opts==="undefined"){opts={}}opts=utils.clone(opts);opts.PouchConstructor=opts.PouchConstructor||this;src=replication.toPouch(src,opts);target=replication.toPouch(target,opts);return new Sync(src,target,opts,callback)}function Sync(src,target,opts,callback){var self=this;this.canceled=false;var onChange,complete;if("onChange"in opts){onChange=opts.onChange;delete opts.onChange}if(typeof callback==="function"&&!opts.complete){complete=callback}else if("complete"in opts){complete=opts.complete;delete opts.complete}this.push=replicate(src,target,opts);this.pull=replicate(target,src,opts);var emittedCancel=false;function onCancel(data){if(!emittedCancel){emittedCancel=true;self.emit("cancel",data)}}function pullChange(change){self.emit("change",{direction:"pull",change:change})}function pushChange(change){self.emit("change",{direction:"push",change:change})}var listeners={};var removed={};function removeAll(type){return function(event,func){var isChange=event==="change"&&(func===pullChange||func===pushChange);var isCancel=event==="cancel"&&func===onCancel;var isOtherEvent=event in listeners&&func===listeners[event];if(isChange||isCancel||isOtherEvent){if(!(event in removed)){removed[event]={}}removed[event][type]=true;if(Object.keys(removed[event]).length===2){self.removeAllListeners(event)}}}}this.on("newListener",function(event){if(event==="change"){self.pull.on("change",pullChange);self.push.on("change",pushChange)}else if(event==="cancel"){self.pull.on("cancel",onCancel);self.push.on("cancel",onCancel)}else if(event!=="error"&&event!=="removeListener"&&event!=="complete"&&!(event in listeners)){listeners[event]=function(e){self.emit(event,e)};self.pull.on(event,listeners[event]);self.push.on(event,listeners[event])}});this.on("removeListener",function(event){if(event==="change"){self.pull.removeListener("change",pullChange);self.push.removeListener("change",pushChange)}else if(event==="cancel"){self.pull.removeListener("cancel",onCancel);self.push.removeListener("cancel",onCancel)}else if(event in listeners){if(typeof listeners[event]==="function"){self.pull.removeListener(event,listeners[event]);self.push.removeListener(event,listeners[event]);delete listeners[event]}}});this.pull.on("removeListener",removeAll("pull"));this.push.on("removeListener",removeAll("push"));var promise=utils.Promise.all([this.push,this.pull]).then(function(resp){var out={push:resp[0],pull:resp[1]};self.emit("complete",out);if(complete){complete(null,out)}self.removeAllListeners();return out},function(err){self.cancel();self.emit("error",err);if(complete){complete(err)}self.removeAllListeners();throw err});this.then=function(success,err){return promise.then(success,err)};this["catch"]=function(err){return promise["catch"](err)}}Sync.prototype.cancel=function(){if(!this.canceled){this.canceled=true;this.push.cancel();this.pull.cancel()}}},{"./replicate":24,"./utils":28,events:2}],27:[function(require,module,exports){"use strict";module.exports=TaskQueue;function TaskQueue(){this.isReady=false;this.failed=false;this.queue=[]}TaskQueue.prototype.execute=function(){var d,func;if(this.failed){while(d=this.queue.shift()){if(typeof d==="function"){d(this.failed);continue}func=d.parameters[d.parameters.length-1];if(typeof func==="function"){func(this.failed)}else if(d.name==="changes"&&typeof func.complete==="function"){func.complete(this.failed)}}}else if(this.isReady){while(d=this.queue.shift()){if(typeof d==="function"){d()}else{d.task=this.db[d.name].apply(this.db,d.parameters)}}}};TaskQueue.prototype.fail=function(err){this.failed=err;this.execute()};TaskQueue.prototype.ready=function(db){if(this.failed){return false}else if(arguments.length===0){return this.isReady}this.isReady=db?true:false;this.db=db;this.execute()};TaskQueue.prototype.addTask=function(name,parameters){if(typeof name==="function"){this.queue.push(name);if(this.failed){this.execute()}}else{var task={name:name,parameters:parameters};this.queue.push(task);if(this.failed){this.execute()}return task}}},{}],28:[function(require,module,exports){(function(process,global){var merge=require("./merge");exports.extend=require("pouchdb-extend");exports.ajax=require("./deps/ajax");exports.createBlob=require("./deps/blob");exports.uuid=require("./deps/uuid");exports.getArguments=require("argsarray");var buffer=require("./deps/buffer");var errors=require("./deps/errors");var EventEmitter=require("events").EventEmitter;var collections=require("./deps/collections");exports.Map=collections.Map;exports.Set=collections.Set;if(typeof global.Promise==="function"){exports.Promise=global.Promise}else{exports.Promise=require("bluebird")}var Promise=exports.Promise;function toObject(array){var obj={};array.forEach(function(item){obj[item]=true});return obj}var reservedWords=toObject(["_id","_rev","_attachments","_deleted","_revisions","_revs_info","_conflicts","_deleted_conflicts","_local_seq","_rev_tree","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats"]);var dataWords=toObject(["_attachments","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats"]);exports.lastIndexOf=function(str,char){for(var i=str.length-1;i>=0;i--){if(str.charAt(i)===char){return i}}return-1};exports.clone=function(obj){return exports.extend(true,{},obj)};exports.inherits=require("inherits");exports.invalidIdError=function(id){var err;if(!id){err=new TypeError(errors.MISSING_ID.message);err.status=412}else if(typeof id!=="string"){err=new TypeError(errors.INVALID_ID.message);err.status=400}else if(/^_/.test(id)&&!/^_(design|local)/.test(id)){err=new TypeError(errors.RESERVED_ID.message);err.status=400}if(err){throw err}};function isChromeApp(){return typeof chrome!=="undefined"&&typeof chrome.storage!=="undefined"&&typeof chrome.storage.local!=="undefined"}exports.call=exports.getArguments(function(args){if(!args.length){return}var fun=args.shift();if(typeof fun==="function"){fun.apply(this,args)}});exports.isLocalId=function(id){return/^_local/.test(id)};exports.isDeleted=function(metadata,rev){if(!rev){rev=merge.winningRev(metadata)}var dashIndex=rev.indexOf("-");if(dashIndex!==-1){rev=rev.substring(dashIndex+1)}var deleted=false;merge.traverseRevTree(metadata.rev_tree,function(isLeaf,pos,id,acc,opts){if(id===rev){deleted=!!opts.deleted}});return deleted};exports.revExists=function(metadata,rev){var found=false;merge.traverseRevTree(metadata.rev_tree,function(leaf,pos,id,acc,opts){if(pos+"-"+id===rev){found=true}});return found};exports.filterChange=function(opts){return function(change){var req={};var hasFilter=opts.filter&&typeof opts.filter==="function";req.query=opts.query_params;if(opts.filter&&hasFilter&&!opts.filter.call(this,change.doc,req)){return false}if(opts.doc_ids&&opts.doc_ids.indexOf(change.id)===-1){return false}if(!opts.include_docs){delete change.doc}else{for(var att in change.doc._attachments){if(change.doc._attachments.hasOwnProperty(att)){change.doc._attachments[att].stub=true}}}return true}};exports.parseDoc=function(doc,newEdits){var nRevNum;var newRevId;var revInfo;var error;var opts={status:"available"};if(doc._deleted){opts.deleted=true}if(newEdits){if(!doc._id){doc._id=exports.uuid()}newRevId=exports.uuid(32,16).toLowerCase();if(doc._rev){revInfo=/^(\d+)-(.+)$/.exec(doc._rev);if(!revInfo){var err=new TypeError("invalid value for property '_rev'");err.status=400}doc._rev_tree=[{pos:parseInt(revInfo[1],10),ids:[revInfo[2],{status:"missing"},[[newRevId,opts,[]]]]}];nRevNum=parseInt(revInfo[1],10)+1}else{doc._rev_tree=[{pos:1,ids:[newRevId,opts,[]]}];nRevNum=1}}else{if(doc._revisions){doc._rev_tree=[{pos:doc._revisions.start-doc._revisions.ids.length+1,ids:doc._revisions.ids.reduce(function(acc,x){if(acc===null){return[x,opts,[]]}else{return[x,{status:"missing"},[acc]]}},null)}];nRevNum=doc._revisions.start;newRevId=doc._revisions.ids[0]}if(!doc._rev_tree){revInfo=/^(\d+)-(.+)$/.exec(doc._rev);if(!revInfo){error=new TypeError(errors.BAD_ARG.message);error.status=errors.BAD_ARG.status;throw error}nRevNum=parseInt(revInfo[1],10);newRevId=revInfo[2];doc._rev_tree=[{pos:parseInt(revInfo[1],10),ids:[revInfo[2],opts,[]]}]}}exports.invalidIdError(doc._id);doc._rev=[nRevNum,newRevId].join("-");var result={metadata:{},data:{}};for(var key in doc){if(doc.hasOwnProperty(key)){var specialKey=key[0]==="_";if(specialKey&&!reservedWords[key]){error=new Error(errors.DOC_VALIDATION.message+": "+key);error.status=errors.DOC_VALIDATION.status;throw error}else if(specialKey&&!dataWords[key]){result.metadata[key.slice(1)]=doc[key]}else{result.data[key]=doc[key]}}}return result};exports.isCordova=function(){return typeof cordova!=="undefined"||typeof PhoneGap!=="undefined"||typeof phonegap!=="undefined"};exports.hasLocalStorage=function(){if(isChromeApp()){return false}try{return global.localStorage}catch(e){return false}};exports.Changes=Changes;exports.inherits(Changes,EventEmitter);function Changes(){if(!(this instanceof Changes)){return new Changes}var self=this;EventEmitter.call(this);this.isChrome=isChromeApp();this.listeners={};this.hasLocal=false;if(!this.isChrome){this.hasLocal=exports.hasLocalStorage()}if(this.isChrome){chrome.storage.onChanged.addListener(function(e){if(e.db_name!=null){self.emit(e.dbName.newValue)}})}else if(this.hasLocal){if(global.addEventListener){global.addEventListener("storage",function(e){self.emit(e.key)})}else{global.attachEvent("storage",function(e){self.emit(e.key)})}}}Changes.prototype.addListener=function(dbName,id,db,opts){if(this.listeners[id]){return}function eventFunction(){db.changes({include_docs:opts.include_docs,conflicts:opts.conflicts,continuous:false,descending:false,filter:opts.filter,view:opts.view,since:opts.since,query_params:opts.query_params,onChange:function(c){if(c.seq>opts.since&&!opts.cancelled){opts.since=c.seq;exports.call(opts.onChange,c)}}})}this.listeners[id]=eventFunction;this.on(dbName,eventFunction)};Changes.prototype.removeListener=function(dbName,id){if(!(id in this.listeners)){return}EventEmitter.prototype.removeListener.call(this,dbName,this.listeners[id])};Changes.prototype.notifyLocalWindows=function(dbName){if(this.isChrome){chrome.storage.local.set({dbName:dbName})}else if(this.hasLocal){localStorage[dbName]=localStorage[dbName]==="a"?"b":"a"}};Changes.prototype.notify=function(dbName){this.emit(dbName);this.notifyLocalWindows(dbName)};if(!process.browser||!("atob"in global)){exports.atob=function(str){var base64=new buffer(str,"base64");if(base64.toString("base64")!==str){throw"Cannot base64 encode full string"}return base64.toString("binary")}}else{exports.atob=function(str){return atob(str)}}if(!process.browser||!("btoa"in global)){exports.btoa=function(str){return new buffer(str,"binary").toString("base64")}}else{exports.btoa=function(str){return btoa(str)}}exports.fixBinary=function(bin){if(!process.browser){return 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};exports.readAsBinaryString=function(blob,callback){var reader=new FileReader;var hasBinaryString=typeof reader.readAsBinaryString==="function";reader.onloadend=function(e){var result=e.target.result||"";if(hasBinaryString){return callback(result)}callback(exports.arrayBufferToBinaryString(result))};if(hasBinaryString){reader.readAsBinaryString(blob)}else{reader.readAsArrayBuffer(blob)}};exports.once=function(fun){var called=false;return exports.getArguments(function(args){if(called){throw new Error("once called more than once")}else{called=true;fun.apply(this,args)}})};exports.toPromise=function(func){return exports.getArguments(function(args){var self=this;var tempCB=typeof args[args.length-1]==="function"?args.pop():false;var usedCB;if(tempCB){usedCB=function(err,resp){process.nextTick(function(){tempCB(err,resp)})}}var promise=new Promise(function(fulfill,reject){var resp;try{var callback=exports.once(function(err,mesg){if(err){reject(err)}else{fulfill(mesg)}});args.push(callback);resp=func.apply(self,args);if(resp&&typeof resp.then==="function"){fulfill(resp)}}catch(e){reject(e)}});if(usedCB){promise.then(function(result){usedCB(null,result)},usedCB)}promise.cancel=function(){return this};return promise})};exports.adapterFun=function(name,callback){return exports.toPromise(exports.getArguments(function(args){if(this._closed){return Promise.reject(new Error("database is closed"))}var self=this;if(!this.taskqueue.isReady){return new exports.Promise(function(fulfill,reject){self.taskqueue.addTask(function(failed){if(failed){reject(failed)}else{fulfill(self[name].apply(self,args))}})})}return callback.apply(this,args)}))};exports.arrayBufferToBinaryString=function(buffer){var binary="";var bytes=new Uint8Array(buffer);var length=bytes.byteLength;for(var i=0;i<length;i++){binary+=String.fromCharCode(bytes[i])}return binary};exports.cancellableFun=function(fun,self,opts){opts=opts?exports.clone(true,{},opts):{};var emitter=new EventEmitter;var oldComplete=opts.complete||function(){};var complete=opts.complete=exports.once(function(err,resp){if(err){oldComplete(err)}else{emitter.emit("end",resp);oldComplete(null,resp)}emitter.removeAllListeners()});var oldOnChange=opts.onChange||function(){};var lastChange=0;self.on("destroyed",function(){emitter.removeAllListeners()});opts.onChange=function(change){oldOnChange(change);if(change.seq<=lastChange){return}lastChange=change.seq;emitter.emit("change",change);if(change.deleted){emitter.emit("delete",change)}else if(change.changes.length===1&&change.changes[0].rev.slice(0,1)==="1-"){emitter.emit("create",change)}else{emitter.emit("update",change)}};var promise=new Promise(function(fulfill,reject){opts.complete=function(err,res){if(err){reject(err)}else{fulfill(res)}}});promise.then(function(result){complete(null,result)},complete);promise.cancel=function(){promise.isCancelled=true;if(self.taskqueue.isReady){opts.complete(null,{status:"cancelled"})}};if(!self.taskqueue.isReady){self.taskqueue.addTask(function(){if(promise.isCancelled){opts.complete(null,{status:"cancelled"})}else{fun(self,opts,promise)}})}else{fun(self,opts,promise)}promise.on=emitter.on.bind(emitter);promise.once=emitter.once.bind(emitter);promise.addListener=emitter.addListener.bind(emitter);promise.removeListener=emitter.removeListener.bind(emitter);promise.removeAllListeners=emitter.removeAllListeners.bind(emitter);promise.setMaxListeners=emitter.setMaxListeners.bind(emitter);promise.listeners=emitter.listeners.bind(emitter);promise.emit=emitter.emit.bind(emitter);return promise};exports.MD5=exports.toPromise(require("./deps/md5"));exports.explain404=function(str){if(process.browser&&"console"in global&&"info"in console){console.info("The above 404 is totally normal. "+str+"\n♥ the PouchDB team")}};exports.parseUri=require("./deps/parse-uri");exports.compare=function(left,right){return left<right?-1:left>right?1:0}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./deps/ajax":12,"./deps/blob":13,"./deps/buffer":1,"./deps/collections":14,"./deps/errors":15,"./deps/md5":16,"./deps/parse-uri":18,"./deps/uuid":20,"./merge":23,_process:3,argsarray:30,bluebird:35,events:2,inherits:31,"pouchdb-extend":50}],29:[function(require,module,exports){module.exports="3.1.0"},{}],30:[function(require,module,exports){"use strict";module.exports=argsArray;function argsArray(fun){return function(){var len=arguments.length;if(len){var args=[];var i=-1;while(++i<len){args[i]=arguments[i]}return fun.call(this,args)}else{return fun.call(this,[])}}}},{}],31:[function(require,module,exports){if(typeof Object.create==="function"){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{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],32:[function(require,module,exports){"use strict";module.exports=INTERNAL;function INTERNAL(){}},{}],33:[function(require,module,exports){"use strict";var Promise=require("./promise");var reject=require("./reject");var resolve=require("./resolve");var INTERNAL=require("./INTERNAL");var handlers=require("./handlers");module.exports=all;function all(iterable){if(Object.prototype.toString.call(iterable)!=="[object Array]"){return reject(new TypeError("must be an array"))}var len=iterable.length;var called=false;if(!len){return resolve([])}var values=new Array(len);var resolved=0;var i=-1;var promise=new Promise(INTERNAL);while(++i<len){allResolver(iterable[i],i)}return promise;function allResolver(value,i){resolve(value).then(resolveFromAll,function(error){if(!called){called=true;handlers.reject(promise,error)}});function resolveFromAll(outValue){values[i]=outValue;if(++resolved===len&!called){called=true;handlers.resolve(promise,values)}}}}},{"./INTERNAL":32,"./handlers":34,"./promise":36,"./reject":39,"./resolve":40}],34:[function(require,module,exports){"use strict";var tryCatch=require("./tryCatch");var resolveThenable=require("./resolveThenable");var states=require("./states");exports.resolve=function(self,value){var result=tryCatch(getThen,value);if(result.status==="error"){return exports.reject(self,result.value)}var thenable=result.value;if(thenable){resolveThenable.safely(self,thenable)}else{self.state=states.FULFILLED;self.outcome=value;var i=-1;var len=self.queue.length;while(++i<len){self.queue[i].callFulfilled(value)}}return self};exports.reject=function(self,error){self.state=states.REJECTED;self.outcome=error;var i=-1;var len=self.queue.length;while(++i<len){self.queue[i].callRejected(error)}return self};function getThen(obj){var then=obj&&obj.then;if(obj&&typeof obj==="object"&&typeof then==="function"){return function appyThen(){then.apply(obj,arguments)}}}},{"./resolveThenable":41,"./states":42,"./tryCatch":43}],35:[function(require,module,exports){module.exports=exports=require("./promise");exports.resolve=require("./resolve");exports.reject=require("./reject");exports.all=require("./all");exports.race=require("./race")},{"./all":33,"./promise":36,"./race":38,"./reject":39,"./resolve":40}],36:[function(require,module,exports){"use strict";var unwrap=require("./unwrap");var INTERNAL=require("./INTERNAL");var resolveThenable=require("./resolveThenable");var states=require("./states");var QueueItem=require("./queueItem");module.exports=Promise;function Promise(resolver){if(!(this instanceof Promise)){return new Promise(resolver)}if(typeof resolver!=="function"){throw new TypeError("reslover must be a function")}this.state=states.PENDING;this.queue=[];this.outcome=void 0;if(resolver!==INTERNAL){resolveThenable.safely(this,resolver)}}Promise.prototype["catch"]=function(onRejected){return this.then(null,onRejected)};Promise.prototype.then=function(onFulfilled,onRejected){if(typeof onFulfilled!=="function"&&this.state===states.FULFILLED||typeof onRejected!=="function"&&this.state===states.REJECTED){return this}var promise=new Promise(INTERNAL);if(this.state!==states.PENDING){var resolver=this.state===states.FULFILLED?onFulfilled:onRejected;unwrap(promise,resolver,this.outcome)}else{this.queue.push(new QueueItem(promise,onFulfilled,onRejected)) | |
}return promise}},{"./INTERNAL":32,"./queueItem":37,"./resolveThenable":41,"./states":42,"./unwrap":44}],37:[function(require,module,exports){"use strict";var handlers=require("./handlers");var unwrap=require("./unwrap");module.exports=QueueItem;function QueueItem(promise,onFulfilled,onRejected){this.promise=promise;if(typeof onFulfilled==="function"){this.onFulfilled=onFulfilled;this.callFulfilled=this.otherCallFulfilled}if(typeof onRejected==="function"){this.onRejected=onRejected;this.callRejected=this.otherCallRejected}}QueueItem.prototype.callFulfilled=function(value){handlers.resolve(this.promise,value)};QueueItem.prototype.otherCallFulfilled=function(value){unwrap(this.promise,this.onFulfilled,value)};QueueItem.prototype.callRejected=function(value){handlers.reject(this.promise,value)};QueueItem.prototype.otherCallRejected=function(value){unwrap(this.promise,this.onRejected,value)}},{"./handlers":34,"./unwrap":44}],38:[function(require,module,exports){"use strict";var Promise=require("./promise");var reject=require("./reject");var resolve=require("./resolve");var INTERNAL=require("./INTERNAL");var handlers=require("./handlers");module.exports=race;function race(iterable){if(Object.prototype.toString.call(iterable)!=="[object Array]"){return reject(new TypeError("must be an array"))}var len=iterable.length;var called=false;if(!len){return resolve([])}var resolved=0;var i=-1;var promise=new Promise(INTERNAL);while(++i<len){resolver(iterable[i])}return promise;function resolver(value){resolve(value).then(function(response){if(!called){called=true;handlers.resolve(promise,response)}},function(error){if(!called){called=true;handlers.reject(promise,error)}})}}},{"./INTERNAL":32,"./handlers":34,"./promise":36,"./reject":39,"./resolve":40}],39:[function(require,module,exports){"use strict";var Promise=require("./promise");var INTERNAL=require("./INTERNAL");var handlers=require("./handlers");module.exports=reject;function reject(reason){var promise=new Promise(INTERNAL);return handlers.reject(promise,reason)}},{"./INTERNAL":32,"./handlers":34,"./promise":36}],40:[function(require,module,exports){"use strict";var Promise=require("./promise");var INTERNAL=require("./INTERNAL");var handlers=require("./handlers");module.exports=resolve;var FALSE=handlers.resolve(new Promise(INTERNAL),false);var NULL=handlers.resolve(new Promise(INTERNAL),null);var UNDEFINED=handlers.resolve(new Promise(INTERNAL),void 0);var ZERO=handlers.resolve(new Promise(INTERNAL),0);var EMPTYSTRING=handlers.resolve(new Promise(INTERNAL),"");function resolve(value){if(value){if(value instanceof Promise){return value}return handlers.resolve(new Promise(INTERNAL),value)}var valueType=typeof value;switch(valueType){case"boolean":return FALSE;case"undefined":return UNDEFINED;case"object":return NULL;case"number":return ZERO;case"string":return EMPTYSTRING}}},{"./INTERNAL":32,"./handlers":34,"./promise":36}],41:[function(require,module,exports){"use strict";var handlers=require("./handlers");var tryCatch=require("./tryCatch");function safelyResolveThenable(self,thenable){var called=false;function onError(value){if(called){return}called=true;handlers.reject(self,value)}function onSuccess(value){if(called){return}called=true;handlers.resolve(self,value)}function tryToUnwrap(){thenable(onSuccess,onError)}var result=tryCatch(tryToUnwrap);if(result.status==="error"){onError(result.value)}}exports.safely=safelyResolveThenable},{"./handlers":34,"./tryCatch":43}],42:[function(require,module,exports){exports.REJECTED=["REJECTED"];exports.FULFILLED=["FULFILLED"];exports.PENDING=["PENDING"]},{}],43:[function(require,module,exports){"use strict";module.exports=tryCatch;function tryCatch(func,value){var out={};try{out.value=func(value);out.status="success"}catch(e){out.status="error";out.value=e}return out}},{}],44:[function(require,module,exports){"use strict";var immediate=require("immediate");var handlers=require("./handlers");module.exports=unwrap;function unwrap(promise,func,value){immediate(function(){var returnValue;try{returnValue=func(value)}catch(e){return handlers.reject(promise,e)}if(returnValue===promise){handlers.reject(promise,new TypeError("Cannot resolve promise with itself"))}else{handlers.resolve(promise,returnValue)}})}},{"./handlers":34,immediate:45}],45:[function(require,module,exports){"use strict";var types=[require("./nextTick"),require("./mutation.js"),require("./messageChannel"),require("./stateChange"),require("./timeout")];var draining;var queue=[];function nextTick(){draining=true;var i,oldQueue;var len=queue.length;while(len){oldQueue=queue;queue=[];i=-1;while(++i<len){oldQueue[i]()}len=queue.length}draining=false}var scheduleDrain;var i=-1;var len=types.length;while(++i<len){if(types[i]&&types[i].test&&types[i].test()){scheduleDrain=types[i].install(nextTick);break}}module.exports=immediate;function immediate(task){if(queue.push(task)===1&&!draining){scheduleDrain()}}},{"./messageChannel":46,"./mutation.js":47,"./nextTick":1,"./stateChange":48,"./timeout":49}],46:[function(require,module,exports){(function(global){"use strict";exports.test=function(){if(global.setImmediate){return false}return typeof global.MessageChannel!=="undefined"};exports.install=function(func){var channel=new global.MessageChannel;channel.port1.onmessage=func;return function(){channel.port2.postMessage(0)}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],47:[function(require,module,exports){(function(global){"use strict";var Mutation=global.MutationObserver||global.WebKitMutationObserver;exports.test=function(){return Mutation};exports.install=function(handle){var called=0;var observer=new Mutation(handle);var element=global.document.createTextNode("");observer.observe(element,{characterData:true});return function(){element.data=called=++called%2}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],48:[function(require,module,exports){(function(global){"use strict";exports.test=function(){return"document"in global&&"onreadystatechange"in global.document.createElement("script")};exports.install=function(handle){return function(){var scriptEl=global.document.createElement("script");scriptEl.onreadystatechange=function(){handle();scriptEl.onreadystatechange=null;scriptEl.parentNode.removeChild(scriptEl);scriptEl=null};global.document.documentElement.appendChild(scriptEl);return handle}}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],49:[function(require,module,exports){"use strict";exports.test=function(){return true};exports.install=function(t){return function(){setTimeout(t,0)}}},{}],50:[function(require,module,exports){"use strict";var class2type={};var types=["Boolean","Number","String","Function","Array","Date","RegExp","Object","Error"];for(var i=0;i<types.length;i++){var typename=types[i];class2type["[object "+typename+"]"]=typename.toLowerCase()}var core_toString=class2type.toString;var core_hasOwn=class2type.hasOwnProperty;function type(obj){if(obj===null){return String(obj)}return typeof obj==="object"||typeof obj==="function"?class2type[core_toString.call(obj)]||"object":typeof obj}function isWindow(obj){return obj!==null&&obj===obj.window}function isPlainObject(obj){if(!obj||type(obj)!=="object"||obj.nodeType||isWindow(obj)){return false}try{if(obj.constructor&&!core_hasOwn.call(obj,"constructor")&&!core_hasOwn.call(obj.constructor.prototype,"isPrototypeOf")){return false}}catch(e){return false}var key;for(key in obj){}return key===undefined||core_hasOwn.call(obj,key)}function isFunction(obj){return type(obj)==="function"}var isArray=Array.isArray||function(obj){return type(obj)==="array"};function extend(){var stack=[];var i=-1;var len=arguments.length;var args=new Array(len);while(++i<len){args[i]=arguments[i]}var container={};stack.push({args:args,result:{container:container,key:"key"}});var next;while(next=stack.pop()){extendInner(stack,next.args,next.result)}return container.key}function extendInner(stack,args,result){var options,name,src,copy,copyIsArray,clone,target=args[0]||{},i=1,length=args.length,deep=false,numericStringRegex=/\d+/,optionsIsArray;if(typeof target==="boolean"){deep=target;target=args[1]||{};i=2}if(typeof target!=="object"&&!isFunction(target)){target={}}if(length===i){target=this;--i}for(;i<length;i++){if((options=args[i])!=null){optionsIsArray=isArray(options);for(name in options){if(!(name in Object.prototype)){if(optionsIsArray&&!numericStringRegex.test(name)){continue}src=target[name];copy=options[name];if(target===copy){continue}if(deep&©&&(isPlainObject(copy)||(copyIsArray=isArray(copy)))){if(copyIsArray){copyIsArray=false;clone=src&&isArray(src)?src:[]}else{clone=src&&isPlainObject(src)?src:{}}stack.push({args:[deep,clone,copy],result:{container:target,key:name}})}else if(copy!==undefined){if(!(isArray(options)&&isFunction(copy))){target[name]=copy}}}}}}result.container[result.key]=target}module.exports=extend},{}],51:[function(require,module,exports){"use strict";var upsert=require("./upsert");var utils=require("./utils");var Promise=utils.Promise;module.exports=function(opts){var sourceDB=opts.db;var viewName=opts.viewName;var mapFun=opts.map;var reduceFun=opts.reduce;var temporary=opts.temporary;var viewSignature=mapFun.toString()+(reduceFun&&reduceFun.toString())+"undefined";if(!temporary&&sourceDB._cachedViews){var cachedView=sourceDB._cachedViews[viewSignature];if(cachedView){return Promise.resolve(cachedView)}}return sourceDB.info().then(function(info){var depDbName=info.db_name+"-mrview-"+(temporary?"temp":utils.MD5(viewSignature));function diffFunction(doc){doc.views=doc.views||{};var fullViewName=viewName;if(fullViewName.indexOf("/")===-1){fullViewName=viewName+"/"+viewName}var depDbs=doc.views[fullViewName]=doc.views[fullViewName]||{};if(depDbs[depDbName]){return}depDbs[depDbName]=true;return doc}return upsert(sourceDB,"_local/mrviews",diffFunction).then(function(){return sourceDB.registerDependentDatabase(depDbName).then(function(res){var db=res.db;db.auto_compaction=true;var view={name:depDbName,db:db,sourceDB:sourceDB,adapter:sourceDB.adapter,mapFun:mapFun,reduceFun:reduceFun};return view.db.get("_local/lastSeq")["catch"](function(err){if(err.status!==404){throw err}}).then(function(lastSeqDoc){view.seq=lastSeqDoc?lastSeqDoc.seq:0;if(!temporary){sourceDB._cachedViews=sourceDB._cachedViews||{};sourceDB._cachedViews[viewSignature]=view;view.db.on("destroyed",function(){delete sourceDB._cachedViews[viewSignature]})}return view})})})})}},{"./upsert":57,"./utils":58}],52:[function(require,module,exports){"use strict";module.exports=function(func,emit,sum,log,isArray,toJSON){return eval("'use strict'; ("+func.replace(/;\s*$/,"")+");")}},{}],53:[function(require,module,exports){(function(process){"use strict";var pouchCollate=require("pouchdb-collate");var TaskQueue=require("./taskqueue");var collate=pouchCollate.collate;var toIndexableString=pouchCollate.toIndexableString;var normalizeKey=pouchCollate.normalizeKey;var createView=require("./create-view");var evalFunc=require("./evalfunc");var log;if(typeof console!=="undefined"&&typeof console.log==="function"){log=Function.prototype.bind.call(console.log,console)}else{log=function(){}}var utils=require("./utils");var Promise=utils.Promise;var mainQueue=new TaskQueue;var tempViewQueue=new TaskQueue;var CHANGES_BATCH_SIZE=50;function parseViewName(name){return name.indexOf("/")===-1?[name,name]:name.split("/")}function tryCode(db,fun,args){try{return{output:fun.apply(null,args)}}catch(e){db.emit("error",e);return{error:e}}}function sortByKeyThenValue(x,y){var keyCompare=collate(x.key,y.key);return keyCompare!==0?keyCompare:collate(x.value,y.value)}function sliceResults(results,limit,skip){skip=skip||0;if(typeof limit==="number"){return results.slice(skip,limit+skip)}else if(skip>0){return results.slice(skip)}return results}function createBuiltInError(name){var error=new Error("builtin "+name+" function requires map values to be numbers"+" or number arrays");error.name="invalid_value";error.status=500;return error}function sum(values){var result=0;for(var i=0,len=values.length;i<len;i++){var num=values[i];if(typeof num!=="number"){if(Array.isArray(num)){result=typeof result==="number"?[result]:result;for(var j=0,jLen=num.length;j<jLen;j++){var jNum=num[j];if(typeof jNum!=="number"){throw createBuiltInError("_sum")}else if(typeof result[j]==="undefined"){result.push(jNum)}else{result[j]+=jNum}}}else{throw createBuiltInError("_sum")}}else if(typeof result==="number"){result+=num}else{result[0]+=num}}return result}var builtInReduce={_sum:function(keys,values){return sum(values)},_count:function(keys,values){return values.length},_stats:function(keys,values){function sumsqr(values){var _sumsqr=0;for(var i=0,len=values.length;i<len;i++){var num=values[i];_sumsqr+=num*num}return _sumsqr}return{sum:sum(values),min:Math.min.apply(null,values),max:Math.max.apply(null,values),count:values.length,sumsqr:sumsqr(values)}}};function addHttpParam(paramName,opts,params,asJson){var val=opts[paramName];if(typeof val!=="undefined"){if(asJson){val=encodeURIComponent(JSON.stringify(val))}params.push(paramName+"="+val)}}function checkQueryParseError(options,fun){var startkeyName=options.descending?"endkey":"startkey";var endkeyName=options.descending?"startkey":"endkey";if(typeof options[startkeyName]!=="undefined"&&typeof options[endkeyName]!=="undefined"&&collate(options[startkeyName],options[endkeyName])>0){throw new QueryParseError("No rows can match your key range, reverse your "+"start_key and end_key or set {descending : true}")}else if(fun.reduce&&options.reduce!==false){if(options.include_docs){throw new QueryParseError("{include_docs:true} is invalid for reduce")}else if(options.keys&&options.keys.length>1&&!options.group&&!options.group_level){throw new QueryParseError("Multi-key fetches for reduce views must use {group: true}")}}if(options.group_level){if(typeof options.group_level!=="number"){throw new QueryParseError('Invalid value for integer: "'+options.group_level+'"')}if(options.group_level<0){throw new QueryParseError("Invalid value for positive integer: "+'"'+options.group_level+'"')}}}function httpQuery(db,fun,opts){var params=[];var body;var method="GET";addHttpParam("reduce",opts,params);addHttpParam("include_docs",opts,params);addHttpParam("limit",opts,params);addHttpParam("descending",opts,params);addHttpParam("group",opts,params);addHttpParam("group_level",opts,params);addHttpParam("skip",opts,params);addHttpParam("stale",opts,params);addHttpParam("conflicts",opts,params);addHttpParam("startkey",opts,params,true);addHttpParam("endkey",opts,params,true);addHttpParam("inclusive_end",opts,params);addHttpParam("key",opts,params,true);params=params.join("&");params=params===""?"":"?"+params;if(typeof opts.keys!=="undefined"){var MAX_URL_LENGTH=2e3;var keysAsString="keys="+encodeURIComponent(JSON.stringify(opts.keys));if(keysAsString.length+params.length+1<=MAX_URL_LENGTH){params+=(params[0]==="?"?"&":"?")+keysAsString}else{method="POST";if(typeof fun==="string"){body=JSON.stringify({keys:opts.keys})}else{fun.keys=opts.keys}}}if(typeof fun==="string"){var parts=parseViewName(fun);return db.request({method:method,url:"_design/"+parts[0]+"/_view/"+parts[1]+params,body:body})}body=body||{};Object.keys(fun).forEach(function(key){if(Array.isArray(fun[key])){body[key]=fun[key]}else{body[key]=fun[key].toString()}});return db.request({method:"POST",url:"_temp_view"+params,body:body})}function defaultsTo(value){return function(reason){if(reason.status===404){return value}else{throw reason}}}function getDocsToPersist(docId,view,docIdsToEmits){var metaDocId="_local/doc_"+docId;return view.db.get(metaDocId)["catch"](defaultsTo({_id:metaDocId,keys:[]})).then(function(metaDoc){return Promise.resolve().then(function(){if(metaDoc.keys.length){return view.db.allDocs({keys:metaDoc.keys,include_docs:true})}return{rows:[]}}).then(function(res){var kvDocs=res.rows.map(function(row){return row.doc}).filter(function(row){return row});var indexableKeysToKeyValues=docIdsToEmits[docId];var oldKeysMap={};kvDocs.forEach(function(kvDoc){oldKeysMap[kvDoc._id]=true;kvDoc._deleted=!indexableKeysToKeyValues[kvDoc._id];if(!kvDoc._deleted){var keyValue=indexableKeysToKeyValues[kvDoc._id];if("value"in keyValue){kvDoc.value=keyValue.value}}});var newKeys=Object.keys(indexableKeysToKeyValues);newKeys.forEach(function(key){if(!oldKeysMap[key]){var kvDoc={_id:key};var keyValue=indexableKeysToKeyValues[key];if("value"in keyValue){kvDoc.value=keyValue.value}kvDocs.push(kvDoc)}});metaDoc.keys=utils.uniq(newKeys.concat(metaDoc.keys));kvDocs.splice(0,0,metaDoc);return kvDocs})})}function saveKeyValues(view,docIdsToEmits,seq){var seqDocId="_local/lastSeq";return view.db.get(seqDocId)["catch"](defaultsTo({_id:seqDocId,seq:0})).then(function(lastSeqDoc){var docIds=Object.keys(docIdsToEmits);return Promise.all(docIds.map(function(docId){return getDocsToPersist(docId,view,docIdsToEmits)})).then(function(listOfDocsToPersist){var docsToPersist=[];listOfDocsToPersist.forEach(function(docList){docsToPersist=docsToPersist.concat(docList)});lastSeqDoc.seq=seq;docsToPersist.push(lastSeqDoc);return view.db.bulkDocs({docs:docsToPersist})})})}var updateView=utils.sequentialize(mainQueue,function(view){var mapResults;var doc;function emit(key,value){var output={id:doc._id,key:normalizeKey(key)};if(typeof value!=="undefined"&&value!==null){output.value=normalizeKey(value)}mapResults.push(output)}var mapFun;if(typeof view.mapFun==="function"&&view.mapFun.length===2){var origMap=view.mapFun;mapFun=function(doc){return origMap(doc,emit)}}else{mapFun=evalFunc(view.mapFun.toString(),emit,sum,log,Array.isArray,JSON.parse)}var currentSeq=view.seq||0;function processChange(docIdsToEmits,seq){return function(){return saveKeyValues(view,docIdsToEmits,seq)}}var queue=new TaskQueue;return new Promise(function(resolve,reject){function complete(){queue.finish().then(function(){view.seq=currentSeq;resolve()})}function processNextBatch(){view.sourceDB.changes({conflicts:true,include_docs:true,since:currentSeq,limit:CHANGES_BATCH_SIZE}).on("complete",function(response){var results=response.results;if(!results.length){return complete()}var docIdsToEmits={};for(var i=0,l=results.length;i<l;i++){var change=results[i];if(change.doc._id[0]!=="_"){mapResults=[];doc=change.doc;if(!doc._deleted){tryCode(view.sourceDB,mapFun,[doc])}mapResults.sort(sortByKeyThenValue);var indexableKeysToKeyValues={};var lastKey;for(var j=0,jl=mapResults.length;j<jl;j++){var obj=mapResults[j];var complexKey=[obj.key,obj.id];if(obj.key===lastKey){complexKey.push(j)}var indexableKey=toIndexableString(complexKey);indexableKeysToKeyValues[indexableKey]=obj;lastKey=obj.key}docIdsToEmits[change.doc._id]=indexableKeysToKeyValues}currentSeq=change.seq}queue.add(processChange(docIdsToEmits,currentSeq));if(results.length<CHANGES_BATCH_SIZE){return complete()}return processNextBatch()}).on("error",onError);function onError(err){reject(err)}}processNextBatch()})});function reduceView(view,results,options){if(options.group_level===0){delete options.group_level}var shouldGroup=options.group||options.group_level;var reduceFun;if(builtInReduce[view.reduceFun]){reduceFun=builtInReduce[view.reduceFun]}else{reduceFun=evalFunc(view.reduceFun.toString(),null,sum,log,Array.isArray,JSON.parse)}var groups=[];var lvl=options.group_level;results.forEach(function(e){var last=groups[groups.length-1];var key=shouldGroup?e.key:null;if(shouldGroup&&Array.isArray(key)&&typeof lvl==="number"){key=key.length>lvl?key.slice(0,lvl):key}if(last&&collate(last.key[0][0],key)===0){last.key.push([key,e.id]);last.value.push(e.value);return}groups.push({key:[[key,e.id]],value:[e.value]})});for(var i=0,len=groups.length;i<len;i++){var e=groups[i];var reduceTry=tryCode(view.sourceDB,reduceFun,[e.key,e.value,false]);e.value=reduceTry.error?null:reduceTry.output;e.key=e.key[0][0]}return{rows:sliceResults(groups,options.limit,options.skip)}}var queryView=utils.sequentialize(mainQueue,function(view,opts){var totalRows;var shouldReduce=view.reduceFun&&opts.reduce!==false;var skip=opts.skip||0;if(typeof opts.keys!=="undefined"&&!opts.keys.length){opts.limit=0;delete opts.keys}function fetchFromView(viewOpts){viewOpts.include_docs=true;return view.db.allDocs(viewOpts).then(function(res){totalRows=res.total_rows;return res.rows.map(function(result){if("value"in result.doc&&typeof result.doc.value==="object"&&result.doc.value!==null){var keys=Object.keys(result.doc.value).sort();var expectedKeys=["id","key","value"];if(!(keys<expectedKeys||keys>expectedKeys)){return result.doc.value}}var parsedKeyAndDocId=pouchCollate.parseIndexableString(result.doc._id);return{key:parsedKeyAndDocId[0],id:parsedKeyAndDocId[1],value:"value"in result.doc?result.doc.value:null}})})}function onMapResultsReady(results){var res;if(shouldReduce){res=reduceView(view,results,opts)}else{res={total_rows:totalRows,offset:skip,rows:results}}if(opts.include_docs){var getDocsPromises=results.map(function(row){var val=row.value;var docId=val&&typeof val==="object"&&val._id||row.id;return view.sourceDB.get(docId,{conflicts:opts.conflicts}).then(function(joinedDoc){row.doc=joinedDoc},function(){})});return Promise.all(getDocsPromises).then(function(){return res})}else{return res}}var flatten=function(array){return array.reduce(function(prev,cur){return prev.concat(cur)})};if(typeof opts.keys!=="undefined"){var keys=opts.keys;var fetchPromises=keys.map(function(key){var viewOpts={startkey:toIndexableString([key]),endkey:toIndexableString([key,{}])};return fetchFromView(viewOpts)});return Promise.all(fetchPromises).then(flatten).then(onMapResultsReady)}else{var viewOpts={descending:opts.descending};if(typeof opts.startkey!=="undefined"){viewOpts.startkey=opts.descending?toIndexableString([opts.startkey,{}]):toIndexableString([opts.startkey])}if(typeof opts.endkey!=="undefined"){var inclusiveEnd=opts.inclusive_end!==false;if(opts.descending){inclusiveEnd=!inclusiveEnd}viewOpts.endkey=toIndexableString(inclusiveEnd?[opts.endkey,{}]:[opts.endkey])}if(typeof opts.key!=="undefined"){var keyStart=toIndexableString([opts.key]);var keyEnd=toIndexableString([opts.key,{}]);if(viewOpts.descending){viewOpts.endkey=keyStart;viewOpts.startkey=keyEnd}else{viewOpts.startkey=keyStart;viewOpts.endkey=keyEnd}}if(!shouldReduce){if(typeof opts.limit==="number"){viewOpts.limit=opts.limit}viewOpts.skip=skip}return fetchFromView(viewOpts).then(onMapResultsReady)}});function httpViewCleanup(db){return db.request({method:"POST",url:"_view_cleanup"})}var localViewCleanup=utils.sequentialize(mainQueue,function(db){return db.get("_local/mrviews").then(function(metaDoc){var docsToViews={};Object.keys(metaDoc.views).forEach(function(fullViewName){var parts=parseViewName(fullViewName);var designDocName="_design/"+parts[0];var viewName=parts[1];docsToViews[designDocName]=docsToViews[designDocName]||{};docsToViews[designDocName][viewName]=true});var opts={keys:Object.keys(docsToViews),include_docs:true};return db.allDocs(opts).then(function(res){var viewsToStatus={};res.rows.forEach(function(row){var ddocName=row.key.substring(8);Object.keys(docsToViews[row.key]).forEach(function(viewName){var fullViewName=ddocName+"/"+viewName;if(!metaDoc.views[fullViewName]){fullViewName=viewName}var viewDBNames=Object.keys(metaDoc.views[fullViewName]);var statusIsGood=row.doc&&row.doc.views&&row.doc.views[viewName];viewDBNames.forEach(function(viewDBName){viewsToStatus[viewDBName]=viewsToStatus[viewDBName]||statusIsGood})})});var dbsToDelete=Object.keys(viewsToStatus).filter(function(viewDBName){return!viewsToStatus[viewDBName]});var destroyPromises=dbsToDelete.map(function(viewDBName){return db.constructor.destroy(viewDBName,{adapter:db.adapter})});return Promise.all(destroyPromises).then(function(){return{ok:true}})})},defaultsTo({ok:true}))});exports.viewCleanup=utils.callbackify(function(){var db=this;if(db.type()==="http"){return httpViewCleanup(db)}return localViewCleanup(db)});function queryPromised(db,fun,opts){if(db.type()==="http"){return httpQuery(db,fun,opts)}if(typeof fun!=="string"){checkQueryParseError(opts,fun);var createViewOpts={db:db,viewName:"temp_view/temp_view",map:fun.map,reduce:fun.reduce,temporary:true};tempViewQueue.add(function(){return createView(createViewOpts).then(function(view){function cleanup(){return view.db.destroy()}return utils.fin(updateView(view).then(function(){return queryView(view,opts)}),cleanup)})});return tempViewQueue.finish()}else{var fullViewName=fun;var parts=parseViewName(fullViewName);var designDocName=parts[0];var viewName=parts[1];return db.get("_design/"+designDocName).then(function(doc){var fun=doc.views&&doc.views[viewName];if(!fun||typeof fun.map!=="string"){throw new NotFoundError("ddoc "+designDocName+" has no view named "+viewName)}checkQueryParseError(opts,fun);var createViewOpts={db:db,viewName:fullViewName,map:fun.map,reduce:fun.reduce};return createView(createViewOpts).then(function(view){if(opts.stale==="ok"||opts.stale==="update_after"){if(opts.stale==="update_after"){process.nextTick(function(){updateView(view)})}return queryView(view,opts)}else{return updateView(view).then(function(){return queryView(view,opts)})}})})}}exports.query=function(fun,opts,callback){if(typeof opts==="function"){callback=opts;opts={}}opts=utils.extend(true,{},opts);if(typeof fun==="function"){fun={map:fun}}var db=this;var promise=Promise.resolve().then(function(){return queryPromised(db,fun,opts)});utils.promisedCallback(promise,callback);return promise};function QueryParseError(message){this.status=400;this.name="query_parse_error";this.message=message;this.error=true;try{Error.captureStackTrace(this,QueryParseError)}catch(e){}}utils.inherits(QueryParseError,Error);function NotFoundError(message){this.status=404;this.name="not_found";this.message=message;this.error=true;try{Error.captureStackTrace(this,NotFoundError)}catch(e){}}utils.inherits(NotFoundError,Error)}).call(this,require("_process"))},{"./create-view":51,"./evalfunc":52,"./taskqueue":56,"./utils":58,_process:3,"pouchdb-collate":54}],54:[function(require,module,exports){"use strict";var MIN_MAGNITUDE=-324;var MAGNITUDE_DIGITS=3;var SEP="";var utils=require("./utils");exports.collate=function(a,b){if(a===b){return 0}a=exports.normalizeKey(a);b=exports.normalizeKey(b);var ai=collationIndex(a);var bi=collationIndex(b);if(ai-bi!==0){return ai-bi}if(a===null){return 0}switch(typeof a){case"number":return a-b;case"boolean":return a===b?0:a<b?-1:1;case"string":return stringCollate(a,b)}return Array.isArray(a)?arrayCollate(a,b):objectCollate(a,b)};exports.normalizeKey=function(key){switch(typeof key){case"undefined":return null;case"number":if(key===Infinity||key===-Infinity||isNaN(key)){return null}return key;case"object":var origKey=key;if(Array.isArray(key)){var len=key.length;key=new Array(len);for(var i=0;i<len;i++){key[i]=exports.normalizeKey(origKey[i])}}else if(key instanceof Date){return key.toJSON()}else if(key!==null){key={};for(var k in origKey){if(origKey.hasOwnProperty(k)){var val=origKey[k];if(typeof val!=="undefined"){key[k]=exports.normalizeKey(val)}}}}}return key};function indexify(key){if(key!==null){switch(typeof key){case"boolean":return key?1:0;case"number":return numToIndexableString(key);case"string":return key.replace(/\u0002/g,"").replace(/\u0001/g,"").replace(/\u0000/g,"");case"object":var isArray=Array.isArray(key);var arr=isArray?key:Object.keys(key);var i=-1;var len=arr.length;var result="";if(isArray){while(++i<len){result+=exports.toIndexableString(arr[i])}}else{while(++i<len){var objKey=arr[i];result+=exports.toIndexableString(objKey)+exports.toIndexableString(key[objKey])}}return result}}return""}exports.toIndexableString=function(key){var zero="\x00";key=exports.normalizeKey(key);return collationIndex(key)+SEP+indexify(key)+zero};function parseNumber(str,i){var originalIdx=i;var num;var zero=str[i]==="1";if(zero){num=0;i++}else{var neg=str[i]==="0";i++;var numAsString="";var magAsString=str.substring(i,i+MAGNITUDE_DIGITS);var magnitude=parseInt(magAsString,10)+MIN_MAGNITUDE;if(neg){magnitude=-magnitude}i+=MAGNITUDE_DIGITS;while(true){var ch=str[i];if(ch==="\x00"){break}else{numAsString+=ch}i++}numAsString=numAsString.split(".");if(numAsString.length===1){num=parseInt(numAsString,10)}else{num=parseFloat(numAsString[0]+"."+numAsString[1])}if(neg){num=num-10}if(magnitude!==0){num=parseFloat(num+"e"+magnitude)}}return{num:num,length:i-originalIdx}}function pop(stack,metaStack){var obj=stack.pop();if(metaStack.length){var lastMetaElement=metaStack[metaStack.length-1];if(obj===lastMetaElement.element){metaStack.pop();lastMetaElement=metaStack[metaStack.length-1]}var element=lastMetaElement.element;var lastElementIndex=lastMetaElement.index;if(Array.isArray(element)){element.push(obj)}else if(lastElementIndex===stack.length-2){var key=stack.pop();element[key]=obj}else{stack.push(obj)}}}exports.parseIndexableString=function(str){var stack=[];var metaStack=[];var i=0;while(true){var collationIndex=str[i++];if(collationIndex==="\x00"){if(stack.length===1){return stack.pop()}else{pop(stack,metaStack);continue}}switch(collationIndex){case"1":stack.push(null);break;case"2":stack.push(str[i]==="1");i++;break;case"3":var parsedNum=parseNumber(str,i);stack.push(parsedNum.num);i+=parsedNum.length;break;case"4":var parsedStr="";while(true){var ch=str[i];if(ch==="\x00"){break}parsedStr+=ch;i++}parsedStr=parsedStr.replace(/\u0001\u0001/g,"\x00").replace(/\u0001\u0002/g,"").replace(/\u0002\u0002/g,"");stack.push(parsedStr);break;case"5":var arrayElement={element:[],index:stack.length};stack.push(arrayElement.element);metaStack.push(arrayElement);break;case"6":var objElement={element:{},index:stack.length};stack.push(objElement.element);metaStack.push(objElement);break;default:throw new Error("bad collationIndex or unexpectedly reached end of input: "+collationIndex)}}};function arrayCollate(a,b){var len=Math.min(a.length,b.length);for(var i=0;i<len;i++){var sort=exports.collate(a[i],b[i]);if(sort!==0){return sort}}return a.length===b.length?0:a.length>b.length?1:-1}function stringCollate(a,b){return a===b?0:a>b?1:-1}function objectCollate(a,b){var ak=Object.keys(a),bk=Object.keys(b);var len=Math.min(ak.length,bk.length);for(var i=0;i<len;i++){var sort=exports.collate(ak[i],bk[i]);if(sort!==0){return sort}sort=exports.collate(a[ak[i]],b[bk[i]]);if(sort!==0){return sort}}return ak.length===bk.length?0:ak.length>bk.length?1:-1}function collationIndex(x){var id=["boolean","number","string","object"];var idx=id.indexOf(typeof x);if(~idx){if(x===null){return 1}if(Array.isArray(x)){return 5}return idx<3?idx+2:idx+3}if(Array.isArray(x)){return 5}}function numToIndexableString(num){if(num===0){return"1"}var expFormat=num.toExponential().split(/e\+?/);var magnitude=parseInt(expFormat[1],10);var neg=num<0;var result=neg?"0":"2";var magForComparison=(neg?-magnitude:magnitude)-MIN_MAGNITUDE;var magString=utils.padLeft(magForComparison.toString(),"0",MAGNITUDE_DIGITS);result+=SEP+magString;var factor=Math.abs(parseFloat(expFormat[0]));if(neg){factor=10-factor}var factorStr=factor.toFixed(20);factorStr=factorStr.replace(/\.?0+$/,"");result+=SEP+factorStr;return result}},{"./utils":55}],55:[function(require,module,exports){"use strict";function pad(str,padWith,upToLength){var padding="";var targetLength=upToLength-str.length;while(padding.length<targetLength){padding+=padWith}return padding}exports.padLeft=function(str,padWith,upToLength){var padding=pad(str,padWith,upToLength);return padding+str};exports.padRight=function(str,padWith,upToLength){var padding=pad(str,padWith,upToLength);return str+padding};exports.stringLexCompare=function(a,b){var aLen=a.length;var bLen=b.length;var i;for(i=0;i<aLen;i++){if(i===bLen){return 1}var aChar=a.charAt(i);var bChar=b.charAt(i); | |
if(aChar!==bChar){return aChar<bChar?-1:1}}if(aLen<bLen){return-1}return 0};exports.intToDecimalForm=function(int){var isNeg=int<0;var result="";do{var remainder=isNeg?-Math.ceil(int%10):Math.floor(int%10);result=remainder+result;int=isNeg?Math.ceil(int/10):Math.floor(int/10)}while(int);if(isNeg&&result!=="0"){result="-"+result}return result}},{}],56:[function(require,module,exports){"use strict";var Promise=require("./utils").Promise;function TaskQueue(){this.promise=new Promise(function(fulfill){fulfill()})}TaskQueue.prototype.add=function(promiseFactory){this.promise=this.promise["catch"](function(){}).then(function(){return promiseFactory()});return this.promise};TaskQueue.prototype.finish=function(){return this.promise};module.exports=TaskQueue},{"./utils":58}],57:[function(require,module,exports){"use strict";var Promise=require("./utils").Promise;function upsert(db,docId,diffFun){return new Promise(function(fulfill,reject){if(docId&&typeof docId==="object"){docId=docId._id}if(typeof docId!=="string"){return reject(new Error("doc id is required"))}db.get(docId,function(err,doc){if(err){if(err.status!==404){return reject(err)}return fulfill(tryAndPut(db,diffFun({_id:docId}),diffFun))}var newDoc=diffFun(doc);if(!newDoc){return fulfill(doc)}fulfill(tryAndPut(db,newDoc,diffFun))})})}function tryAndPut(db,doc,diffFun){return db.put(doc)["catch"](function(err){if(err.status!==409){throw err}return upsert(db,doc,diffFun)})}module.exports=upsert},{"./utils":58}],58:[function(require,module,exports){(function(process,global){"use strict";if(typeof global.Promise==="function"){exports.Promise=global.Promise}else{exports.Promise=require("lie")}exports.uniq=function(arr){var map={};arr.forEach(function(element){map[element]=true});return Object.keys(map)};exports.inherits=require("inherits");exports.extend=require("pouchdb-extend");var argsarray=require("argsarray");exports.promisedCallback=function(promise,callback){if(callback){promise.then(function(res){process.nextTick(function(){callback(null,res)})},function(reason){process.nextTick(function(){callback(reason)})})}return promise};exports.callbackify=function(fun){return argsarray(function(args){var cb=args.pop();var promise=fun.apply(this,args);if(typeof cb==="function"){exports.promisedCallback(promise,cb)}return promise})};exports.fin=function(promise,cb){return promise.then(function(res){var promise2=cb();if(typeof promise2.then==="function"){return promise2.then(function(){return res})}return res},function(reason){var promise2=cb();if(typeof promise2.then==="function"){return promise2.then(function(){throw reason})}throw reason})};exports.sequentialize=function(queue,promiseFactory){return function(){var args=arguments;var that=this;return queue.add(function(){return promiseFactory.apply(that,args)})}};var crypto=require("crypto");var Md5=require("spark-md5");exports.MD5=function(string){if(!process.browser){return crypto.createHash("md5").update(string).digest("hex")}else{return Md5.hash(string)}}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{_process:3,argsarray:30,crypto:1,inherits:31,lie:35,"pouchdb-extend":50,"spark-md5":59}],59:[function(require,module,exports){(function(factory){if(typeof exports==="object"){module.exports=factory()}else if(typeof define==="function"&&define.amd){define(factory)}else{var glob;try{glob=window}catch(e){glob=self}glob.SparkMD5=factory()}})(function(undefined){"use strict";var add32=function(a,b){return a+b&4294967295},cmn=function(q,a,b,x,s,t){a=add32(add32(a,q),add32(x,t));return add32(a<<s|a>>>32-s,b)},ff=function(a,b,c,d,x,s,t){return cmn(b&c|~b&d,a,b,x,s,t)},gg=function(a,b,c,d,x,s,t){return cmn(b&d|c&~d,a,b,x,s,t)},hh=function(a,b,c,d,x,s,t){return cmn(b^c^d,a,b,x,s,t)},ii=function(a,b,c,d,x,s,t){return cmn(c^(b|~d),a,b,x,s,t)},md5cycle=function(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])},md5blk=function(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},md5blk_array=function(a){var md5blks=[],i;for(i=0;i<64;i+=4){md5blks[i>>2]=a[i]+(a[i+1]<<8)+(a[i+2]<<16)+(a[i+3]<<24)}return md5blks},md51=function(s){var n=s.length,state=[1732584193,-271733879,-1732584194,271733878],i,length,tail,tmp,lo,hi;for(i=64;i<=n;i+=64){md5cycle(state,md5blk(s.substring(i-64,i)))}s=s.substring(i-64);length=s.length;tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i=0;i<length;i+=1){tail[i>>2]|=s.charCodeAt(i)<<(i%4<<3)}tail[i>>2]|=128<<(i%4<<3);if(i>55){md5cycle(state,tail);for(i=0;i<16;i+=1){tail[i]=0}}tmp=n*8;tmp=tmp.toString(16).match(/(.*?)(.{0,8})$/);lo=parseInt(tmp[2],16);hi=parseInt(tmp[1],16)||0;tail[14]=lo;tail[15]=hi;md5cycle(state,tail);return state},md51_array=function(a){var n=a.length,state=[1732584193,-271733879,-1732584194,271733878],i,length,tail,tmp,lo,hi;for(i=64;i<=n;i+=64){md5cycle(state,md5blk_array(a.subarray(i-64,i)))}a=i-64<n?a.subarray(i-64):new Uint8Array(0);length=a.length;tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i=0;i<length;i+=1){tail[i>>2]|=a[i]<<(i%4<<3)}tail[i>>2]|=128<<(i%4<<3);if(i>55){md5cycle(state,tail);for(i=0;i<16;i+=1){tail[i]=0}}tmp=n*8;tmp=tmp.toString(16).match(/(.*?)(.{0,8})$/);lo=parseInt(tmp[2],16);hi=parseInt(tmp[1],16)||0;tail[14]=lo;tail[15]=hi;md5cycle(state,tail);return state},hex_chr=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],rhex=function(n){var s="",j;for(j=0;j<4;j+=1){s+=hex_chr[n>>j*8+4&15]+hex_chr[n>>j*8&15]}return s},hex=function(x){var i;for(i=0;i<x.length;i+=1){x[i]=rhex(x[i])}return x.join("")},md5=function(s){return hex(md51(s))},SparkMD5=function(){this.reset()};if(md5("hello")!=="5d41402abc4b2a76b9719d911017c592"){add32=function(x,y){var lsw=(x&65535)+(y&65535),msw=(x>>16)+(y>>16)+(lsw>>16);return msw<<16|lsw&65535}}SparkMD5.prototype.append=function(str){if(/[\u0080-\uFFFF]/.test(str)){str=unescape(encodeURIComponent(str))}this.appendBinary(str);return this};SparkMD5.prototype.appendBinary=function(contents){this._buff+=contents;this._length+=contents.length;var length=this._buff.length,i;for(i=64;i<=length;i+=64){md5cycle(this._state,md5blk(this._buff.substring(i-64,i)))}this._buff=this._buff.substr(i-64);return this};SparkMD5.prototype.end=function(raw){var buff=this._buff,length=buff.length,i,tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],ret;for(i=0;i<length;i+=1){tail[i>>2]|=buff.charCodeAt(i)<<(i%4<<3)}this._finish(tail,length);ret=!!raw?this._state:hex(this._state);this.reset();return ret};SparkMD5.prototype._finish=function(tail,length){var i=length,tmp,lo,hi;tail[i>>2]|=128<<(i%4<<3);if(i>55){md5cycle(this._state,tail);for(i=0;i<16;i+=1){tail[i]=0}}tmp=this._length*8;tmp=tmp.toString(16).match(/(.*?)(.{0,8})$/);lo=parseInt(tmp[2],16);hi=parseInt(tmp[1],16)||0;tail[14]=lo;tail[15]=hi;md5cycle(this._state,tail)};SparkMD5.prototype.reset=function(){this._buff="";this._length=0;this._state=[1732584193,-271733879,-1732584194,271733878];return this};SparkMD5.prototype.destroy=function(){delete this._state;delete this._buff;delete this._length};SparkMD5.hash=function(str,raw){if(/[\u0080-\uFFFF]/.test(str)){str=unescape(encodeURIComponent(str))}var hash=md51(str);return!!raw?hash:hex(hash)};SparkMD5.hashBinary=function(content,raw){var hash=md51(content);return!!raw?hash:hex(hash)};SparkMD5.ArrayBuffer=function(){this.reset()};SparkMD5.ArrayBuffer.prototype.append=function(arr){var buff=this._concatArrayBuffer(this._buff,arr),length=buff.length,i;this._length+=arr.byteLength;for(i=64;i<=length;i+=64){md5cycle(this._state,md5blk_array(buff.subarray(i-64,i)))}this._buff=i-64<length?buff.subarray(i-64):new Uint8Array(0);return this};SparkMD5.ArrayBuffer.prototype.end=function(raw){var buff=this._buff,length=buff.length,tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],i,ret;for(i=0;i<length;i+=1){tail[i>>2]|=buff[i]<<(i%4<<3)}this._finish(tail,length);ret=!!raw?this._state:hex(this._state);this.reset();return ret};SparkMD5.ArrayBuffer.prototype._finish=SparkMD5.prototype._finish;SparkMD5.ArrayBuffer.prototype.reset=function(){this._buff=new Uint8Array(0);this._length=0;this._state=[1732584193,-271733879,-1732584194,271733878];return this};SparkMD5.ArrayBuffer.prototype.destroy=SparkMD5.prototype.destroy;SparkMD5.ArrayBuffer.prototype._concatArrayBuffer=function(first,second){var firstLength=first.length,result=new Uint8Array(firstLength+second.byteLength);result.set(first);result.set(new Uint8Array(second),firstLength);return result};SparkMD5.ArrayBuffer.hash=function(arr,raw){var hash=md51_array(new Uint8Array(arr));return!!raw?hash:hex(hash)};return SparkMD5})},{}],60:[function(require,module,exports){"use strict";exports.stringify=function stringify(input){var queue=[];queue.push({obj:input});var res="";var next,obj,prefix,val,i,arrayPrefix,keys,k,key,value,objPrefix;while(next=queue.pop()){obj=next.obj;prefix=next.prefix||"";val=next.val||"";res+=prefix;if(val){res+=val}else if(typeof obj!=="object"){res+=typeof obj==="undefined"?null:JSON.stringify(obj)}else if(obj===null){res+="null"}else if(Array.isArray(obj)){queue.push({val:"]"});for(i=obj.length-1;i>=0;i--){arrayPrefix=i===0?"":",";queue.push({obj:obj[i],prefix:arrayPrefix})}queue.push({val:"["})}else{keys=[];for(k in obj){if(obj.hasOwnProperty(k)){keys.push(k)}}queue.push({val:"}"});for(i=keys.length-1;i>=0;i--){key=keys[i];value=obj[key];objPrefix=i>0?",":"";objPrefix+=JSON.stringify(key)+":";queue.push({obj:value,prefix:objPrefix})}queue.push({val:"{"})}}return res};function pop(obj,stack,metaStack){var lastMetaElement=metaStack[metaStack.length-1];if(obj===lastMetaElement.element){metaStack.pop();lastMetaElement=metaStack[metaStack.length-1]}var element=lastMetaElement.element;var lastElementIndex=lastMetaElement.index;if(Array.isArray(element)){element.push(obj)}else if(lastElementIndex===stack.length-2){var key=stack.pop();element[key]=obj}else{stack.push(obj)}}exports.parse=function(str){var stack=[];var metaStack=[];var i=0;var collationIndex,parsedNum,numChar;var parsedString,lastCh,numConsecutiveSlashes,ch;var arrayElement,objElement;while(true){collationIndex=str[i++];if(collationIndex==="}"||collationIndex==="]"||typeof collationIndex==="undefined"){if(stack.length===1){return stack.pop()}else{pop(stack.pop(),stack,metaStack);continue}}switch(collationIndex){case" ":case" ":case"\n":case":":case",":break;case"n":i+=3;pop(null,stack,metaStack);break;case"t":i+=3;pop(true,stack,metaStack);break;case"f":i+=4;pop(false,stack,metaStack);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"-":parsedNum="";i--;while(true){numChar=str[i++];if(/[\d\.\-e\+]/.test(numChar)){parsedNum+=numChar}else{i--;break}}pop(parseFloat(parsedNum),stack,metaStack);break;case'"':parsedString="";lastCh=void 0;numConsecutiveSlashes=0;while(true){ch=str[i++];if(ch!=='"'||lastCh==="\\"&&numConsecutiveSlashes%2===1){parsedString+=ch;lastCh=ch;if(lastCh==="\\"){numConsecutiveSlashes++}else{numConsecutiveSlashes=0}}else{break}}pop(JSON.parse('"'+parsedString+'"'),stack,metaStack);break;case"[":arrayElement={element:[],index:stack.length};stack.push(arrayElement.element);metaStack.push(arrayElement);break;case"{":objElement={element:{},index:stack.length};stack.push(objElement.element);metaStack.push(objElement);break;default:throw new Error("unexpectedly reached end of input: "+collationIndex)}}}},{}],pouchdb:[function(require,module,exports){(function(process){"use strict";var PouchDB=require("./setup");module.exports=PouchDB;PouchDB.ajax=require("./deps/ajax");PouchDB.extend=require("pouchdb-extend");PouchDB.utils=require("./utils");PouchDB.Errors=require("./deps/errors");PouchDB.replicate=require("./replicate").replicate;PouchDB.sync=require("./sync");PouchDB.version=require("./version");var httpAdapter=require("./adapters/http");PouchDB.adapter("http",httpAdapter);PouchDB.adapter("https",httpAdapter);PouchDB.adapter("idb",require("./adapters/idb"));PouchDB.adapter("websql",require("./adapters/websql"));PouchDB.plugin(require("pouchdb-mapreduce"));if(!process.browser){var ldbAdapter=require("./adapters/leveldb");PouchDB.adapter("ldb",ldbAdapter);PouchDB.adapter("leveldb",ldbAdapter)}}).call(this,require("_process"))},{"./adapters/http":5,"./adapters/idb":6,"./adapters/leveldb":1,"./adapters/websql":8,"./deps/ajax":12,"./deps/errors":15,"./replicate":24,"./setup":25,"./sync":26,"./utils":28,"./version":29,_process:3,"pouchdb-extend":50,"pouchdb-mapreduce":53}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);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}({"br-jquery":[function(require,module,exports){(function(){function create(window){var location,navigator,XMLHttpRequest;(function(window,undefined){var document=window.document,navigator=window.navigator,location=window.location;var jQuery=function(){var jQuery=function(selector,context){return new jQuery.fn.init(selector,context,rootjQuery)},_jQuery=window.jQuery,_$=window.$,rootjQuery,quickExpr=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,rnotwhite=/\S/,trimLeft=/^\s+/,trimRight=/\s+$/,rsingleTag=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,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,rwebkit=/(webkit)[ \/]([\w.]+)/,ropera=/(opera)(?:.*version)?[ \/]([\w.]+)/,rmsie=/(msie) ([\w.]+)/,rmozilla=/(mozilla)(?:.*? rv:([\w.]+))?/,rdashAlpha=/-([a-z]|[0-9])/gi,rmsPrefix=/^-ms-/,fcamelCase=function(all,letter){return(letter+"").toUpperCase()},userAgent=navigator.userAgent,browserMatch,readyList,DOMContentLoaded,toString=Object.prototype.toString,hasOwn=Object.prototype.hasOwnProperty,push=Array.prototype.push,slice=Array.prototype.slice,trim=String.prototype.trim,indexOf=Array.prototype.indexOf,class2type={};jQuery.fn=jQuery.prototype={constructor:jQuery,init:function(selector,context,rootjQuery){var match,elem,ret,doc;if(!selector){return this}if(selector.nodeType){this.context=this[0]=selector;this.length=1;return this}if(selector==="body"&&!context&&document.body){this.context=document;this[0]=document.body;this.selector=selector;this.length=1;return this}if(typeof selector==="string"){if(selector.charAt(0)==="<"&&selector.charAt(selector.length-1)===">"&&selector.length>=3){match=[null,selector,null]}else{match=quickExpr.exec(selector)}if(match&&(match[1]||!context)){if(match[1]){context=context instanceof jQuery?context[0]:context;doc=context?context.ownerDocument||context:document;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)}else{elem=document.getElementById(match[2]);if(elem&&elem.parentNode){if(elem.id!==match[2]){return rootjQuery.find(selector)}this.length=1;this[0]=elem}this.context=document;this.selector=selector;return this}}else if(!context||context.jquery){return(context||rootjQuery).find(selector)}else{return this.constructor(context).find(selector)}}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)},selector:"",jquery:"1.7.2",length:0,size:function(){return this.length},toArray:function(){return slice.call(this,0)},get:function(num){return num==null?this.toArray():num<0?this[this.length+num]:this[num]},pushStack:function(elems,name,selector){var ret=this.constructor();if(jQuery.isArray(elems)){push.apply(ret,elems)}else{jQuery.merge(ret,elems)}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 ret},each:function(callback,args){return jQuery.each(this,callback,args)},ready:function(fn){jQuery.bindReady();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)},push:push,sort:[].sort,splice:[].splice};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;if(typeof target==="boolean"){deep=target;target=arguments[1]||{};i=2}if(typeof target!=="object"&&!jQuery.isFunction(target)){target={}}if(length===i){target=this;--i}for(;i<length;i++){if((options=arguments[i])!=null){for(name in options){src=target[name];copy=options[name];if(target===copy){continue}if(deep&©&&(jQuery.isPlainObject(copy)||(copyIsArray=jQuery.isArray(copy)))){if(copyIsArray){copyIsArray=false;clone=src&&jQuery.isArray(src)?src:[]}else{clone=src&&jQuery.isPlainObject(src)?src:{}}target[name]=jQuery.extend(deep,clone,copy)}else if(copy!==undefined){target[name]=copy}}}}return target};jQuery.extend({noConflict:function(deep){if(window.$===jQuery){window.$=_$}if(deep&&window.jQuery===jQuery){window.jQuery=_jQuery}return jQuery},isReady:false,readyWait:1,holdReady:function(hold){if(hold){jQuery.readyWait++}else{jQuery.ready(true)}},ready:function(wait){if(wait===true&&!--jQuery.readyWait||wait!==true&&!jQuery.isReady){if(!document.body){return setTimeout(jQuery.ready,1)}jQuery.isReady=true;if(wait!==true&&--jQuery.readyWait>0){return}readyList.fireWith(document,[jQuery]);if(jQuery.fn.trigger){jQuery(document).trigger("ready").off("ready")}}},bindReady:function(){if(readyList){return}readyList=jQuery.Callbacks("once memory");if(document.readyState==="complete"){return setTimeout(jQuery.ready,1)}if(document.addEventListener){document.addEventListener("DOMContentLoaded",DOMContentLoaded,false);window.addEventListener("load",jQuery.ready,false)}else if(document.attachEvent){document.attachEvent("onreadystatechange",DOMContentLoaded);window.attachEvent("onload",jQuery.ready);var toplevel=false;try{toplevel=window.frameElement==null}catch(e){}if(document.documentElement.doScroll&&toplevel){doScrollCheck()}}},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){if(!obj||jQuery.type(obj)!=="object"||obj.nodeType||jQuery.isWindow(obj)){return false}try{if(obj.constructor&&!hasOwn.call(obj,"constructor")&&!hasOwn.call(obj.constructor.prototype,"isPrototypeOf")){return false}}catch(e){return false}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}data=jQuery.trim(data);if(window.JSON&&window.JSON.parse){return window.JSON.parse(data)}if(rvalidchars.test(data.replace(rvalidescape,"@").replace(rvalidtokens,"]").replace(rvalidbraces,""))){return new Function("return "+data)()}jQuery.error("Invalid JSON: "+data)},parseXML:function(data){if(typeof data!=="string"||!data){return null}var xml,tmp;try{if(window.DOMParser){tmp=new DOMParser;xml=tmp.parseFromString(data,"text/xml")}else{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(){},globalEval:function(data){if(data&&rnotwhite.test(data)){(window.execScript||function(data){window["eval"].call(window,data)})(data)}},camelCase:function(string){return string.replace(rmsPrefix,"ms-").replace(rdashAlpha,fcamelCase)},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()===name.toUpperCase()},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}}}}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},trim:trim?function(text){return text==null?"":trim.call(text)}:function(text){return text==null?"":text.toString().replace(trimLeft,"").replace(trimRight,"")},makeArray:function(array,results){var ret=results||[];if(array!=null){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++){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;for(var i=0,length=elems.length;i<length;i++){retVal=!!callback(elems[i],i);if(inv!==retVal){ret.push(elems[i])}}return ret},map:function(elems,callback,arg){var value,key,ret=[],i=0,length=elems.length,isArray=elems instanceof jQuery||length!==undefined&&typeof length==="number"&&(length>0&&elems[0]&&elems[length-1]||length===0||jQuery.isArray(elems));if(isArray){for(;i<length;i++){value=callback(elems[i],i,arg);if(value!=null){ret[ret.length]=value}}}else{for(key in elems){value=callback(elems[key],key,arg);if(value!=null){ret[ret.length]=value}}}return ret.concat.apply([],ret)},guid:1,proxy:function(fn,context){if(typeof context==="string"){var tmp=fn[context];context=fn;fn=tmp}if(!jQuery.isFunction(fn)){return undefined}var args=slice.call(arguments,2),proxy=function(){return fn.apply(context,args.concat(slice.call(arguments)))};proxy.guid=fn.guid=fn.guid||proxy.guid||jQuery.guid++;return proxy},access:function(elems,fn,key,value,chainable,emptyGet,pass){var exec,bulk=key==null,i=0,length=elems.length;if(key&&typeof key==="object"){for(i in key){jQuery.access(elems,fn,i,key[i],1,emptyGet,value)}chainable=1}else if(value!==undefined){exec=pass===undefined&&jQuery.isFunction(value);if(bulk){if(exec){exec=fn;fn=function(elem,key,value){return exec.call(jQuery(elem),value)}}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:bulk?fn.call(elems):length?fn(elems[0],key):emptyGet},now:function(){return(new Date).getTime()},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:{}});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}if(jQuery.browser.webkit){jQuery.browser.safari=true}if(rnotwhite.test(" ")){trimLeft=/^[\s\xA0]+/;trimRight=/[\s\xA0]+$/}rootjQuery=jQuery(document);if(document.addEventListener){DOMContentLoaded=function(){document.removeEventListener("DOMContentLoaded",DOMContentLoaded,false);jQuery.ready()}}else if(document.attachEvent){DOMContentLoaded=function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",DOMContentLoaded);jQuery.ready()}}}function doScrollCheck(){if(jQuery.isReady){return}try{document.documentElement.doScroll("left")}catch(e){setTimeout(doScrollCheck,1);return}jQuery.ready()}return jQuery}();var flagsCache={};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}jQuery.Callbacks=function(flags){flags=flags?flagsCache[flags]||createFlags(flags):{};var list=[],stack=[],memory,fired,firing,firingStart,firingLength,firingIndex,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"){add(elem)}else if(type==="function"){if(!flags.unique||!self.has(elem)){list.push(elem)}}}},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;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=[]}}},self={add:function(){if(list){var length=list.length;add(arguments);if(firing){firingLength=list.length}else if(memory&&memory!==true){firingStart=length;fire(memory[0],memory[1])}}return this},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]){if(firing){if(i<=firingLength){firingLength--;if(i<=firingIndex){firingIndex--}}}list.splice(i--,1);if(flags.unique){break}}}}}return this},has:function(fn){if(list){var i=0,length=list.length;for(;i<length;i++){if(fn===list[i]){return true}}}return false},empty:function(){list=[];return this},disable:function(){list=stack=memory=undefined;return this},disabled:function(){return!list},lock:function(){stack=undefined;if(!memory||memory===true){self.disable()}return this},locked:function(){return!stack},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},fire:function(){self.fireWith(this,arguments);return this},fired:function(){return!!fired}};return self};var 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},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()},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}deferred.done(function(){state="resolved"},failList.disable,progressList.lock).fail(function(){state="rejected"},doneList.disable,progressList.lock);if(func){func.call(deferred,deferred)}return deferred},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;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];if(!all||!all.length||!a){return{}}select=document.createElement("select");opt=select.appendChild(document.createElement("option"));input=div.getElementsByTagName("input")[0];support={leadingWhitespace:div.firstChild.nodeType===3,tbody:!div.getElementsByTagName("tbody").length,htmlSerialize:!!div.getElementsByTagName("link").length,style:/top/.test(a.getAttribute("style")),hrefNormalized:a.getAttribute("href")==="/a",opacity:/^0.55/.test(a.style.opacity),cssFloat:!!a.style.cssFloat,checkOn:input.value==="on",optSelected:opt.selected,getSetAttribute:div.className!=="t",enctype:!!document.createElement("form").enctype,html5Clone:document.createElement("nav").cloneNode(true).outerHTML!=="<:nav></:nav>",submitBubbles:true,changeBubbles:true,focusinBubbles:false,deleteExpando:true,noCloneEvent:true,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableMarginRight:true,pixelMargin:true};jQuery.boxModel=support.boxModel=document.compatMode==="CSS1Compat";input.checked=true;support.noCloneChecked=input.cloneNode(true).checked;select.disabled=true;support.optDisabled=!opt.disabled;try{delete div.test}catch(e){support.deleteExpando=false}if(!div.addEventListener&&div.attachEvent&&div.fireEvent){div.attachEvent("onclick",function(){support.noCloneEvent=false});div.cloneNode(true).fireEvent("onclick")}input=document.createElement("input");input.value="t";input.setAttribute("type","radio");support.radioValue=input.value==="t";input.setAttribute("checked","checked");input.setAttribute("name","t");div.appendChild(input);fragment=document.createDocumentFragment();fragment.appendChild(div.lastChild);support.checkClone=fragment.cloneNode(true).cloneNode(true).lastChild.checked;support.appendChecked=input.checked;fragment.removeChild(input);fragment.appendChild(div);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);fragment=select=opt=div=input=null;jQuery(function(){var container,outer,inner,table,td,offsetSupport,marginDiv,conMarginTop,style,html,positionTopLeftWidthHeight,paddingMarginBorderVisibility,paddingMarginBorder,body=document.getElementsByTagName("body")[0];if(!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);div=document.createElement("div");container.appendChild(div);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";support.reliableHiddenOffsets=isSupported&&tds[0].offsetHeight===0;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"){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;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";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:{},uuid:0,expando:"jQuery"+(jQuery.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:true,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){if(!jQuery.acceptData(elem)){return}var privateCache,thisCache,ret,internalKey=jQuery.expando,getByName=typeof name==="string",isNode=elem.nodeType,cache=isNode?jQuery.cache:elem,id=isNode?elem[internalKey]:elem[internalKey]&&internalKey,isEvents=name==="events";if((!id||!cache[id]||!isEvents&&!pvt&&!cache[id].data)&&getByName&&data===undefined){return}if(!id){if(isNode){elem[internalKey]=id=++jQuery.uuid}else{id=internalKey}}if(!cache[id]){cache[id]={};if(!isNode){cache[id].toJSON=jQuery.noop}}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];if(!pvt){if(!thisCache.data){thisCache.data={}}thisCache=thisCache.data}if(data!==undefined){thisCache[jQuery.camelCase(name)]=data}if(isEvents&&!thisCache[name]){return privateCache.events}if(getByName){ret=thisCache[name];if(ret==null){ret=thisCache[jQuery.camelCase(name)]}}else{ret=thisCache}return ret},removeData:function(elem,name,pvt){if(!jQuery.acceptData(elem)){return}var thisCache,i,l,internalKey=jQuery.expando,isNode=elem.nodeType,cache=isNode?jQuery.cache:elem,id=isNode?elem[internalKey]:internalKey;if(!cache[id]){return}if(name){thisCache=pvt?cache[id]:cache[id].data;if(thisCache){if(!jQuery.isArray(name)){if(name in thisCache){name=[name]}else{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(!(pvt?isEmptyDataObject:jQuery.isEmptyObject)(thisCache)){return}}}if(!pvt){delete cache[id].data;if(!isEmptyDataObject(cache[id])){return}}if(jQuery.support.deleteExpando||!cache.setInterval){delete cache[id]}else{cache[id]=null}if(isNode){if(jQuery.support.deleteExpando){delete elem[internalKey]}else if(elem.removeAttribute){elem.removeAttribute(internalKey)}else{elem[internalKey]=null}}},_data:function(elem,name,data){return jQuery.data(elem,name,data,true)},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;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}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]]);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(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){}jQuery.data(elem,key,data)}else{data=undefined}}return data}function isEmptyDataObject(obj){for(var name in obj){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))){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);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(fn==="inprogress"){fn=queue.shift()}if(fn){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)})},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",[])},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{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"){var className,i=0,self=jQuery(this),state=stateVal,classNames=value.split(rspace);while(className=classNames[i++]){state=isBool?state:!self.hasClass(className);self[state?"addClass":"removeClass"](className)}}else if(type==="undefined"||type==="boolean"){if(this.className){jQuery._data(this,"__className__",this.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"?ret.replace(rreturn,""):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}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(!hooks||!("set"in hooks)||hooks.set(this,val,"value")===undefined){this.value=val}})}});jQuery.extend({valHooks:{option:{get:function(elem){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";if(index<0){return null}i=one?index:0;max=one?index+1:options.length;for(;i<max;i++){option=options[i];if(option.selected&&(jQuery.support.optDisabled?!option.disabled:option.getAttribute("disabled")===null)&&(!option.parentNode.disabled||!jQuery.nodeName(option.parentNode,"optgroup"))){value=jQuery(option).val();if(one){return value}values.push(value)}}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;if(!elem||nType===3||nType===8||nType===2){return}if(pass&&name in jQuery.attrFn){return jQuery(elem)[name](value)}if(typeof elem.getAttribute==="undefined"){return jQuery.prop(elem,name,value)}notxml=nType!==1||!jQuery.isXMLDoc(elem);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&¬xml&&(ret=hooks.set(elem,value,name))!==undefined){return ret}else{elem.setAttribute(name,""+value);return value}}else if(hooks&&"get"in hooks&¬xml&&(ret=hooks.get(elem,name))!==null){return ret}else{ret=elem.getAttribute(name);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);if(!isBool){jQuery.attr(elem,name,"")}elem.removeAttribute(getSetAttribute?name:propName);if(isBool&&propName in elem){elem[propName]=false}}}}},attrHooks:{type:{set:function(elem,value){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")){var val=elem.value;elem.setAttribute("type",value);if(val){elem.value=val}return value}}},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)}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;if(!elem||nType===3||nType===8||nType===2){return}notxml=nType!==1||!jQuery.isXMLDoc(elem);if(notxml){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){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}}}});jQuery.attrHooks.tabindex=jQuery.propHooks.tabIndex;boolHook={get:function(elem,name){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){jQuery.removeAttr(elem,name)}else{propName=jQuery.propFix[name]||name;if(propName in elem){elem[propName]=true}elem.setAttribute(name,name.toLowerCase())}return name}};if(!getSetAttribute){fixSpecified={name:true,id:true,coords:true};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){var ret=elem.getAttributeNode(name);if(!ret){ret=document.createAttribute(name);elem.setAttributeNode(ret)}return ret.nodeValue=value+""}};jQuery.attrHooks.tabindex.set=nodeHook.set;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}}})});jQuery.attrHooks.contenteditable={get:nodeHook.get,set:function(elem,value,name){if(value===""){value="false"}nodeHook.set(elem,value,name)}}}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 elem.style.cssText.toLowerCase()||undefined},set:function(elem,value){return elem.style.cssText=""+value}}}if(!jQuery.support.optSelected){jQuery.propHooks.selected=jQuery.extend(jQuery.propHooks.selected,{get:function(elem){var parent=elem.parentNode;if(parent){parent.selectedIndex;if(parent.parentNode){parent.parentNode.selectedIndex}}return null}})}if(!jQuery.support.enctype){jQuery.propFix.enctype="encoding"}if(!jQuery.support.checkOn){jQuery.each(["radio","checkbox"],function(){jQuery.valHooks[this]={get:function(elem){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){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")};jQuery.event={add:function(elem,types,handler,data,selector){var elemData,eventHandle,events,t,tns,type,namespaces,handleObj,handleObjIn,quick,handlers,special;if(elem.nodeType===3||elem.nodeType===8||!types||!handler||!(elemData=jQuery._data(elem))){return}if(handler.handler){handleObjIn=handler;handler=handleObjIn.handler;selector=handleObjIn.selector}if(!handler.guid){handler.guid=jQuery.guid++}events=elemData.events;if(!events){elemData.events=events={}}eventHandle=elemData.handle;if(!eventHandle){elemData.handle=eventHandle=function(e){return typeof jQuery!=="undefined"&&(!e||jQuery.event.triggered!==e.type)?jQuery.event.dispatch.apply(eventHandle.elem,arguments):undefined};eventHandle.elem=elem}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();special=jQuery.event.special[type]||{};type=(selector?special.delegateType:special.bindType)||type;special=jQuery.event.special[type]||{};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);handlers=events[type];if(!handlers){handlers=events[type]=[];handlers.delegateCount=0;if(!special.setup||special.setup.call(elem,data,namespaces,eventHandle)===false){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}}if(selector){handlers.splice(handlers.delegateCount++,0,handleObj)}else{handlers.push(handleObj)}jQuery.event.global[type]=true}elem=null},global:{},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}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];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;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)}}}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]}}if(jQuery.isEmptyObject(events)){handle=elemData.handle;if(handle){handle.elem=null}jQuery.removeData(elem,["events","handle"],true)}},customEvent:{getData:true,setData:true,changeData:true},trigger:function(event,data,elem,onlyHandlers){if(elem&&(elem.nodeType===3||elem.nodeType===8)){return}var type=event.type||event,namespaces=[],cache,exclusive,i,cur,old,ontype,special,handle,eventPath,bubbleType;if(rfocusMorph.test(type+jQuery.event.triggered)){return}if(type.indexOf("!")>=0){type=type.slice(0,-1);exclusive=true}if(type.indexOf(".")>=0){namespaces=type.split(".");type=namespaces.shift();namespaces.sort()}if((!elem||jQuery.event.customEvent[type])&&!jQuery.event.global[type]){return}event=typeof event==="object"?event[jQuery.expando]?event:new jQuery.Event(type,event):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:"";if(!elem){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}event.result=undefined;if(!event.target){event.target=elem}data=data!=null?jQuery.makeArray(data):[];data.unshift(event);special=jQuery.event.special[type]||{};if(special.trigger&&special.trigger.apply(elem,data)===false){return}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}if(old&&old===elem.ownerDocument){eventPath.push([old.defaultView||old.parentWindow||window,bubbleType])}}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)}handle=ontype&&cur[ontype];if(handle&&jQuery.acceptData(cur)&&handle.apply(cur,data)===false){event.preventDefault()}}event.type=type;if(!onlyHandlers&&!event.isDefaultPrevented()){if((!special._default||special._default.apply(elem.ownerDocument,data)===false)&&!(type==="click"&&jQuery.nodeName(elem,"a"))&&jQuery.acceptData(elem)){if(ontype&&elem[type]&&(type!=="focus"&&type!=="blur"||event.target.offsetWidth!==0)&&!jQuery.isWindow(elem)){old=elem[ontype];if(old){elem[ontype]=null}jQuery.event.triggered=type;elem[type]();jQuery.event.triggered=undefined;if(old){elem[ontype]=old}}}}return event.result},dispatch:function(event){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;args[0]=event;event.delegateTarget=this;if(special.preDispatch&&special.preDispatch.call(this,event)===false){return}if(delegateCount&&!(event.button&&event.type==="click")){jqcur=jQuery(this);jqcur.context=this.ownerDocument||this;for(cur=event.target;cur!=this;cur=cur.parentNode||this){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})}}}}if(handlers.length>delegateCount){handlerQueue.push({elem:this,matches:handlers.slice(delegateCount)})}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];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()}}}}}if(special.postDispatch){special.postDispatch.call(this,event)}return event.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(event,original){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; | |
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)}if(!event.relatedTarget&&fromElement){event.relatedTarget=fromElement===event.target?original.toElement:fromElement}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}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]}if(!event.target){event.target=originalEvent.srcElement||document}if(event.target.nodeType===3){event.target=event.target.parentNode}if(event.metaKey===undefined){event.metaKey=event.ctrlKey}return fixHook.filter?fixHook.filter(event,originalEvent):event},special:{ready:{setup:jQuery.bindReady},load:{noBubble:true},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(data,namespaces,eventHandle){if(jQuery.isWindow(this)){this.onbeforeunload=eventHandle}},teardown:function(namespaces,eventHandle){if(this.onbeforeunload===eventHandle){this.onbeforeunload=null}}}},simulate:function(type,elem,event,bubble){var e=jQuery.extend(new jQuery.Event,event,{type:type,isSimulated:true,originalEvent:{}});if(bubble){jQuery.event.trigger(e,null,elem)}else{jQuery.event.dispatch.call(elem,e)}if(e.isDefaultPrevented()){event.preventDefault()}}};jQuery.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){if(!(this instanceof jQuery.Event)){return new jQuery.Event(src,props)}if(src&&src.type){this.originalEvent=src;this.type=src.type;this.isDefaultPrevented=src.defaultPrevented||src.returnValue===false||src.getPreventDefault&&src.getPreventDefault()?returnTrue:returnFalse}else{this.type=src}if(props){jQuery.extend(this,props)}this.timeStamp=src&&src.timeStamp||jQuery.now();this[jQuery.expando]=true};function returnFalse(){return false}function returnTrue(){return true}jQuery.Event.prototype={preventDefault:function(){this.isDefaultPrevented=returnTrue;var e=this.originalEvent;if(!e){return}if(e.preventDefault){e.preventDefault()}else{e.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=returnTrue;var e=this.originalEvent;if(!e){return}if(e.stopPropagation){e.stopPropagation()}e.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=returnTrue;this.stopPropagation()},isDefaultPrevented:returnFalse,isPropagationStopped:returnFalse,isImmediatePropagationStopped:returnFalse};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;if(!related||related!==target&&!jQuery.contains(target,related)){event.type=handleObj.origType;ret=handleObj.handler.apply(this,arguments);event.type=fix}return ret}}});if(!jQuery.support.submitBubbles){jQuery.event.special.submit={setup:function(){if(jQuery.nodeName(this,"form")){return false}jQuery.event.add(this,"click._submit keypress._submit",function(e){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}})},postDispatch:function(event){if(event._submit_bubble){delete event._submit_bubble;if(this.parentNode&&!event.isTrigger){jQuery.event.simulate("submit",this.parentNode,event,true)}}},teardown:function(){if(jQuery.nodeName(this,"form")){return false}jQuery.event.remove(this,"._submit")}}}if(!jQuery.support.changeBubbles){jQuery.event.special.change={setup:function(){if(rformElems.test(this.nodeName)){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}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;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)}}}if(!jQuery.support.focusinBubbles){jQuery.each({focus:"focusin",blur:"focusout"},function(orig,fix){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,one){var origFn,type;if(typeof types==="object"){if(typeof selector!=="string"){data=data||selector;selector=undefined}for(type in types){this.on(type,selector,data,types[type],one)}return this}if(data==null&&fn==null){fn=selector;data=selector=undefined}else if(fn==null){if(typeof selector==="string"){fn=data;data=undefined}else{fn=data;data=selector;selector=undefined}}if(fn===false){fn=returnFalse}else if(!fn){return this}if(one===1){origFn=fn;fn=function(event){jQuery().off(event);return origFn.apply(this,arguments)};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){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"){for(var type in types){this.off(type,selector,types[type])}return this}if(selector===false||typeof selector==="function"){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){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){var args=arguments,guid=fn.guid||jQuery.guid++,i=0,toggler=function(event){var lastToggle=(jQuery._data(this,"lastToggle"+fn.guid)||0)%i;jQuery._data(this,"lastToggle"+fn.guid,lastToggle+1);event.preventDefault();return args[lastToggle].apply(this,arguments)||false};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){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}});(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/;[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;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{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}}}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)};var getText=Sizzle.getText=function(elem){var i,node,nodeType=elem.nodeType,ret="";if(nodeType){if(nodeType===1||nodeType===9||nodeType===11){if(typeof elem.textContent==="string"){return elem.textContent}else if(typeof elem.innerText==="string"){return elem.innerText.replace(rReturn,"")}else{for(elem=elem.firstChild;elem;elem=elem.nextSibling){ret+=getText(elem)}}}else if(nodeType===3||nodeType===4){return elem.nodeValue}}else{for(i=0;node=elem[i];i++){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]);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,"");var test=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(match[2]==="even"&&"2n"||match[2]==="odd"&&"2n+1"||!/\D/.test(match[2])&&"0n+"+match[2]||match[2]);match[2]=test[1]+(test[2]||1)-0;match[3]=test[3]-0}else if(match[2]){Sizzle.error(match[0])}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]}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((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){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;return elem.nodeName.toLowerCase()==="input"&&"text"===type&&(attr===type||attr===null)},radio:function(elem){return elem.nodeName.toLowerCase()==="input"&&"radio"===elem.type},checkbox:function(elem){return elem.nodeName.toLowerCase()==="input"&&"checkbox"===elem.type},file:function(elem){return elem.nodeName.toLowerCase()==="input"&&"file"===elem.type},password:function(elem){return elem.nodeName.toLowerCase()==="input"&&"password"===elem.type},submit:function(elem){var name=elem.nodeName.toLowerCase();return(name==="input"||name==="button")&&"submit"===elem.type},image:function(elem){return elem.nodeName.toLowerCase()==="input"&&"image"===elem.type},reset:function(elem){var name=elem.nodeName.toLowerCase();return(name==="input"||name==="button")&&"reset"===elem.type},button:function(elem){var name=elem.nodeName.toLowerCase();return name==="input"&&"button"===elem.type||name==="button"},input:function(elem){return/input|select|textarea|button/i.test(elem.nodeName)},focus:function(elem){return elem===elem.ownerDocument.activeElement}},setFilters:{first:function(elem,i){return i===0},last:function(elem,i,match,array){return i===array.length-1},even:function(elem,i){return i%2===0},odd:function(elem,i){return i%2===1},lt:function(elem,i,match){return i<match[3]-0},gt:function(elem,i,match){return i>match[3]-0},nth:function(elem,i,match){return match[3]-0===i},eq:function(elem,i,match){return match[3]-0===i}},filter:{PSEUDO:function(elem,match,i,array){var name=match[1],filter=Expr.filters[name];if(filter){return filter(elem,i,match,array)}else if(name==="contains"){return(elem.textContent||elem.innerText||getText([elem])||"").indexOf(match[3])>=0}else if(name==="not"){var not=match[3];for(var j=0,l=not.length;j<l;j++){if(not[j]===elem){return false}}return true}else{Sizzle.error(name)}},CHILD:function(elem,match){var first,last,doneName,parent,cache,count,diff,type=match[1],node=elem;switch(type){case"only":case"first":while(node=node.previousSibling){if(node.nodeType===1){return false}}if(type==="first"){return true}node=elem;case"last":while(node=node.nextSibling){if(node.nodeType===1){return false}}return true;case"nth":first=match[2];last=match[3];if(first===1&&last===0){return true}doneName=match[0];parent=elem.parentNode;if(parent&&(parent[expando]!==doneName||!elem.nodeIndex)){count=0;for(node=parent.firstChild;node;node=node.nextSibling){if(node.nodeType===1){node.nodeIndex=++count}}parent[expando]=doneName}diff=elem.nodeIndex-last;if(first===0){return diff===0}else{return diff%first===0&&diff/first>=0}}},ID:function(elem,match){return elem.nodeType===1&&elem.getAttribute("id")===match},TAG:function(elem,match){return match==="*"&&elem.nodeType===1||!!elem.nodeName&&elem.nodeName.toLowerCase()===match},CLASS:function(elem,match){return(" "+(elem.className||elem.getAttribute("class"))+" ").indexOf(match)>-1},ATTR:function(elem,match){var name=match[1],result=Sizzle.attr?Sizzle.attr(elem,name):Expr.attrHandle[name]?Expr.attrHandle[name](elem):elem[name]!=null?elem[name]:elem.getAttribute(name),value=result+"",type=match[2],check=match[4];return result==null?type==="!=":!type&&Sizzle.attr?result!=null:type==="="?value===check:type==="*="?value.indexOf(check)>=0:type==="~="?(" "+value+" ").indexOf(check)>=0:!check?value&&result!==false:type==="!="?value!==check:type==="^="?value.indexOf(check)===0:type==="$="?value.substr(value.length-check.length)===check:type==="|="?value===check||value.substr(0,check.length+1)===check+"-":false},POS:function(elem,match,i,array){var name=match[2],filter=Expr.setFilters[name];if(filter){return filter(elem,i,match,array)}}}};var origPOS=Expr.match.POS,fescape=function(all,num){return"\\"+(num-0+1)};for(var type in Expr.match){Expr.match[type]=new RegExp(Expr.match[type].source+/(?![^\[]*\])(?![^\(]*\))/.source);Expr.leftMatch[type]=new RegExp(/(^(?:.|\r|\n)*?)/.source+Expr.match[type].source.replace(/\\(\d+)/g,fescape))}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};try{Array.prototype.slice.call(document.documentElement.childNodes,0)[0].nodeType}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){if(a===b){hasDuplicate=true;return 0}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(aup===bup){return siblingCheck(a,b)}else if(!aup){return-1}else if(!bup){return 1}while(cur){ap.unshift(cur);cur=cur.parentNode}cur=bup;while(cur){bp.unshift(cur);cur=cur.parentNode}al=ap.length;bl=bp.length;for(var i=0;i<al&&i<bl;i++){if(ap[i]!==bp[i]){return siblingCheck(ap[i],bp[i])}}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}}(function(){var form=document.createElement("div"),id="script"+(new Date).getTime(),root=document.documentElement;form.innerHTML="<a name='"+id+"'/>";root.insertBefore(form,root.firstChild);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);root=form=null})();(function(){var div=document.createElement("div");div.appendChild(document.createComment(""));if(div.getElementsByTagName("*").length>0){Expr.find.TAG=function(match,context){var results=context.getElementsByTagName(match[1]);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}}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)}}div=null})();if(document.querySelectorAll){(function(){var oldSizzle=Sizzle,div=document.createElement("div"),id="__sizzle__";div.innerHTML="<p class='TEST'></p>";if(div.querySelectorAll&&div.querySelectorAll(".TEST").length===0){return}Sizzle=function(query,context,extra,seed){context=context||document;if(!seed&&!Sizzle.isXML(context)){var match=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(query);if(match&&(context.nodeType===1||context.nodeType===9)){if(match[1]){return makeArray(context.getElementsByTagName(query),extra)}else if(match[2]&&Expr.find.CLASS&&context.getElementsByClassName){return makeArray(context.getElementsByClassName(match[2]),extra)}}if(context.nodeType===9){if(query==="body"&&context.body){return makeArray([context.body],extra)}else if(match&&match[3]){var elem=context.getElementById(match[3]);if(elem&&elem.parentNode){if(elem.id===match[3]){return makeArray([elem],extra)}}else{return makeArray([],extra)}}try{return makeArray(context.querySelectorAll(query),extra)}catch(qsaError){}}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,"\\//--jquery--")}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]}div=null})()}(function(){var html=document.documentElement,matches=html.matchesSelector||html.mozMatchesSelector||html.webkitMatchesSelector||html.msMatchesSelector;if(matches){var disconnectedMatch=!matches.call(document.createElement("div"),"div"),pseudoWorks=false;try{matches.call(document.documentElement,"[test!='']:sizzle")}catch(pseudoError){pseudoWorks=true}Sizzle.matchesSelector=function(node,expr){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);if(ret||!disconnectedMatch||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>";if(!div.getElementsByClassName||div.getElementsByClassName("e").length===0){return}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])}};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){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;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)};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)/,rmultiselector=/,/,isSimple=/^.[^:#\[\.,]*$/,slice=Array.prototype.slice,POS=jQuery.expr.match.globalPOS,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){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"?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];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}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)},index:function(elem){if(!elem){return this[0]&&this[0].parentNode?this.prevAll().length:-1}if(typeof elem==="string"){return jQuery.inArray(this[0],jQuery(elem))}return jQuery.inArray(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)}});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}});function winnow(elements,qualifier,keep){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:]+)[^>]*)\/>/gi,rtagName=/<([\w:]+)/,rtbody=/<tbody/i,rhtml=/<|&#?\w+;/,rnoInnerhtml=/<(?:script|style)/i,rnocache=/<(?:script|object|embed|option|style)/i,rnoshimcache=new RegExp("<(?:"+nodeNames+")[\\s/>]","i"),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;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]){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}},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++){if(elem.nodeType===1){jQuery.cleanData(elem.getElementsByTagName("*"))}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++){elem=this[i]||{};if(elem.nodeType===1){jQuery.cleanData(elem.getElementsByTagName("*"));elem.innerHTML=value}}elem=0}catch(e){}}if(elem){this.empty().append(value)}},null,value,arguments.length)},replaceWith:function(value){if(this[0]&&this[0].parentNode){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=[];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(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],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])}}}if(curData.data){curData.data=jQuery.extend({},curData.data)}}function cloneFixAttributes(src,dest){var nodeName;if(dest.nodeType!==1){return}if(dest.clearAttributes){dest.clearAttributes()}if(dest.mergeAttributes){dest.mergeAttributes(src)}nodeName=dest.nodeName.toLowerCase();if(nodeName==="object"){dest.outerHTML=src.outerHTML}else if(nodeName==="input"&&(src.type==="checkbox"||src.type==="radio")){if(src.checked){dest.defaultChecked=dest.checked=src.checked}if(dest.value!==src.value){dest.value=src.value}}else if(nodeName==="option"){dest.selected=src.defaultSelected}else if(nodeName==="input"||nodeName==="textarea"){dest.defaultValue=src.defaultValue}else if(nodeName==="script"&&dest.text!==src.text){dest.text=src.text}dest.removeAttribute(jQuery.expando);dest.removeAttribute("_submit_attached");dest.removeAttribute("_change_attached")}jQuery.buildFragment=function(args,nodes,scripts){var fragment,cacheable,cacheresults,doc,first=args[0];if(nodes&&nodes[0]){doc=nodes[0].ownerDocument||nodes[0]}if(!doc.createDocumentFragment){doc=document}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[]}}function fixDefaultChecked(elem){if(elem.type==="checkbox"||elem.type==="radio"){elem.defaultChecked=elem.checked}}function findInputs(elem){var nodeName=(elem.nodeName||"").toLowerCase();if(nodeName==="input"){fixDefaultChecked(elem)}else if(nodeName!=="script"&&typeof elem.getElementsByTagName!=="undefined"){jQuery.grep(elem.getElementsByTagName("input"),fixDefaultChecked)}}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,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)){cloneFixAttributes(elem,clone);srcElements=getAll(elem);destElements=getAll(clone);for(i=0;srcElements[i];++i){if(destElements[i]){cloneFixAttributes(srcElements[i],destElements[i])}}}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 clone},clean:function(elems,context,fragment,scripts){var checkScriptType,script,j,ret=[];context=context||document;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}if(typeof elem==="string"){if(!rhtml.test(elem)){elem=context.createTextNode(elem)}else{elem=elem.replace(rxhtmlTag,"<$1></$2>");var tag=(rtagName.exec(elem)||["",""])[1].toLowerCase(),wrap=wrapMap[tag]||wrapMap._default,depth=wrap[0],div=context.createElement("div"),safeChildNodes=safeFragment.childNodes,remove;if(context===document){safeFragment.appendChild(div)}else{createSafeFragment(context).appendChild(div)}div.innerHTML=wrap[1]+elem+wrap[2];while(depth--){div=div.lastChild}if(!jQuery.support.tbody){var hasBody=rtbody.test(elem),tbody=tag==="table"&&!hasBody?div.firstChild&&div.firstChild.childNodes: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])}}}if(!jQuery.support.leadingWhitespace&&rleadingWhitespace.test(elem)){div.insertBefore(context.createTextNode(rleadingWhitespace.exec(elem)[0]),div.firstChild)}elem=div.childNodes;if(div){div.parentNode.removeChild(div);if(safeChildNodes.length>0){remove=safeChildNodes[safeChildNodes.length-1];if(remove&&remove.parentNode){remove.parentNode.removeChild(remove)}}}}}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)}else{jQuery.removeEvent(elem,type,data.handle)}}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=([^)]*)/,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"},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({cssHooks:{opacity:{get:function(elem,computed){if(computed){var ret=curCSS(elem,"opacity");return ret===""?"1":ret}else{return elem.style.opacity}}}},cssNumber:{fillOpacity:true,fontWeight:true,lineHeight:true,opacity:true,orphans:true,widows:true,zIndex:true,zoom:true},cssProps:{"float":jQuery.support.cssFloat?"cssFloat":"styleFloat"},style:function(elem,name,value,extra){if(!elem||elem.nodeType===3||elem.nodeType===8||!elem.style){return}var ret,type,origName=jQuery.camelCase(name),style=elem.style,hooks=jQuery.cssHooks[origName];name=jQuery.cssProps[origName]||origName;if(value!==undefined){type=typeof value;if(type==="string"&&(ret=rrelNum.exec(value))){value=+(ret[1]+1)*+ret[2]+parseFloat(jQuery.css(elem,name));type="number"}if(value==null||type==="number"&&isNaN(value)){return}if(type==="number"&&!jQuery.cssNumber[origName]){value+="px"}if(!hooks||!("set"in hooks)||(value=hooks.set(elem,value))!==undefined){try{style[name]=value}catch(e){}}}else{if(hooks&&"get"in hooks&&(ret=hooks.get(elem,false,extra))!==undefined){return ret}return style[name]}},css:function(elem,name,extra){var ret,hooks;name=jQuery.camelCase(name);hooks=jQuery.cssHooks[name];name=jQuery.cssProps[name]||name;if(name==="cssFloat"){name="float"}if(hooks&&"get"in hooks&&(ret=hooks.get(elem,true,extra))!==undefined){return ret}else if(curCSS){return curCSS(elem,name)}},swap:function(elem,options,callback){var old={},ret,name;for(name in options){old[name]=elem.style[name];elem.style[name]=options[name]}ret=callback.call(elem);for(name in options){elem.style[name]=old[name]}return ret}});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)}}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;if(ret==null&&style&&(uncomputed=style[name])){ret=uncomputed}if(rnumnonpx.test(ret)){left=style.left;rsLeft=elem.runtimeStyle&&elem.runtimeStyle.left;if(rsLeft){elem.runtimeStyle.left=elem.currentStyle.left}style.left=name==="fontSize"?"1em":ret;ret=style.pixelLeft+"px";style.left=left;if(rsLeft){elem.runtimeStyle.left=rsLeft}}return ret===""?"auto":ret}}curCSS=getComputedStyle||currentStyle;function getWidthOrHeight(elem,name,extra){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"}val=curCSS(elem,name);if(val<0||val==null){val=elem.style[name]}if(rnumnonpx.test(val)){return val}val=parseFloat(val)||0;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){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&¤tStyle.filter||style.filter||"";style.zoom=1;if(value>=1&&jQuery.trim(filter.replace(ralpha,""))===""){style.removeAttribute("filter");if(currentStyle&&!currentStyle.filter){return}}style.filter=ralpha.test(filter)?filter.replace(ralpha,opacity):filter+" "+opacity}}}jQuery(function(){if(!jQuery.support.reliableMarginRight){jQuery.cssHooks.marginRight={get:function(elem,computed){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)}}jQuery.each({margin:"",padding:"",border:"Width"},function(prefix,suffix){jQuery.cssHooks[prefix+suffix]={expand:function(value){var i,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?$/gm,rinput=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,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+))?)?/,_load=jQuery.fn.load,prefilters={},transports={},ajaxLocation,ajaxLocParts,allTypes=["*/"]+["*"];try{ajaxLocation=location.href}catch(e){ajaxLocation=document.createElement("a");ajaxLocation.href="";ajaxLocation=ajaxLocation.href}ajaxLocParts=rurl.exec(ajaxLocation.toLowerCase())||[];function addToPrefiltersOrTransports(structure){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(;i<length;i++){dataType=dataTypes[i];placeBefore=/^\+/.test(dataType);if(placeBefore){dataType=dataType.substr(1)||"*"}list=structure[dataType]=structure[dataType]||[];list[placeBefore?"unshift":"push"](func)}}}}function inspectPrefiltersOrTransports(structure,options,originalOptions,jqXHR,dataType,inspected){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(typeof selection==="string"){if(!executeOnly||inspected[selection]){selection=undefined}else{options.dataTypes.unshift(selection);selection=inspectPrefiltersOrTransports(structure,options,originalOptions,jqXHR,selection,inspected)}}}if((executeOnly||!selection)&&!inspected["*"]){selection=inspectPrefiltersOrTransports(structure,options,originalOptions,jqXHR,"*",inspected)}return selection}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)}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)}var type="GET";if(params){if(jQuery.isFunction(params)){callback=params;params=undefined}else if(typeof params==="object"){params=jQuery.param(params,jQuery.ajaxSettings.traditional);type="POST"}}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(jqXHR,status,responseText){responseText=jqXHR.responseText;if(jqXHR.isResolved()){jqXHR.done(function(r){responseText=r});self.html(selector?jQuery("<div>").append(responseText.replace(rscript,"")).find(selector):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()}});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){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")},ajaxSetup:function(target,settings){if(settings){ajaxExtend(target,jQuery.ajaxSettings)}else{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,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"},converters:{"* text":window.String,"text html":true,"text json":jQuery.parseJSON,"text xml":jQuery.parseXML},flatOptions:{context:true,url:true}},ajaxPrefilter:addToPrefiltersOrTransports(prefilters),ajaxTransport:addToPrefiltersOrTransports(transports),ajax:function(url,options){if(typeof url==="object"){options=url;url=undefined}options=options||{};var s=jQuery.ajaxSetup({},options),callbackContext=s.context||s,globalEventContext=callbackContext!==s&&(callbackContext.nodeType||callbackContext instanceof jQuery)?jQuery(callbackContext):jQuery.event,deferred=jQuery.Deferred(),completeDeferred=jQuery.Callbacks("once memory"),statusCode=s.statusCode||{},ifModifiedKey,requestHeaders={},requestHeadersNames={},responseHeadersString,responseHeaders,transport,timeoutTimer,parts,state=0,fireGlobals,i,jqXHR={readyState:0,setRequestHeader:function(name,value){if(!state){var lname=name.toLowerCase();name=requestHeadersNames[lname]=requestHeadersNames[lname]||name;requestHeaders[name]=value}return this},getAllResponseHeaders:function(){return state===2?responseHeadersString:null},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},overrideMimeType:function(type){if(!state){s.mimeType=type}return this},abort:function(statusText){statusText=statusText||"abort";if(transport){transport.abort(statusText)}done(0,statusText);return this}};function done(status,nativeStatusText,responses,headers){if(state===2){return}state=2;if(timeoutTimer){clearTimeout(timeoutTimer)}transport=undefined;responseHeadersString=headers||"";jqXHR.readyState=status>0?4:0;var isSuccess,success,error,statusText=nativeStatusText,response=responses?ajaxHandleResponses(s,jqXHR,responses):undefined,lastModified,etag;if(status>=200&&status<300||status===304){if(s.ifModified){if(lastModified=jqXHR.getResponseHeader("Last-Modified")){jQuery.lastModified[ifModifiedKey]=lastModified}if(etag=jqXHR.getResponseHeader("Etag")){jQuery.etag[ifModifiedKey]=etag}}if(status===304){statusText="notmodified";isSuccess=true}else{try{success=ajaxConvert(s,response);statusText="success";isSuccess=true}catch(e){statusText="parsererror";error=e}}}else{error=statusText;if(!statusText||status){statusText="error";if(status<0){status=0}}}jqXHR.status=status;jqXHR.statusText=""+(nativeStatusText||statusText);if(isSuccess){deferred.resolveWith(callbackContext,[success,statusText,jqXHR])}else{deferred.rejectWith(callbackContext,[jqXHR,statusText,error])}jqXHR.statusCode(statusCode);statusCode=undefined;if(fireGlobals){globalEventContext.trigger("ajax"+(isSuccess?"Success":"Error"),[jqXHR,s,isSuccess?success:error])}completeDeferred.fireWith(callbackContext,[jqXHR,statusText]);if(fireGlobals){globalEventContext.trigger("ajaxComplete",[jqXHR,s]);if(!--jQuery.active){jQuery.event.trigger("ajaxStop")}}}deferred.promise(jqXHR);jqXHR.success=jqXHR.done;jqXHR.error=jqXHR.fail;jqXHR.complete=completeDeferred.add;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};s.url=((url||s.url)+"").replace(rhash,"").replace(rprotocol,ajaxLocParts[1]+"//");s.dataTypes=jQuery.trim(s.dataType||"*").toLowerCase().split(rspacesAjax);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))))}if(s.data&&s.processData&&typeof s.data!=="string"){s.data=jQuery.param(s.data,s.traditional)}inspectPrefiltersOrTransports(prefilters,s,options,jqXHR);if(state===2){return false}fireGlobals=s.global;s.type=s.type.toUpperCase();s.hasContent=!rnoContent.test(s.type);if(fireGlobals&&jQuery.active++===0){jQuery.event.trigger("ajaxStart")}if(!s.hasContent){if(s.data){s.url+=(rquery.test(s.url)?"&":"?")+s.data;delete s.data}ifModifiedKey=s.url;if(s.cache===false){var ts=jQuery.now(),ret=s.url.replace(rts,"$1_="+ts);s.url=ret+(ret===s.url?(rquery.test(s.url)?"&":"?")+"_="+ts:"")}}if(s.data&&s.hasContent&&s.contentType!==false||options.contentType){jqXHR.setRequestHeader("Content-Type",s.contentType)}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])}}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["*"]);for(i in s.headers){jqXHR.setRequestHeader(i,s.headers[i])}if(s.beforeSend&&(s.beforeSend.call(callbackContext,jqXHR,s)===false||state===2)){jqXHR.abort();return false}for(i in{success:1,error:1,complete:1}){jqXHR[i](s[i])}transport=inspectPrefiltersOrTransports(transports,s,options,jqXHR);if(!transport){done(-1,"No Transport")}else{jqXHR.readyState=1;if(fireGlobals){globalEventContext.trigger("ajaxSend",[jqXHR,s])}if(s.async&&s.timeout>0){timeoutTimer=setTimeout(function(){jqXHR.abort("timeout")},s.timeout)}try{state=1;transport.send(requestHeaders,done)}catch(e){if(state<2){done(-1,e)}else{throw e}}}return jqXHR},param:function(a,traditional){var s=[],add=function(key,value){value=jQuery.isFunction(value)?value():value;s[s.length]=encodeURIComponent(key)+"="+encodeURIComponent(value)};if(traditional===undefined){traditional=jQuery.ajaxSettings.traditional}if(jQuery.isArray(a)||a.jquery&&!jQuery.isPlainObject(a)){jQuery.each(a,function(){add(this.name,this.value)})}else{for(var prefix in a){buildParams(prefix,a[prefix],traditional,add)}}return s.join("&").replace(r20,"+")}});function buildParams(prefix,obj,traditional,add){if(jQuery.isArray(obj)){jQuery.each(obj,function(i,v){if(traditional||rbracket.test(prefix)){add(prefix,v)}else{buildParams(prefix+"["+(typeof v==="object"?i:"")+"]",v,traditional,add)}})}else if(!traditional&&jQuery.type(obj)==="object"){for(var name in obj){buildParams(prefix+"["+name+"]",obj[name],traditional,add)}}else{add(prefix,obj)}}jQuery.extend({active:0,lastModified:{},etag:{}});function ajaxHandleResponses(s,jqXHR,responses){var contents=s.contents,dataTypes=s.dataTypes,responseFields=s.responseFields,ct,type,finalDataType,firstDataType;for(type in responseFields){if(type in responses){jqXHR[responseFields[type]]=responses[type]}}while(dataTypes[0]==="*"){dataTypes.shift();if(ct===undefined){ct=s.mimeType||jqXHR.getResponseHeader("content-type")}}if(ct){for(type in contents){if(contents[type]&&contents[type].test(ct)){dataTypes.unshift(type);break}}}if(dataTypes[0]in responses){finalDataType=dataTypes[0]}else{for(type in responses){if(!dataTypes[0]||s.converters[type+" "+dataTypes[0]]){finalDataType=type;break}if(!firstDataType){firstDataType=type}}finalDataType=finalDataType||firstDataType}if(finalDataType){if(finalDataType!==dataTypes[0]){dataTypes.unshift(finalDataType)}return responses[finalDataType]}}function ajaxConvert(s,response){if(s.dataFilter){response=s.dataFilter(response,s.dataType)}var dataTypes=s.dataTypes,converters={},i,key,length=dataTypes.length,tmp,current=dataTypes[0],prev,conversion,conv,conv1,conv2;for(i=1;i<length;i++){if(i===1){for(key in s.converters){if(typeof key==="string"){converters[key.toLowerCase()]=s.converters[key]}}}prev=current;current=dataTypes[i];if(current==="*"){current=prev}else if(prev!=="*"&&prev!==current){conversion=prev+" "+current;conv=converters[conversion]||converters["* "+current];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(!(conv||conv2)){jQuery.error("No conversion from "+conversion.replace(" "," to "))}if(conv!==true){response=conv?conv(response):conv2(conv1(response))}}}return response}var jsc=jQuery.now(),jsre=/(\=)\?(&|$)|\?\?/i;jQuery.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return jQuery.expando+"_"+jsc++}});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){url+=(/\?/.test(url)?"&":"?")+s.jsonp+"="+jsonpCallback}}}s.url=url;s.data=data;window[jsonpCallback]=function(response){responseContainer=[response]};jqXHR.always(function(){window[jsonpCallback]=previous;if(responseContainer&&jQuery.isFunction(previous)){window[jsonpCallback](responseContainer[0])}});s.converters["script json"]=function(){if(!responseContainer){jQuery.error(jsonpCallback+" was not called")}return responseContainer[0]};s.dataTypes[0]="json";return"script"}});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}}});jQuery.ajaxPrefilter("script",function(s){if(s.cache===undefined){s.cache=false}if(s.crossDomain){s.type="GET";s.global=false}});jQuery.ajaxTransport("script",function(s){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;script.onload=script.onreadystatechange=function(_,isAbort){if(isAbort||!script.readyState||/loaded|complete/.test(script.readyState)){script.onload=script.onreadystatechange=null;if(head&&script.parentNode){head.removeChild(script)}script=undefined;if(!isAbort){callback(200,"success")}}};head.insertBefore(script,head.firstChild)},abort:function(){if(script){script.onload(0,1)}}}}});var xhrOnUnloadAbort=window.ActiveXObject?function(){for(var key in xhrCallbacks){xhrCallbacks[key](0,1)}}:false,xhrId=0,xhrCallbacks;function createStandardXHR(){try{return new window.XMLHttpRequest}catch(e){}}function createActiveXHR(){try{return new window.ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}jQuery.ajaxSettings.xhr=window.ActiveXObject?function(){return!this.isLocal&&createStandardXHR()||createActiveXHR()}:createStandardXHR;(function(xhr){jQuery.extend(jQuery.support,{ajax:!!xhr,cors:!!xhr&&"withCredentials"in xhr})})(jQuery.ajaxSettings.xhr());if(jQuery.support.ajax){jQuery.ajaxTransport(function(s){if(!s.crossDomain||jQuery.support.cors){var callback;return{send:function(headers,complete){var xhr=s.xhr(),handle,i;if(s.username){xhr.open(s.type,s.url,s.async,s.username,s.password)}else{xhr.open(s.type,s.url,s.async)}if(s.xhrFields){for(i in s.xhrFields){xhr[i]=s.xhrFields[i]}}if(s.mimeType&&xhr.overrideMimeType){xhr.overrideMimeType(s.mimeType)}if(!s.crossDomain&&!headers["X-Requested-With"]){headers["X-Requested-With"]="XMLHttpRequest"}try{for(i in headers){xhr.setRequestHeader(i,headers[i])}}catch(_){}xhr.send(s.hasContent&&s.data||null);callback=function(_,isAbort){var status,statusText,responseHeaders,responses,xml;try{if(callback&&(isAbort||xhr.readyState===4)){callback=undefined;if(handle){xhr.onreadystatechange=jQuery.noop;if(xhrOnUnloadAbort){delete xhrCallbacks[handle]}}if(isAbort){if(xhr.readyState!==4){xhr.abort()}}else{status=xhr.status;responseHeaders=xhr.getAllResponseHeaders();responses={};xml=xhr.responseXML;if(xml&&xml.documentElement){responses.xml=xml}try{responses.text=xhr.responseText}catch(_){}try{statusText=xhr.statusText}catch(e){statusText=""}if(!status&&s.isLocal&&!s.crossDomain){status=responses.text?200:404}else if(status===1223){status=204}}}}catch(firefoxAccessException){if(!isAbort){complete(-1,firefoxAccessException)}}if(responses){complete(status,statusText,responses,responseHeaders)}};if(!s.async||xhr.readyState===4){callback()}else{handle=++xhrId;if(xhrOnUnloadAbort){if(!xhrCallbacks){xhrCallbacks={};jQuery(window).unload(xhrOnUnloadAbort)}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","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["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;if(!jQuery._data(elem,"olddisplay")&&display==="none"){display=elem.style.display=""}if(display===""&&jQuery.css(elem,"display")==="none"||!jQuery.contains(elem.ownerDocument.documentElement,elem)){jQuery._data(elem,"olddisplay",defaultDisplay(elem.nodeName))}}}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)}}}for(i=0;i<j;i++){if(this[i].style){this[i].style.display="none"}}return this}},_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])}prop=jQuery.extend({},prop);function doAnimation(){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;opt.animatedProperties={};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];for(p in replace){if(!(p in prop)){prop[p]=replace[p]}}}}for(name in prop){val=prop[name];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")){opt.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(jQuery.css(this,"display")==="inline"&&jQuery.css(this,"float")==="none"){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)){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");if(unit!=="px"){jQuery.style(this,p,(end||1)+unit);start=(end||1)/e.cur()*start;jQuery.style(this,p,start+unit)}if(parts[1]){end=(parts[1]==="-="?-1:1)*end+start}e.custom(start,end,unit)}else{e.custom(start,val,"")}}}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);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){timers[index](true)}else{timers[index].saveState()}hadTimers=true;timers.splice(index,1)}}if(!(gotoEnd&&hadTimers)){jQuery.dequeue(this,type)}})}});function createFxNow(){setTimeout(clearFxNow,0);return fxNow=jQuery.now()}function clearFxNow(){fxNow=undefined}function genFx(type,num){var obj={};jQuery.each(fxAttrs.concat.apply([],fxAttrs.slice(0,num)),function(){obj[this]=type});return obj}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;if(opt.queue==null||opt.queue===true){opt.queue="fx"}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+.5}},timers:[],fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;options.orig=options.orig||{}}});jQuery.fx.prototype={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)},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);return isNaN(parsed=parseFloat(r))?!r||r==="auto"?0:r:parsed},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)}},show:function(){var dataShow=jQuery._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=dataShow||jQuery.style(this.elem,this.prop);this.options.show=true;if(dataShow!==undefined){this.custom(this.cur(),dataShow)}else{this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur())}jQuery(this.elem).show()},hide:function(){this.options.orig[this.prop]=jQuery._data(this.elem,"fxshow"+this.prop)||jQuery.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},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){if(options.overflow!=null&&!jQuery.support.shrinkWrapBlocks){jQuery.each(["","X","Y"],function(index,value){elem.style["overflow"+value]=options.overflow[index]})}if(options.hide){jQuery(elem).hide()}if(options.hide||options.show){for(p in options.animatedProperties){jQuery.style(elem,p,options.orig[p]);jQuery.removeData(elem,"fxshow"+p,true);jQuery.removeData(elem,"toggle"+p,true)}}complete=options.complete;if(complete){options.complete=false;complete.call(elem)}}return false}else{if(options.duration==Infinity){this.now=t}else{n=t-this.startTime;this.state=n/options.duration;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}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];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: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}}}});jQuery.each(fxAttrs.concat.apply([],fxAttrs),function(i,prop){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}}function defaultDisplay(nodeName){if(!elemdisplay[nodeName]){var body=document.body,elem=jQuery("<"+nodeName+">").appendTo(body),display=elem.css("display");elem.remove();if(display==="none"||display===""){if(!iframe){iframe=document.createElement("iframe");iframe.frameBorder=iframe.width=iframe.height=0}body.appendChild(iframe);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)}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){}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");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;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],offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=rroot.test(offsetParent[0].nodeName)?{top:0,left:0}:offsetParent.offset();offset.top-=parseFloat(jQuery.css(elem,"marginTop"))||0;offset.left-=parseFloat(jQuery.css(elem,"marginLeft"))||0;parentOffset.top+=parseFloat(jQuery.css(offsetParent[0],"borderTopWidth"))||0;parentOffset.left+=parseFloat(jQuery.css(offsetParent[0],"borderLeftWidth"))||0;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})}});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}jQuery.each({Height:"height",Width:"width"},function(name,type){var clientProp="client"+name,scrollProp="scroll"+name,offsetProp="offset"+name;jQuery.fn["inner"+name]=function(){var elem=this[0];return elem?elem.style?parseFloat(jQuery.css(elem,type,"padding")):this[type]():null};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)){doc=elem.document;docElemProp=doc.documentElement[clientProp];return jQuery.support.boxModel&&docElemProp||doc.body&&doc.body[clientProp]||docElemProp}if(elem.nodeType===9){doc=elem.documentElement;if(doc[clientProp]>=doc[scrollProp]){return doc[clientProp]}return Math.max(elem.body[scrollProp],doc[scrollProp],elem.body[offsetProp],doc[offsetProp])}if(value===undefined){orig=jQuery.css(elem,type);ret=parseFloat(orig);return jQuery.isNumeric(ret)?ret:orig}jQuery(elem).css(type,value)},type,value,arguments.length,null)}});window.jQuery=window.$=jQuery;if(typeof define==="function"&&define.amd&&define.amd.jQuery){define("jquery",[],function(){return jQuery})}})(window);window.jQuery.noConflict();return window.jQuery}module.exports=create("undefined"===typeof window?undefined:window);module.exports.create=create})()},{}]},{},[]);require=function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);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}({baconjs:[function(require,module,exports){(function(global){(function(){var Bacon,BufferingSource,Bus,CompositeUnsubscribe,ConsumingSource,Desc,Dispatcher,End,Error,Event,EventStream,Exception,Initial,Next,None,Observable,Property,PropertyDispatcher,Some,Source,UpdateBarrier,addPropertyInitValueToStream,assert,assertArray,assertEventStream,assertFunction,assertNoArguments,assertString,cloneArray,compositeUnsubscribe,containsDuplicateDeps,convertArgsToFunction,describe,end,eventIdCounter,findDeps,flatMap_,former,idCounter,initial,isArray,isFieldKey,isFunction,isObservable,latterF,liftCallback,makeFunction,makeFunctionArgs,makeFunction_,makeObservable,makeSpawner,next,nop,partiallyApplied,recursionDepth,registerObs,spys,toCombinator,toEvent,toFieldExtractor,toFieldKey,toOption,toSimpleExtractor,withDescription,withMethodCallSupport,_,_ref,__slice=[].slice,__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},__bind=function(fn,me){return function(){return fn.apply(me,arguments)}};Bacon={toString:function(){return"Bacon"}};Bacon.version="0.7.32";Exception=(typeof global!=="undefined"&&global!==null?global:this).Error;Bacon.fromBinder=function(binder,eventTransformer){if(eventTransformer==null){eventTransformer=_.id}return new EventStream(describe(Bacon,"fromBinder",binder,eventTransformer),function(sink){var unbind,unbinder,unbound;unbound=false;unbind=function(){if(typeof unbinder!=="undefined"&&unbinder!==null){if(!unbound){unbinder()}return unbound=true}};unbinder=binder(function(){var args,event,reply,value,_i,_len;args=1<=arguments.length?__slice.call(arguments,0):[];value=eventTransformer.apply(this,args);if(!(isArray(value)&&_.last(value)instanceof Event)){value=[value]}reply=Bacon.more;for(_i=0,_len=value.length;_i<_len;_i++){event=value[_i];reply=sink(event=toEvent(event));if(reply===Bacon.noMore||event.isEnd()){if(unbinder!=null){unbind()}else{Bacon.scheduler.setTimeout(unbind,0)}return reply}}return reply});return unbind})};Bacon.$={};Bacon.$.asEventStream=function(eventName,selector,eventTransformer){var _ref;if(isFunction(selector)){_ref=[selector,void 0],eventTransformer=_ref[0],selector=_ref[1]}return withDescription(this.selector||this,"asEventStream",eventName,Bacon.fromBinder(function(_this){return function(handler){_this.on(eventName,selector,handler);return function(){return _this.off(eventName,selector,handler)}}}(this),eventTransformer))};if((_ref=typeof jQuery!=="undefined"&&jQuery!==null?jQuery:typeof Zepto!=="undefined"&&Zepto!==null?Zepto:void 0)!=null){_ref.fn.asEventStream=Bacon.$.asEventStream}Bacon.fromEventTarget=function(target,eventName,eventTransformer){var sub,unsub,_ref1,_ref2,_ref3,_ref4,_ref5,_ref6;sub=(_ref1=(_ref2=(_ref3=target.addEventListener)!=null?_ref3:target.addListener)!=null?_ref2:target.bind)!=null?_ref1:target.on;unsub=(_ref4=(_ref5=(_ref6=target.removeEventListener)!=null?_ref6:target.removeListener)!=null?_ref5:target.unbind)!=null?_ref4:target.off;return withDescription(Bacon,"fromEventTarget",target,eventName,Bacon.fromBinder(function(handler){sub.call(target,eventName,handler);return function(){return unsub.call(target,eventName,handler)}},eventTransformer))};Bacon.fromPromise=function(promise,abort){return withDescription(Bacon,"fromPromise",promise,Bacon.fromBinder(function(handler){promise.then(handler,function(e){return handler(new Error(e))});return function(){if(abort){return typeof promise.abort==="function"?promise.abort():void 0}}},function(value){return[value,end()]}))};Bacon.noMore=["<no-more>"];Bacon.more=["<more>"];Bacon.later=function(delay,value){return withDescription(Bacon,"later",delay,value,Bacon.fromPoll(delay,function(){return[value,end()]}))};Bacon.sequentially=function(delay,values){var index;index=0;return withDescription(Bacon,"sequentially",delay,values,Bacon.fromPoll(delay,function(){var value;value=values[index++];if(index<values.length){return value}else if(index===values.length){return[value,end()]}else{return end()}}))};Bacon.repeatedly=function(delay,values){var index;index=0;return withDescription(Bacon,"repeatedly",delay,values,Bacon.fromPoll(delay,function(){return values[index++%values.length]}))};Bacon.spy=function(spy){return spys.push(spy)};spys=[];registerObs=function(obs){var spy,_i,_len;if(spys.length){if(!registerObs.running){try{registerObs.running=true;for(_i=0,_len=spys.length;_i<_len;_i++){spy=spys[_i];spy(obs)}}finally{delete registerObs.running}}}return void 0};withMethodCallSupport=function(wrapped){return function(){var args,context,f,methodName;f=arguments[0],args=2<=arguments.length?__slice.call(arguments,1):[];if(typeof f==="object"&&args.length){context=f;methodName=args[0];f=function(){return context[methodName].apply(context,arguments)};args=args.slice(1)}return wrapped.apply(null,[f].concat(__slice.call(args)))}};liftCallback=function(desc,wrapped){return withMethodCallSupport(function(){var args,f,stream; | |
f=arguments[0],args=2<=arguments.length?__slice.call(arguments,1):[];stream=partiallyApplied(wrapped,[function(values,callback){return f.apply(null,__slice.call(values).concat([callback]))}]);return withDescription.apply(null,[Bacon,desc,f].concat(__slice.call(args),[Bacon.combineAsArray(args).flatMap(stream)]))})};Bacon.fromCallback=liftCallback("fromCallback",function(){var args,f;f=arguments[0],args=2<=arguments.length?__slice.call(arguments,1):[];return Bacon.fromBinder(function(handler){makeFunction(f,args)(handler);return nop},function(value){return[value,end()]})});Bacon.fromNodeCallback=liftCallback("fromNodeCallback",function(){var args,f;f=arguments[0],args=2<=arguments.length?__slice.call(arguments,1):[];return Bacon.fromBinder(function(handler){makeFunction(f,args)(handler);return nop},function(error,value){if(error){return[new Error(error),end()]}return[value,end()]})});Bacon.fromPoll=function(delay,poll){return withDescription(Bacon,"fromPoll",delay,poll,Bacon.fromBinder(function(handler){var id;id=Bacon.scheduler.setInterval(handler,delay);return function(){return Bacon.scheduler.clearInterval(id)}},poll))};Bacon.interval=function(delay,value){if(value==null){value={}}return withDescription(Bacon,"interval",delay,value,Bacon.fromPoll(delay,function(){return next(value)}))};Bacon.constant=function(value){return new Property(describe(Bacon,"constant",value),function(sink){sink(initial(value));sink(end());return nop})};Bacon.never=function(){return new EventStream(describe(Bacon,"never"),function(sink){sink(end());return nop})};Bacon.once=function(value){return new EventStream(describe(Bacon,"once",value),function(sink){sink(toEvent(value));sink(end());return nop})};Bacon.fromArray=function(values){var i;assertArray(values);i=0;return new EventStream(describe(Bacon,"fromArray",values),function(sink){var reply,unsubd,value;unsubd=false;reply=Bacon.more;while(reply!==Bacon.noMore&&!unsubd){if(i>=values.length){sink(end());reply=Bacon.noMore}else{value=values[i++];reply=sink(toEvent(value))}}return function(){return unsubd=true}})};Bacon.mergeAll=function(){var streams;streams=1<=arguments.length?__slice.call(arguments,0):[];if(isArray(streams[0])){streams=streams[0]}if(streams.length){return new EventStream(describe.apply(null,[Bacon,"mergeAll"].concat(__slice.call(streams))),function(sink){var ends,sinks,smartSink;ends=0;smartSink=function(obs){return function(unsubBoth){return obs.dispatcher.subscribe(function(event){var reply;if(event.isEnd()){ends++;if(ends===streams.length){return sink(end())}else{return Bacon.more}}else{reply=sink(event);if(reply===Bacon.noMore){unsubBoth()}return reply}})}};sinks=_.map(smartSink,streams);return compositeUnsubscribe.apply(null,sinks)})}else{return Bacon.never()}};Bacon.zipAsArray=function(){var streams;streams=1<=arguments.length?__slice.call(arguments,0):[];if(isArray(streams[0])){streams=streams[0]}return withDescription.apply(null,[Bacon,"zipAsArray"].concat(__slice.call(streams),[Bacon.zipWith(streams,function(){var xs;xs=1<=arguments.length?__slice.call(arguments,0):[];return xs})]))};Bacon.zipWith=function(){var f,streams,_ref1;f=arguments[0],streams=2<=arguments.length?__slice.call(arguments,1):[];if(!isFunction(f)){_ref1=[f,streams[0]],streams=_ref1[0],f=_ref1[1]}streams=_.map(function(s){return s.toEventStream()},streams);return withDescription.apply(null,[Bacon,"zipWith",f].concat(__slice.call(streams),[Bacon.when(streams,f)]))};Bacon.groupSimultaneous=function(){var s,sources,streams;streams=1<=arguments.length?__slice.call(arguments,0):[];if(streams.length===1&&isArray(streams[0])){streams=streams[0]}sources=function(){var _i,_len,_results;_results=[];for(_i=0,_len=streams.length;_i<_len;_i++){s=streams[_i];_results.push(new BufferingSource(s))}return _results}();return withDescription.apply(null,[Bacon,"groupSimultaneous"].concat(__slice.call(streams),[Bacon.when(sources,function(){var xs;xs=1<=arguments.length?__slice.call(arguments,0):[];return xs})]))};Bacon.combineAsArray=function(){var index,s,sources,stream,streams,_i,_len;streams=1<=arguments.length?__slice.call(arguments,0):[];if(streams.length===1&&isArray(streams[0])){streams=streams[0]}for(index=_i=0,_len=streams.length;_i<_len;index=++_i){stream=streams[index];if(!isObservable(stream)){streams[index]=Bacon.constant(stream)}}if(streams.length){sources=function(){var _j,_len1,_results;_results=[];for(_j=0,_len1=streams.length;_j<_len1;_j++){s=streams[_j];_results.push(new Source(s,true))}return _results}();return withDescription.apply(null,[Bacon,"combineAsArray"].concat(__slice.call(streams),[Bacon.when(sources,function(){var xs;xs=1<=arguments.length?__slice.call(arguments,0):[];return xs}).toProperty()]))}else{return Bacon.constant([])}};Bacon.onValues=function(){var f,streams,_i;streams=2<=arguments.length?__slice.call(arguments,0,_i=arguments.length-1):(_i=0,[]),f=arguments[_i++];return Bacon.combineAsArray(streams).onValues(f)};Bacon.combineWith=function(){var f,streams;f=arguments[0],streams=2<=arguments.length?__slice.call(arguments,1):[];return withDescription.apply(null,[Bacon,"combineWith",f].concat(__slice.call(streams),[Bacon.combineAsArray(streams).map(function(values){return f.apply(null,values)})]))};Bacon.combineTemplate=function(template){var applyStreamValue,combinator,compile,compileTemplate,constantValue,current,funcs,mkContext,setValue,streams;funcs=[];streams=[];current=function(ctxStack){return ctxStack[ctxStack.length-1]};setValue=function(ctxStack,key,value){return current(ctxStack)[key]=value};applyStreamValue=function(key,index){return function(ctxStack,values){return setValue(ctxStack,key,values[index])}};constantValue=function(key,value){return function(ctxStack){return setValue(ctxStack,key,value)}};mkContext=function(template){if(isArray(template)){return[]}else{return{}}};compile=function(key,value){var popContext,pushContext;if(isObservable(value)){streams.push(value);return funcs.push(applyStreamValue(key,streams.length-1))}else if(value===Object(value)&&typeof value!=="function"&&!(value instanceof RegExp)&&!(value instanceof Date)){pushContext=function(key){return function(ctxStack){var newContext;newContext=mkContext(value);setValue(ctxStack,key,newContext);return ctxStack.push(newContext)}};popContext=function(ctxStack){return ctxStack.pop()};funcs.push(pushContext(key));compileTemplate(value);return funcs.push(popContext)}else{return funcs.push(constantValue(key,value))}};compileTemplate=function(template){return _.each(template,compile)};compileTemplate(template);combinator=function(values){var ctxStack,f,rootContext,_i,_len;rootContext=mkContext(template);ctxStack=[rootContext];for(_i=0,_len=funcs.length;_i<_len;_i++){f=funcs[_i];f(ctxStack,values)}return rootContext};return withDescription(Bacon,"combineTemplate",template,Bacon.combineAsArray(streams).map(combinator))};Bacon.retry=function(options){var delay,isRetryable,maxRetries,retries,retry,source;if(!isFunction(options.source)){throw new Exception("'source' option has to be a function")}source=options.source;retries=options.retries||0;maxRetries=options.maxRetries||retries;delay=options.delay||function(){return 0};isRetryable=options.isRetryable||function(){return true};retry=function(context){var delayedRetry,nextAttemptOptions;nextAttemptOptions={source:source,retries:retries-1,maxRetries:maxRetries,delay:delay,isRetryable:isRetryable};delayedRetry=function(){return Bacon.retry(nextAttemptOptions)};return Bacon.later(delay(context)).filter(false).concat(Bacon.once().flatMap(delayedRetry))};return withDescription(Bacon,"retry",options,source().flatMapError(function(e){if(isRetryable(e)&&retries>0){return retry({error:e,retriesDone:maxRetries-retries})}else{return Bacon.once(new Error(e))}}))};eventIdCounter=0;Event=function(){function Event(){this.id=++eventIdCounter}Event.prototype.isEvent=function(){return true};Event.prototype.isEnd=function(){return false};Event.prototype.isInitial=function(){return false};Event.prototype.isNext=function(){return false};Event.prototype.isError=function(){return false};Event.prototype.hasValue=function(){return false};Event.prototype.filter=function(){return true};Event.prototype.inspect=function(){return this.toString()};Event.prototype.log=function(){return this.toString()};return Event}();Next=function(_super){__extends(Next,_super);function Next(valueF){Next.__super__.constructor.call(this);if(isFunction(valueF)){this.value=_.cached(valueF)}else{this.value=_.always(valueF)}}Next.prototype.isNext=function(){return true};Next.prototype.hasValue=function(){return true};Next.prototype.fmap=function(f){var value;value=this.value;return this.apply(function(){return f(value())})};Next.prototype.apply=function(value){return new Next(value)};Next.prototype.filter=function(f){return f(this.value())};Next.prototype.toString=function(){return _.toString(this.value())};Next.prototype.log=function(){return this.value()};return Next}(Event);Initial=function(_super){__extends(Initial,_super);function Initial(){return Initial.__super__.constructor.apply(this,arguments)}Initial.prototype.isInitial=function(){return true};Initial.prototype.isNext=function(){return false};Initial.prototype.apply=function(value){return new Initial(value)};Initial.prototype.toNext=function(){return new Next(this.value)};return Initial}(Next);End=function(_super){__extends(End,_super);function End(){return End.__super__.constructor.apply(this,arguments)}End.prototype.isEnd=function(){return true};End.prototype.fmap=function(){return this};End.prototype.apply=function(){return this};End.prototype.toString=function(){return"<end>"};return End}(Event);Error=function(_super){__extends(Error,_super);function Error(error){this.error=error}Error.prototype.isError=function(){return true};Error.prototype.fmap=function(){return this};Error.prototype.apply=function(){return this};Error.prototype.toString=function(){return"<error> "+_.toString(this.error)};return Error}(Event);idCounter=0;Observable=function(){function Observable(desc){this.id=++idCounter;withDescription(desc,this);this.initialDesc=this.desc}Observable.prototype.subscribe=function(sink){return UpdateBarrier.wrappedSubscribe(this,sink)};Observable.prototype.subscribeInternal=function(sink){return this.dispatcher.subscribe(sink)};Observable.prototype.onValue=function(){var f;f=makeFunctionArgs(arguments);return this.subscribe(function(event){if(event.hasValue()){return f(event.value())}})};Observable.prototype.onValues=function(f){return this.onValue(function(args){return f.apply(null,args)})};Observable.prototype.onError=function(){var f;f=makeFunctionArgs(arguments);return this.subscribe(function(event){if(event.isError()){return f(event.error)}})};Observable.prototype.onEnd=function(){var f;f=makeFunctionArgs(arguments);return this.subscribe(function(event){if(event.isEnd()){return f()}})};Observable.prototype.errors=function(){return withDescription(this,"errors",this.filter(function(){return false}))};Observable.prototype.filter=function(){var args,f;f=arguments[0],args=2<=arguments.length?__slice.call(arguments,1):[];return convertArgsToFunction(this,f,args,function(f){return withDescription(this,"filter",f,this.withHandler(function(event){if(event.filter(f)){return this.push(event)}else{return Bacon.more}}))})};Observable.prototype.takeWhile=function(){var args,f;f=arguments[0],args=2<=arguments.length?__slice.call(arguments,1):[];return convertArgsToFunction(this,f,args,function(f){return withDescription(this,"takeWhile",f,this.withHandler(function(event){if(event.filter(f)){return this.push(event)}else{this.push(end());return Bacon.noMore}}))})};Observable.prototype.endOnError=function(){var args,f;f=arguments[0],args=2<=arguments.length?__slice.call(arguments,1):[];if(f==null){f=true}return convertArgsToFunction(this,f,args,function(f){return withDescription(this,"endOnError",this.withHandler(function(event){if(event.isError()&&f(event.error)){this.push(event);return this.push(end())}else{return this.push(event)}}))})};Observable.prototype.take=function(count){if(count<=0){return Bacon.never()}return withDescription(this,"take",count,this.withHandler(function(event){if(!event.hasValue()){return this.push(event)}else{count--;if(count>0){return this.push(event)}else{if(count===0){this.push(event)}this.push(end());return Bacon.noMore}}}))};Observable.prototype.map=function(){var args,p;p=arguments[0],args=2<=arguments.length?__slice.call(arguments,1):[];if(p instanceof Property){return p.sampledBy(this,former)}else{return convertArgsToFunction(this,p,args,function(f){return withDescription(this,"map",f,this.withHandler(function(event){return this.push(event.fmap(f))}))})}};Observable.prototype.mapError=function(){var f;f=makeFunctionArgs(arguments);return withDescription(this,"mapError",f,this.withHandler(function(event){if(event.isError()){return this.push(next(f(event.error)))}else{return this.push(event)}}))};Observable.prototype.mapEnd=function(){var f;f=makeFunctionArgs(arguments);return withDescription(this,"mapEnd",f,this.withHandler(function(event){if(event.isEnd()){this.push(next(f(event)));this.push(end());return Bacon.noMore}else{return this.push(event)}}))};Observable.prototype.doAction=function(){var f;f=makeFunctionArgs(arguments);return withDescription(this,"doAction",f,this.withHandler(function(event){if(event.hasValue()){f(event.value())}return this.push(event)}))};Observable.prototype.skip=function(count){return withDescription(this,"skip",count,this.withHandler(function(event){if(!event.hasValue()){return this.push(event)}else if(count>0){count--;return Bacon.more}else{return this.push(event)}}))};Observable.prototype.skipDuplicates=function(isEqual){if(isEqual==null){isEqual=function(a,b){return a===b}}return withDescription(this,"skipDuplicates",this.withStateMachine(None,function(prev,event){if(!event.hasValue()){return[prev,[event]]}else if(event.isInitial()||prev===None||!isEqual(prev.get(),event.value())){return[new Some(event.value()),[event]]}else{return[prev,[]]}}))};Observable.prototype.skipErrors=function(){return withDescription(this,"skipErrors",this.withHandler(function(event){if(event.isError()){return Bacon.more}else{return this.push(event)}}))};Observable.prototype.withStateMachine=function(initState,f){var state;state=initState;return withDescription(this,"withStateMachine",initState,f,this.withHandler(function(event){var fromF,newState,output,outputs,reply,_i,_len;fromF=f(state,event);newState=fromF[0],outputs=fromF[1];state=newState;reply=Bacon.more;for(_i=0,_len=outputs.length;_i<_len;_i++){output=outputs[_i];reply=this.push(output);if(reply===Bacon.noMore){return reply}}return reply}))};Observable.prototype.scan=function(seed,f,options){var acc,f_,resultProperty,subscribe;if(options==null){options={}}f_=toCombinator(f);f=options.lazyF?f_:function(x,y){return f_(x(),y())};acc=toOption(seed).map(function(x){return _.always(x)});subscribe=function(_this){return function(sink){var initSent,reply,sendInit,unsub;initSent=false;unsub=nop;reply=Bacon.more;sendInit=function(){if(!initSent){return acc.forEach(function(valueF){initSent=true;reply=sink(new Initial(valueF));if(reply===Bacon.noMore){unsub();return unsub=nop}})}};unsub=_this.dispatcher.subscribe(function(event){var next,prev;if(event.hasValue()){if(initSent&&event.isInitial()){return Bacon.more}else{if(!event.isInitial()){sendInit()}initSent=true;prev=acc.getOrElse(function(){return void 0});next=_.cached(function(){return f(prev,event.value)});acc=new Some(next);if(options.eager){next()}return sink(event.apply(next))}}else{if(event.isEnd()){reply=sendInit()}if(reply!==Bacon.noMore){return sink(event)}}});UpdateBarrier.whenDoneWith(resultProperty,sendInit);return unsub}}(this);return resultProperty=new Property(describe(this,"scan",seed,f),subscribe)};Observable.prototype.fold=function(seed,f,options){return withDescription(this,"fold",seed,f,this.scan(seed,f,options).sampledBy(this.filter(false).mapEnd().toProperty()))};Observable.prototype.zip=function(other,f){if(f==null){f=Array}return withDescription(this,"zip",other,Bacon.zipWith([this,other],f))};Observable.prototype.diff=function(start,f){f=toCombinator(f);return withDescription(this,"diff",start,f,this.scan([start],function(prevTuple,next){return[next,f(prevTuple[0],next)]}).filter(function(tuple){return tuple.length===2}).map(function(tuple){return tuple[1]}))};Observable.prototype.flatMap=function(){return flatMap_(this,makeSpawner(arguments))};Observable.prototype.flatMapFirst=function(){return flatMap_(this,makeSpawner(arguments),true)};Observable.prototype.flatMapWithConcurrencyLimit=function(){var args,limit;limit=arguments[0],args=2<=arguments.length?__slice.call(arguments,1):[];return withDescription.apply(null,[this,"flatMapWithConcurrencyLimit",limit].concat(__slice.call(args),[flatMap_(this,makeSpawner(args),false,limit)]))};Observable.prototype.flatMapLatest=function(){var f,stream;f=makeSpawner(arguments);stream=this.toEventStream();return withDescription(this,"flatMapLatest",f,stream.flatMap(function(value){return makeObservable(f(value)).takeUntil(stream)}))};Observable.prototype.flatMapError=function(fn){return withDescription(this,"flatMapError",fn,this.mapError(function(err){return new Error(err)}).flatMap(function(x){if(x instanceof Error){return fn(x.error)}else{return Bacon.once(x)}}))};Observable.prototype.flatMapConcat=function(){return withDescription.apply(null,[this,"flatMapConcat"].concat(__slice.call(arguments),[this.flatMapWithConcurrencyLimit.apply(this,[1].concat(__slice.call(arguments)))]))};Observable.prototype.bufferingThrottle=function(minimumInterval){return withDescription(this,"bufferingThrottle",minimumInterval,this.flatMapConcat(function(x){return Bacon.once(x).concat(Bacon.later(minimumInterval).filter(false))}))};Observable.prototype.not=function(){return withDescription(this,"not",this.map(function(x){return!x}))};Observable.prototype.log=function(){var args;args=1<=arguments.length?__slice.call(arguments,0):[];this.subscribe(function(event){return typeof console!=="undefined"&&console!==null?typeof console.log==="function"?console.log.apply(console,__slice.call(args).concat([event.log()])):void 0:void 0});return this};Observable.prototype.slidingWindow=function(n,minValues){if(minValues==null){minValues=0}return withDescription(this,"slidingWindow",n,minValues,this.scan([],function(window,value){return window.concat([value]).slice(-n)}).filter(function(values){return values.length>=minValues}))};Observable.prototype.combine=function(other,f){var combinator;combinator=toCombinator(f);return withDescription(this,"combine",other,f,Bacon.combineAsArray(this,other).map(function(values){return combinator(values[0],values[1])}))};Observable.prototype.decode=function(cases){return withDescription(this,"decode",cases,this.combine(Bacon.combineTemplate(cases),function(key,values){return values[key]}))};Observable.prototype.awaiting=function(other){return withDescription(this,"awaiting",other,Bacon.groupSimultaneous(this,other).map(function(_arg){var myValues,otherValues;myValues=_arg[0],otherValues=_arg[1];return otherValues.length===0}).toProperty(false).skipDuplicates())};Observable.prototype.name=function(name){this._name=name;return this};Observable.prototype.withDescription=function(){return describe.apply(null,arguments).apply(this)};Observable.prototype.toString=function(){if(this._name){return this._name}else{return this.desc.toString()}};Observable.prototype.internalDeps=function(){return this.initialDesc.deps()};return Observable}();Observable.prototype.reduce=Observable.prototype.fold;Observable.prototype.assign=Observable.prototype.onValue;Observable.prototype.inspect=Observable.prototype.toString;flatMap_=function(root,f,firstOnly,limit){var childDeps,result,rootDep;rootDep=[root];childDeps=[];result=new EventStream(describe(root,"flatMap"+(firstOnly?"First":""),f),function(sink){var checkEnd,checkQueue,composite,queue,spawn;composite=new CompositeUnsubscribe;queue=[];spawn=function(event){var child;child=makeObservable(f(event.value()));childDeps.push(child);return composite.add(function(unsubAll,unsubMe){return child.dispatcher.subscribe(function(event){var reply;if(event.isEnd()){_.remove(child,childDeps);checkQueue();checkEnd(unsubMe);return Bacon.noMore}else{if(event instanceof Initial){event=event.toNext()}reply=sink(event);if(reply===Bacon.noMore){unsubAll()}return reply}})})};checkQueue=function(){var event;event=queue.shift();if(event){return spawn(event)}};checkEnd=function(unsub){unsub();if(composite.empty()){return sink(end())}};composite.add(function(__,unsubRoot){return root.dispatcher.subscribe(function(event){if(event.isEnd()){return checkEnd(unsubRoot)}else if(event.isError()){return sink(event)}else if(firstOnly&&composite.count()>1){return Bacon.more}else{if(composite.unsubscribed){return Bacon.noMore}if(limit&&composite.count()>limit){return queue.push(event)}else{return spawn(event)}}})});return composite.unsubscribe});result.internalDeps=function(){if(childDeps.length){return rootDep.concat(childDeps)}else{return rootDep}};return result};EventStream=function(_super){__extends(EventStream,_super);function EventStream(desc,subscribe,handler){if(isFunction(desc)){handler=subscribe;subscribe=desc;desc=[]}EventStream.__super__.constructor.call(this,desc);assertFunction(subscribe);this.dispatcher=new Dispatcher(subscribe,handler);registerObs(this)}EventStream.prototype.delay=function(delay){return withDescription(this,"delay",delay,this.flatMap(function(value){return Bacon.later(delay,value)}))};EventStream.prototype.debounce=function(delay){return withDescription(this,"debounce",delay,this.flatMapLatest(function(value){return Bacon.later(delay,value)}))};EventStream.prototype.debounceImmediate=function(delay){return withDescription(this,"debounceImmediate",delay,this.flatMapFirst(function(value){return Bacon.once(value).concat(Bacon.later(delay).filter(false))}))};EventStream.prototype.throttle=function(delay){return withDescription(this,"throttle",delay,this.bufferWithTime(delay).map(function(values){return values[values.length-1]}))};EventStream.prototype.bufferWithTime=function(delay){return withDescription(this,"bufferWithTime",delay,this.bufferWithTimeOrCount(delay,Number.MAX_VALUE))};EventStream.prototype.bufferWithCount=function(count){return withDescription(this,"bufferWithCount",count,this.bufferWithTimeOrCount(void 0,count))};EventStream.prototype.bufferWithTimeOrCount=function(delay,count){var flushOrSchedule;flushOrSchedule=function(buffer){if(buffer.values.length===count){return buffer.flush()}else if(delay!==void 0){return buffer.schedule()}};return withDescription(this,"bufferWithTimeOrCount",delay,count,this.buffer(delay,flushOrSchedule,flushOrSchedule))};EventStream.prototype.buffer=function(delay,onInput,onFlush){var buffer,delayMs,reply;if(onInput==null){onInput=nop}if(onFlush==null){onFlush=nop}buffer={scheduled:false,end:void 0,values:[],flush:function(){var reply;this.scheduled=false;if(this.values.length>0){reply=this.push(next(this.values));this.values=[];if(this.end!=null){return this.push(this.end)}else if(reply!==Bacon.noMore){return onFlush(this)}}else{if(this.end!=null){return this.push(this.end)}}},schedule:function(){if(!this.scheduled){this.scheduled=true;return delay(function(_this){return function(){return _this.flush()}}(this))}}};reply=Bacon.more;if(!isFunction(delay)){delayMs=delay;delay=function(f){return Bacon.scheduler.setTimeout(f,delayMs)}}return withDescription(this,"buffer",this.withHandler(function(event){buffer.push=function(_this){return function(event){return _this.push(event)}}(this);if(event.isError()){reply=this.push(event)}else if(event.isEnd()){buffer.end=event;if(!buffer.scheduled){buffer.flush()}}else{buffer.values.push(event.value());onInput(buffer)}return reply}))};EventStream.prototype.merge=function(right){var left;assertEventStream(right);left=this;return withDescription(left,"merge",right,Bacon.mergeAll(this,right))};EventStream.prototype.toProperty=function(initValue){if(arguments.length===0){initValue=None}return withDescription(this,"toProperty",initValue,this.scan(initValue,latterF,{lazyF:true}))};EventStream.prototype.toEventStream=function(){return this};EventStream.prototype.sampledBy=function(sampler,combinator){return withDescription(this,"sampledBy",sampler,combinator,this.toProperty().sampledBy(sampler,combinator))};EventStream.prototype.concat=function(right){var left;left=this;return new EventStream(describe(left,"concat",right),function(sink){var unsubLeft,unsubRight;unsubRight=nop;unsubLeft=left.dispatcher.subscribe(function(e){if(e.isEnd()){return unsubRight=right.dispatcher.subscribe(sink)}else{return sink(e)}});return function(){unsubLeft();return unsubRight()}})};EventStream.prototype.takeUntil=function(stopper){var endMarker;endMarker={};return withDescription(this,"takeUntil",stopper,Bacon.groupSimultaneous(this.mapEnd(endMarker),stopper.skipErrors()).withHandler(function(event){var data,reply,value,_i,_len,_ref1;if(!event.hasValue()){return this.push(event)}else{_ref1=event.value(),data=_ref1[0],stopper=_ref1[1];if(stopper.length){return this.push(end())}else{reply=Bacon.more;for(_i=0,_len=data.length;_i<_len;_i++){value=data[_i];if(value===endMarker){reply=this.push(end())}else{reply=this.push(next(value))}}return reply}}}))};EventStream.prototype.skipUntil=function(starter){var started;started=starter.take(1).map(true).toProperty(false);return withDescription(this,"skipUntil",starter,this.filter(started))};EventStream.prototype.skipWhile=function(){var args,f,ok;f=arguments[0],args=2<=arguments.length?__slice.call(arguments,1):[];ok=false;return convertArgsToFunction(this,f,args,function(f){return withDescription(this,"skipWhile",f,this.withHandler(function(event){if(ok||!event.hasValue()||!f(event.value())){if(event.hasValue()){ok=true}return this.push(event)}else{return Bacon.more}}))})};EventStream.prototype.holdWhen=function(valve){var putToHold,releaseHold,valve_;valve_=valve.startWith(false);releaseHold=valve_.filter(function(x){return!x});putToHold=valve_.filter(_.id);return withDescription(this,"holdWhen",valve,this.filter(false).merge(valve_.flatMapConcat(function(_this){return function(shouldHold){if(!shouldHold){return _this.takeUntil(putToHold)}else{return _this.scan([],function(xs,x){return xs.concat(x)},{eager:true}).sampledBy(releaseHold).take(1).flatMap(Bacon.fromArray)}}}(this))))};EventStream.prototype.startWith=function(seed){return withDescription(this,"startWith",seed,Bacon.once(seed).concat(this))};EventStream.prototype.withHandler=function(handler){return new EventStream(describe(this,"withHandler",handler),this.dispatcher.subscribe,handler)};return EventStream}(Observable);Property=function(_super){__extends(Property,_super);function Property(desc,subscribe,handler){if(isFunction(desc)){handler=subscribe;subscribe=desc;desc=[]}Property.__super__.constructor.call(this,desc);assertFunction(subscribe);this.dispatcher=new PropertyDispatcher(this,subscribe,handler);registerObs(this)}Property.prototype.sampledBy=function(sampler,combinator){var lazy,result,samplerSource,stream,thisSource;if(combinator!=null){combinator=toCombinator(combinator)}else{lazy=true;combinator=function(f){return f()}}thisSource=new Source(this,false,lazy);samplerSource=new Source(sampler,true,lazy);stream=Bacon.when([thisSource,samplerSource],combinator);result=sampler instanceof Property?stream.toProperty():stream;return withDescription(this,"sampledBy",sampler,combinator,result)};Property.prototype.sample=function(interval){return withDescription(this,"sample",interval,this.sampledBy(Bacon.interval(interval,{})))};Property.prototype.changes=function(){return new EventStream(describe(this,"changes"),function(_this){return function(sink){return _this.dispatcher.subscribe(function(event){if(!event.isInitial()){return sink(event)}})}}(this))};Property.prototype.withHandler=function(handler){return new Property(describe(this,"withHandler",handler),this.dispatcher.subscribe,handler)};Property.prototype.toProperty=function(){assertNoArguments(arguments);return this};Property.prototype.toEventStream=function(){return new EventStream(describe(this,"toEventStream"),function(_this){return function(sink){return _this.dispatcher.subscribe(function(event){if(event.isInitial()){event=event.toNext()}return sink(event)})}}(this))};Property.prototype.and=function(other){return withDescription(this,"and",other,this.combine(other,function(x,y){return x&&y}))};Property.prototype.or=function(other){return withDescription(this,"or",other,this.combine(other,function(x,y){return x||y}))};Property.prototype.delay=function(delay){return this.delayChanges("delay",delay,function(changes){return changes.delay(delay)})};Property.prototype.debounce=function(delay){return this.delayChanges("debounce",delay,function(changes){return changes.debounce(delay)})};Property.prototype.throttle=function(delay){return this.delayChanges("throttle",delay,function(changes){return changes.throttle(delay)})};Property.prototype.delayChanges=function(){var desc,f,_i;desc=2<=arguments.length?__slice.call(arguments,0,_i=arguments.length-1):(_i=0,[]),f=arguments[_i++];return withDescription.apply(null,[this].concat(__slice.call(desc),[addPropertyInitValueToStream(this,f(this.changes()))]))};Property.prototype.takeUntil=function(stopper){var changes;changes=this.changes().takeUntil(stopper);return withDescription(this,"takeUntil",stopper,addPropertyInitValueToStream(this,changes))};Property.prototype.startWith=function(value){return withDescription(this,"startWith",value,this.scan(value,function(prev,next){return next}))};Property.prototype.bufferingThrottle=function(){var _ref1;return(_ref1=Property.__super__.bufferingThrottle.apply(this,arguments)).bufferingThrottle.apply(_ref1,arguments).toProperty()};return Property}(Observable);convertArgsToFunction=function(obs,f,args,method){var sampled;if(f instanceof Property){sampled=f.sampledBy(obs,function(p,s){return[p,s]});return method.call(sampled,function(_arg){var p,s;p=_arg[0],s=_arg[1];return p}).map(function(_arg){var p,s;p=_arg[0],s=_arg[1];return s})}else{f=makeFunction(f,args);return method.call(obs,f)}};addPropertyInitValueToStream=function(property,stream){var justInitValue;justInitValue=new EventStream(describe(property,"justInitValue"),function(sink){var unsub,value;value=void 0;unsub=property.dispatcher.subscribe(function(event){if(!event.isEnd()){value=event}return Bacon.noMore});UpdateBarrier.whenDoneWith(justInitValue,function(){if(value!=null){sink(value)}return sink(end())});return unsub});return justInitValue.concat(stream).toProperty()};Dispatcher=function(){function Dispatcher(_subscribe,_handleEvent){this._subscribe=_subscribe;this._handleEvent=_handleEvent;this.subscribe=__bind(this.subscribe,this);this.handleEvent=__bind(this.handleEvent,this);this.subscriptions=[];this.queue=[];this.pushing=false;this.ended=false;this.prevError=void 0;this.unsubSrc=void 0}Dispatcher.prototype.hasSubscribers=function(){return this.subscriptions.length>0};Dispatcher.prototype.removeSub=function(subscription){return this.subscriptions=_.without(subscription,this.subscriptions)};Dispatcher.prototype.push=function(event){if(event.isEnd()){this.ended=true}return UpdateBarrier.inTransaction(event,this,this.pushIt,[event])};Dispatcher.prototype.pushIt=function(event){var reply,sub,success,tmp,_i,_len;if(!this.pushing){if(event===this.prevError){return}if(event.isError()){this.prevError=event}success=false;try{this.pushing=true;tmp=this.subscriptions;for(_i=0,_len=tmp.length;_i<_len;_i++){sub=tmp[_i];reply=sub.sink(event);if(reply===Bacon.noMore||event.isEnd()){this.removeSub(sub)}}success=true}finally{this.pushing=false;if(!success){this.queue=[]}}success=true;while(this.queue.length){event=this.queue.shift();this.push(event)}if(this.hasSubscribers()){return Bacon.more}else{this.unsubscribeFromSource();return Bacon.noMore | |
}}else{this.queue.push(event);return Bacon.more}};Dispatcher.prototype.handleEvent=function(event){if(this._handleEvent){return this._handleEvent(event)}else{return this.push(event)}};Dispatcher.prototype.unsubscribeFromSource=function(){if(this.unsubSrc){this.unsubSrc()}return this.unsubSrc=void 0};Dispatcher.prototype.subscribe=function(sink){var subscription;if(this.ended){sink(end());return nop}else{assertFunction(sink);subscription={sink:sink};this.subscriptions.push(subscription);if(this.subscriptions.length===1){this.unsubSrc=this._subscribe(this.handleEvent);assertFunction(this.unsubSrc)}return function(_this){return function(){_this.removeSub(subscription);if(!_this.hasSubscribers()){return _this.unsubscribeFromSource()}}}(this)}};return Dispatcher}();PropertyDispatcher=function(_super){__extends(PropertyDispatcher,_super);function PropertyDispatcher(property,subscribe,handleEvent){this.property=property;this.subscribe=__bind(this.subscribe,this);PropertyDispatcher.__super__.constructor.call(this,subscribe,handleEvent);this.current=None;this.currentValueRootId=void 0;this.propertyEnded=false}PropertyDispatcher.prototype.push=function(event){if(event.isEnd()){this.propertyEnded=true}if(event.hasValue()){this.current=new Some(event);this.currentValueRootId=UpdateBarrier.currentEventId()}return PropertyDispatcher.__super__.push.call(this,event)};PropertyDispatcher.prototype.maybeSubSource=function(sink,reply){if(reply===Bacon.noMore){return nop}else if(this.propertyEnded){sink(end());return nop}else{return Dispatcher.prototype.subscribe.call(this,sink)}};PropertyDispatcher.prototype.subscribe=function(sink){var dispatchingId,initSent,reply,valId;initSent=false;reply=Bacon.more;if(this.current.isDefined&&(this.hasSubscribers()||this.propertyEnded)){dispatchingId=UpdateBarrier.currentEventId();valId=this.currentValueRootId;if(!this.propertyEnded&&valId&&dispatchingId&&dispatchingId!==valId){UpdateBarrier.whenDoneWith(this.property,function(_this){return function(){if(_this.currentValueRootId===valId){return sink(initial(_this.current.get().value()))}}}(this));return this.maybeSubSource(sink,reply)}else{UpdateBarrier.inTransaction(void 0,this,function(){return reply=function(){try{return sink(initial(this.current.get().value()))}catch(_error){return Bacon.more}}.call(this)},[]);return this.maybeSubSource(sink,reply)}}else{return this.maybeSubSource(sink,reply)}};return PropertyDispatcher}(Dispatcher);Bus=function(_super){__extends(Bus,_super);function Bus(){this.guardedSink=__bind(this.guardedSink,this);this.subscribeAll=__bind(this.subscribeAll,this);this.unsubAll=__bind(this.unsubAll,this);this.sink=void 0;this.subscriptions=[];this.ended=false;Bus.__super__.constructor.call(this,describe(Bacon,"Bus"),this.subscribeAll)}Bus.prototype.unsubAll=function(){var sub,_i,_len,_ref1;_ref1=this.subscriptions;for(_i=0,_len=_ref1.length;_i<_len;_i++){sub=_ref1[_i];if(typeof sub.unsub==="function"){sub.unsub()}}return void 0};Bus.prototype.subscribeAll=function(newSink){var subscription,_i,_len,_ref1;this.sink=newSink;_ref1=cloneArray(this.subscriptions);for(_i=0,_len=_ref1.length;_i<_len;_i++){subscription=_ref1[_i];this.subscribeInput(subscription)}return this.unsubAll};Bus.prototype.guardedSink=function(input){return function(_this){return function(event){if(event.isEnd()){_this.unsubscribeInput(input);return Bacon.noMore}else{return _this.sink(event)}}}(this)};Bus.prototype.subscribeInput=function(subscription){return subscription.unsub=subscription.input.dispatcher.subscribe(this.guardedSink(subscription.input))};Bus.prototype.unsubscribeInput=function(input){var i,sub,_i,_len,_ref1;_ref1=this.subscriptions;for(i=_i=0,_len=_ref1.length;_i<_len;i=++_i){sub=_ref1[i];if(sub.input===input){if(typeof sub.unsub==="function"){sub.unsub()}this.subscriptions.splice(i,1);return}}};Bus.prototype.plug=function(input){var sub;if(this.ended){return}sub={input:input};this.subscriptions.push(sub);if(this.sink!=null){this.subscribeInput(sub)}return function(_this){return function(){return _this.unsubscribeInput(input)}}(this)};Bus.prototype.end=function(){this.ended=true;this.unsubAll();return typeof this.sink==="function"?this.sink(end()):void 0};Bus.prototype.push=function(value){return typeof this.sink==="function"?this.sink(next(value)):void 0};Bus.prototype.error=function(error){return typeof this.sink==="function"?this.sink(new Error(error)):void 0};return Bus}(EventStream);Source=function(){function Source(obs,sync,lazy){this.obs=obs;this.sync=sync;this.lazy=lazy!=null?lazy:false;this.queue=[]}Source.prototype.subscribe=function(sink){return this.obs.dispatcher.subscribe(sink)};Source.prototype.toString=function(){return this.obs.toString()};Source.prototype.markEnded=function(){return this.ended=true};Source.prototype.consume=function(){if(this.lazy){return _.always(this.queue[0])}else{return this.queue[0]}};Source.prototype.push=function(x){return this.queue=[x]};Source.prototype.mayHave=function(){return true};Source.prototype.hasAtLeast=function(){return this.queue.length};Source.prototype.flatten=true;return Source}();ConsumingSource=function(_super){__extends(ConsumingSource,_super);function ConsumingSource(){return ConsumingSource.__super__.constructor.apply(this,arguments)}ConsumingSource.prototype.consume=function(){return this.queue.shift()};ConsumingSource.prototype.push=function(x){return this.queue.push(x)};ConsumingSource.prototype.mayHave=function(c){return!this.ended||this.queue.length>=c};ConsumingSource.prototype.hasAtLeast=function(c){return this.queue.length>=c};ConsumingSource.prototype.flatten=false;return ConsumingSource}(Source);BufferingSource=function(_super){__extends(BufferingSource,_super);function BufferingSource(obs){BufferingSource.__super__.constructor.call(this,obs,true)}BufferingSource.prototype.consume=function(){var values;values=this.queue;this.queue=[];return function(){return values}};BufferingSource.prototype.push=function(x){return this.queue.push(x())};BufferingSource.prototype.hasAtLeast=function(){return true};return BufferingSource}(Source);Source.isTrigger=function(s){if(s instanceof Source){return s.sync}else{return s instanceof EventStream}};Source.fromObservable=function(s){if(s instanceof Source){return s}else if(s instanceof Property){return new Source(s,false)}else{return new ConsumingSource(s,true)}};describe=function(){var args,context,method;context=arguments[0],method=arguments[1],args=3<=arguments.length?__slice.call(arguments,2):[];if((context||method)instanceof Desc){return context||method}else{return new Desc(context,method,args)}};findDeps=function(x){if(isArray(x)){return _.flatMap(findDeps,x)}else if(isObservable(x)){return[x]}else if(x instanceof Source){return[x.obs]}else{return[]}};Desc=function(){function Desc(context,method,args){this.context=context;this.method=method;this.args=args;this.cached=void 0}Desc.prototype.deps=function(){return this.cached||(this.cached=findDeps([this.context].concat(this.args)))};Desc.prototype.apply=function(obs){obs.desc=this;return obs};Desc.prototype.toString=function(){return _.toString(this.context)+"."+_.toString(this.method)+"("+_.map(_.toString,this.args)+")"};return Desc}();withDescription=function(){var desc,obs,_i;desc=2<=arguments.length?__slice.call(arguments,0,_i=arguments.length-1):(_i=0,[]),obs=arguments[_i++];return describe.apply(null,desc).apply(obs)};Bacon.when=function(){var f,i,index,ix,len,needsBarrier,pat,patSources,pats,patterns,resultStream,s,sources,triggerFound,usage,_i,_j,_len,_len1,_ref1;if(arguments.length===0){return Bacon.never()}len=arguments.length;usage="when: expecting arguments in the form (Observable+,function)+";assert(usage,len%2===0);sources=[];pats=[];i=0;patterns=[];while(i<len){patterns[i]=arguments[i];patterns[i+1]=arguments[i+1];patSources=_.toArray(arguments[i]);f=arguments[i+1];pat={f:isFunction(f)?f:function(){return f},ixs:[]};triggerFound=false;for(_i=0,_len=patSources.length;_i<_len;_i++){s=patSources[_i];index=_.indexOf(sources,s);if(!triggerFound){triggerFound=Source.isTrigger(s)}if(index<0){sources.push(s);index=sources.length-1}_ref1=pat.ixs;for(_j=0,_len1=_ref1.length;_j<_len1;_j++){ix=_ref1[_j];if(ix.index===index){ix.count++}}pat.ixs.push({index:index,count:1})}assert("At least one EventStream required",triggerFound||!patSources.length);if(patSources.length>0){pats.push(pat)}i=i+2}if(!sources.length){return Bacon.never()}sources=_.map(Source.fromObservable,sources);needsBarrier=_.any(sources,function(s){return s.flatten})&&containsDuplicateDeps(_.map(function(s){return s.obs},sources));return resultStream=new EventStream(describe.apply(null,[Bacon,"when"].concat(__slice.call(patterns))),function(sink){var cannotMatch,cannotSync,ends,match,nonFlattened,part,triggers;triggers=[];ends=false;match=function(p){var _k,_len2,_ref2;_ref2=p.ixs;for(_k=0,_len2=_ref2.length;_k<_len2;_k++){i=_ref2[_k];if(!sources[i.index].hasAtLeast(i.count)){return false}}return true};cannotSync=function(source){return!source.sync||source.ended};cannotMatch=function(p){var _k,_len2,_ref2;_ref2=p.ixs;for(_k=0,_len2=_ref2.length;_k<_len2;_k++){i=_ref2[_k];if(!sources[i.index].mayHave(i.count)){return true}}};nonFlattened=function(trigger){return!trigger.source.flatten};part=function(source){return function(unsubAll){var flush,flushLater,flushWhileTriggers;flushLater=function(){return UpdateBarrier.whenDoneWith(resultStream,flush)};flushWhileTriggers=function(){var functions,p,reply,trigger,_k,_len2;if(triggers.length>0){reply=Bacon.more;trigger=triggers.pop();for(_k=0,_len2=pats.length;_k<_len2;_k++){p=pats[_k];if(match(p)){functions=function(){var _l,_len3,_ref2,_results;_ref2=p.ixs;_results=[];for(_l=0,_len3=_ref2.length;_l<_len3;_l++){i=_ref2[_l];_results.push(sources[i.index].consume())}return _results}();reply=sink(trigger.e.apply(function(){var fun,values;values=function(){var _l,_len3,_results;_results=[];for(_l=0,_len3=functions.length;_l<_len3;_l++){fun=functions[_l];_results.push(fun())}return _results}();return p.f.apply(p,values)}));if(triggers.length){triggers=_.filter(nonFlattened,triggers)}if(reply===Bacon.noMore){return reply}else{return flushWhileTriggers()}}}}else{return Bacon.more}};flush=function(){var reply;reply=flushWhileTriggers();if(ends){ends=false;if(_.all(sources,cannotSync)||_.all(pats,cannotMatch)){reply=Bacon.noMore;sink(end())}}if(reply===Bacon.noMore){unsubAll()}return reply};return source.subscribe(function(e){var reply;if(e.isEnd()){ends=true;source.markEnded();flushLater()}else if(e.isError()){reply=sink(e)}else{source.push(e.value);if(source.sync){triggers.push({source:source,e:e});if(needsBarrier||UpdateBarrier.hasWaiters()){flushLater()}else{flush()}}}if(reply===Bacon.noMore){unsubAll()}return reply||Bacon.more})}};return compositeUnsubscribe.apply(null,function(){var _k,_len2,_results;_results=[];for(_k=0,_len2=sources.length;_k<_len2;_k++){s=sources[_k];_results.push(part(s))}return _results}())})};containsDuplicateDeps=function(observables,state){var checkObservable;if(state==null){state=[]}checkObservable=function(obs){var deps;if(_.contains(state,obs)){return true}else{deps=obs.internalDeps();if(deps.length){state.push(obs);return _.any(deps,checkObservable)}else{state.push(obs);return false}}};return _.any(observables,checkObservable)};Bacon.update=function(){var i,initial,lateBindFirst,patterns;initial=arguments[0],patterns=2<=arguments.length?__slice.call(arguments,1):[];lateBindFirst=function(f){return function(){var args;args=1<=arguments.length?__slice.call(arguments,0):[];return function(i){return f.apply(null,[i].concat(args))}}};i=patterns.length-1;while(i>0){if(!(patterns[i]instanceof Function)){patterns[i]=function(x){return function(){return x}}(patterns[i])}patterns[i]=lateBindFirst(patterns[i]);i=i-2}return withDescription.apply(null,[Bacon,"update",initial].concat(__slice.call(patterns),[Bacon.when.apply(Bacon,patterns).scan(initial,function(x,f){return f(x)})]))};compositeUnsubscribe=function(){var ss;ss=1<=arguments.length?__slice.call(arguments,0):[];return new CompositeUnsubscribe(ss).unsubscribe};CompositeUnsubscribe=function(){function CompositeUnsubscribe(ss){var s,_i,_len;if(ss==null){ss=[]}this.unsubscribe=__bind(this.unsubscribe,this);this.unsubscribed=false;this.subscriptions=[];this.starting=[];for(_i=0,_len=ss.length;_i<_len;_i++){s=ss[_i];this.add(s)}}CompositeUnsubscribe.prototype.add=function(subscription){var ended,unsub,unsubMe;if(this.unsubscribed){return}ended=false;unsub=nop;this.starting.push(subscription);unsubMe=function(_this){return function(){if(_this.unsubscribed){return}ended=true;_this.remove(unsub);return _.remove(subscription,_this.starting)}}(this);unsub=subscription(this.unsubscribe,unsubMe);if(!(this.unsubscribed||ended)){this.subscriptions.push(unsub)}_.remove(subscription,this.starting);return unsub};CompositeUnsubscribe.prototype.remove=function(unsub){if(this.unsubscribed){return}if(_.remove(unsub,this.subscriptions)!==void 0){return unsub()}};CompositeUnsubscribe.prototype.unsubscribe=function(){var s,_i,_len,_ref1;if(this.unsubscribed){return}this.unsubscribed=true;_ref1=this.subscriptions;for(_i=0,_len=_ref1.length;_i<_len;_i++){s=_ref1[_i];s()}this.subscriptions=[];return this.starting=[]};CompositeUnsubscribe.prototype.count=function(){if(this.unsubscribed){return 0}return this.subscriptions.length+this.starting.length};CompositeUnsubscribe.prototype.empty=function(){return this.count()===0};return CompositeUnsubscribe}();Bacon.CompositeUnsubscribe=CompositeUnsubscribe;Some=function(){function Some(value){this.value=value}Some.prototype.getOrElse=function(){return this.value};Some.prototype.get=function(){return this.value};Some.prototype.filter=function(f){if(f(this.value)){return new Some(this.value)}else{return None}};Some.prototype.map=function(f){return new Some(f(this.value))};Some.prototype.forEach=function(f){return f(this.value)};Some.prototype.isDefined=true;Some.prototype.toArray=function(){return[this.value]};Some.prototype.inspect=function(){return"Some("+this.value+")"};Some.prototype.toString=function(){return this.inspect()};return Some}();None={getOrElse:function(value){return value},filter:function(){return None},map:function(){return None},forEach:function(){},isDefined:false,toArray:function(){return[]},inspect:function(){return"None"},toString:function(){return this.inspect()}};UpdateBarrier=function(){var afterTransaction,afters,currentEventId,flush,flushDepsOf,flushWaiters,hasWaiters,inTransaction,rootEvent,waiterObs,waiters,whenDoneWith,wrappedSubscribe;rootEvent=void 0;waiterObs=[];waiters={};afters=[];afterTransaction=function(f){if(rootEvent){return afters.push(f)}else{return f()}};whenDoneWith=function(obs,f){var obsWaiters;if(rootEvent){obsWaiters=waiters[obs.id];if(obsWaiters==null){obsWaiters=waiters[obs.id]=[f];return waiterObs.push(obs)}else{return obsWaiters.push(f)}}else{return f()}};flush=function(){while(waiterObs.length>0){flushWaiters(0)}return void 0};flushWaiters=function(index){var f,obs,obsId,obsWaiters,_i,_len;obs=waiterObs[index];obsId=obs.id;obsWaiters=waiters[obsId];waiterObs.splice(index,1);delete waiters[obsId];flushDepsOf(obs);for(_i=0,_len=obsWaiters.length;_i<_len;_i++){f=obsWaiters[_i];f()}return void 0};flushDepsOf=function(obs){var dep,deps,index,_i,_len;deps=obs.internalDeps();for(_i=0,_len=deps.length;_i<_len;_i++){dep=deps[_i];flushDepsOf(dep);if(waiters[dep.id]){index=_.indexOf(waiterObs,dep);flushWaiters(index)}}return void 0};inTransaction=function(event,context,f,args){var result,theseAfters,_i,_len;if(rootEvent){return f.apply(context,args)}else{rootEvent=event;result=f.apply(context,args);flush();rootEvent=void 0;while(afters.length){theseAfters=afters;afters=[];for(_i=0,_len=theseAfters.length;_i<_len;_i++){f=theseAfters[_i];f()}}return result}};currentEventId=function(){if(rootEvent){return rootEvent.id}else{return void 0}};wrappedSubscribe=function(obs,sink){var doUnsub,unsub,unsubd;unsubd=false;doUnsub=function(){};unsub=function(){unsubd=true;return doUnsub()};doUnsub=obs.dispatcher.subscribe(function(event){return afterTransaction(function(){var reply;if(!unsubd){reply=sink(event);if(reply===Bacon.noMore){return unsub()}}})});return unsub};hasWaiters=function(){return waiterObs.length>0};return{whenDoneWith:whenDoneWith,hasWaiters:hasWaiters,inTransaction:inTransaction,currentEventId:currentEventId,wrappedSubscribe:wrappedSubscribe}}();Bacon.EventStream=EventStream;Bacon.Property=Property;Bacon.Observable=Observable;Bacon.Bus=Bus;Bacon.Initial=Initial;Bacon.Next=Next;Bacon.End=End;Bacon.Error=Error;nop=function(){};latterF=function(_,x){return x()};former=function(x,_){return x};initial=function(value){return new Initial(_.always(value))};next=function(value){return new Next(_.always(value))};end=function(){return new End};toEvent=function(x){if(x instanceof Event){return x}else{return next(x)}};cloneArray=function(xs){return xs.slice(0)};assert=function(message,condition){if(!condition){throw new Exception(message)}};assertEventStream=function(event){if(!(event instanceof EventStream)){throw new Exception("not an EventStream : "+event)}};assertFunction=function(f){return assert("not a function : "+f,isFunction(f))};isFunction=function(f){return typeof f==="function"};isArray=function(xs){return xs instanceof Array};isObservable=function(x){return x instanceof Observable};assertArray=function(xs){if(!isArray(xs)){throw new Exception("not an array : "+xs)}};assertNoArguments=function(args){return assert("no arguments supported",args.length===0)};assertString=function(x){if(typeof x!=="string"){throw new Exception("not a string : "+x)}};partiallyApplied=function(f,applied){return function(){var args;args=1<=arguments.length?__slice.call(arguments,0):[];return f.apply(null,applied.concat(args))}};makeSpawner=function(args){if(args.length===1&&isObservable(args[0])){return _.always(args[0])}else{return makeFunctionArgs(args)}};makeFunctionArgs=function(args){args=Array.prototype.slice.call(args);return makeFunction_.apply(null,args)};makeFunction_=withMethodCallSupport(function(){var args,f;f=arguments[0],args=2<=arguments.length?__slice.call(arguments,1):[];if(isFunction(f)){if(args.length){return partiallyApplied(f,args)}else{return f}}else if(isFieldKey(f)){return toFieldExtractor(f,args)}else{return _.always(f)}});makeFunction=function(f,args){return makeFunction_.apply(null,[f].concat(__slice.call(args)))};makeObservable=function(x){if(isObservable(x)){return x}else{return Bacon.once(x)}};isFieldKey=function(f){return typeof f==="string"&&f.length>1&&f.charAt(0)==="."};Bacon.isFieldKey=isFieldKey;toFieldExtractor=function(f,args){var partFuncs,parts;parts=f.slice(1).split(".");partFuncs=_.map(toSimpleExtractor(args),parts);return function(value){var _i,_len;for(_i=0,_len=partFuncs.length;_i<_len;_i++){f=partFuncs[_i];value=f(value)}return value}};toSimpleExtractor=function(args){return function(key){return function(value){var fieldValue;if(value==null){return void 0}else{fieldValue=value[key];if(isFunction(fieldValue)){return fieldValue.apply(value,args)}else{return fieldValue}}}}};toFieldKey=function(f){return f.slice(1)};toCombinator=function(f){var key;if(isFunction(f)){return f}else if(isFieldKey(f)){key=toFieldKey(f);return function(left,right){return left[key](right)}}else{return assert("not a function or a field key: "+f,false)}};toOption=function(v){if(v instanceof Some||v===None){return v}else{return new Some(v)}};_={indexOf:Array.prototype.indexOf?function(xs,x){return xs.indexOf(x)}:function(xs,x){var i,y,_i,_len;for(i=_i=0,_len=xs.length;_i<_len;i=++_i){y=xs[i];if(x===y){return i}}return-1},indexWhere:function(xs,f){var i,y,_i,_len;for(i=_i=0,_len=xs.length;_i<_len;i=++_i){y=xs[i];if(f(y)){return i}}return-1},head:function(xs){return xs[0]},always:function(x){return function(){return x}},negate:function(f){return function(x){return!f(x)}},empty:function(xs){return xs.length===0},tail:function(xs){return xs.slice(1,xs.length)},filter:function(f,xs){var filtered,x,_i,_len;filtered=[];for(_i=0,_len=xs.length;_i<_len;_i++){x=xs[_i];if(f(x)){filtered.push(x)}}return filtered},map:function(f,xs){var x,_i,_len,_results;_results=[];for(_i=0,_len=xs.length;_i<_len;_i++){x=xs[_i];_results.push(f(x))}return _results},each:function(xs,f){var key,value;for(key in xs){value=xs[key];f(key,value)}return void 0},toArray:function(xs){if(isArray(xs)){return xs}else{return[xs]}},contains:function(xs,x){return _.indexOf(xs,x)!==-1},id:function(x){return x},last:function(xs){return xs[xs.length-1]},all:function(xs,f){var x,_i,_len;if(f==null){f=_.id}for(_i=0,_len=xs.length;_i<_len;_i++){x=xs[_i];if(!f(x)){return false}}return true},any:function(xs,f){var x,_i,_len;if(f==null){f=_.id}for(_i=0,_len=xs.length;_i<_len;_i++){x=xs[_i];if(f(x)){return true}}return false},without:function(x,xs){return _.filter(function(y){return y!==x},xs)},remove:function(x,xs){var i;i=_.indexOf(xs,x);if(i>=0){return xs.splice(i,1)}},fold:function(xs,seed,f){var x,_i,_len;for(_i=0,_len=xs.length;_i<_len;_i++){x=xs[_i];seed=f(seed,x)}return seed},flatMap:function(f,xs){return _.fold(xs,[],function(ys,x){return ys.concat(f(x))})},cached:function(f){var value;value=None;return function(){if(value===None){value=f();f=void 0}return value}},toString:function(obj){var ex,internals,key,value;try{recursionDepth++;if(obj==null){return"undefined"}else if(isFunction(obj)){return"function"}else if(isArray(obj)){if(recursionDepth>5){return"[..]"}return"["+_.map(_.toString,obj).toString()+"]"}else if((obj!=null?obj.toString:void 0)!=null&&obj.toString!==Object.prototype.toString){return obj.toString()}else if(typeof obj==="object"){if(recursionDepth>5){return"{..}"}internals=function(){var _results;_results=[];for(key in obj){if(!__hasProp.call(obj,key))continue;value=function(){try{return obj[key]}catch(_error){ex=_error;return ex}}();_results.push(_.toString(key)+":"+_.toString(value))}return _results}();return"{"+internals+"}"}else{return obj}}finally{recursionDepth--}}};recursionDepth=0;Bacon._=_;Bacon.scheduler={setTimeout:function(f,d){return setTimeout(f,d)},setInterval:function(f,i){return setInterval(f,i)},clearInterval:function(id){return clearInterval(id)},now:function(){return(new Date).getTime()}};if(typeof define!=="undefined"&&define!==null&&define.amd!=null){define([],function(){return Bacon});this.Bacon=Bacon}else if(typeof module!=="undefined"&&module!==null&&module.exports!=null){module.exports=Bacon;Bacon.Bacon=Bacon}else{this.Bacon=Bacon}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}]},{},[]);var h=require("virtual-dom/h");var diff=require("virtual-dom/diff");var patch=require("virtual-dom/patch");var createElement=require("virtual-dom/create-element");var pouchdb=require("pouchdb");var $=require("br-jquery");var bacon=require("baconjs");var requester=bacon.fromPoll("10000",function(){return bacon.fromPromise($.ajax("https://api.educ.ar/0.9/recursos/juego/316532?key=808509ff7e847aabbb73c4396fbaabe6010cfdd0"))});function render(count){return h("div",[h("a",{href:"blah"},count),h("a",{href:"http://google.com"},"google")])}var count="ponele";var tree=render(count);var rootNode=createElement(tree);document.body.appendChild(rootNode);var update=function(data){var newTree=render(data);var patches=diff(tree,newTree);rootNode=patch(rootNode,patches);tree=newTree};var filterClicks=function(event){if(event.target.host==window.location.host&&!event.ctrlKey&&!event.shiftKey&&!event.altKey&&!event.metaKey){return event}};var preventDefault=function(event){event.preventDefault();return event};var updateUrl=function(event){window.history.pushState(null,event.target.pathname.slice(1),event.target.pathname);return event};var router=$("a").asEventStream("click").filter(filterClicks).map(preventDefault).map(updateUrl).flatMapLatest(function(event){return $.ajax("https://api.educ.ar/0.9/recursos/juegos?key=808509ff7e847aabbb73c4396fbaabe6010cfdd0").then(function(data){event.payload=data;return event})}).mapError("Search fail");router.onValue(function(value){value.then(function(data){update(JSON.stringify(data))})}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "requirebin-sketch", | |
"version": "1.0.0", | |
"dependencies": { | |
"virtual-dom": "0.0.21", | |
"pouchdb": "3.1.0", | |
"br-jquery": "0.0.3", | |
"baconjs": "0.7.32" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<style type='text/css'>html, body { margin: 0; padding: 0; border: 0; } | |
body, html { height: 100%; width: 100%; }</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment