diff --git a/README.md b/README.md index a53531cc..3ef721ef 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ Maki ============== [![Build Status](https://img.shields.io/travis/martindale/maki.svg?branch=master&style=flat-square)](https://travis-ci.org/martindale/maki) [![Coverage Status](https://img.shields.io/coveralls/martindale/maki.svg?style=flat-square)](https://coveralls.io/r/martindale/maki) +![Project Status](https://img.shields.io/badge/status-alpha-red.svg?style=flat-square) [![Community](https://chat.maki.io/badge.svg)](https://chat.maki.io/) The complete stack for building extensible apps, faster than ever. Hand-roll your application by telling Maki what your application does, and it takes care of the rest – without getting in your way if you want to customize it. diff --git a/components/404.jade b/components/404.jade index 4ce6b115..78d5f02a 100644 --- a/components/404.jade +++ b/components/404.jade @@ -1,7 +1,16 @@ dom-module#maki-undefined template - .ui.container - h1 Not Found + .ui.text.container + h1 Nothing known. + p We're sorry, but we don't know anything about that. Here are some alternative resources you might be interested in. + + .ui.horizontal.segments + .ui.segment + p One + .ui.segment + p Two + .ui.segment + p Two script. Polymer({ is: 'maki-undefined' diff --git a/components/application.jade b/components/application.jade index 39b91beb..0c95a7be 100644 --- a/components/application.jade +++ b/components/application.jade @@ -48,8 +48,8 @@ dom-module#maki-application i.icon.medium | Medium - script(src="/js/page.min.js") - script(src="/js/jquery.js") + script(src="/js/page.min.js", async) + script(src="/js/jquery.js", async) script. window.maki = Polymer({ is: 'maki-application', diff --git a/components/channel.jade b/components/channel.jade index 9a943436..8b302c22 100644 --- a/components/channel.jade +++ b/components/channel.jade @@ -1,10 +1,13 @@ dom-module#maki-channel - script(src="/js/uuid.js") - script(src="/js/jsonrpc.js") + script(src="/js/uuid.js", async) + script(src="/js/jsonrpc.js", async) script. Polymer({ is: 'maki-channel', properties: { + namespace: { + type: String + }, autoconnect: { type: Boolean }, @@ -21,13 +24,6 @@ dom-module#maki-channel type: String }, }, - ready: function() { - var self = this; - console.log('[MAKI:CHANNEL]', 'ready'); - if (self.autoconnect === true) { - self._connect(); - } - }, _send: function(method, params) { var self = this; self.ws.send(JSON.stringify({ @@ -55,9 +51,54 @@ dom-module#maki-channel self._subscribe(element.src); } }, + _handleMessage: function(msg) { + var self = this; + console.log('[MAKI:CHANNEL]', '_handleMessage', msg); + + try { + var data = JSON.parse( msg.data ); + } catch (e) { + var data = {}; + } + + console.log('[MAKI:CHANNEL]', '_handleMessage', 'resulting data:', data); + + // experimental JSON-RPC implementation + if (data.jsonrpc === '2.0') { + console.log('[MAKI:CHANNEL]', '_handleMessage', 'valid jsonrpc!'); + + switch (data.method) { + case 'ping': + console.log('[MAKI:CHANNEL]', 'received ping. playing pong...'); + self.ws.send(JSON.stringify({ + 'jsonrpc': '2.0', + 'result': 'pong', + 'id': data.id + })); + break; + case 'patch': + // TODO: update in-memory data (two-way binding); + console.log('[MAKI:CHANNEL]', 'received `patch` event:', data.params.channel , data ); + var channel = data.params.channel; + var ops = data.params.ops; + var datastore = document.querySelector('maki-datastore[name='+self.namespace+']'); + var manager = document.querySelector('maki-peer-manager'); + + datastore._patch(channel, ops); + manager._relay(data); + + break; + default: + console.error('[MAKI:CHANNEL]', 'unhandled jsonrpc method ' , data.method); + break; + } + } else { + + } + }, _connect: function() { var self = this; - var maki = document.querySelectorAll('maki-application')[0]; + var maki = document.querySelector('maki-application'); var protocol = (document.location.protocol === 'http:') ? 'ws://' : 'wss://'; var path = protocol + document.location.host; // + self.src; @@ -71,43 +112,16 @@ dom-module#maki-channel }, 500); } } - self.ws.onmessage = function onMessage(msg) { - try { - var data = JSON.parse( msg.data ); - } catch (e) { - var data = {}; - } - // experimental JSON-RPC implementation - if (data.jsonrpc === '2.0') { - switch (data.method) { - case 'ping': - console.log('[MAKI:CHANNEL]', 'received ping. playing pong...'); - self.ws.send(JSON.stringify({ - 'jsonrpc': '2.0', - 'result': 'pong', - 'id': data.id - })); - break; - case 'patch': - // TODO: update in-memory data (two-way binding); - console.log('[MAKI:CHANNEL]', 'received `patch` event:', data.params.channel , data ); - var channel = data.params.channel; - var ops = data.params.ops; - var datastore = document.querySelectorAll('maki-datastore')[0]; - - datastore._patch(channel, ops); - - break; - default: - console.error('[MAKI:CHANNEL]', 'unhandled jsonrpc method ' , data.method); - break; - } - } else { - - } - } + self.ws.onmessage = self._handleMessage.bind(self); self.ws.onopen = function onOpen() { console.log('[MAKI:CHANNEL]', 'websocket open.'); } }, + ready: function() { + var self = this; + console.log('[MAKI:CHANNEL]', 'ready'); + if (self.autoconnect === true) { + self._connect(); + } + }, }); diff --git a/components/content-store.jade b/components/content-store.jade new file mode 100644 index 00000000..3781ecc6 --- /dev/null +++ b/components/content-store.jade @@ -0,0 +1,25 @@ +dom-module#maki-content-store + template + maki-crypto-worker + //- TODO: replace this with maki-peer-manager + maki-key-value(name="fabric") + script. + Polymer({ + is: 'maki-content-store', + _get: function(key, cb) { + var db = document.querySelector('maki-key-value[name=fabric]'); + db._retrieve(key, cb); + }, + _store: function(doc, cb) { + var db = document.querySelector('maki-key-value[name=fabric]'); + var worker = document.querySelector('maki-crypto-worker'); + if (typeof doc !== 'string') { + doc = JSON.stringify(doc); + } + worker._digest(doc, function(err, hash) { + db._store(hash, doc, function(err) { + cb(err, hash); + }); + }); + } + }); diff --git a/components/datastore.jade b/components/datastore.jade index bd471e2c..f200d8e5 100644 --- a/components/datastore.jade +++ b/components/datastore.jade @@ -1,4 +1,11 @@ +//- maki-datastore +//- is a top-level manager of data +//- maps /path to dom-module#maki-datastore + template + maki-crypto-worker(name="datastore") + maki-key-value(name="tips", for$="{{name}}") + maki-key-value(name$="{{name}}") script(src="/js/json-patch-duplex.min.js") script. Polymer({ @@ -7,92 +14,349 @@ dom-module#maki-datastore name: { type: String }, - store: { + for: { + type: String + }, + db: { + type: Object + }, + fabric: { + type: Object + }, + tips: { type: Object }, private: { type: Boolean + }, + resources: { + type: Object, + value: {} } }, listeners: { 'datastore:miss': '_handleMiss', - 'datastore:change': '_handleChange' + 'datastore:change': '_handleChange', + 'datastore:patch': '_handlePatch', + }, + _query: function(path, query, opts, cb) { + var self = this; + var name = self.name; + if (typeof opts === 'function') { + cb = opts; + opts = {}; + } + + console.log('[MAKI:DATASTORE]', name, '_query', 'incoming:', path, query, opts); + + // TODO: not do this + var application = document.querySelector(self.for + '-application'); + var resource = application._pathToResource(path); + console.log('[MAKI:DATASTORE]', name, '_query', 'dat path', path, resource); + resource.store.find(query, function(err, docs) { + console.log('[MAKI:DATASTORE]',name, '_query', 'dat result', err, docs); + cb(err, docs); + }); }, - _store: function(key, val, cb) { + _post: function(path, obj, cb) { + // TODO: middlewares var self = this; - console.log('[MAKI:DATASTORE]', '_store', typeof val, key, val); - if (val instanceof Array && val.length === 0) return cb('Empty array not allowed.'); - self.store.put(key, val, function(err) { + console.log('[MAKI:DATASTORE]', '_post', '_publish', 'adding', path, obj); + + self.tips._get(path, function(err, tip) { + if (err) console.error('[MAKI:DATASTORE]', '_post', 'tip retrieval err:', err); + self.db._get(tip, { + convert: true + }, function(err, collection) { + if (err) console.error('[MAKI:DATASTORE]', '_post', 'getTip error:', err); + if (!collection) { + collection = []; + } + if (!(collection instanceof Array)) { + console.error('[MAKI:DATASTORE]', '_post', 'getTip not collection', collection); + return cb('Tip exists, but does not store a collection.'); + } + + console.log('[MAKI:DATASTORE]', '_post', '_publish', 'getTip results', collection); + + self._put(path + '/' + obj['id'], obj, function(err, doc) { + if (err) console.error('[MAKI:DATASTORE]', '_post', '_put', path + '/' + obj['id'], err); + // TODO: remove this condition, understand where and why `null` + // happens to `doc` sometimes... + if (doc) { + collection.unshift(doc); + } + + console.error('[MAKI:DATASTORE]', '_post', '_publish', 'collection (before):', path, collection); + + collection = collection.map(function(x) { + if (x['@id']) { + return x['@id']; + } else { + return x; + } + }); + collection = JSON.parse(JSON.stringify(collection)); + + console.error('[MAKI:DATASTORE]', '_post', '_publish', 'collection (after):', path, collection); + + self._put(path, collection, function(err) { + if (err) console.error('[MAKI:DATASTORE]', '_post', '_publish', 'adding result', err); + return cb(err, doc); + }); + }); + }); + }); + }, + _put: function(path, val, cb) { + // TODO: middlewares + var self = this; + var name = self.name; + self._bundle(val, function(err, obj) { if (err) console.error(err); - self.fire('datastore:change', { - key: key, - val: val + console.log('[MAKI:DATASTORE]', '_put', '_post', '_bundle', '_publish', 'output', obj); + if (!obj) console.log('[MAKI:DATASTORE]', '_put', 'grave concern! no obj from bundle', path, val); + if (!obj['@id']) console.log('[MAKI:DATASTORE]', '_put', 'grave concern! no @id from bundle', obj); + + /*if (obj['@id'] === val['@id']) { + return cb(null, obj); + }*/ + + self.db._set(obj['@id'], obj, function(err) { + if (err) console.error(err); + console.log('[MAKI:DATASTORE]', name, '_put', '_publish', 'setting tip...', path, obj['@id']); + self.tips._set(path, obj['@id'], function(err) { + if (err) console.error(err); + console.log('[MAKI:DATASTORE]', name, '_put', '_publish', 'set the tip!', path, obj); + + self._flatten(obj, function(err, doc) { + var application = document.querySelector(self.for + '-application'); + // TODO: not do this. maybe use the `private` property? + if (!application) { + console.error('[MAKI:DATASTORE]', name, '_put', '_publish', 'could not find application', self.for); + self.fire('datastore:change', { + path: path, + val: obj, + old: undefined + }); + + return cb(err, obj); + } else { + var resource = application._pathToResource(path); + + resource.store.insert(obj, function(err, result) { + if (err) console.error('[MAKI:DATASTORE]', name, '_put', '_publish', 'store.insert:', err); + + self.fire('datastore:change', { + path: path, + val: obj, + old: undefined + }); + + console.log('[MAKI:DATASTORE]', name, '_put', '_publish', 'shared:', path, obj, result); + + return cb(err, obj); + }); + } + }); + }); }); - return cb(err); }); }, - _retrieve: function(key, cb) { + _update: function(path, query, updates, opts, cb) { + var self = this; + + console.log('[MAKI:DATASTORE]', '_update', self.for); + console.log('[MAKI:DATASTORE]', '_update', path, query, updates, opts); + console.log('[MAKI:DATASTORE]', '_update', 'updates:', updates, 'opts:', opts); + + var application = document.querySelector(self.for + '-application'); + var resource = application._pathToResource(path); + resource.store.update(query, updates, opts, cb); + }, + _upsert: function(path, query, item, cb) { var self = this; - console.log('[MAKI:DATASTORE]', '_retrieve looking for:', key); - self.store.get(key, { - asBuffer: false - }, function(err, val) { + self._update(path, query, item, { + upsert: true + }, function(err, numAffected) { + console.log('[MAKI:DATASTORE]', '_upsert end', err, numAffected); + cb(err); + }); + }, + _flatten: function(item, cb) { + var self = this; + window.traverse(item, function(node, next) { + var context = this; + if (context.isRoot) return next(); + var key = context.key; + var val = context.parent[key]; + if (val['@id']) { + context.parent[key] = val['@id']; + } + next(); + }, function(final) { + cb(null, final); + }); + }, + // HTTP-emulated GET request + _get: function(path, cb) { + // TODO: middlewares + var self = this; + var name = self.name; + console.log('[MAKI:DATASTORE]', '_get looking for:', path); + + var eventName = 'key-value:'+name+':open'; + console.log('[MAKI:DATASTORE]', name, '_get', 'waiting for (eventName):', eventName); + self.tips._get(path, function(err, tip) { + if (err) console.error('[MAKI:DATASTORE]', '_get', path, err); + + console.log('[MAKI:DATASTORE]', name, '_get', path, 'tip is:', tip); + + self.db._get(tip, { + convert: true, + //hydrate: true + }, function(err, obj) { + if (err || !obj) { + obj = []; + } + + console.log('[MAKI:DATASTORE]', name, '_get', 'db.get', 'will traverse:', err, tip, obj); + function resolveReferences(node, next) { + var context = this; + var key = context.key; + console.log('[MAKI:DATASTORE]', name, '_get', 'traverse', 'key', key, context, node); + if (typeof node !== 'string') return next(); + if (key === '@id') return next(); + + console.log('[MAKI:DATASTORE]', name, '_get', 'traverse', 'populating', key); + self.db._get(node, { + convert: true + }, function(err, item) { + if (err) console.error('[MAKI:DATASTORE]', '_get', 'error:', err); + if (!item) return next(); + console.log('[MAKI:DATASTORE]', name, '_get', 'key:', key, 'found:', item); + console.log('[MAKI:DATASTORE]', name, '_get', 'key:', key, 'replacing:', key, 'with', item, 'in', context.parent); + + console.log('[MAKI:DATASTORE]', name, '_get', 'key:', key, 'was:', context.parent[key], 'in', context.parent); + context.parent[key] = item; + console.log('[MAKI:DATASTORE]', name, '_get', 'key:', key, 'now:', context.parent[key]); + console.log('[MAKI:DATASTORE]', name, '_get', 'deep diving...', item); + // deep dive. + window.traverse(item, resolveReferences, function(inner) { + if (!inner) return next(); + console.log('[MAKI:DATASTORE]', name, '_get', 'inner:', inner); + next(); + }); + }); + } + + // TODO: make modular + window.traverse(obj, resolveReferences, function(final) { + console.log('[MAKI:DATASTORE]', '_get', path, 'final:', null, final); + return cb(null, final); + }); + }); + }); + + /*self.db._get(key, function(err, val) { if (err) console.error(err); - if (val) return cb(null, val); + if (val) return cb(null, val) && self.fire('datastore:miss', key); self.fire('datastore:miss', key); return cb('datastore:miss'); - }); + });*/ }, _patch: function(key, ops, cb) { + // TODO: middlewares var self = this; console.log('[MAKI:DATASTORE]', 'datastore:patch:', key, ops); - self._retrieve(key, function(err, obj) { + self._get(key, function(err, obj) { if (err) console.error(err); console.log('[MAKI:DATASTORE]', 'applying to:', obj); jsonpatch.apply(obj, ops); console.log('[MAKI:DATASTORE]', 'obj now:', obj); - - self._store(key, obj, function(err) { + self._put(key, obj, function(err) { if (err) console.error(err); }); }); }, + _bundle: function(obj, cb) { + var self = this; + console.log('[MAKI:DATASTORE]', '_bundle', '_post', 'pre-parse', obj); + obj['@id'] = undefined; + console.log('[MAKI:DATASTORE]', '_bundle', '_post', 'post-parse', obj); + var worker = document.querySelector('maki-crypto-worker[name=datastore]'); + worker._digest(obj, function(err, hash) { + console.log('[MAKI:DATASTORE]', '_bundle', '_put', '_post', 'post-parse digest:', hash); + obj['@id'] = hash; + cb(err, obj); + }); + }, _handleMiss: function(e, detail) { + return; var self = this; var key = e.detail; - console.log('[MAKI:DATASTORE]', '_handleMiss', e, detail); - console.log('private:', self.private); if (self.private) return; - + + // TODO: query network instead of server $.getJSON(key, function(data) { console.log('[MAKI:DATASTORE]', 'retrieved (from remote)', data); if (!data) return; - self._store(key, data, function(err) { + self._put(key, data, function(err) { if (err) console.error('[MAKI:DATASTORE]', '_handeMiss error:', err); }); }); }, + _handlePatch: function(e) { + var self = this; + console.log('[MAKI:DATASTORE]', '_handlePatch', e.detail); + var channel = document.querySelector('maki-channel'); + channel._send('patch', { + channel: e.detail.key, + ops: e.detail.patches + }); + }, _handleChange: function(e, detail) { var self = this; - var key = detail.key; - var val = detail.val; - console.log('[MAKI:DATASTORE]', '_handleChange', detail); + console.log('[MAKI:DATASTORE]', '_handleChange', e, detail); + if (!detail) { + var detail = e.detail; + } - var channel = document.querySelectorAll('maki-channel'); - /*channel._send('patch', { - channel: key, - ops: [{ op: 'add', }] - });*/ + var path = detail.path; + var val = detail.val; + var old = detail.old; - var pattern = '[src="'+key+'"]'; - console.log('[MAKI:DATASTORE]', 'pattern:', pattern); - - var elements = document.querySelectorAll(pattern); + /* if (!old) { + if (val instanceof Array) { + old = []; + } else { + old = {}; + } + } - console.log('[MAKI:DATASTORE]', 'elements bound to this key:', key, elements); + if (old) { + var worker = document.querySelector('maki-crypto-worker'); + var observer = jsonpatch.observe(old); + + console.log('[MAKI:DATASTORE]', 'extending', old, 'with', val); + var now = _.extend(old, val); + console.log('[MAKI:DATASTORE]', 'final:', now); + var patches = jsonpatch.generate(observer); + + console.log('[MAKI:DATASTORE]', 'patch set generated:', patches); + + var channel = document.querySelectorAll('maki-channel'); + /*channel._send('patch', { + channel: key, + ops: [{ op: 'add', }] + });**** + } */ + var pattern = '[src="'+path+'"]'; + var elements = document.querySelectorAll(pattern); + console.log('[MAKI:DATASTORE]', 'elements bound to this key:', path, elements); for (var i = 0; i < elements.length; i++) { var element = elements[i]; element._sync(); @@ -100,9 +364,7 @@ dom-module#maki-datastore }, _sync: function() { var elements = document.querySelectorAll('[src]'); - console.log('[MAKI:DATASTORE]', '_sync', elements); - for (var i = 0; i < elements.length; i++) { var element = elements[i]; if (typeof element._sync === 'function') { @@ -118,16 +380,18 @@ dom-module#maki-datastore ready: function() { var self = this; console.log('[MAKI:DATASTORE]', 'ready'); - self.store = level(self.name); - self.store.open(function(err) { - console.log('[MAKI:DATASTORE]', 'open'); - var event = new Event('datastore:open') - document.dispatchEvent(event); - var event = new Event('datastore:'+self.name+':open') - document.dispatchEvent(event); - - if (err) console.error(err); - self._sync(); + document.addEventListener('key-value:tips:open', function() { + self.tips = document.querySelector('maki-key-value[name=tips][for='+self.name+']'); + }); + document.addEventListener('key-value:'+self.name+':open', function() { + console.log('[MAKI:DATASTORE]', 'key-value open received!'); + self.db = document.querySelector('maki-key-value[name='+self.name+']'); + + self.db.addEventListener('key-value:change', self._handleChange.bind(self)); + + self.fire('datastore:'+self.name+':open'); + self.fire('datastore:open'); }); + //self.listen(self.db, 'key-value:change', '_handleChange'); } }); diff --git a/components/identity-card.jade b/components/identity-card.jade index d2bed575..fbbf8036 100644 --- a/components/identity-card.jade +++ b/components/identity-card.jade @@ -1,10 +1,4 @@ dom-module#maki-identity-card - template - .image - img(src="/img/stevie.jpg") - .content - .header {{identity.name}} - .ui.bottom.attached.button(on-tap="_selectIdentity") use {{identity.name}} script. Polymer({ is: 'maki-identity-card', @@ -12,12 +6,5 @@ dom-module#maki-identity-card identity: { type: Object } - }, - _selectIdentity: function(e, detail) { - var self = this; - console.log('[MAKI:IDENTITY]', '_selectIdentity', e, detail); - var manager = document.querySelectorAll('maki-identity')[0]; - manager.identity = self.identity; - manager._register(); - }, + } }); diff --git a/components/identity.jade b/components/identity.jade index 1a8029c0..aa340460 100644 --- a/components/identity.jade +++ b/components/identity.jade @@ -1,246 +1,404 @@ dom-module#maki-identity template - maki-datastore(name="identity", private) + maki-crypto-worker(name="identity") + maki-datastore(name="identity", for$="{{for}}", private) + a.item(href="/", on-tap="_reset") Reset //- TODO: this should be a /people thing, not an identity - template(is="dom-if", if="{{!isLoggedIn}}") - .ui.button.item(on-tap="_onboard") + template(is="dom-if", if="{{!hasIdentities}}") + a.item(on-tap="_onboard") i.icon.sign.in | Sign In - - template(is="dom-if", if="{{isLoggedIn}}") - a.item(href="/people/{{identity.name}}") - template(is="dom-if", if="{{isNamed}}") {{identity.name}} - template(is="dom-if", if="{{!isNamed}}") anonymous - .ui.button.item(on-tap="_logout") - i.icon.sign.out - | Sign Out + template(is="dom-if", if="{{hasIdentities}}") + template(is="dom-if", if="{{!isLoggedIn}}") + .ui.dropdown.item + i.icon.sign.in + | Sign In + i.icon.dropdown + maki-identity-list.menu + template(is="dom-repeat", items="{{identities}}") + maki-identity-card.item(identity="{{item}}", on-tap="_selectIdentity") {{item.name}} + .green.icon.labeled.item(on-tap="_onboard") + i.icon.leaf + | Start Fresh + template(is="dom-if", if="{{isLoggedIn}}") + //-a.item(href="/settings") + i.icon.setting + a.item(href="/people/{{identity.name}}") + template(is="dom-if", if="{{isNamed}}") {{identity.name}} + template(is="dom-if", if="{{!isNamed}}") anonymous + .ui.button.item(on-tap="_logout") + i.icon.sign.out + | Sign Out maki-modal.ui.modal#identity-confirm - .header With which identity? + .header Let's introduce ourselves. How? .content .description - .ui.four.cards - template(is="dom-repeat", items="{{identities}}") - maki-identity-card.ui.card(identity="{{item}}") - .ui.card - .image - img(src="/img/image.png") - .content - .ui.bottom.attached.labeled.button(on-tap="_generate") Create New - i.icon.chevron.right + .ui.two.massive.stackable.buttons + .ui.blue.labeled.icon.button(on-tap="_importFromSeed") + i.icon.eyedropper + | Existing Seed + .or + .ui.green.right.labeled.icon.button(on-tap="_displayGeneratorModal") + i.icon.leaf + | Fresh Start + + .ui.icon.fluid.message + i.icon.idea + .content + .header Forget your worries, not your passwords. + p Maki-powered apps remember you, so you never have to click "forgot password" again. + a(href="/") Learn More » + .actions - .ui.right.labeled.icon.button(on-tap="_closeSelectionModal") Nevermind, don't sign in. - i.cancel.icon - - form.ui.modal#identity-name - .header What should we call you? - .content - .description - .ui.large.form - .field - label Your Name - input(type="text", placeholder="SomeUsername", value="{{identity.name}}") - p Other people will see this, so pick something good. - .actions - button.ui.positive.right.labeled.icon.button(type="submit", on-tap="_setName") Set Name and Sign In - i.right.chevron.icon + .ui.right.labeled.icon.button(on-tap="_closeSelectionModal") Some other time. + i.remove.icon maki-modal.ui.modal#identity-create - .header Who are you? + .header Identity Generator .content .description - p It doesn't look like we've seen you before. - h3 {{words}} - p - strong Please write this down and keep it in a safe place! - | We can't recover this for you, and without it, you'll lose everything. + maki-step-ladder + .clearing + .actions - .ui.positive.right.labeled.icon.button(on-tap="_displayNameModal") Yep, I've written it down. - i.checkmark.icon + .ui.cancel.labeled.icon.button.hidden(on-tap="_displayNameModal") Nevermind, I'm done here. + i.remove.icon - script(src="/js/lodash.min.js") - script(src="/assets/bitcore.min.js") - script(src="/assets/bitcore-mnemonic.min.js") + script(src="/js/lodash.min.js", async) + script(src="/assets/bitcore.min.js", async) + script(src="/assets/bitcore-mnemonic.min.js", async) script. Polymer({ is: 'maki-identity', properties: { - seed: { - type: String - }, - words: { - type: String - }, - identity: { - type: Object, - notify: true, - observer: '_identityChanged' - }, - isLoggedIn: { - type: Boolean, - value: false - }, - isNamed: { - type: Boolean, - value: false - }, - display: { - type: String - } + for: { type: String }, + seed: { type: String }, + words: { type: String }, + identity: { type: Object, notify: true, observer: '_identityChanged' }, + identityFull: { type: Object, }, + isLoggedIn: { type: Boolean, value: false }, + autoselect: { type: Boolean, value: false }, + hasIdentities: { type: Boolean, value: false }, + isNamed: { type: Boolean, value: false }, + display: { type: String } }, - _setName: function(e) { - e.preventDefault(); + _generate: function(cb) { var self = this; - var name = $('.modal#identity-name input').val(); - console.log('setting name:', name); - self.set('identity.name', name); - self.isNamed = true; - self._save(); - self._register(); - }, - _authenticate: function() { + console.log('[MAKI:IDENTITY]', '_generate'); + // TODO: do this in a Web Worker to prevent UI jank + var Mnemonic = require('bitcore-mnemonic'); + var mnemonic = new Mnemonic(); + + var key = mnemonic.toHDPrivateKey(); + var sub = key.derive('m/0'); + + self.seed = mnemonic; + self.words = mnemonic.toString(); + var identity = { + id: sub.hdPublicKey.toString(), + _id: ObjectId().toString(), + seed: mnemonic.toString(), + //address: sub.hdPublicKey.toAddress(), + key: { + hd: true, + private: key.toString(), + public: sub.hdPublicKey.toString() + } + }; + + var clone = _.cloneDeep(identity); + delete clone.seed; + delete clone.key.private; + + self.identity = clone; + self.identityFull = identity; + + self._save(cb); }, - _displayCreatedModal: function() { - $('.modal#identity-create').modal('setting', 'closable', false).modal('show'); - }, - _displayNameModal: function() { - var self = this; - $('.modal#identity-name').on('submit', self._setName.bind(self)); - $('.modal#identity-name').modal('show'); - $('.modal#identity-name input').focus(); - }, - _displaySelectionModal: function() { - $('.modal#identity-confirm').modal('show'); - }, - _closeSelectionModal: function() { - $('.modal#identity-confirm').modal('hide'); - }, - _sign: function(input, done) { - var Message = require('bitcore-message'); - }, - _identityChanged: function(identity, old) { - var self = this; - console.log('[MAKI:IDENTITY]', '_identityChanged', identity, old); - self.isLoggedIn = true; - if (identity && identity.name) { - self.isNamed = true; - } - $('.modal#identity-confirm').modal('hide'); - self.fire('identity', identity); - }, - _onboard: function() { - var self = this; - self._select(); - }, - _register: function() { + _save: function(cb) { var self = this; - console.log('[MAKI:IDENTITY]', '_register'); - self._publish(); - // TODO: use purely local store - $.ajax({ - type: 'POST', - url: '/people', - data: { - name: self.identity.name, - _identity: self.identity.key.public - }, - headers: { - Accept: 'application/json' - }, - success: function(data, res) { - console.log('[MAKI:IDENTITY]', '_register result:', res); - } + var datastore = document.querySelector('maki-datastore[name=identity]'); + var identity = self.identityFull; + console.log('[MAKI:IDENTITY]', '_save', identity); + + datastore._upsert('/identities', { + 'key.public': identity.key.public + }, identity, function(err) { + if (err) console.log('err', err); + + console.log('[MAKI:IDENTITY]', '_upsert', 'callback', err, identity); + + datastore._query('/identities', { + 'key.public': identity.key.public + }, function(err, identities) { + if (err) console.error('[MAKI-IDENTITY]', '_save', '_query', err); + console.log('[MAKI-IDENTITY]', '_save', '_query', 'identities', identities); + cb(err, identities); + }); }); }, - _publish: function() { + // publishes to the local application scoped for this control + // makes the application aware of an identity + _publish: function(cb) { var self = this; console.log('[MAKI:IDENTITY]', '_publish'); + if (!cb) cb = new Function(); var clone = _.cloneDeep(self.identity); delete clone.seed; delete clone.key.private; - // TODO: use purely local store - $.ajax({ - type: 'PUT', - url: '/identities/' + clone.key.public, + // a simple stub to emulate only having a single identity. + // just queries the application datastore and assumes the first identity + // it finds is ours. net effect: will always overwrite one user. + var datastore = document.querySelector('maki-datastore[for='+self.for+']'); + console.log('[MAKI:IDENTITY]', '_publish', 'query', datastore); + // TODO: add unique keys to `maki-datastore` and/or `maki-resource`. + datastore._query('/identities', { + 'key.public': clone.key.public + }, function(err, identities) { + console.log('[MAKI:IDENTITY]', '_publish', 'melody knows these identities:', err, identities); + console.log('[MAKI:IDENTITY]', '_publish', 'you are:', clone.key.public); + + async.filter(identities, function(identity, callback) { + var doesMatch = (identity.key.public === clone.key.public); + console.log('[MAKI:IDENTITY]', '_publish', 'comparing:', identity.key.public, clone.key.public); + callback(null, doesMatch); + }, function(err, known) { + console.log('[MAKI:IDENTITY]', '_publish', 'matching', err, known); + if (!known.length) { + // TODO: transform into JSON-LD + datastore._post('/identities', clone, function(err, stored) { + console.log('[MAKI:IDENTITY]', '_publish', 'datastore put, identity return:', err, stored); + cb(err, stored); + }); + } else { + console.log('[MAKI:IDENTITY]', '_publish', 'datastore returning obj:', known[0]); + cb(err, known[0]); + } + }); + }); + + /*$.ajax({ + type: 'POST', + url: '/identities', data: clone, headers: { Accept: 'application/json' }, success: function(data) { console.log('[MAKI:IDENTITY]', 'published:', data); + self.identity._id = data._id; + cb(null, data); } + });*/ + }, + _reset: function() { + var dbs = [ + 'IDBWrapper-fabric-key-value', + 'IDBWrapper-identity-key-value', + 'IDBWrapper-identity:tips-key-value', + 'IDBWrapper-melody-key-value', + 'IDBWrapper-melody:tips-key-value', + 'NeDB', + 'fabric-identity', + ]; + + dbs.forEach(function(name) { + var req = indexedDB.deleteDatabase(name); + req.onsuccess = function () { + console.log('[MAKI:IDENTITY]', "Deleted database successfully"); + }; + req.onerror = function () { + console.log('[MAKI:IDENTITY]', "Couldn't delete database"); + }; + req.onblocked = function () { + console.log('[MAKI:IDENTITY]', "Couldn't delete database due to the operation being blocked"); + }; }); + + }, + _authenticate: function() { }, - _save: function() { - var self = this; - var db = document.querySelectorAll('maki-datastore[name=identity]')[0]; - var identity = self.identity; - - db._store('/identities', [identity], function(err) { - if (err) console.log('err', err); + _displaySelectionModal: function() { + $('.modal#identity-confirm').modal('show'); + }, + _closeSelectionModal: function() { + $('.modal#identity-confirm').modal('hide'); + }, + _displayGeneratorModal: function() { + $('.modal#identity-create').modal('show'); + }, + _closeGeneratorModal: function() { + $('.modal#identity-create').modal('hide'); + }, + _initializeDropdown: function() { + $('.ui.dropdown').dropdown({ + action: 'nothing' }); + }, + _initiateGeneration: function() { + var self = this; + self._closeSelectionModal(); + self._generate(); + }, + _onboard: function() { + var self = this; + self._select(); + }, + _sign: function(input, done) { + var Message = require('bitcore-message'); + }, + _identityChanged: function(identity, old) { + var self = this; + self.identityFull = identity; - db._store('/identities/' + identity.key.public, identity, function(err) { - - }); + if (self.identity) { + self.isLoggedIn = true; + } + if (self.identities) { + self.hasIdentities = true; + } + if (identity && identity.name) { + self.isNamed = true; + self.fire('identity', identity); + } }, - _generate: function() { + _register: function() { var self = this; - console.log('[MAKI:IDENTITY]', '_generate'); - // TODO: do this in a Web Worker to prevent UI jank - var Mnemonic = require('bitcore-mnemonic'); - var mnemonic = new Mnemonic(); + console.log('[MAKI:IDENTITY]', '_register', 'calling publish...'); + self._publish(function(err, identity) { + if (err) console.error(err); + + var identity = self.identity; + console.log('[MAKI:IDENTITY]', '_register', '_publish', 'identity:', identity); - var key = mnemonic.toHDPrivateKey(); - var sub = key.derive('m/0'); + var datastore = document.querySelector('maki-datastore[name=melody]'); + datastore._bundle(identity, function(err, ident) { + console.log('[MAKI:IDENTITY]', '_register', '_publish', 'bundled:', ident); + console.log('[MAKI:IDENTITY]', '_register', '_publish', 'querying...', ident['@id']); + datastore._query('/people', { + identity: ident['@id'] + }, function(err, known) { + console.log('[MAKI:IDENTITY]', '_register', '_publish', 'melody knew:', err, known); + if (err || known.length) { + return console.log('[MAKI:IDENTITY]', '_register', 'application "melody" knew identity:', ident['@id'], 'as', known[0].name); + } + + datastore._post('/people', { + id: identity.name.toLowerCase(), + _id: ObjectId().toString(), + name: identity.name, + slug: identity.name.toLowerCase(), + identity: ident['@id'] + }, function(err, person) { + console.log('[MAKI:IDENTITY]', '_register', 'datastore put, person return:', err, person); + }); + }); - self.seed = mnemonic; - self.words = mnemonic.toString(); - self.identity = { - seed: mnemonic.toString(), - //address: sub.hdPublicKey.toAddress(), - key: { - hd: true, - private: key.toString(), - public: sub.hdPublicKey.toString() - } - }; - - self._save(self.identity); - self._displayCreatedModal(); + }); + + /* $.ajax({ + type: 'POST', + url: '/people', + data: { + name: identity.name, + identity: identity.key.public, + _identity: identity._id + }, + headers: { + Accept: 'application/json' + }, + success: function(data, res) { + console.log('[MAKI:IDENTITY]', '_register result:', res); + } + }); */ + }); }, _select: function() { var self = this; - var db = document.querySelectorAll('maki-identity maki-datastore')[0]; - var melody = document.querySelectorAll('melody-application')[0]; + var db = document.querySelector('maki-datastore[name=identity]'); + var melody = document.querySelector('melody-application'); console.log('[MAKI:IDENTITY]', '_select'); - db._retrieve('/identities', function(err, identities) { + db._get('/identities', function(err, identities) { console.log('[MAKI:IDENTITY]', 'retrieved', identities); - if (!identities || !identities.length) { - return self._generate(); - } - self.identities = identities; + self.identities = identities || []; self._displaySelectionModal(); }); }, + _selectIdentity: function(e, detail) { + var self = this; + console.log('[MAKI:IDENTITY]', '_selectIdentity', e, detail); + var manager = document.querySelector('maki-identity'); + e.target.classList.add('loading'); + manager.identity = e.target.identity; + manager._register(); + }, + _startAgent: function() { + if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('/worker.js').then(function(reg) { + console.log('[MAKI:IDENTITY]', 'service worker installled!'); + + navigator.serviceWorker.addEventListener('message', function(event) { + console.log('[MAKI:IDENTITY]', 'serviceworker message:', event ); + }); + + }).catch(function(err) { + console.log('[MAKI:IDENTITY]', 'service worker failed:', err); + }); + } + }, + _attach: function() { + var self = this; + var localIdentityStore = document.querySelector('maki-datastore[name=identity]'); + console.log('[MAKI:IDENTITY]', '_attach', 'querying...'); + //self._startAgent(); + // this emulates the HTTP API, but don't be fooled – this could be + // replaced with anything. use the tools you have, right? :) + // TODO: look at this. + //localIdentityStore._get('/identities', function(err, identities) { + localIdentityStore._query('/identities', {}, function(err, identities) { + console.log('[MAKI:IDENTITY]', '_attach', 'recovered:', identities); + + if (err) console.warn('[MAKI:IDENTITY]', 'retrieved', identities); + if (!identities) identities = []; + self.identities = identities; + if (identities.length) { + self.hasIdentities = true; + if (self.autoselect) { + self.identity = identities[0]; + console.warn('[MAKI:IDENTITY]', 'autoselect _register', self.identity); + self._register(); + } + } + self._initializeDropdown(); + }); + }, _logout: function() { var self = this; self.identity = null; self.isLoggedIn = false; - console.log('[MAKI:IDENTITY]', '_logout', self.identity); - self.fire('identity', null); + // TODO: why is a delay required here? + setTimeout(function() { + self._initializeDropdown(); + }, 50); + }, + attached: function() { + var self = this; + console.log('[MAKI:IDENTITY]', 'attached'); + self._initializeDropdown(); }, ready: function() { var self = this; console.log('[MAKI:IDENTITY]', 'ready'); - //document.addEventListener('datastore:identity:open', self._select.bind(self), false); + document.addEventListener('datastore:identity:open', self._attach.bind(self), false); + //self.addEventListener('identity', self._initializeDropdown.bind(self), false); } }); diff --git a/components/item.jade b/components/item.jade index 475199c2..04e91bb8 100644 --- a/components/item.jade +++ b/components/item.jade @@ -9,7 +9,7 @@ dom-module#maki-item template(if="{{item.action}}") a.ui.bottom.attached.button(if="{{item.action}}", href="{{item.action.href}}") {{item.action.text}} - script(src="/js/jquery.js") + script(src="/js/jquery.js", async) script. Polymer({ is: 'maki-item', diff --git a/components/key-value.jade b/components/key-value.jade new file mode 100644 index 00000000..b2c0009c --- /dev/null +++ b/components/key-value.jade @@ -0,0 +1,87 @@ +//- maki-key-value +//- keeps a simple key:value mapping +//- backed by LevelDB +dom-module#maki-key-value + //-script(src="/assets/level.js") + script. + Polymer({ + is: 'maki-key-value', + properties: { + name: { + type: String + }, + for: { + type: String + }, + level: { + type: Object + } + }, + _get: function(key, opts, cb) { + var self = this; + if (typeof opts == 'function') { + cb = opts; + opts = {}; + } + console.log('[MAKI:KV]', '_get', 'key', key); + self.level.get(key, { + asBuffer: false + }, function(err, val) { + + console.log('[MAKI:KV]', '_get', 'valfor', key, val); + + if (err) console.error(err); + if (!val) return cb('No such value: ' + key, null); + if (opts.convert) { + console.log('[MAKI:KV]', '_get', 'converting:', val); + try { + val = JSON.parse(val); + } catch (e) { + console.error('[MAKI:KV]', '_get', e); + } + } + console.log('[MAKI:KV]', '_get', key, val); + return cb(err, val); + }); + }, + _set: function(key, val, cb) { + var self = this; + console.log('[MAKI:KV]', '_set', key, val); + + if (typeof val !== 'string') { + val = JSON.stringify(val); + } + + // TODO: use async. + self.level.get(key, { + asBuffer: false + }, function(err, old) { + if (err) console.error(err); + self.level.put(key, val, function(err) { + if (err) console.error(err); + self.fire('key-value:change', { + key: key, + val: val, + old: old + }); + console.log('[MAKI:KV]', '_set', key, val); + return cb(err); + }); + }); + }, + ready: function() { + var self = this; + var name = self.name + '-key-value'; + if (self.for) { + name = self.for + ':' + name; + } + self.level = level(name); + self.level.open(function(err) { + if (err) console.error(err); + var event = new Event('key-value:open'); + document.dispatchEvent(event); + var event = new Event('key-value:'+self.name+':open'); + document.dispatchEvent(event); + }); + } + }); diff --git a/components/maki-splash.jade b/components/maki-splash.jade index c6f7ce69..9f7502f8 100644 --- a/components/maki-splash.jade +++ b/components/maki-splash.jade @@ -5,7 +5,6 @@ dom-module#maki-splash } template - .ui.inverted.vertical.masthead.center.aligned.segment .ui.text.container h1.ui.inverted.header Code less. @@ -80,3 +79,15 @@ dom-module#maki-splash hljs.initHighlightingOnLoad(); } }); + + /*(function () { + window._BlabNS = {}; + window._BlabNS.user_id = '7f64ecb8166943cd896ea28ff8d0c5d0'; + window._BlabNS.enableMobile = true; + var s = document.createElement('script'); + s.type = 'text/javascript'; + s.async = true; + s.src = 'https://cdn.blab.im/tinyplayer/js/sdk.js'; + var x = document.getElementsByTagName('script')[0]; + x.parentNode.insertBefore(s, x); + })();*/ diff --git a/components/peer-list.jade b/components/peer-list.jade new file mode 100644 index 00000000..4b7380ef --- /dev/null +++ b/components/peer-list.jade @@ -0,0 +1,25 @@ +dom-module#maki-peer-list + template + maki-datastore(name="fabric") + h2 Currently Connected Peers + .ui.cards + template(is="dom-repeat", items="{{peers}}") + .ui.card + .content + .header {{item.id}} + script. + Polymer({ + is: 'maki-peer-list', + properties: { + peers: Array + }, + ready: function() { + var self = this; + var fabric = document.querySelector('maki-datastore[name=melody]'); + console.log('[FABRIC:PEER-LIST]', 'ready'); + fabric._retrieve('/peers', function(err, peers) { + console.log('[FABRIC:PEER-LIST]', 'ready _retrieve', err, peers); + self.set('peers', peers); + }); + } + }); diff --git a/components/peer-manager.jade b/components/peer-manager.jade new file mode 100644 index 00000000..9eb71b21 --- /dev/null +++ b/components/peer-manager.jade @@ -0,0 +1,261 @@ +dom-module#maki-peer-manager + template + //-maki-datastore(name="fabric") + script(src="/assets/peer.min.js", async) + script. + Polymer({ + is: 'maki-peer-manager', + properties: { + peer: { + type: Object + }, + connections: { + type: Object, + value: {} + }, + peers: { + type: Object, + value: {}, + //observer: '_peersChanged', + notify: true + } + }, + observers: [ + //'_peersChanged(peers)' + '_peersChangedDeep(peers.*)' + ], + _broadcast: function(msg) { + var self = this; + console.log('[MAKI:PEER-MANAGER]', '_broadcast', msg); + if (typeof msg !== 'string') { + msg = JSON.stringify(msg); + } + + Object.keys(self.connections).forEach(function(id) { + var conn = self.connections[id]; + console.log('[MAKI:PEER-MANAGER]', 'connection iterator:', id); + conn.send(msg); + }); + }, + _relay: function(msg) { + var self = this; + console.log('[MAKI:PEER-MANAGER]', '_relay', msg); + self._broadcast(msg); + }, + _peerWith: function(id) { + var self = this; + if (!self.peer) return console.error('[MAKI:PEER-MANAGER]', 'no local peer'); + console.log('[MAKI:PEER-MANAGER]', '_peerWith', id, 'from:', self.peer.id)//, id); + if (id === self.peer.id) return console.error('[MAKI:PEER-MANAGER]', 'cannot peer with self'); + if (self.connections[id]) { + console.log('[MAKI:PEER-MANAGER]', 'connection exists!'); + } else { + var conn = self.peer.connect(id); + conn.on('open', function() { + conn.on('data', function(data) { + console.log('[MAKI:PEER-MANAGER]', 'connection data:', data); + + var channel = document.querySelector('maki-channel'); + channel._handleMessage({ + data: data + }); + + }); + self.connections[id] = conn; + }); + } + }, + _peersChangedDeep: function(change) { + var self = this; + console.log('[MAKI:PEER-MANAGER]', '_peersChangedDeep', change); + + var peer = change.value; + + if (peer && peer.state !== 'connected') { + return self._peerWith(peer.id); + } + + }, + _peersChanged: function(peers, old) { + var self = this; + console.log('[MAKI:PEER-MANAGER]', '_peersChanged', peers, old); + + Object.keys(peers).forEach(function(id) { + console.log('[MAKI:PEER-MANAGER]', 'iterating over:', id); + var peer = self.peers[id]; + if (peer && peer.state !== 'connected') { + return self._peerWith(id); + } + }); + + //setTimeout(self._connect.bind(self), 2500); + }, + _receivePeerChange: function(e) { + var self = this; + var db = document.querySelector('maki-datastore[name=melody]'); + console.log('[MAKI:PEER-MANAGER]', 'found datastore change:', e);//, detail); + if (e.detail.key === '/peers') { + var knownPeerIDs = Object.keys(self.peers); + var others = e.detail.val.map(function(x) { + return x.id; + }); + + var newPeerIDs = _.difference(others, knownPeerIDs); + + /*newPeerIDs.forEach(function(id) { + self._peerWith(id); + });*/ + + console.log('[MAKI:PEER-MANAGER]', 'peering with:', newPeerIDs[0]); + + self._peerWith(newPeerIDs[0]); + + console.log('[MAKI:PEER-MANAGER]', 'currently known', knownPeerIDs); + console.log('[MAKI:PEER-MANAGER]', 'others', others); + console.log('[MAKI:PEER-MANAGER]', 'newPeerIDs', newPeerIDs); + + } + }, + _register: function(done) { + var self = this; + console.log('[MAKI:PEER-MANAGER]', '_register', self.peer); + + var obj = { + id: self.peer.id + }; + + $.ajax({ + type: 'POST', + url: '/peers', + data: obj, + headers: { + 'Accept': 'application/json' + } + }).done(function(data) { + console.log('[MAKI:PEER-MANAGER]', '_register success:', data); + done(); + }).error(function(data) { + console.log('[MAKI:PEER-MANAGER]', '_register error:', data); + done(); + }); + }, + ready: function() { + var self = this; + console.log('[MAKI:PEER-MANAGER]', 'ready'); + /*var db = document.querySelector('maki-datastore[name=melody]'); + db.addEventListener('datastore:change', function(e) { + console.log('[MAKI:PEER-MANAGER]', 'found datastore change:', e); + });*/ + // TODO: get peerJS server working directly on the edge node + /*var options = { + host: window.location.hostname, + port: window.location.port, + path: '/peerjs' + };*/ + + var options = { + key: 'i31eg2i9x5p9o1or' + }; + // TODO: pass a peer ID based on a cryptographic identity + var peer = new Peer(options); + self.peer = peer; + + peer.on('connection', function(conn) { + console.log('[MAKI:PEER-MANAGER]', 'inbound connection', conn); + self.connections[conn.peer] = conn; + }); + + peer.on('open', function() { + console.log('[MAKI:PEER-MANAGER]', 'peer id:', peer.id); + self._register(function(err) { + self.peers[peer.id] = peer; + self.set('peers.' + peer.id, peer); + self.notifyPath('peers', self.peers); + + var db = document.querySelector('maki-datastore[name=melody]'); + db.addEventListener('datastore:change', self._receivePeerChange.bind(self)); + console.log('[MAKI:PEER-MANAGER]', 'peers now:', self.peers); + }); + }); + + /*var alice = new Peer({ + initiator: true, + trickle: false + }); + alice.on('error', function(err) { + console.error('[MAKI:PEER-MANAGER]', '(alice) error:', err); + }); + alice.on('signal', function(data) { + console.log('[MAKI:PEER-MANAGER]', '(alice) signal:', data); + bob.signal(data); + }); + alice.on('message', function(msg) { + console.log('[MAKI:PEER-MANAGER]', '(alice) message:', msg); + }); + alice.on('connect', function() { + console.log('[MAKI:PEER-MANAGER]', '(alice) connect'); + alice.send('Well hello there!'); + }); + + var bob = new Peer({ + //initiator: true, + trickle: false + }); + bob.on('error', function(err) { + console.error('[MAKI:PEER-MANAGER]', '(bob) error:', err); + }); + bob.on('signal', function(data) { + console.log('[MAKI:PEER-MANAGER]', '(bob) signal:', data); + alice.signal(data); + }); + bob.on('message', function(msg) { + console.log('[MAKI:PEER-MANAGER]', '(bob) message:', msg); + }); + bob.on('connect', function() { + console.log('[MAKI:PEER-MANAGER]', '(bob) connect'); + bob.send('Well hello there!'); + });*/ + + }, + _connect: function() { + console.log('[MAKI:PEER-MANAGER]', '_connect'); + + // TODO: get peerJS server working directly in Maki server + var options = { + host: window.location.hostname, + port: window.location.port, + path: '/peerjs' + }; + + var options = { + key: 'i31eg2i9x5p9o1or' + }; + + var alice = new Peer('alice', options); + var aliceConn = alice.connect('bob'); + aliceConn.on('open', function() { + console.log('[MAKI:PEER-MANAGER]', '(alice) open'); + aliceConn.send('ahem. hello there.'); + }); + alice.on('connection', function(peer) { + console.log('[MAKI:PEER-MANAGER]', '(alice) connection:', peer); + peer.on('data', function(data) { + console.log('[MAKI:PEER-MANAGER]', '(alice) data:', data); + }); + }); + + var bob = new Peer('bob', options); + var bobConn = bob.connect('alice'); + bobConn.on('open', function() { + console.log('[MAKI:PEER-MANAGER]', '(bob) open'); + bobConn.send('ahem. hello there.'); + }); + bob.on('connection', function(peer) { + console.log('[MAKI:PEER-MANAGER]', '(bob) connection:', peer); + peer.on('data', function(data) { + console.log('[MAKI:PEER-MANAGER]', '(bob) data:', data); + }); + }); + + }, + }); diff --git a/components/resource.jade b/components/resource.jade new file mode 100644 index 00000000..1ee8caaf --- /dev/null +++ b/components/resource.jade @@ -0,0 +1,29 @@ +dom-module#maki-resource + script(src="/assets/nedb.min.js", async) + script. + Polymer({ + is: 'maki-resource', + properties: { + name: { + type: String + }, + store: { + type: Object + }, + definition: { + type: Object + } + }, + _load: function() { + var self = this; + console.log('[MAKI:RESOURCE]', '_load', self.name); + self.store = new Nedb({ + filename: self.name, + autoload: true + }); + }, + ready: function() { + var self = this; + console.log('[MAKI:RESOURCE]', 'ready', self.name); + } + }); diff --git a/components/step-ladder.jade b/components/step-ladder.jade new file mode 100644 index 00000000..5633907c --- /dev/null +++ b/components/step-ladder.jade @@ -0,0 +1,158 @@ +dom-module#maki-step-ladder + style. + .hidden { + display: none; + } + template + .ui.three.steps + .active.step(data-step="generate") + i.leaf.icon + .content + .title Generate + .description Create a key. + .step(data-step="secure") + i.icon.lock + .content + .title Secure + .description Keep it safe. + .step(data-step="configure") + i.icon.setting + .content + .title Configure + .description Name yourself. + template(is="dom-repeat", items="{{steps}}") + .step x:{{item}} + + .step-view(data-step="generate") + .ui.bottom.attached.clearing.segment + h3 This is a different way. + p Instead of remembering passwords, your computer will always remember you. You can re-invent yourself any time you want, and even switch back and forth. + p But it's important to keep this one thing, the seed. The seed is a short list of words that can be used to restore your identity. Once we give it to you, we don't have it anymore. + p If you're ready to save your seed, generate it by using the button below. + .right.floated.buttons + a.ui.yellow.huge.fluid.button(on-tap="_startGenerator") + i.icon.plug + | Generate Seed + .step-view(data-step="secure") + .ui.bottom.attached.clearing.segment + h3 Write this down. + p This is your seed. It can be used to sign in as you anywhere, any time. Write it down and put it somewhere very safe. + pre + code {{words}} + p If you lose your seed, it's gone. We cannot recover it for you. Make sure you've really got it. + a.ui.huge.fluid.green.button(on-tap="_moveToConfigure") + i.icon.checkmark + | Yep, I've written it down. + .step-view(data-step="configure") + .ui.bottom.attached.clearing.segment + h3 Give yourself a name! + p This is how other people will see you! You can change it at any time, but then people might forget you. Make it memorable! + .ui.large.form + .field + label Your Name + input(type="text", placeholder="SomeUsername", name="name", value="{{identity.name}}") + .button.ui.positive.right.labeled.huge.icon.fluid.button(type="submit", on-tap="_setName") I'm happy. + i.right.chevron.icon + script. + Polymer({ + is: 'maki-step-ladder', + properties: { + words: { + type: String + }, + steps: { + type: Object + }, + step: { + type: String, + observer: '_stepChanged', + notify: true + } + }, + _createIdentity: function() { + var self = this; + var manager = document.querySelector('maki-identity'); + var button = document.querySelector('.step-view[data-step=generate] .segment .button'); + var step = document.querySelector('.step[data-step=generate]'); + var next = document.querySelector('.step[data-step=secure]'); + manager._generate(function(err, identity) { + console.log('generate complete:', err); + button.classList.remove('loading'); + step.classList.remove('active'); + next.classList.add('active'); + self.words = manager.words; + self.step = 'secure'; + }); + }, + _setName: function(e) { + e.preventDefault(); + var self = this; + var manager = document.querySelector('maki-identity'); + var name = $('*[data-step=configure] input[name=name]').val(); + var step = document.querySelector('.step[data-step=configure]'); + + $('*[data-step=configure] input[name=name]').val(''); + + console.log('[MAKI:STEP-LADDER]', '_setName', name); + // hack. + // TODO: fix this + manager.identity.name = name; + manager.identityFull.name = name; + // other old dust. unsure if necessary. + manager.set('identity.name', name); + manager.isNamed = true; + + console.log('[MAKI:STEP-LADDER]', '_setName', 'result:', manager.identity.name); + + manager._save(function(err) { + step.classList.remove('active'); + manager._register(); + manager._closeGeneratorModal(); + self.step = 'generate'; + }); + }, + _moveToConfigure: function() { + var self = this; + var step = document.querySelector('.step[data-step=secure]'); + var next = document.querySelector('.step[data-step=configure]'); + step.classList.remove('active'); + next.classList.add('active'); + self.step = 'configure'; + }, + _stepChanged: function(step) { + var self = this; + console.log('[MAKI:STEP-LADDER]', '_stepChanged', step); + + var steps = document.querySelectorAll('.step-view'); + console.log('[MAKI:STEP-LADDER]', 'pages found:', steps); + + for (var i = 0; i < steps.length; i++) { + var el = steps[i]; + var name = el.getAttribute('data-step'); + var cond = (self.step !== name); + var step = document.querySelector('.step[data-step='+name+']'); + + console.log('[MAKI:STEP-LADDER]', '_stepChanged cond', cond); + if (cond) { + el.classList.add('hidden'); + step.classList.remove('active'); + } else { + el.classList.remove('hidden'); + step.classList.add('active'); + } + } + }, + _startGenerator: function(e) { + var self = this; + var button = document.querySelector('.step-view[data-step=generate] .segment .button'); + + button.classList.add('loading'); + + self._createIdentity(); + + }, + attached: function() { + var self = this; + self.step = 'generate'; + } + }); diff --git a/lib/Resource/index.js b/lib/Resource/index.js index 8690363a..23e72592 100644 --- a/lib/Resource/index.js +++ b/lib/Resource/index.js @@ -444,7 +444,7 @@ Resource.prototype.get = function( q , opts , complete ) { }); function executeMethod( q , done ) { - var query = Model.findOne( q ).sort('-_id'); + var query = Model.findOne( q ).sort( opts.sort || '-_id' ); if (opts.populate instanceof String) { query.populate( opts.populate.path ); @@ -489,9 +489,9 @@ Resource.prototype.get = function( q , opts , complete ) { } -Resource.prototype.create = function( doc , params , complete ) { +Resource.prototype.create = function( doc , opts , complete ) { var self = this; - if (typeof( params ) === 'function') var complete = params; + if (typeof( opts ) === 'function') var complete = opts; if (!complete) var complete = new Function(); if (self.options.static) return complete(); @@ -511,6 +511,21 @@ Resource.prototype.create = function( doc , params , complete ) { var instance = new Model( doc ); instance.save(function(err) { if (err) return complete(err); + + if (opts.populate instanceof String) { + return instance.populate( opts.populate , done ); + } + + if (opts.populate instanceof Array) { + return opts.populate.forEach(function(field) { + if (field.fields) { + instance.populate( field , done ); + } else { + instance.populate( field , done ); + } + }); + } + return done( null , instance ); }); } @@ -522,7 +537,9 @@ Resource.prototype.create = function( doc , params , complete ) { // find one based on our query, and return it if it exists Model.findOne( query ).exec(function(err, instance) { if (err) return complete(err); - if (instance) return complete( err , instance ); + if (instance) { + return complete( err , instance ); + } return done( null ); }); } @@ -547,6 +564,12 @@ Resource.prototype.create = function( doc , params , complete ) { } +Resource.prototype.count = function(query, complete) { + var self = this; + var Model = self.Model; + Model.count(query, complete); +} + Resource.prototype.patch = function( query , params, complete ) { var self = this; if (!complete) var complete = new Function(); @@ -611,8 +634,6 @@ Resource.prototype.update = function( query , params , complete ) { var Model = self.Model; - console.log('hello', query, params); - async.waterfall([ executePreFunctions, executeMethod, diff --git a/lib/Service/http.js b/lib/Service/http.js index b00ed184..9460946d 100644 --- a/lib/Service/http.js +++ b/lib/Service/http.js @@ -24,10 +24,14 @@ var HTTP = function() { this._scripts = [ __dirname + '/../../public/js/webcomponents-lite.min.js', __dirname + '/../../public/js/semantic.min.js', + __dirname + '/../../public/assets/objectid.js', + //__dirname + '/../../public/assets/peer.js', //'public/js/jquery.js', //'public/js/maki.js' ]; this._workers = []; + this._resourceMap = {}; + this._flatResourceMap = {}; }; require('util').inherits( HTTP , Service ); @@ -247,6 +251,36 @@ HTTP.prototype.attach = function( maki ) { maki.socks = new WebSocketServer(); maki.app.use( require('maki-forms') ); + Object.keys(maki.resources).forEach(function(name) { + var resource = maki.resources[name]; + self._resourceMap[name] = []; + Object.keys(resource.paths).forEach(function(method) { + self._resourceMap[name].push(resource.paths[method]); + }); + }); + + console.log('resourceMap:', self._resourceMap); + + /* maki.socks.on('patch', function(patch) { + console.log('inner received patch:', patch); + var match = null; + for (var name in self._resourceMap) { + var regii = self._resourceMap[name]; + for (var i = 0; i < regii.length; i++) { + var regex = regii[i]; + if (regex.test(patch.channel)) { + match = name; + break; + } + } + if (match) { + break; + }; + }; + console.log('match!', match); + maki.resources[match]._patch(patch.channel, patch.ops); + }); */ + var map = { 'query': 'get', 'create': 'post', @@ -283,6 +317,17 @@ HTTP.prototype.attach = function( maki ) { inMemory: true })); + maki.httpd = require('http').createServer( maki.app ); + + var ExpressPeerServer = require('peer').ExpressPeerServer; + var peerServer = ExpressPeerServer(maki.httpd); + maki.app.use('/peerjs', peerServer); + peerServer.on('connection', function(id) { + var self = this; + console.log(self); + console.log('peerserver connection:', id); + }); + maki.app.locals[ 'config' ] = maki.config; maki.app.locals[ 'resources' ] = maki.resources; maki.app.locals[ 'services' ] = maki.services; @@ -400,8 +445,10 @@ HTTP.prototype.attach = function( maki ) { maki.app.get('/components/:name', function(req, res, next) { var name = req.params.name; var path = __dirname + '/../../components/'+name+'.jade'; - if (!fs.existsSync(path)) return next(); - return res.render(path); + if (fs.existsSync(path)) return res.render(path); + var path = process.env.PWD + '/components/'+name+'.jade'; + if (fs.existsSync(path)) return res.render(path); + return next(); }); maki.app.get('/api', function(req, res, next) { @@ -732,7 +779,9 @@ HTTP.prototype.attach = function( maki ) { doc[ field ] = file._id; }); - resource[ p ]( doc , function(err, instance) { + resource[ p ]( doc , { + populate: methodPopulationMap[ p ] + }, function(err, instance) { if (err) return res.error( err ); req.locals = instance; return res.provide( r , instance , handlers ); @@ -746,7 +795,9 @@ HTTP.prototype.attach = function( maki ) { // TODO: query pipeline (facades) var doc = req.body; - resource[ p ]( doc , function(err, instance) { + resource[ p ]( doc , { + populate: methodPopulationMap[ p ] + }, function(err, instance) { if (err) return res.error( err ); req.locals = instance; return res.provide( r , instance ); @@ -866,14 +917,14 @@ HTTP.prototype.start = function( started ) { // TODO: allow configurable certificate, supplied by config // this will allow for standalone mode, as well as a "backend worker" mode. pem.createCertificate({ - days: 1, + days: 90, selfSigned: true }, function(err, keys) { var sslPort = self.maki.config.services.http.port + 443 - 80; //self.maki.config.services.spdy.port = sslPort; - self.maki.httpd = require('http').createServer( self.maki.app ); + //self.maki.httpd = require('http').createServer( self.maki.app ); self.maki.spdyd = require('spdy').createServer({ key: keys.serviceKey, cert: keys.certificate diff --git a/package.json b/package.json index 8f51db70..6927f06f 100644 --- a/package.json +++ b/package.json @@ -33,6 +33,7 @@ "async": "~0.7.0", "body-parser": "~1.2.2", "browserify": "^11.0.1", + "browserify-shim": "^3.8.12", "coalescent": "^0.5.0-alpha.3", "colors": "^1.0.3", "connect-busboy": "0.0.2", @@ -47,7 +48,7 @@ "json-patch": "^0.4.3", "jsonpath-object-transform": "git://github.com/dvdln/jsonpath-object-transform", "less-middleware": "git://github.com/martindale/less.js-middleware#maki", - "lodash": "^2.4.1", + "lodash": "^4.6.1", "maki-analytics": "git://github.com/martindale/maki-analytics", "maki-auth-simple": "0.0.1", "maki-client-level": "^0.1.0", @@ -70,6 +71,7 @@ "node-torrent-stream": "git://github.com/unusualbob/node-torrent-stream#master", "node-uuid": "^1.4.1", "path-to-regexp": "~0.2.1", + "peer": "^0.2.8", "pem": "^1.4.1", "pluralize": "^1.0.0", "procure": "^0.1.4", diff --git a/public/assets/async.min.js b/public/assets/async.min.js new file mode 100644 index 00000000..9e8eaf4b --- /dev/null +++ b/public/assets/async.min.js @@ -0,0 +1,2 @@ +!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n(t.async=t.async||{})}(this,function(t){"use strict";function n(t,n,r){var e=r.length;switch(e){case 0:return t.call(n);case 1:return t.call(n,r[0]);case 2:return t.call(n,r[0],r[1]);case 3:return t.call(n,r[0],r[1],r[2])}return t.apply(n,r)}function r(t){var n=typeof t;return!!t&&("object"==n||"function"==n)}function e(t){var n=r(t)?Zn.call(t):"";return n==Vn||n==Xn}function o(t){if(r(t)){var n=e(t.valueOf)?t.valueOf():t;t=r(n)?n+"":n}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(nr,"");var o=er.test(t);return o||or.test(t)?ur(t.slice(2),o?2:8):rr.test(t)?tr:+t}function u(t){if(!t)return 0===t?t:0;if(t=o(t),t===ir||t===-ir){var n=0>t?-1:1;return n*cr}var r=t%1;return t===t?r?t-r:t:0}function i(t,r){if("function"!=typeof t)throw new TypeError(ar);return r=fr(void 0===r?t.length-1:u(r),0),function(){for(var e=arguments,o=-1,u=fr(e.length-r,0),i=Array(u);++o0&&(r=n.apply(this,arguments)),1>=t&&(n=void 0),r}}function s(t){return l(2,t)}function p(t){return function(n){return null==n?void 0:n[t]}}function y(t){return"number"==typeof t&&t>-1&&t%1==0&&pr>=t}function h(t){return null!=t&&y(sr(t))&&!e(t)}function v(t){return yr&&t[yr]&&t[yr]()}function d(t,n){return vr.call(t,n)||"object"==typeof t&&n in t&&null===dr(t)}function m(t){return mr(Object(t))}function g(t,n){for(var r=-1,e=Array(t);++r-1&&t%1==0&&n>t}function k(t){var n=t&&t.constructor,r="function"==typeof n&&n.prototype||Lr;return t===r}function E(t){var n=k(t);if(!n&&!h(t))return m(t);var r=S(t),e=!!r,o=r||[],u=o.length;for(var i in t)!d(t,i)||e&&("length"==i||_(i,u))||n&&"constructor"==i||o.push(i);return o}function A(t){var n,r=-1;if(h(t))return n=t.length,function(){return r++,n>r?{value:t[r],key:r}:null};var e=v(t);if(e)return function(){var t=e.next();return t.done?null:(r++,{value:t.value,key:r})};var o=E(t);return n=o.length,function(){r++;var e=o[r];return n>r?{value:t[e],key:e}:null}}function x(t){return function(){if(null===t)throw new Error("Callback was already called.");t.apply(this,arguments),t=null}}function L(t){return function(n,r,e){e=s(e||f),n=n||[];var o=A(n);if(0>=t)return e(null);var u=!1,i=0,c=!1;!function a(){if(u&&0>=i)return e(null);for(;t>i&&!c;){var n=o();if(null===n)return u=!0,void(0>=i&&e(null));i+=1,r(n.value,n.key,x(function(t){i-=1,t?(e(t),c=!0):a()}))}}()}}function I(t,n,r,e){L(n)(t,r,e)}function T(t,n){return function(r,e,o){return t(r,n,e,o)}}function F(t){return c(function(n,e){var o;try{o=t.apply(this,n)}catch(u){return e(u)}r(o)&&"function"==typeof o.then?o.then(function(t){e(null,t)})["catch"](function(t){e(t.message?t:new Error(t))}):e(null,o)})}function M(t,n){for(var r=-1,e=t.length;++rr&&(r=Pr(e+r,0)),q(t,n,r)):-1}function R(t,n,r){function e(t,n){m.push(function(){a(t,n)})}function o(){if(0===m.length&&0===h)return r(null,y);for(;m.length&&n>h;){var t=m.shift();t()}}function u(t,n){var r=d[t];r||(r=d[t]=[]),r.push(n)}function c(t){var n=d[t]||[];M(n,function(t){t()}),o()}function a(t,n){if(!v){var e=x(i(function(n,e){if(h--,e.length<=1&&(e=e[0]),n){var o={};B(y,function(t,n){o[n]=t}),o[t]=e,v=!0,d=[],r(n,o)}else y[t]=e,c(t)}));h++;var o=n[n.length-1];n.length>1?o(y,e):o(e)}}"function"==typeof n&&(r=n,n=null),r=s(r||f);var l=E(t),p=l.length;if(!p)return r(null);n||(n=p);var y={},h=0,v=!1,d={},m=[];B(t,function(n,r){function o(){for(var n,e=i.length;e--;){if(!(n=t[i[e]]))throw new Error("async.auto task `"+r+"` has non-existent dependency in "+i.join(", "));if(Sr(n)&&D(n,r)>=0)throw new Error("async.auto task `"+r+"`Has cyclic dependencies")}}if(!Sr(n))return void e(r,[n]);var i=n.slice(0,n.length-1),c=i.length;o(),M(i,function(t){u(t,function(){c--,0===c&&e(r,n)})})}),o()}function W(t,n){for(var r=-1,e=t.length,o=Array(e);++rr)return!1;var e=t.length-1;return r==e?t.pop():Br.call(t,r,1),!0}function J(t){var n=this.__data__,r=n.array;return r?H(r,t):n.map["delete"](t)}function K(t,n){var r=Q(t,n);return 0>r?void 0:t[r][1]}function V(t){var n=this.__data__,r=n.array;return r?K(r,t):n.map.get(t)}function X(t,n){return Q(t,n)>-1}function Y(t){var n=this.__data__,r=n.array;return r?X(r,t):n.map.has(t)}function Z(t){var n=!1;if(null!=t&&"function"!=typeof t.toString)try{n=!!(t+"")}catch(r){}return n}function tt(t){return null==t?!1:e(t)?Nr.test(Rr.call(t)):b(t)&&(Z(t)?Nr:qr).test(t)}function nt(t,n){var r=t[n];return tt(r)?r:void 0}function rt(){}function et(t){return t&&t.Object===Object?t:null}function ot(){this.__data__={hash:new rt,map:ne?new ne:[],string:new rt}}function ut(t,n){return Gr?void 0!==t[n]:ee.call(t,n)}function it(t,n){return ut(t,n)&&delete t[n]}function ct(t){var n=typeof t;return"number"==n||"boolean"==n||"string"==n&&"__proto__"!=t||null==t}function at(t){var n=this.__data__;return ct(t)?it("string"==typeof t?n.string:n.hash,t):ne?n.map["delete"](t):H(n.map,t)}function ft(t,n){if(Gr){var r=t[n];return r===oe?void 0:r}return ie.call(t,n)?t[n]:void 0}function lt(t){var n=this.__data__;return ct(t)?ft("string"==typeof t?n.string:n.hash,t):ne?n.map.get(t):K(n.map,t)}function st(t){var n=this.__data__;return ct(t)?ut("string"==typeof t?n.string:n.hash,t):ne?n.map.has(t):X(n.map,t)}function pt(t,n,r){var e=Q(t,n);0>e?t.push([n,r]):t[e][1]=r}function yt(t,n,r){t[n]=Gr&&void 0===r?ce:r}function ht(t,n){var r=this.__data__;return ct(t)?yt("string"==typeof t?r.string:r.hash,t,n):ne?r.map.set(t,n):pt(r.map,t,n),this}function vt(t){var n=-1,r=t?t.length:0;for(this.clear();++n=n;n++)Uo(c.process)}}};return c}function Qt(t,n){return Gt(t,1,n)}function Ht(t,n,r,e){Fr(t,function(t,e,o){r(n,t,function(t,r){n=r,o(t)})},function(t){e(t,n)})}function Jt(){var t=arguments;return i(function(n){var r=this,e=n[n.length-1];"function"==typeof e?n.pop():e=f,Ht(t,n,function(t,n,e){n.apply(r,t.concat([i(function(t,n){e(t,n)})]))},function(t,n){e.apply(r,[t].concat(n))})})}function Kt(){return Jt.apply(null,Po.call(arguments))}function Vt(t,n,r,e){var o=[];t(n,function(t,n,e){r(t,function(t,n){o=o.concat(n||[]),e(t)})},function(t){e(t,o)})}function Xt(t){return function(n,r,e){return t(Ir,n,r,e)}}function Yt(t){return function(n,r,e){return t(Fr,n,r,e)}}function Zt(t,n,r){return function(e,o,u,i){function c(t){i&&(t?i(t):i(null,r(!1)))}function a(t,e,o){return i?void u(t,function(e,c){i&&(e?(i(e),i=u=!1):n(c)&&(i(null,r(!0,t)),i=u=!1)),o()}):o()}arguments.length>3?t(e,o,a,c):(i=u,u=o,t(e,a,c))}}function tn(t,n){return n}function nn(t){return i(function(n,r){n.apply(null,r.concat([i(function(n,r){"object"==typeof console&&(n?console.error&&console.error(n):console[t]&&M(r,function(n){console[t](n)}))})]))})}function rn(t,n,r){r=r||f;var e=i(function(n,e){n?r(n):(e.push(o),t.apply(this,e))}),o=function(t,o){return t?r(t):o?void n(e):r(null)};t(o)}function en(t,n,r){var e=0;rn(function(t){return e++<1?t(null,!0):void n.apply(this,arguments)},t,r)}function on(t,n,r){if(r=r||f,!t())return r(null);var e=i(function(o,u){return o?r(o):t.apply(this,u)?n(e):void r.apply(null,[null].concat(u))});n(e)}function un(t,n,r){var e=0;return on(function(){return++e<=1||n.apply(this,arguments)},t,r)}function cn(t,n,r){return un(t,function(){return!n.apply(this,arguments)},r)}function an(t){return function(n,r,e){return t(n,e)}}function fn(t,n,r,e){return L(n)(t,an(r),e)}function ln(t){return c(function(n,r){var e=!0;n.push(function(){var t=arguments;e?Uo(function(){r.apply(null,t)}):r.apply(null,t)}),t.apply(this,n),e=!1})}function sn(t){return!t}function pn(t,n,r,e){var o=[];t(n,function(t,n,e){r(t,function(r,u){r?e(r):(u&&o.push({index:n,value:t}),e())})},function(t){t?e(t):e(null,W(o.sort(function(t,n){return t.index-n.index}),p("value")))})}function yn(t){return function(n,r,e,o){return t(L(r),n,e,o)}}function hn(t,n){function r(t){return t?e(t):void o(r)}var e=x(n||f),o=ln(t);r()}function vn(t){function n(r){function e(){return t.length&&t[r].apply(null,arguments),e.next()}return e.next=function(){return rn&&(n=-n>o?0:o+n),r=r>o?o:r,0>r&&(r+=o),o=n>r?0:r-n>>>0,n>>>=0;for(var u=Array(o);++er;)t=t[n[r++]];return r&&r==e?t:void 0}function kn(t,n,r){var e=null==t?void 0:_n(t,n);return void 0===e?r:e}function En(t,n){return 1==n.length?t:kn(t,Sn(n,0,-1))}function An(t,n,r){if(null==t)return!1;var e=r(t,n);e||wn(n)||(n=jn(n),t=En(t,n),null!=t&&(n=On(n),e=r(t,n)));var o=t?t.length:void 0;return e||!!o&&y(o)&&_(n,o)&&(Sr(t)||O(t)||w(t))}function xn(t,n){return An(t,n,d)}function Ln(t,n){var r=Object.create(null),e=Object.create(null);n=n||$;var o=c(function(o,u){var c=n.apply(null,o);xn(r,c)?Uo(function(){u.apply(null,r[c])}):xn(e,c)?e[c].push(u):(e[c]=[u],t.apply(null,o.concat([i(function(t){r[c]=t;var n=e[c];delete e[c];for(var o=0,u=n.length;u>o;o++)n[o].apply(null,t)})])))});return o.memo=r,o.unmemoized=t,o}function In(t,n,r){r=r||f;var e=h(n)?[]:{};t(n,function(t,n,r){t(i(function(t,o){o.length<=1&&(o=o[0]),e[n]=o,r(t)}))},function(t){r(t,e)})}function Tn(t,n,r){return In(L(n),t,r)}function Fn(t,n){return Gt(function(n,r){t(n[0],r)},n,1)}function Mn(t,n){function r(t,n){return t.priority-n.priority}function e(t,n,r){for(var e=-1,o=t.length-1;o>e;){var u=e+(o-e+1>>>1);r(n,t[u])>=0?e=u:o=u-1}return e}function o(t,n,o,u){if(null!=u&&"function"!=typeof u)throw new Error("task callback must be a function");return t.started=!0,Sr(n)||(n=[n]),0===n.length?Uo(function(){t.drain()}):void M(n,function(n){var i={data:n,priority:o,callback:"function"==typeof u?u:f};t.tasks.splice(e(t.tasks,i,r)+1,0,i),t.tasks.length===t.concurrency&&t.saturated(),t.tasks.length<=t.concurrency-t.buffer&&t.unsaturated(),Uo(t.process)})}var u=Fn(t,n);return u.push=function(t,n,r){o(u,t,n,r)},delete u.unshift,u}function $n(t,n){return function(r,e){if(null==r)return r;if(!h(r))return t(r,e);for(var o=r.length,u=n?o:-1,i=Object(r);(n?u--:++u0&&l.push(u(a.interval))}Cn(l,function(t,n){n=n[n.length-1],r(n.err,n.result)})}function Dn(t,n){return n||(n=t,t=null),c(function(r,e){function o(t){n.apply(null,r.concat([t]))}t?qn(t,o,e):qn(o,e)})}function Rn(t,n,r){function e(t,n){var r=t.criteria,e=n.criteria;return e>r?-1:r>e?1:0}tu(t,function(t,r){n(t,function(n,e){return n?r(n):void r(null,{value:t,criteria:e})})},function(t,n){return t?r(t):void r(null,W(n.sort(e),p("value")))})}function Wn(t,n){function r(){i||(o.apply(null,arguments),clearTimeout(u))}function e(){var t=new Error("Callback function timed out.");t.code="ETIMEDOUT",i=!0,o(t)}var o,u,i=!1;return c(function(i,c){o=c,u=setTimeout(e,n),t.apply(null,i.concat(r))})}function Nn(t,n,r,e){for(var o=-1,u=Ou(wu((n-t)/(r||1)),0),i=Array(u);u--;)i[e?u:++o]=t,t+=r;return i}function Gn(t,n,r,e){return Zo(Nn(0,t,1),n,r,e)}function Qn(t,n,r,e){3===arguments.length&&(e=r,r=n,n=Sr(t)?[]:{}),Ir(t,function(t,e,o){r(n,t,e,o)},function(t){e(t,n)})}function Hn(t){return function(){return(t.unmemoized||t).apply(null,arguments)}}function Jn(t,n,r){return on(function(){return!t.apply(this,arguments)},n,r)}function Kn(t,n){function r(o){if(e===t.length)return n.apply(null,[null].concat(o));var u=x(i(function(t,e){return t?n.apply(null,[t].concat(e)):void r(e)}));o.push(u);var c=t[e++];c.apply(null,o)}if(n=s(n||f),!Sr(t))return n(new Error("First argument to waterfall must be an array of functions"));if(!t.length)return n();var e=0;r([])}var Vn="[object Function]",Xn="[object GeneratorFunction]",Yn=Object.prototype,Zn=Yn.toString,tr=NaN,nr=/^\s+|\s+$/g,rr=/^[-+]0x[0-9a-f]+$/i,er=/^0b[01]+$/i,or=/^0o[0-7]+$/i,ur=parseInt,ir=1/0,cr=1.7976931348623157e308,ar="Expected a function",fr=Math.max,lr="Expected a function",sr=p("length"),pr=9007199254740991,yr="function"==typeof Symbol&&Symbol.iterator,hr=Object.prototype,vr=hr.hasOwnProperty,dr=Object.getPrototypeOf,mr=Object.keys,gr="[object Arguments]",br=Object.prototype,jr=br.hasOwnProperty,wr=br.toString,Or=br.propertyIsEnumerable,Sr=Array.isArray,_r="[object String]",kr=Object.prototype,Er=kr.toString,Ar=9007199254740991,xr=/^(?:0|[1-9]\d*)$/,Lr=Object.prototype,Ir=T(I,1/0),Tr=a(Ir),Fr=T(I,1),Mr=a(Fr),$r=i(function(t,n){return i(function(r){return t.apply(null,n.concat(r))})}),Ur=P(),Pr=Math.max,zr=Array.prototype,Br=zr.splice,Cr=/[\\^$.*+?()[\]{}|]/g,qr=/^\[object .+?Constructor\]$/,Dr=Object.prototype,Rr=Function.prototype.toString,Wr=Dr.hasOwnProperty,Nr=RegExp("^"+Rr.call(Wr).replace(Cr,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Gr=nt(Object,"create"),Qr=Object.prototype;rt.prototype=Gr?Gr(null):Qr;var Hr={"function":!0,object:!0},Jr=Hr[typeof t]&&t&&!t.nodeType?t:void 0,Kr=Hr[typeof module]&&module&&!module.nodeType?module:void 0,Vr=et(Jr&&Kr&&"object"==typeof global&&global),Xr=et(Hr[typeof self]&&self),Yr=et(Hr[typeof window]&&window),Zr=et(Hr[typeof this]&&this),te=Vr||Yr!==(Zr&&Zr.window)&&Yr||Xr||Zr||Function("return this")(),ne=nt(te,"Map"),re=Object.prototype,ee=re.hasOwnProperty,oe="__lodash_hash_undefined__",ue=Object.prototype,ie=ue.hasOwnProperty,ce="__lodash_hash_undefined__";vt.prototype.clear=ot,vt.prototype["delete"]=at,vt.prototype.get=lt,vt.prototype.has=st,vt.prototype.set=ht;var ae=200;mt.prototype.clear=N,mt.prototype["delete"]=J,mt.prototype.get=V,mt.prototype.has=Y,mt.prototype.set=dt;var fe=Object.prototype,le=fe.hasOwnProperty,se=Object.getOwnPropertySymbols,pe=se||function(){return[]},ye=nt(te,"Set"),he=nt(te,"WeakMap"),ve="[object Map]",de="[object Object]",me="[object Set]",ge="[object WeakMap]",be=Object.prototype,je=Function.prototype.toString,we=be.toString,Oe=ne?je.call(ne):"",Se=ye?je.call(ye):"",_e=he?je.call(he):"";(ne&&kt(new ne)!=ve||ye&&kt(new ye)!=me||he&&kt(new he)!=ge)&&(kt=function(t){var n=we.call(t),r=n==de?t.constructor:null,e="function"==typeof r?je.call(r):"";if(e)switch(e){case Oe:return ve;case Se:return me;case _e:return ge}return n});var ke=kt,Ee=Object.prototype,Ae=Ee.hasOwnProperty,xe=te.Uint8Array,Le=/\w*$/,Ie=te.Symbol,Te=Ie?Ie.prototype:void 0,Fe=Te?Te.valueOf:void 0,Me="[object Boolean]",$e="[object Date]",Ue="[object Map]",Pe="[object Number]",ze="[object RegExp]",Be="[object Set]",Ce="[object String]",qe="[object Symbol]",De="[object ArrayBuffer]",Re="[object Float32Array]",We="[object Float64Array]",Ne="[object Int8Array]",Ge="[object Int16Array]",Qe="[object Int32Array]",He="[object Uint8Array]",Je="[object Uint8ClampedArray]",Ke="[object Uint16Array]",Ve="[object Uint32Array]",Xe=Object.create,Ye=Object.getPrototypeOf,Ze={"function":!0,object:!0},to=Ze[typeof t]&&t&&!t.nodeType?t:void 0,no=Ze[typeof module]&&module&&!module.nodeType?module:void 0,ro=no&&no.exports===to?to:void 0,eo=ro?te.Buffer:void 0,oo=eo?function(t){return t instanceof eo}:Dt(!1),uo="[object Arguments]",io="[object Array]",co="[object Boolean]",ao="[object Date]",fo="[object Error]",lo="[object Function]",so="[object GeneratorFunction]",po="[object Map]",yo="[object Number]",ho="[object Object]",vo="[object RegExp]",mo="[object Set]",go="[object String]",bo="[object Symbol]",jo="[object WeakMap]",wo="[object ArrayBuffer]",Oo="[object Float32Array]",So="[object Float64Array]",_o="[object Int8Array]",ko="[object Int16Array]",Eo="[object Int32Array]",Ao="[object Uint8Array]",xo="[object Uint8ClampedArray]",Lo="[object Uint16Array]",Io="[object Uint32Array]",To={};To[uo]=To[io]=To[wo]=To[co]=To[ao]=To[Oo]=To[So]=To[_o]=To[ko]=To[Eo]=To[po]=To[yo]=To[ho]=To[vo]=To[mo]=To[go]=To[bo]=To[Ao]=To[xo]=To[Lo]=To[Io]=!0,To[fo]=To[lo]=To[jo]=!1;var Fo,Mo=/^function\s*[^\(]*\(\s*([^\)]*)\)/m,$o="function"==typeof setImmediate&&setImmediate;Fo=$o?$o:"object"==typeof process&&"function"==typeof process.nextTick?process.nextTick:function(t){setTimeout(t,0)};var Uo=i(function(t,n){Fo(function(){t.apply(null,n)})}),Po=Array.prototype.reverse,zo=Xt(Vt),Bo=Yt(Vt),Co=i(function(t){var n=[null].concat(t);return c(function(t,r){return r.apply(this,n)})}),qo=Zt(Ir,$,tn),Do=Zt(I,$,tn),Ro=Zt(Fr,$,tn),Wo=nn("dir"),No=T(fn,1/0),Go=T(fn,1),Qo=Zt(I,sn,sn),Ho=T(Qo,1/0),Jo=T(Qo,1),Ko=yn(pn),Vo=T(Ko,1/0),Xo=T(Ko,1),Yo=nn("log"),Zo=yn(dn),tu=T(Zo,1/0),nu=T(Zo,1),ru="[object Symbol]",eu=Object.prototype,ou=eu.toString,uu=1/0,iu=Ie?Ie.prototype:void 0,cu=iu?iu.toString:void 0,au=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g,fu=/\\(\\)?/g,lu=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,su=/^\w*$/,pu=T(Tn,1/0),yu=$n(z),hu=Array.prototype.slice,vu=yn(Bn),du=T(vu,1/0),mu=T(vu,1),gu=Zt(I,Boolean,$),bu=T(gu,1/0),ju=T(gu,1),wu=Math.ceil,Ou=Math.max,Su=T(Gn,1/0),_u=T(Gn,1),ku={applyEach:Tr,applyEachSeries:Mr,apply:$r,asyncify:F,auto:R,autoInject:Nt,cargo:Qt,compose:Kt,concat:zo,concatSeries:Bo,constant:Co,detect:qo,detectLimit:Do,detectSeries:Ro,dir:Wo,doDuring:en,doUntil:cn,doWhilst:un,during:rn,each:No,eachLimit:fn,eachOf:Ir,eachOfLimit:I,eachOfSeries:Fr,eachSeries:Go,ensureAsync:ln,every:Ho,everyLimit:Qo,everySeries:Jo,filter:Vo,filterLimit:Ko,filterSeries:Xo,forever:hn,iterator:vn,log:Yo,map:tu,mapLimit:Zo,mapSeries:nu,memoize:Ln,nextTick:Uo,parallel:pu,parallelLimit:Tn,priorityQueue:Mn,queue:Fn,race:Pn,reduce:Ht,reduceRight:zn,reject:du,rejectLimit:vu,rejectSeries:mu,retry:qn,retryable:Dn,seq:Jt,series:Cn,setImmediate:Uo,some:bu,someLimit:gu,someSeries:ju,sortBy:Rn,timeout:Wn,times:Su,timesLimit:Gn,timesSeries:_u,transform:Qn,unmemoize:Hn,until:Jn,waterfall:Kn,whilst:on,all:Ho,any:bu,forEach:No,forEachSeries:Go,forEachLimit:fn,forEachOf:Ir,forEachOfSeries:Fr,forEachOfLimit:I,inject:Ht,foldl:Ht,foldr:zn,select:Vo,selectLimit:Ko,selectSeries:Xo,wrapSync:F};t["default"]=ku,t.applyEach=Tr,t.applyEachSeries=Mr,t.apply=$r,t.asyncify=F,t.auto=R,t.autoInject=Nt,t.cargo=Qt,t.compose=Kt,t.concat=zo,t.concatSeries=Bo,t.constant=Co,t.detect=qo,t.detectLimit=Do,t.detectSeries=Ro,t.dir=Wo,t.doDuring=en,t.doUntil=cn,t.doWhilst=un,t.during=rn,t.each=No,t.eachLimit=fn,t.eachOf=Ir,t.eachOfLimit=I,t.eachOfSeries=Fr,t.eachSeries=Go,t.ensureAsync=ln,t.every=Ho,t.everyLimit=Qo,t.everySeries=Jo,t.filter=Vo,t.filterLimit=Ko,t.filterSeries=Xo,t.forever=hn,t.iterator=vn,t.log=Yo,t.map=tu,t.mapLimit=Zo,t.mapSeries=nu,t.memoize=Ln,t.nextTick=Uo,t.parallel=pu,t.parallelLimit=Tn,t.priorityQueue=Mn,t.queue=Fn,t.race=Pn,t.reduce=Ht,t.reduceRight=zn,t.reject=du,t.rejectLimit=vu,t.rejectSeries=mu,t.retry=qn,t.retryable=Dn,t.seq=Jt,t.series=Cn,t.setImmediate=Uo,t.some=bu,t.someLimit=gu,t.someSeries=ju,t.sortBy=Rn,t.timeout=Wn,t.times=Su,t.timesLimit=Gn,t.timesSeries=_u,t.transform=Qn,t.unmemoize=Hn,t.until=Jn,t.waterfall=Kn,t.whilst=on,t.all=Ho,t.allLimit=Qo,t.allSeries=Jo,t.any=bu,t.anyLimit=gu,t.anySeries=ju,t.find=qo,t.findLimit=Do,t.findSeries=Ro,t.forEach=No,t.forEachSeries=Go,t.forEachLimit=fn,t.forEachOf=Ir,t.forEachOfSeries=Fr,t.forEachOfLimit=I,t.inject=Ht,t.foldl=Ht,t.foldr=zn,t.select=Vo,t.selectLimit=Ko,t.selectSeries=Xo,t.wrapSync=F}); +//# sourceMappingURL=dist/async.min.map \ No newline at end of file diff --git a/public/assets/nedb.min.js b/public/assets/nedb.min.js new file mode 100644 index 00000000..b251dcbe --- /dev/null +++ b/public/assets/nedb.min.js @@ -0,0 +1,4 @@ +!function(t){if("function"==typeof bootstrap)bootstrap("nedb",t);else if("object"==typeof exports)module.exports=t();else if("function"==typeof define&&define.amd)define(t);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeNedb=t}else"undefined"!=typeof window?window.Nedb=t():global.Nedb=t()}(function(){var t;return function(t,e,n){function r(n,o){if(!e[n]){if(!t[n]){var a="function"==typeof require&&require;if(!o&&a)return a(n,!0);if(i)return i(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=e[n]={exports:{}};t[n][0].call(u.exports,function(e){var i=t[n][1][e];return r(i?i:e)},u,u.exports)}return e[n].exports}for(var i="function"==typeof require&&require,o=0;oi;i++)r[i].apply(this,n);return!0}return!1},o.prototype.addListener=function(t,e){if("function"!=typeof e)throw new Error("addListener only takes instances of Function");if(this._events||(this._events={}),this.emit("newListener",t,e),this._events[t])if(a(this._events[t])){if(!this._events[t].warned){var n;n=void 0!==this._events.maxListeners?this._events.maxListeners:u,n&&n>0&&this._events[t].length>n&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),console.trace())}this._events[t].push(e)}else this._events[t]=[this._events[t],e];else this._events[t]=e;return this},o.prototype.on=o.prototype.addListener,o.prototype.once=function(t,e){var n=this;return n.on(t,function r(){n.removeListener(t,r),e.apply(this,arguments)}),this},o.prototype.removeListener=function(t,e){if("function"!=typeof e)throw new Error("removeListener only takes instances of Function");if(!this._events||!this._events[t])return this;var n=this._events[t];if(a(n)){var i=r(n,e);if(0>i)return this;n.splice(i,1),0==n.length&&delete this._events[t]}else this._events[t]===e&&delete this._events[t];return this},o.prototype.removeAllListeners=function(t){return 0===arguments.length?(this._events={},this):(t&&this._events&&this._events[t]&&(this._events[t]=null),this)},o.prototype.listeners=function(t){return this._events||(this._events={}),this._events[t]||(this._events[t]=[]),a(this._events[t])||(this._events[t]=[this._events[t]]),this._events[t]},o.listenerCount=function(t,e){var n;return n=t._events&&t._events[e]?"function"==typeof t._events[e]?1:t._events[e].length:0}},{__browserify_process:4}],2:[function(t,e,n){function r(t,e){for(var n=[],r=0;r=0;r--){var i=t[r];"."==i?t.splice(r,1):".."===i?(t.splice(r,1),n++):n&&(t.splice(r,1),n--)}if(e)for(;n--;n)t.unshift("..");return t}var o=t("__browserify_process"),a=/^(.+\/(?!$)|\/)?((?:.+?)?(\.[^.]*)?)$/;n.resolve=function(){for(var t="",e=!1,n=arguments.length;n>=-1&&!e;n--){var a=n>=0?arguments[n]:o.cwd();"string"==typeof a&&a&&(t=a+"/"+t,e="/"===a.charAt(0))}return t=i(r(t.split("/"),function(t){return!!t}),!e).join("/"),(e?"/":"")+t||"."},n.normalize=function(t){var e="/"===t.charAt(0),n="/"===t.slice(-1);return t=i(r(t.split("/"),function(t){return!!t}),!e).join("/"),t||e||(t="."),t&&n&&(t+="/"),(e?"/":"")+t},n.join=function(){var t=Array.prototype.slice.call(arguments,0);return n.normalize(r(t,function(t){return t&&"string"==typeof t}).join("/"))},n.dirname=function(t){var e=a.exec(t)[1]||"",n=!1;return e?1===e.length||n&&e.length<=3&&":"===e.charAt(1)?e:e.substring(0,e.length-1):"."},n.basename=function(t,e){var n=a.exec(t)[2]||"";return e&&n.substr(-1*e.length)===e&&(n=n.substr(0,n.length-e.length)),n},n.extname=function(t){return a.exec(t)[3]||""},n.relative=function(t,e){function r(t){for(var e=0;e=0&&""===t[n];n--);return e>n?[]:t.slice(e,n-e+1)}t=n.resolve(t).substr(1),e=n.resolve(e).substr(1);for(var i=r(t.split("/")),o=r(e.split("/")),a=Math.min(i.length,o.length),u=a,s=0;a>s;s++)if(i[s]!==o[s]){u=s;break}for(var c=[],s=u;ss)return i(t)?h(""+t,"regexp"):h("[Object]","special");l.push(t);var w=d.map(function(e){var n,i;if(t.__lookupGetter__&&(t.__lookupGetter__(e)?i=t.__lookupSetter__(e)?h("[Getter/Setter]","special"):h("[Getter]","special"):t.__lookupSetter__(e)&&(i=h("[Setter]","special"))),p.indexOf(e)<0&&(n="["+e+"]"),i||(l.indexOf(t[e])<0?(i=null===s?f(t[e]):f(t[e],s-1),i.indexOf("\n")>-1&&(i=r(t)?i.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+i.split("\n").map(function(t){return" "+t}).join("\n"))):i=h("[Circular]","special")),"undefined"==typeof n){if("Array"===g&&e.match(/^\d+$/))return i;n=JSON.stringify(""+e),n.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(n=n.substr(1,n.length-2),n=h(n,"name")):(n=n.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),n=h(n,"string"))}return n+": "+i});l.pop();var _=0,k=w.reduce(function(t,e){return _++,e.indexOf("\n")>=0&&_++,t+e.length+1},0);return w=k>50?m[0]+(""===v?"":v+"\n ")+" "+w.join(",\n ")+" "+m[1]:m[0]+v+" "+w.join(", ")+" "+m[1]}var l=[],h=function(t,e){var n={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},r={special:"cyan",number:"blue","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"}[e];return r?"["+n[r][0]+"m"+t+"["+n[r][1]+"m":t};return c||(h=function(t){return t}),f(t,"undefined"==typeof s?2:s)},n.log=function(){},n.pump=null;var a=Object.keys||function(t){var e=[];for(var n in t)e.push(n);return e},u=Object.getOwnPropertyNames||function(t){var e=[];for(var n in t)Object.hasOwnProperty.call(t,n)&&e.push(n);return e},s=Object.create||function(t,e){var n;if(null===t)n={__proto__:null};else{if("object"!=typeof t)throw new TypeError("typeof prototype["+typeof t+"] != 'object'");var r=function(){};r.prototype=t,n=new r,n.__proto__=t}return"undefined"!=typeof e&&Object.defineProperties&&Object.defineProperties(n,e),n};n.inherits=function(t,e){t.super_=e,t.prototype=s(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})};var c=/%[sdj%]/g;n.format=function(t){if("string"!=typeof t){for(var e=[],r=0;r=o)return t;switch(t){case"%s":return String(i[r++]);case"%d":return Number(i[r++]);case"%j":return JSON.stringify(i[r++]);default:return t}}),u=i[r];o>r;u=i[++r])a+=null===u||"object"!=typeof u?" "+u:" "+n.inspect(u);return a}},{events:1}],4:[function(t,e){var n=e.exports={};n.nextTick=function(){var t="undefined"!=typeof window&&window.setImmediate,e="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(t)return function(t){return window.setImmediate(t)};if(e){var n=[];return window.addEventListener("message",function(t){var e=t.source;if((e===window||null===e)&&"process-tick"===t.data&&(t.stopPropagation(),n.length>0)){var r=n.shift();r()}},!0),function(t){n.push(t),window.postMessage("process-tick","*")}}return function(t){setTimeout(t,0)}}(),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.binding=function(){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(){throw new Error("process.chdir is not supported")}},{}],5:[function(t,e){function n(t,e,n){this.db=t,this.query=e||{},n&&(this.execFn=n)}var r=t("./model"),i=t("underscore");n.prototype.limit=function(t){return this._limit=t,this},n.prototype.skip=function(t){return this._skip=t,this},n.prototype.sort=function(t){return this._sort=t,this},n.prototype.projection=function(t){return this._projection=t,this},n.prototype.project=function(t){var e,n,o,a=[],u=this;return void 0===this._projection||0===Object.keys(this._projection).length?t:(e=0===this._projection._id?!1:!0,this._projection=i.omit(this._projection,"_id"),o=Object.keys(this._projection),o.forEach(function(t){if(void 0!==n&&u._projection[t]!==n)throw new Error("Can't both keep and omit fields except for _id");n=u._projection[t]}),t.forEach(function(t){var i;1===n?(i={$set:{}},o.forEach(function(e){i.$set[e]=r.getDotValue(t,e),void 0===i.$set[e]&&delete i.$set[e]}),i=r.modify({},i)):(i={$unset:{}},o.forEach(function(t){i.$unset[t]=!0}),i=r.modify(t,i)),e?i._id=t._id:delete i._id,a.push(i)}),a)},n.prototype._exec=function(t){function e(e,n){return c.execFn?c.execFn(e,n,t):t(e,n)}var n,i,o,a=[],u=0,s=0,c=this,f=null;this.db.getCandidates(this.query,function(t,l){if(t)return e(t);try{for(n=0;ns)s+=1;else if(a.push(l[n]),u+=1,c._limit&&c._limit<=u)break}catch(t){return e(t)}if(c._sort){i=Object.keys(c._sort);var h=[];for(n=0;nr;r++)0==(3&r)&&(e=4294967296*Math.random()),n[r]=255&e>>>((3&r)<<3);return n}function r(t){function e(t){return o[63&t>>18]+o[63&t>>12]+o[63&t>>6]+o[63&t]}var n,r,i,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=t.length%3,u="";for(i=0,r=t.length-a;r>i;i+=3)n=(t[i]<<16)+(t[i+1]<<8)+t[i+2],u+=e(n);switch(a){case 1:n=t[t.length-1],u+=o[n>>2],u+=o[63&n<<4],u+="==";break;case 2:n=(t[t.length-2]<<8)+t[t.length-1],u+=o[n>>10],u+=o[63&n>>4],u+=o[63&n<<2],u+="="}return u}function i(t){return r(n(Math.ceil(Math.max(8,2*t)))).replace(/[+\/]/g,"").slice(0,t)}e.exports.uid=i},{}],7:[function(t,e){function n(t){var e;"string"==typeof t?(e=t,this.inMemoryOnly=!1):(t=t||{},e=t.filename,this.inMemoryOnly=t.inMemoryOnly||!1,this.autoload=t.autoload||!1,this.timestampData=t.timestampData||!1),e&&"string"==typeof e&&0!==e.length?this.filename=e:(this.filename=null,this.inMemoryOnly=!0),this.compareStrings=t.compareStrings,this.persistence=new f({db:this,nodeWebkitAppName:t.nodeWebkitAppName,afterSerialization:t.afterSerialization,beforeDeserialization:t.beforeDeserialization,corruptAlertThreshold:t.corruptAlertThreshold}),this.executor=new a,this.inMemoryOnly&&(this.executor.ready=!0),this.indexes={},this.indexes._id=new u({fieldName:"_id",unique:!0}),this.ttlIndexes={},this.autoload&&this.loadDatabase(t.onload||function(t){if(t)throw t})}var r=t("./customUtils"),i=t("./model"),o=t("async"),a=t("./executor"),u=t("./indexes"),s=t("util"),c=t("underscore"),f=t("./persistence"),l=t("./cursor");s.inherits(n,t("events").EventEmitter),n.prototype.loadDatabase=function(){this.executor.push({"this":this.persistence,fn:this.persistence.loadDatabase,arguments:arguments},!0)},n.prototype.getAllData=function(){return this.indexes._id.getAll()},n.prototype.resetIndexes=function(t){var e=this;Object.keys(this.indexes).forEach(function(n){e.indexes[n].reset(t)})},n.prototype.ensureIndex=function(t,e){var n,r=e||function(){};if(t=t||{},!t.fieldName)return n=new Error("Cannot create an index without a fieldName"),n.missingFieldName=!0,r(n);if(this.indexes[t.fieldName])return r(null);this.indexes[t.fieldName]=new u(t),void 0!==t.expireAfterSeconds&&(this.ttlIndexes[t.fieldName]=t.expireAfterSeconds);try{this.indexes[t.fieldName].insert(this.getAllData())}catch(i){return delete this.indexes[t.fieldName],r(i)}this.persistence.persistNewState([{$$indexCreated:t}],function(t){return t?r(t):r(null)})},n.prototype.removeIndex=function(t,e){var n=e||function(){};delete this.indexes[t],this.persistence.persistNewState([{$$indexRemoved:t}],function(t){return t?n(t):n(null)})},n.prototype.addToIndexes=function(t){var e,n,r,i=Object.keys(this.indexes);for(e=0;ee;e+=1)this.indexes[i[e]].remove(t);throw r}},n.prototype.removeFromIndexes=function(t){var e=this;Object.keys(this.indexes).forEach(function(n){e.indexes[n].remove(t)})},n.prototype.updateIndexes=function(t,e){var n,r,i,o=Object.keys(this.indexes);for(n=0;nn;n+=1)this.indexes[o[n]].revertUpdate(t,e);throw i}},n.prototype.getCandidates=function(t,e,n){var r,i=Object.keys(this.indexes),a=this;"function"==typeof e&&(n=e,e=!1),o.waterfall([function(e){return r=[],Object.keys(t).forEach(function(e){("string"==typeof t[e]||"number"==typeof t[e]||"boolean"==typeof t[e]||s.isDate(t[e])||null===t[e])&&r.push(e)}),r=c.intersection(r,i),r.length>0?e(null,a.indexes[r[0]].getMatching(t[r[0]])):(r=[],Object.keys(t).forEach(function(e){t[e]&&t[e].hasOwnProperty("$in")&&r.push(e)}),r=c.intersection(r,i),r.length>0?e(null,a.indexes[r[0]].getMatching(t[r[0]].$in)):(r=[],Object.keys(t).forEach(function(e){t[e]&&(t[e].hasOwnProperty("$lt")||t[e].hasOwnProperty("$lte")||t[e].hasOwnProperty("$gt")||t[e].hasOwnProperty("$gte"))&&r.push(e)}),r=c.intersection(r,i),r.length>0?e(null,a.indexes[r[0]].getBetweenBounds(t[r[0]])):e(null,a.getAllData())))},function(t){if(e)return n(null,t);var r=[],i=[],u=Object.keys(a.ttlIndexes);t.forEach(function(t){var e=!0;u.forEach(function(n){void 0!==t[n]&&s.isDate(t[n])&&Date.now()>t[n].getTime()+1e3*a.ttlIndexes[n]&&(e=!1)}),e?i.push(t):r.push(t._id)}),o.eachSeries(r,function(t,e){a._remove({_id:t},{},function(t){return t?n(t):e()})},function(){return n(null,i)})}])},n.prototype._insert=function(t,e){var n,r=e||function(){};try{n=this.prepareDocumentForInsertion(t),this._insertInCache(n)}catch(o){return r(o)}this.persistence.persistNewState(s.isArray(n)?n:[n],function(t){return t?r(t):r(null,i.deepCopy(n))})},n.prototype.createNewId=function(){var t=r.uid(16);return this.indexes._id.getMatching(t).length>0&&(t=this.createNewId()),t},n.prototype.prepareDocumentForInsertion=function(t){var e,n=this;if(s.isArray(t))e=[],t.forEach(function(t){e.push(n.prepareDocumentForInsertion(t))});else{e=i.deepCopy(t),void 0===e._id&&(e._id=this.createNewId());var r=new Date;this.timestampData&&void 0===e.createdAt&&(e.createdAt=r),this.timestampData&&void 0===e.updatedAt&&(e.updatedAt=r),i.checkObject(e)}return e},n.prototype._insertInCache=function(t){s.isArray(t)?this._insertMultipleDocsInCache(t):this.addToIndexes(t)},n.prototype._insertMultipleDocsInCache=function(t){var e,n,r;for(e=0;ee;e+=1)this.removeFromIndexes(t[e]);throw r}},n.prototype.insert=function(){this.executor.push({"this":this,fn:this._insert,arguments:arguments})},n.prototype.count=function(t,e){var n=new l(this,t,function(t,e,n){return t?n(t):n(null,e.length)});return"function"!=typeof e?n:(n.exec(e),void 0)},n.prototype.find=function(t,e,n){switch(arguments.length){case 1:e={};break;case 2:"function"==typeof e&&(n=e,e={})}var r=new l(this,t,function(t,e,n){var r,o=[];if(t)return n(t);for(r=0;ri;i+=1)this.tree.delete(n[i],t);throw c}}else this.tree.insert(e,t)},i.prototype.insertMultipleDocs=function(t){var e,n,r;for(e=0;ee;e+=1)this.remove(t[e]);throw n}},i.prototype.remove=function(t){var e,n=this;return s.isArray(t)?(t.forEach(function(t){n.remove(t)}),void 0):(e=a.getDotValue(t,this.fieldName),void 0===e&&this.sparse||(s.isArray(e)?u.uniq(e,r).forEach(function(e){n.tree.delete(e,t)}):this.tree.delete(e,t)),void 0)},i.prototype.update=function(t,e){if(s.isArray(t))return this.updateMultipleDocs(t),void 0;this.remove(t);try{this.insert(e)}catch(n){throw this.insert(t),n}},i.prototype.updateMultipleDocs=function(t){var e,n,r;for(e=0;ee;e+=1)this.remove(t[e].newDoc);for(e=0;et?-1:t>e?1:0}function c(t,e){var n,r;for(n=0;n0){for(i=0;i=3||2===Object.keys(n).length&&void 0===n.$slice)throw new Error("Can only use $slice in cunjunction with $each when $push to array");if(!m.isArray(n.$each))throw new Error("$each requires an array value");if(n.$each.forEach(function(n){t[e].push(n)}),void 0===n.$slice||"number"!=typeof n.$slice)return;if(0===n.$slice)t[e]=[];else{var r,i,o=t[e].length;n.$slice<0?(r=Math.max(0,o+n.$slice),i=o):n.$slice>0&&(r=0,i=Math.min(o,n.$slice)),t[e]=t[e].slice(r,i)}}else t[e].push(n)},_.$addToSet=function(t,e,n){var r=!0;if(t.hasOwnProperty(e)||(t[e]=[]),!m.isArray(t[e]))throw new Error("Can't $addToSet an element on non-array values");if(null!==n&&"object"==typeof n&&n.$each){if(Object.keys(n).length>1)throw new Error("Can't use another field in conjunction with $each");if(!m.isArray(n.$each))throw new Error("$each requires an array value");n.$each.forEach(function(n){_.$addToSet(t,e,n)})}else t[e].forEach(function(t){0===f(t,n)&&(r=!1)}),r&&t[e].push(n)},_.$pop=function(t,e,n){if(!m.isArray(t[e]))throw new Error("Can't $pop an element from non-array values");if("number"!=typeof n)throw new Error(n+" isn't an integer, can't use it with $pop");0!==n&&(t[e]=n>0?t[e].slice(0,t[e].length-1):t[e].slice(1))},_.$pull=function(t,e,n){var r,i;if(!m.isArray(t[e]))throw new Error("Can't $pull an element from non-array values");for(r=t[e],i=r.length-1;i>=0;i-=1)v(r[i],n)&&r.splice(i,1)},_.$inc=function(t,e,n){if("number"!=typeof n)throw new Error(n+" must be a number");if("number"!=typeof t[e]){if(b.has(t,e))throw new Error("Don't use the $inc modifier on non-number fields");t[e]=n}else t[e]+=n},_.$max=function(t,e,n){"undefined"==typeof t[e]?t[e]=n:n>t[e]&&(t[e]=n)},_.$min=function(t,e,n){"undefined"==typeof t[e]?t[e]=n:nt},k.$lte=function(t,e){return y(t,e)&&e>=t},k.$gt=function(t,e){return y(t,e)&&t>e},k.$gte=function(t,e){return y(t,e)&&t>=e},k.$ne=function(t,e){return void 0===t?!0:!d(t,e)},k.$in=function(t,e){var n;if(!m.isArray(e))throw new Error("$in operator called with a non-array");for(n=0;ne;e+=1)for(r=0;10>r;r+=1)if(i=s.uid(e),this.beforeDeserialization(this.afterSerialization(i))!==i)throw new Error("beforeDeserialization is not the reverse of afterSerialization, cautiously refusing to start NeDB to prevent dataloss");this.filename&&t.nodeWebkitAppName&&(console.log("=================================================================="),console.log("WARNING: The nodeWebkitAppName option is deprecated"),console.log("To get the path to the directory where Node Webkit stores the data"),console.log("for your app, use the internal nw.gui module like this"),console.log("require('nw.gui').App.dataPath"),console.log("See https://github.com/rogerwang/node-webkit/issues/500"),console.log("=================================================================="),this.filename=n.getNWAppFilename(t.nodeWebkitAppName,this.filename))}var r=t("__browserify_process"),i=t("./storage"),o=t("path"),a=t("./model"),u=t("async"),s=t("./customUtils"),c=t("./indexes");n.ensureDirectoryExists=function(t,e){var n=e||function(){};i.mkdirp(t,function(t){return n(t)})},n.getNWAppFilename=function(t,e){var n;switch(r.platform){case"win32":case"win64":if(n=r.env.LOCALAPPDATA||r.env.APPDATA,!n)throw new Error("Couldn't find the base application data folder");n=o.join(n,t);break;case"darwin":if(n=r.env.HOME,!n)throw new Error("Couldn't find the base application data directory");n=o.join(n,"Library","Application Support",t);break;case"linux":if(n=r.env.HOME,!n)throw new Error("Couldn't find the base application data directory");n=o.join(n,".config",t);break;default:throw new Error("Can't use the Node Webkit relative path for platform "+r.platform)}return o.join(n,"nedb-data",e)},n.prototype.persistCachedDatabase=function(t){var e=t||function(){},n="",r=this;return this.inMemoryOnly?e(null):(this.db.getAllData().forEach(function(t){n+=r.afterSerialization(a.serialize(t))+"\n"}),Object.keys(this.db.indexes).forEach(function(t){"_id"!=t&&(n+=r.afterSerialization(a.serialize({$$indexCreated:{fieldName:t,unique:r.db.indexes[t].unique,sparse:r.db.indexes[t].sparse}}))+"\n")}),i.crashSafeWriteFile(this.filename,n,function(t){return t?e(t):(r.db.emit("compaction.done"),e(null))}),void 0)},n.prototype.compactDatafile=function(){this.db.executor.push({"this":this,fn:this.persistCachedDatabase,arguments:[]})},n.prototype.setAutocompactionInterval=function(t){var e=this,n=5e3,r=Math.max(t||0,n);this.stopAutocompaction(),this.autocompactionIntervalId=setInterval(function(){e.compactDatafile()},r)},n.prototype.stopAutocompaction=function(){this.autocompactionIntervalId&&clearInterval(this.autocompactionIntervalId)},n.prototype.persistNewState=function(t,e){var n=this,r="",o=e||function(){};return n.inMemoryOnly?o(null):(t.forEach(function(t){r+=n.afterSerialization(a.serialize(t))+"\n"}),0===r.length?o(null):(i.appendFile(n.filename,r,"utf8",function(t){return o(t)}),void 0))},n.prototype.treatRawData=function(t){var e,n=t.split("\n"),r={},i=[],o={},u=-1;for(e=0;e0&&u/n.length>this.corruptAlertThreshold)throw new Error("More than "+Math.floor(100*this.corruptAlertThreshold)+"% of the data file is corrupt, the wrong beforeDeserialization hook may be used. Cautiously refusing to start NeDB to prevent dataloss");return Object.keys(r).forEach(function(t){i.push(r[t])}),{data:i,indexes:o}},n.prototype.loadDatabase=function(t){var e=t||function(){},r=this;return r.db.resetIndexes(),r.inMemoryOnly?e(null):(u.waterfall([function(t){n.ensureDirectoryExists(o.dirname(r.filename),function(){i.ensureDatafileIntegrity(r.filename,function(){i.readFile(r.filename,"utf8",function(e,n){if(e)return t(e);try{var i=r.treatRawData(n)}catch(o){return t(o)}Object.keys(i.indexes).forEach(function(t){r.db.indexes[t]=new c(i.indexes[t])});try{r.db.resetIndexes(i.data)}catch(o){return r.db.resetIndexes(),t(o)}r.db.persistence.persistCachedDatabase(t)})})})}],function(t){return t?e(t):(r.db.executor.processBuffer(),e(null))}),void 0)},e.exports=n},{"./customUtils":6,"./indexes":9,"./model":10,"./storage":12,__browserify_process:4,async:13,path:2}],12:[function(t,e){function n(t,e){f.getItem(t,function(t,n){return null!==n?e(!0):e(!1)})}function r(t,e,n){f.getItem(t,function(r,i){null===i?f.removeItem(e,function(){return n()}):f.setItem(e,i,function(){f.removeItem(t,function(){return n()})})})}function i(t,e,n,r){"function"==typeof n&&(r=n),f.setItem(t,e,function(){return r()})}function o(t,e,n,r){"function"==typeof n&&(r=n),f.getItem(t,function(n,i){i=i||"",i+=e,f.setItem(t,i,function(){return r()})})}function a(t,e,n){"function"==typeof e&&(n=e),f.getItem(t,function(t,e){return n(null,e||"")})}function u(t,e){f.removeItem(t,function(){return e()})}function s(t,e){return e()}function c(t,e){return e(null)}var f=t("localforage");f.config({name:"NeDB",storeName:"nedbdata"}),e.exports.exists=n,e.exports.rename=r,e.exports.writeFile=i,e.exports.crashSafeWriteFile=i,e.exports.appendFile=o,e.exports.readFile=a,e.exports.unlink=u,e.exports.mkdirp=s,e.exports.ensureDatafileIntegrity=c},{localforage:18}],13:[function(e,n){var r=e("__browserify_process");!function(){function e(t){var e=!1;return function(){if(e)throw new Error("Callback was already called.");e=!0,t.apply(i,arguments)}}var i,o,a={};i=this,null!=i&&(o=i.async),a.noConflict=function(){return i.async=o,a};var u=function(t,e){if(t.forEach)return t.forEach(e);for(var n=0;n=t.length&&r(null))}))})},a.forEach=a.each,a.eachSeries=function(t,e,n){if(n=n||function(){},!t.length)return n();var r=0,i=function(){e(t[r],function(e){e?(n(e),n=function(){}):(r+=1,r>=t.length?n(null):i())})};i()},a.forEachSeries=a.eachSeries,a.eachLimit=function(t,e,n,r){var i=l(e);i.apply(null,[t,n,r])},a.forEachLimit=a.eachLimit;var l=function(t){return function(e,n,r){if(r=r||function(){},!e.length||0>=t)return r();var i=0,o=0,a=0;!function u(){if(i>=e.length)return r();for(;t>a&&o=e.length?r():u())})}()}},h=function(t){return function(){var e=Array.prototype.slice.call(arguments);return t.apply(null,[a.each].concat(e))}},p=function(t,e){return function(){var n=Array.prototype.slice.call(arguments);return e.apply(null,[l(t)].concat(n))}},d=function(t){return function(){var e=Array.prototype.slice.call(arguments);return t.apply(null,[a.eachSeries].concat(e))}},y=function(t,e,n,r){var i=[];e=s(e,function(t,e){return{index:e,value:t}}),t(e,function(t,e){n(t.value,function(n,r){i[t.index]=r,e(n)})},function(t){r(t,i)})};a.map=h(y),a.mapSeries=d(y),a.mapLimit=function(t,e,n,r){return v(e)(t,n,r)};var v=function(t){return p(t,y)};a.reduce=function(t,e,n,r){a.eachSeries(t,function(t,r){n(e,t,function(t,n){e=n,r(t)})},function(t){r(t,e)})},a.inject=a.reduce,a.foldl=a.reduce,a.reduceRight=function(t,e,n,r){var i=s(t,function(t){return t}).reverse();a.reduce(i,e,n,r)},a.foldr=a.reduceRight;var g=function(t,e,n,r){var i=[];e=s(e,function(t,e){return{index:e,value:t}}),t(e,function(t,e){n(t.value,function(n){n&&i.push(t),e()})},function(){r(s(i.sort(function(t,e){return t.index-e.index}),function(t){return t.value}))})};a.filter=h(g),a.filterSeries=d(g),a.select=a.filter,a.selectSeries=a.filterSeries;var m=function(t,e,n,r){var i=[];e=s(e,function(t,e){return{index:e,value:t}}),t(e,function(t,e){n(t.value,function(n){n||i.push(t),e()})},function(){r(s(i.sort(function(t,e){return t.index-e.index}),function(t){return t.value}))})};a.reject=h(m),a.rejectSeries=d(m);var b=function(t,e,n,r){t(e,function(t,e){n(t,function(n){n?(r(t),r=function(){}):e()})},function(){r()})};a.detect=h(b),a.detectSeries=d(b),a.some=function(t,e,n){a.each(t,function(t,r){e(t,function(t){t&&(n(!0),n=function(){}),r()})},function(){n(!1)})},a.any=a.some,a.every=function(t,e,n){a.each(t,function(t,r){e(t,function(t){t||(n(!1),n=function(){}),r()})},function(){n(!0)})},a.all=a.every,a.sortBy=function(t,e,n){a.map(t,function(t,n){e(t,function(e,r){e?n(e):n(null,{value:t,criteria:r})})},function(t,e){if(t)return n(t);var r=function(t,e){var n=t.criteria,r=e.criteria;return r>n?-1:n>r?1:0};n(null,s(e.sort(r),function(t){return t.value}))})},a.auto=function(t,e){e=e||function(){};var n=f(t);if(!n.length)return e(null);var r={},i=[],o=function(t){i.unshift(t)},s=function(t){for(var e=0;ee;e++)t[e].apply(null,arguments)}])))};return i.memo=n,i.unmemoized=t,i},a.unmemoize=function(t){return function(){return(t.unmemoized||t).apply(null,arguments)}},a.times=function(t,e,n){for(var r=[],i=0;t>i;i++)r.push(i);return a.map(r,e,n)},a.timesSeries=function(t,e,n){for(var r=[],i=0;t>i;i++)r.push(i);return a.mapSeries(r,e,n)},a.compose=function(){var t=Array.prototype.reverse.call(arguments);return function(){var e=this,n=Array.prototype.slice.call(arguments),r=n.pop();a.reduce(t,n,function(t,n,r){n.apply(e,t.concat([function(){var t=arguments[0],e=Array.prototype.slice.call(arguments,1);r(t,e)}]))},function(t,n){r.apply(e,[t].concat(n))})}};var x=function(t,e){var n=function(){var n=this,r=Array.prototype.slice.call(arguments),i=r.pop();return t(e,function(t,e){t.apply(n,r.concat([e]))},i)};if(arguments.length>2){var r=Array.prototype.slice.call(arguments,2);return n.apply(this,r)}return n};a.applyEach=h(x),a.applyEachSeries=d(x),a.forever=function(t,e){function n(r){if(r){if(e)return e(r);throw r}t(n)}n()},"undefined"!=typeof t&&t.amd?t([],function(){return a}):"undefined"!=typeof n&&n.exports?n.exports=a:i.async=a}()},{__browserify_process:4}],14:[function(t,e){e.exports.BinarySearchTree=t("./lib/bst"),e.exports.AVLTree=t("./lib/avltree")},{"./lib/avltree":15,"./lib/bst":16}],15:[function(t,e){function n(t){this.tree=new r(t)}function r(t){t=t||{},this.left=null,this.right=null,this.parent=void 0!==t.parent?t.parent:null,t.hasOwnProperty("key")&&(this.key=t.key),this.data=t.hasOwnProperty("value")?[t.value]:[],this.unique=t.unique||!1,this.compareKeys=t.compareKeys||o.defaultCompareKeysFunction,this.checkValueEquality=t.checkValueEquality||o.defaultCheckValueEquality}var i=t("./bst"),o=t("./customUtils"),a=t("util");t("underscore"),a.inherits(r,i),n._AVLTree=r,r.prototype.checkHeightCorrect=function(){var t,e;if(this.hasOwnProperty("key")){if(this.left&&void 0===this.left.height)throw new Error("Undefined height for node "+this.left.key);if(this.right&&void 0===this.right.height)throw new Error("Undefined height for node "+this.right.key);if(void 0===this.height)throw new Error("Undefined height for node "+this.key);if(t=this.left?this.left.height:0,e=this.right?this.right.height:0,this.height!==1+Math.max(t,e))throw new Error("Height constraint failed for node "+this.key);this.left&&this.left.checkHeightCorrect(),this.right&&this.right.checkHeightCorrect()}},r.prototype.balanceFactor=function(){var t=this.left?this.left.height:0,e=this.right?this.right.height:0;return t-e},r.prototype.checkBalanceFactors=function(){if(Math.abs(this.balanceFactor())>1)throw new Error("Tree is unbalanced at node "+this.key);this.left&&this.left.checkBalanceFactors(),this.right&&this.right.checkBalanceFactors()},r.prototype.checkIsAVLT=function(){r.super_.prototype.checkIsBST.call(this),this.checkHeightCorrect(),this.checkBalanceFactors()},n.prototype.checkIsAVLT=function(){this.tree.checkIsAVLT()},r.prototype.rightRotation=function(){var t,e,n,r,i=this,o=this.left;return o?(t=o.right,i.parent?(o.parent=i.parent,i.parent.left===i?i.parent.left=o:i.parent.right=o):o.parent=null,o.right=i,i.parent=o,i.left=t,t&&(t.parent=i),e=o.left?o.left.height:0,n=t?t.height:0,r=i.right?i.right.height:0,i.height=Math.max(n,r)+1,o.height=Math.max(e,i.height)+1,o):this},r.prototype.leftRotation=function(){var t,e,n,r,i=this,o=this.right;return o?(t=o.left,i.parent?(o.parent=i.parent,i.parent.left===i?i.parent.left=o:i.parent.right=o):o.parent=null,o.left=i,i.parent=o,i.right=t,t&&(t.parent=i),e=i.left?i.left.height:0,n=t?t.height:0,r=o.right?o.right.height:0,i.height=Math.max(e,n)+1,o.height=Math.max(r,i.height)+1,o):this},r.prototype.rightTooSmall=function(){return this.balanceFactor()<=1?this:(this.left.balanceFactor()<0&&this.left.leftRotation(),this.rightRotation())},r.prototype.leftTooSmall=function(){return this.balanceFactor()>=-1?this:(this.right.balanceFactor()>0&&this.right.rightRotation(),this.leftRotation())},r.prototype.rebalanceAlongPath=function(t){var e,n,r=this;if(!this.hasOwnProperty("key"))return delete this.height,this;for(n=t.length-1;n>=0;n-=1)t[n].height=1+Math.max(t[n].left?t[n].left.height:0,t[n].right?t[n].right.height:0),t[n].balanceFactor()>1&&(e=t[n].rightTooSmall(),0===n&&(r=e)),t[n].balanceFactor()<-1&&(e=t[n].leftTooSmall(),0===n&&(r=e));return r},r.prototype.insert=function(t,e){var n=[],r=this;if(!this.hasOwnProperty("key"))return this.key=t,this.data.push(e),this.height=1,this;for(;;){if(0===r.compareKeys(r.key,t)){if(r.unique){var i=new Error("Can't insert key "+t+", it violates the unique constraint");throw i.key=t,i.errorType="uniqueViolated",i}return r.data.push(e),this}if(n.push(r),r.compareKeys(t,r.key)<0){if(!r.left){n.push(r.createLeftChild({key:t,value:e}));break}r=r.left}else{if(!r.right){n.push(r.createRightChild({key:t,value:e}));break}r=r.right}}return this.rebalanceAlongPath(n)},n.prototype.insert=function(t,e){var n=this.tree.insert(t,e);n&&(this.tree=n)},r.prototype.delete=function(t,e){var n,r=[],i=this,o=[];if(!this.hasOwnProperty("key"))return this;for(;;){if(0===i.compareKeys(t,i.key))break;if(o.push(i),i.compareKeys(t,i.key)<0){if(!i.left)return this;i=i.left}else{if(!i.right)return this;i=i.right}}if(i.data.length>1&&e)return i.data.forEach(function(t){i.checkValueEquality(t,e)||r.push(t)}),i.data=r,this;if(!i.left&&!i.right)return i===this?(delete i.key,i.data=[],delete i.height,this):(i.parent.left===i?i.parent.left=null:i.parent.right=null,this.rebalanceAlongPath(o));if(!i.left||!i.right)return n=i.left?i.left:i.right,i===this?(n.parent=null,n):(i.parent.left===i?(i.parent.left=n,n.parent=i.parent):(i.parent.right=n,n.parent=i.parent),this.rebalanceAlongPath(o));if(o.push(i),n=i.left,!n.right)return i.key=n.key,i.data=n.data,i.left=n.left,n.left&&(n.left.parent=i),this.rebalanceAlongPath(o);for(;;){if(!n.right)break;o.push(n),n=n.right}return i.key=n.key,i.data=n.data,n.parent.right=n.left,n.left&&(n.left.parent=n.parent),this.rebalanceAlongPath(o)},n.prototype.delete=function(t,e){var n=this.tree.delete(t,e);n&&(this.tree=n)},["getNumberOfKeys","search","betweenBounds","prettyPrint","executeOnEveryNode"].forEach(function(t){n.prototype[t]=function(){return this.tree[t].apply(this.tree,arguments)}}),e.exports=n},{"./bst":16,"./customUtils":17,underscore:19,util:3}],16:[function(t,e){function n(t){t=t||{},this.left=null,this.right=null,this.parent=void 0!==t.parent?t.parent:null,t.hasOwnProperty("key")&&(this.key=t.key),this.data=t.hasOwnProperty("value")?[t.value]:[],this.unique=t.unique||!1,this.compareKeys=t.compareKeys||i.defaultCompareKeysFunction,this.checkValueEquality=t.checkValueEquality||i.defaultCheckValueEquality}function r(t,e){var n;for(n=0;n=0)throw new Error("Tree with root "+t.key+" is not a binary search tree")}),this.left.checkNodeOrdering()),this.right&&(this.right.checkAllNodesFullfillCondition(function(e){if(t.compareKeys(e,t.key)<=0)throw new Error("Tree with root "+t.key+" is not a binary search tree")}),this.right.checkNodeOrdering()))},n.prototype.checkInternalPointers=function(){if(this.left){if(this.left.parent!==this)throw new Error("Parent pointer broken for key "+this.key);this.left.checkInternalPointers()}if(this.right){if(this.right.parent!==this)throw new Error("Parent pointer broken for key "+this.key);this.right.checkInternalPointers()}},n.prototype.checkIsBST=function(){if(this.checkNodeOrdering(),this.checkInternalPointers(),this.parent)throw new Error("The root shouldn't have a parent")},n.prototype.getNumberOfKeys=function(){var t;return this.hasOwnProperty("key")?(t=1,this.left&&(t+=this.left.getNumberOfKeys()),this.right&&(t+=this.right.getNumberOfKeys()),t):0},n.prototype.createSimilar=function(t){return t=t||{},t.unique=this.unique,t.compareKeys=this.compareKeys,t.checkValueEquality=this.checkValueEquality,new this.constructor(t)},n.prototype.createLeftChild=function(t){var e=this.createSimilar(t);return e.parent=this,this.left=e,e},n.prototype.createRightChild=function(t){var e=this.createSimilar(t);return e.parent=this,this.right=e,e},n.prototype.insert=function(t,e){if(!this.hasOwnProperty("key"))return this.key=t,this.data.push(e),void 0;if(0===this.compareKeys(this.key,t)){if(this.unique){var n=new Error("Can't insert key "+t+", it violates the unique constraint");throw n.key=t,n.errorType="uniqueViolated",n}return this.data.push(e),void 0}this.compareKeys(t,this.key)<0?this.left?this.left.insert(t,e):this.createLeftChild({key:t,value:e}):this.right?this.right.insert(t,e):this.createRightChild({key:t,value:e})},n.prototype.search=function(t){return this.hasOwnProperty("key")?0===this.compareKeys(this.key,t)?this.data:this.compareKeys(t,this.key)<0?this.left?this.left.search(t):[]:this.right?this.right.search(t):[]:[]},n.prototype.getLowerBoundMatcher=function(t){var e=this;return t.hasOwnProperty("$gt")||t.hasOwnProperty("$gte")?t.hasOwnProperty("$gt")&&t.hasOwnProperty("$gte")?0===e.compareKeys(t.$gte,t.$gt)?function(n){return e.compareKeys(n,t.$gt)>0}:e.compareKeys(t.$gte,t.$gt)>0?function(n){return e.compareKeys(n,t.$gte)>=0}:function(n){return e.compareKeys(n,t.$gt)>0}:t.hasOwnProperty("$gt")?function(n){return e.compareKeys(n,t.$gt)>0}:function(n){return e.compareKeys(n,t.$gte)>=0}:function(){return!0}},n.prototype.getUpperBoundMatcher=function(t){var e=this;return t.hasOwnProperty("$lt")||t.hasOwnProperty("$lte")?t.hasOwnProperty("$lt")&&t.hasOwnProperty("$lte")?0===e.compareKeys(t.$lte,t.$lt)?function(n){return e.compareKeys(n,t.$lt)<0}:e.compareKeys(t.$lte,t.$lt)<0?function(n){return e.compareKeys(n,t.$lte)<=0}:function(n){return e.compareKeys(n,t.$lt)<0}:t.hasOwnProperty("$lt")?function(n){return e.compareKeys(n,t.$lt)<0}:function(n){return e.compareKeys(n,t.$lte)<=0}:function(){return!0}},n.prototype.betweenBounds=function(t,e,n){var i=[];return this.hasOwnProperty("key")?(e=e||this.getLowerBoundMatcher(t),n=n||this.getUpperBoundMatcher(t),e(this.key)&&this.left&&r(i,this.left.betweenBounds(t,e,n)),e(this.key)&&n(this.key)&&r(i,this.data),n(this.key)&&this.right&&r(i,this.right.betweenBounds(t,e,n)),i):[]},n.prototype.deleteIfLeaf=function(){return this.left||this.right?!1:this.parent?(this.parent.left===this?this.parent.left=null:this.parent.right=null,!0):(delete this.key,this.data=[],!0)},n.prototype.deleteIfOnlyOneChild=function(){var t;return this.left&&!this.right&&(t=this.left),!this.left&&this.right&&(t=this.right),t?this.parent?(this.parent.left===this?(this.parent.left=t,t.parent=this.parent):(this.parent.right=t,t.parent=this.parent),!0):(this.key=t.key,this.data=t.data,this.left=null,t.left&&(this.left=t.left,t.left.parent=this),this.right=null,t.right&&(this.right=t.right,t.right.parent=this),!0):!1},n.prototype.delete=function(t,e){var n,r=[],i=this;if(this.hasOwnProperty("key")){if(this.compareKeys(t,this.key)<0)return this.left&&this.left.delete(t,e),void 0;if(this.compareKeys(t,this.key)>0)return this.right&&this.right.delete(t,e),void 0;if(0!==!this.compareKeys(t,this.key))return this.data.length>1&&void 0!==e?(this.data.forEach(function(t){i.checkValueEquality(t,e)||r.push(t)}),i.data=r,void 0):(this.deleteIfLeaf()||this.deleteIfOnlyOneChild()||(Math.random()>=.5?(n=this.left.getMaxKeyDescendant(),this.key=n.key,this.data=n.data,this===n.parent?(this.left=n.left,n.left&&(n.left.parent=n.parent)):(n.parent.right=n.left,n.left&&(n.left.parent=n.parent))):(n=this.right.getMinKeyDescendant(),this.key=n.key,this.data=n.data,this===n.parent?(this.right=n.right,n.right&&(n.right.parent=n.parent)):(n.parent.left=n.right,n.right&&(n.right.parent=n.parent)))),void 0)}},n.prototype.executeOnEveryNode=function(t){this.left&&this.left.executeOnEveryNode(t),t(this),this.right&&this.right.executeOnEveryNode(t)},n.prototype.prettyPrint=function(t,e){e=e||"",console.log(e+"* "+this.key),t&&console.log(e+"* "+this.data),(this.left||this.right)&&(this.left?this.left.prettyPrint(t,e+" "):console.log(e+" *"),this.right?this.right.prettyPrint(t,e+" "):console.log(e+" *"))},e.exports=n},{"./customUtils":17}],17:[function(t,e){function n(t){var e,r;return 0===t?[]:1===t?[0]:(e=n(t-1),r=Math.floor(Math.random()*t),e.splice(r,0,t-1),e)}function r(t,e){if(e>t)return-1;if(t>e)return 1;if(t===e)return 0;var n=new Error("Couldn't compare elements");throw n.a=t,n.b=e,n}function i(t,e){return t===e}e.exports.getRandomArray=n,e.exports.defaultCompareKeysFunction=r,e.exports.defaultCheckValueEquality=i},{}],18:[function(e,n,r){var i=e("__browserify_process"),o=self;!function(){var t,e,n,r;!function(){var i={},o={};t=function(t,e,n){i[t]={deps:e,callback:n}},r=n=e=function(t){function n(e){if("."!==e.charAt(0))return e;for(var n=e.split("/"),r=t.split("/").slice(0,-1),i=0,o=n.length;o>i;i++){var a=n[i];if(".."===a)r.pop();else{if("."===a)continue;r.push(a)}}return r.join("/")}if(r._eak_seen=i,o[t])return o[t];if(o[t]={},!i[t])throw new Error("Could not find module "+t);for(var a,u=i[t],s=u.deps,c=u.callback,f=[],l=0,h=s.length;h>l;l++)"exports"===s[l]?f.push(a={}):f.push(e(n(s[l])));var p=c.apply(this,f);return o[t]=a||p}}(),t("promise/all",["./utils","exports"],function(t,e){"use strict";function n(t){var e=this;if(!r(t))throw new TypeError("You must pass an array to all.");return new e(function(e,n){function r(t){return function(e){o(t,e)}}function o(t,n){u[t]=n,0===--s&&e(u)}var a,u=[],s=t.length;0===s&&e([]);for(var c=0;cn;n++){var i=t[n];this.supports(i)&&e.push(i)}return e},e.prototype._wrapLibraryMethodsWithReady=function(){for(var e=0;ei;i++)r[i]=t.charCodeAt(i);return n}function r(t){return new Promise(function(e,n){var r=new XMLHttpRequest;r.open("GET",t),r.withCredentials=!0,r.responseType="arraybuffer",r.onreadystatechange=function(){return 4===r.readyState?200===r.status?e({response:r.response,type:r.getResponseHeader("Content-Type")}):(n({status:r.status,response:r.response}),void 0):void 0},r.send()})}function i(e){return new Promise(function(n,i){var o=t([""],{type:"image/png"}),a=e.transaction([S],"readwrite");a.objectStore(S).put(o,"key"),a.oncomplete=function(){var t=e.transaction([S],"readwrite"),o=t.objectStore(S).get("key");o.onerror=i,o.onsuccess=function(t){var e=t.target.result,i=URL.createObjectURL(e);r(i).then(function(t){n(!(!t||"image/png"!==t.type))},function(){n(!1)}).then(function(){URL.revokeObjectURL(i)})}}})["catch"](function(){return!1})}function o(t){return"boolean"==typeof A?Promise.resolve(A):i(t).then(function(t){return A=t})}function a(t){return new Promise(function(e,n){var r=new FileReader;r.onerror=n,r.onloadend=function(n){var r=btoa(n.target.result||"");e({__local_forage_encoded_blob:!0,data:r,type:t.type})},r.readAsBinaryString(t)})}function u(e){var r=n(atob(e.data));return t([r],{type:e.type})}function s(t){return t&&t.__local_forage_encoded_blob}function c(t){function e(){return Promise.resolve()}var n=this,r={db:null};if(t)for(var i in t)r[i]=t[i];O||(O={});var o=O[r.name];o||(o={forages:[],db:null},O[r.name]=o),o.forages.push(this);for(var a=[],u=0;ut.db.version;if(r&&(t.version!==e&&x.console.warn('The database "'+t.name+'"'+" can't be downgraded from version "+t.db.version+" to version "+t.version+"."),t.version=t.db.version),i||n){if(n){var o=t.db.version+1;o>t.version&&(t.version=o)}return!0}return!1}function d(t,e){var n=this;"string"!=typeof t&&(x.console.warn(t+" used as a key, but it is not a string."),t=String(t));var r=new Promise(function(e,r){n.ready().then(function(){var i=n._dbInfo,o=i.db.transaction(i.storeName,"readonly").objectStore(i.storeName),a=o.get(t);a.onsuccess=function(){var t=a.result;void 0===t&&(t=null),s(t)&&(t=u(t)),e(t)},a.onerror=function(){r(a.error)}})["catch"](r)});return k(r,e),r}function y(t,e){var n=this,r=new Promise(function(e,r){n.ready().then(function(){var i=n._dbInfo,o=i.db.transaction(i.storeName,"readonly").objectStore(i.storeName),a=o.openCursor(),c=1;a.onsuccess=function(){var n=a.result;if(n){var r=n.value;s(r)&&(r=u(r));var i=t(r,n.key,c++);void 0!==i?e(i):n["continue"]()}else e()},a.onerror=function(){r(a.error)}})["catch"](r)});return k(r,e),r}function v(t,e,n){var r=this;"string"!=typeof t&&(x.console.warn(t+" used as a key, but it is not a string."),t=String(t));var i=new Promise(function(n,i){var u;r.ready().then(function(){return u=r._dbInfo,o(u.db)}).then(function(t){return!t&&e instanceof Blob?a(e):e}).then(function(e){var r=u.db.transaction(u.storeName,"readwrite"),o=r.objectStore(u.storeName);null===e&&(e=void 0);var a=o.put(e,t);r.oncomplete=function(){void 0===e&&(e=null),n(e)},r.onabort=r.onerror=function(){var t=a.error?a.error:a.transaction.error;i(t)}})["catch"](i)});return k(i,n),i}function g(t,e){var n=this;"string"!=typeof t&&(x.console.warn(t+" used as a key, but it is not a string."),t=String(t));var r=new Promise(function(e,r){n.ready().then(function(){var i=n._dbInfo,o=i.db.transaction(i.storeName,"readwrite"),a=o.objectStore(i.storeName),u=a["delete"](t);o.oncomplete=function(){e()},o.onerror=function(){r(u.error)},o.onabort=function(){var t=u.error?u.error:u.transaction.error;r(t)}})["catch"](r)});return k(r,e),r}function m(t){var e=this,n=new Promise(function(t,n){e.ready().then(function(){var r=e._dbInfo,i=r.db.transaction(r.storeName,"readwrite"),o=i.objectStore(r.storeName),a=o.clear();i.oncomplete=function(){t()},i.onabort=i.onerror=function(){var t=a.error?a.error:a.transaction.error;n(t)}})["catch"](n)});return k(n,t),n}function b(t){var e=this,n=new Promise(function(t,n){e.ready().then(function(){var r=e._dbInfo,i=r.db.transaction(r.storeName,"readonly").objectStore(r.storeName),o=i.count();o.onsuccess=function(){t(o.result)},o.onerror=function(){n(o.error)}})["catch"](n)});return k(n,t),n}function w(t,e){var n=this,r=new Promise(function(e,r){return 0>t?(e(null),void 0):(n.ready().then(function(){var i=n._dbInfo,o=i.db.transaction(i.storeName,"readonly").objectStore(i.storeName),a=!1,u=o.openCursor();u.onsuccess=function(){var n=u.result;return n?(0===t?e(n.key):a?e(n.key):(a=!0,n.advance(t)),void 0):(e(null),void 0)},u.onerror=function(){r(u.error)}})["catch"](r),void 0)});return k(r,e),r}function _(t){var e=this,n=new Promise(function(t,n){e.ready().then(function(){var r=e._dbInfo,i=r.db.transaction(r.storeName,"readonly").objectStore(r.storeName),o=i.openCursor(),a=[];o.onsuccess=function(){var e=o.result;return e?(a.push(e.key),e["continue"](),void 0):(t(a),void 0)},o.onerror=function(){n(o.error)}})["catch"](n)});return k(n,t),n}function k(t,e){e&&t.then(function(t){e(null,t)},function(t){e(t)})}var x=this,E=E||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(E){var A,O,S="local-forage-detect-blob-support",j={_driver:"asyncStorage",_initStorage:c,iterate:y,getItem:d,setItem:v,removeItem:g,clear:m,length:b,key:w,keys:_};e["default"]=j}}.call("undefined"!=typeof window?window:self),t.exports=e["default"]},function(t,e,n){"use strict";e.__esModule=!0,function(){function t(t){var e=this,r={};if(t)for(var i in t)r[i]=t[i];return r.keyPrefix=r.name+"/",r.storeName!==e._defaultConfig.storeName&&(r.keyPrefix+=r.storeName+"/"),e._dbInfo=r,new Promise(function(t){t(n(3))}).then(function(t){return r.serializer=t,Promise.resolve()})}function r(t){var e=this,n=e.ready().then(function(){for(var t=e._dbInfo.keyPrefix,n=p.length-1;n>=0;n--){var r=p.key(n);0===r.indexOf(t)&&p.removeItem(r)}});return l(n,t),n}function i(t,e){var n=this;"string"!=typeof t&&(h.console.warn(t+" used as a key, but it is not a string."),t=String(t));var r=n.ready().then(function(){var e=n._dbInfo,r=p.getItem(e.keyPrefix+t);return r&&(r=e.serializer.deserialize(r)),r});return l(r,e),r}function o(t,e){var n=this,r=n.ready().then(function(){for(var e=n._dbInfo,r=e.keyPrefix,i=r.length,o=p.length,a=1,u=0;o>u;u++){var s=p.key(u);if(0===s.indexOf(r)){var c=p.getItem(s);if(c&&(c=e.serializer.deserialize(c)),c=t(c,s.substring(i),a++),void 0!==c)return c}}});return l(r,e),r}function a(t,e){var n=this,r=n.ready().then(function(){var e,r=n._dbInfo;try{e=p.key(t)}catch(i){e=null}return e&&(e=e.substring(r.keyPrefix.length)),e});return l(r,e),r}function u(t){var e=this,n=e.ready().then(function(){for(var t=e._dbInfo,n=p.length,r=[],i=0;n>i;i++)0===p.key(i).indexOf(t.keyPrefix)&&r.push(p.key(i).substring(t.keyPrefix.length));return r});return l(n,t),n}function s(t){var e=this,n=e.keys().then(function(t){return t.length});return l(n,t),n}function c(t,e){var n=this;"string"!=typeof t&&(h.console.warn(t+" used as a key, but it is not a string."),t=String(t));var r=n.ready().then(function(){var e=n._dbInfo;p.removeItem(e.keyPrefix+t)});return l(r,e),r}function f(t,e,n){var r=this;"string"!=typeof t&&(h.console.warn(t+" used as a key, but it is not a string."),t=String(t));var i=r.ready().then(function(){void 0===e&&(e=null);var n=e;return new Promise(function(i,o){var a=r._dbInfo;a.serializer.serialize(e,function(e,r){if(r)o(r);else try{p.setItem(a.keyPrefix+t,e),i(n)}catch(u){("QuotaExceededError"===u.name||"NS_ERROR_DOM_QUOTA_REACHED"===u.name)&&o(u),o(u)}})})});return l(i,n),i}function l(t,e){e&&t.then(function(t){e(null,t)},function(t){e(t)})}var h=this,p=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;p=this.localStorage}catch(d){return}var y={_driver:"localStorageWrapper",_initStorage:t,iterate:o,getItem:i,setItem:f,removeItem:c,clear:r,length:s,key:a,keys:u};e["default"]=y}.call("undefined"!=typeof window?window:self),t.exports=e["default"]},function(t,e){"use strict";e.__esModule=!0,function(){function t(t,e){t=t||[],e=e||{};try{return new Blob(t,e)}catch(n){if("TypeError"!==n.name)throw n;for(var r=x.BlobBuilder||x.MSBlobBuilder||x.MozBlobBuilder||x.WebKitBlobBuilder,i=new r,o=0;oe;e+=4)n=a.indexOf(t[e]),r=a.indexOf(t[e+1]),i=a.indexOf(t[e+2]),o=a.indexOf(t[e+3]),l[c++]=n<<2|r>>4,l[c++]=(15&r)<<4|i>>2,l[c++]=(3&i)<<6|63&o;return f}function o(t){var e,n=new Uint8Array(t),r="";for(e=0;e>2],r+=a[(3&n[e])<<4|n[e+1]>>4],r+=a[(15&n[e+1])<<2|n[e+2]>>6],r+=a[63&n[e+2]];return 2===n.length%3?r=r.substring(0,r.length-1)+"=":1===n.length%3&&(r=r.substring(0,r.length-2)+"=="),r}var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u="~~local_forage_type~",s=/^~~local_forage_type~([^~]+)~/,c="__lfsc__:",f=c.length,l="arbf",h="blob",p="si08",d="ui08",y="uic8",v="si16",g="si32",m="ur16",b="ui32",w="fl32",_="fl64",k=f+l.length,x=this,E={serialize:n,deserialize:r,stringToBuffer:i,bufferToString:o};e["default"]=E}.call("undefined"!=typeof window?window:self),t.exports=e["default"]},function(t,e,n){"use strict";e.__esModule=!0,function(){function t(t){var e=this,r={db:null};if(t)for(var i in t)r[i]="string"!=typeof t[i]?t[i].toString():t[i];var o=new Promise(function(n,i){try{r.db=p(r.name,String(r.version),r.description,r.size)}catch(o){return e.setDriver(e.LOCALSTORAGE).then(function(){return e._initStorage(t)}).then(n)["catch"](i)}r.db.transaction(function(t){t.executeSql("CREATE TABLE IF NOT EXISTS "+r.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){e._dbInfo=r,n()},function(t,e){i(e)})})});return new Promise(function(t){t(n(3))}).then(function(t){return r.serializer=t,o})}function r(t,e){var n=this;"string"!=typeof t&&(h.console.warn(t+" used as a key, but it is not a string."),t=String(t));var r=new Promise(function(e,r){n.ready().then(function(){var i=n._dbInfo;i.db.transaction(function(n){n.executeSql("SELECT * FROM "+i.storeName+" WHERE key = ? LIMIT 1",[t],function(t,n){var r=n.rows.length?n.rows.item(0).value:null;r&&(r=i.serializer.deserialize(r)),e(r)},function(t,e){r(e)})})})["catch"](r)});return l(r,e),r}function i(t,e){var n=this,r=new Promise(function(e,r){n.ready().then(function(){var i=n._dbInfo;i.db.transaction(function(n){n.executeSql("SELECT * FROM "+i.storeName,[],function(n,r){for(var o=r.rows,a=o.length,u=0;a>u;u++){var s=o.item(u),c=s.value;if(c&&(c=i.serializer.deserialize(c)),c=t(c,s.key,u+1),void 0!==c)return e(c),void 0}e()},function(t,e){r(e)})})})["catch"](r)});return l(r,e),r}function o(t,e,n){var r=this;"string"!=typeof t&&(h.console.warn(t+" used as a key, but it is not a string."),t=String(t));var i=new Promise(function(n,i){r.ready().then(function(){void 0===e&&(e=null);var o=e,a=r._dbInfo;a.serializer.serialize(e,function(e,r){r?i(r):a.db.transaction(function(r){r.executeSql("INSERT OR REPLACE INTO "+a.storeName+" (key, value) VALUES (?, ?)",[t,e],function(){n(o)},function(t,e){i(e)})},function(t){t.code===t.QUOTA_ERR&&i(t)})})})["catch"](i)});return l(i,n),i}function a(t,e){var n=this;"string"!=typeof t&&(h.console.warn(t+" used as a key, but it is not a string."),t=String(t));var r=new Promise(function(e,r){n.ready().then(function(){var i=n._dbInfo;i.db.transaction(function(n){n.executeSql("DELETE FROM "+i.storeName+" WHERE key = ?",[t],function(){e()},function(t,e){r(e)})})})["catch"](r)});return l(r,e),r}function u(t){var e=this,n=new Promise(function(t,n){e.ready().then(function(){var r=e._dbInfo;r.db.transaction(function(e){e.executeSql("DELETE FROM "+r.storeName,[],function(){t()},function(t,e){n(e)})})})["catch"](n)});return l(n,t),n}function s(t){var e=this,n=new Promise(function(t,n){e.ready().then(function(){var r=e._dbInfo;r.db.transaction(function(e){e.executeSql("SELECT COUNT(key) as c FROM "+r.storeName,[],function(e,n){var r=n.rows.item(0).c;t(r)},function(t,e){n(e)})})})["catch"](n)});return l(n,t),n}function c(t,e){var n=this,r=new Promise(function(e,r){n.ready().then(function(){var i=n._dbInfo;i.db.transaction(function(n){n.executeSql("SELECT key FROM "+i.storeName+" WHERE id = ? LIMIT 1",[t+1],function(t,n){var r=n.rows.length?n.rows.item(0).key:null;e(r)},function(t,e){r(e)})})})["catch"](r)});return l(r,e),r}function f(t){var e=this,n=new Promise(function(t,n){e.ready().then(function(){var r=e._dbInfo;r.db.transaction(function(e){e.executeSql("SELECT key FROM "+r.storeName,[],function(e,n){for(var r=[],i=0;ir;r++)if(e.call(n,t[r],r,t)===i)return}else for(var a in t)if(A.has(t,a)&&e.call(n,t[a],a,t)===i)return};A.map=A.collect=function(t,e,n){var r=[];return null==t?r:d&&t.map===d?t.map(e,n):(O(t,function(t,i,o){r[r.length]=e.call(n,t,i,o)}),r)};var S="Reduce of empty array with no initial value";A.reduce=A.foldl=A.inject=function(t,e,n,r){var i=arguments.length>2;if(null==t&&(t=[]),y&&t.reduce===y)return r&&(e=A.bind(e,r)),i?t.reduce(e,n):t.reduce(e);if(O(t,function(t,o,a){i?n=e.call(r,n,t,o,a):(n=t,i=!0)}),!i)throw new TypeError(S);return n},A.reduceRight=A.foldr=function(t,e,n,r){var i=arguments.length>2;if(null==t&&(t=[]),v&&t.reduceRight===v)return r&&(e=A.bind(e,r)),i?t.reduceRight(e,n):t.reduceRight(e);var o=t.length;if(o!==+o){var a=A.keys(t);o=a.length}if(O(t,function(u,s,c){s=a?a[--o]:--o,i?n=e.call(r,n,t[s],s,c):(n=t[s],i=!0)}),!i)throw new TypeError(S);return n},A.find=A.detect=function(t,e,n){var r;return j(t,function(t,i,o){return e.call(n,t,i,o)?(r=t,!0):void 0}),r},A.filter=A.select=function(t,e,n){var r=[];return null==t?r:g&&t.filter===g?t.filter(e,n):(O(t,function(t,i,o){e.call(n,t,i,o)&&(r[r.length]=t)}),r)},A.reject=function(t,e,n){return A.filter(t,function(t,r,i){return!e.call(n,t,r,i)},n)},A.every=A.all=function(t,e,n){e||(e=A.identity);var r=!0;return null==t?r:m&&t.every===m?t.every(e,n):(O(t,function(t,o,a){return(r=r&&e.call(n,t,o,a))?void 0:i}),!!r)};var j=A.some=A.any=function(t,e,n){e||(e=A.identity);var r=!1;return null==t?r:b&&t.some===b?t.some(e,n):(O(t,function(t,o,a){return r||(r=e.call(n,t,o,a))?i:void 0}),!!r)};A.contains=A.include=function(t,e){return null==t?!1:w&&t.indexOf===w?-1!=t.indexOf(e):j(t,function(t){return t===e})},A.invoke=function(t,e){var n=c.call(arguments,2),r=A.isFunction(e);return A.map(t,function(t){return(r?e:t[e]).apply(t,n)})},A.pluck=function(t,e){return A.map(t,function(t){return t[e]})},A.where=function(t,e,n){return A.isEmpty(e)?n?null:[]:A[n?"find":"filter"](t,function(t){for(var n in e)if(e[n]!==t[n])return!1;return!0})},A.findWhere=function(t,e){return A.where(t,e,!0)},A.max=function(t,e,n){if(!e&&A.isArray(t)&&t[0]===+t[0]&&t.length<65535)return Math.max.apply(Math,t);if(!e&&A.isEmpty(t))return-1/0;var r={computed:-1/0,value:-1/0};return O(t,function(t,i,o){var a=e?e.call(n,t,i,o):t;a>=r.computed&&(r={value:t,computed:a})}),r.value},A.min=function(t,e,n){if(!e&&A.isArray(t)&&t[0]===+t[0]&&t.length<65535)return Math.min.apply(Math,t);if(!e&&A.isEmpty(t))return 1/0;var r={computed:1/0,value:1/0};return O(t,function(t,i,o){var a=e?e.call(n,t,i,o):t;ar||void 0===n)return 1;if(r>n||void 0===r)return-1}return t.indexo;){var u=o+a>>>1;n.call(r,t[u])=0})})},A.difference=function(t){var e=f.apply(o,c.call(arguments,1));return A.filter(t,function(t){return!A.contains(e,t)})},A.zip=function(){for(var t=c.call(arguments),e=A.max(A.pluck(t,"length")),n=new Array(e),r=0;e>r;r++)n[r]=A.pluck(t,""+r);return n},A.object=function(t,e){if(null==t)return{};for(var n={},r=0,i=t.length;i>r;r++)e?n[t[r]]=e[r]:n[t[r][0]]=t[r][1];return n},A.indexOf=function(t,e,n){if(null==t)return-1;var r=0,i=t.length;if(n){if("number"!=typeof n)return r=A.sortedIndex(t,e),t[r]===e?r:-1;r=0>n?Math.max(0,i+n):n}if(w&&t.indexOf===w)return t.indexOf(e,n);for(;i>r;r++)if(t[r]===e)return r;return-1},A.lastIndexOf=function(t,e,n){if(null==t)return-1;var r=null!=n;if(_&&t.lastIndexOf===_)return r?t.lastIndexOf(e,n):t.lastIndexOf(e);for(var i=r?n:t.length;i--;)if(t[i]===e)return i;return-1},A.range=function(t,e,n){arguments.length<=1&&(e=t||0,t=0),n=arguments[2]||1;for(var r=Math.max(Math.ceil((e-t)/n),0),i=0,o=new Array(r);r>i;)o[i++]=t,t+=n;return o},A.bind=function(t,e){if(t.bind===E&&E)return E.apply(t,c.call(arguments,1));var n=c.call(arguments,2);return function(){return t.apply(e,n.concat(c.call(arguments)))}},A.partial=function(t){var e=c.call(arguments,1);return function(){return t.apply(this,e.concat(c.call(arguments)))}},A.bindAll=function(t){var e=c.call(arguments,1);return 0===e.length&&(e=A.functions(t)),O(e,function(e){t[e]=A.bind(t[e],t)}),t},A.memoize=function(t,e){var n={};return e||(e=A.identity),function(){var r=e.apply(this,arguments);return A.has(n,r)?n[r]:n[r]=t.apply(this,arguments)}},A.delay=function(t,e){var n=c.call(arguments,2);return setTimeout(function(){return t.apply(null,n)},e)},A.defer=function(t){return A.delay.apply(A,[t,1].concat(c.call(arguments,1)))},A.throttle=function(t,e){var n,r,i,o,a=0,u=function(){a=new Date,i=null,o=t.apply(n,r)};return function(){var s=new Date,c=e-(s-a);return n=this,r=arguments,0>=c?(clearTimeout(i),i=null,a=s,o=t.apply(n,r)):i||(i=setTimeout(u,c)),o}},A.debounce=function(t,e,n){var r,i;return function(){var o=this,a=arguments,u=function(){r=null,n||(i=t.apply(o,a))},s=n&&!r;return clearTimeout(r),r=setTimeout(u,e),s&&(i=t.apply(o,a)),i}},A.once=function(t){var e,n=!1;return function(){return n?e:(n=!0,e=t.apply(this,arguments),t=null,e)}},A.wrap=function(t,e){return function(){var n=[t];return s.apply(n,arguments),e.apply(this,n)}},A.compose=function(){var t=arguments;return function(){for(var e=arguments,n=t.length-1;n>=0;n--)e=[t[n].apply(this,e)];return e[0]}},A.after=function(t,e){return 0>=t?e():function(){return--t<1?e.apply(this,arguments):void 0}},A.keys=x||function(t){if(t!==Object(t))throw new TypeError("Invalid object");var e=[];for(var n in t)A.has(t,n)&&(e[e.length]=n);return e},A.values=function(t){var e=[];for(var n in t)A.has(t,n)&&e.push(t[n]);return e},A.pairs=function(t){var e=[];for(var n in t)A.has(t,n)&&e.push([n,t[n]]);return e},A.invert=function(t){var e={};for(var n in t)A.has(t,n)&&(e[t[n]]=n);return e},A.functions=A.methods=function(t){var e=[];for(var n in t)A.isFunction(t[n])&&e.push(n);return e.sort()},A.extend=function(t){return O(c.call(arguments,1),function(e){if(e)for(var n in e)t[n]=e[n]}),t},A.pick=function(t){var e={},n=f.apply(o,c.call(arguments,1));return O(n,function(n){n in t&&(e[n]=t[n])}),e},A.omit=function(t){var e={},n=f.apply(o,c.call(arguments,1));for(var r in t)A.contains(n,r)||(e[r]=t[r]);return e},A.defaults=function(t){return O(c.call(arguments,1),function(e){if(e)for(var n in e)null==t[n]&&(t[n]=e[n]) +}),t},A.clone=function(t){return A.isObject(t)?A.isArray(t)?t.slice():A.extend({},t):t},A.tap=function(t,e){return e(t),t};var N=function(t,e,n,r){if(t===e)return 0!==t||1/t==1/e;if(null==t||null==e)return t===e;t instanceof A&&(t=t._wrapped),e instanceof A&&(e=e._wrapped);var i=l.call(t);if(i!=l.call(e))return!1;switch(i){case"[object String]":return t==String(e);case"[object Number]":return t!=+t?e!=+e:0==t?1/t==1/e:t==+e;case"[object Date]":case"[object Boolean]":return+t==+e;case"[object RegExp]":return t.source==e.source&&t.global==e.global&&t.multiline==e.multiline&&t.ignoreCase==e.ignoreCase}if("object"!=typeof t||"object"!=typeof e)return!1;for(var o=n.length;o--;)if(n[o]==t)return r[o]==e;n.push(t),r.push(e);var a=0,u=!0;if("[object Array]"==i){if(a=t.length,u=a==e.length)for(;a--&&(u=N(t[a],e[a],n,r)););}else{var s=t.constructor,c=e.constructor;if(s!==c&&!(A.isFunction(s)&&s instanceof s&&A.isFunction(c)&&c instanceof c))return!1;for(var f in t)if(A.has(t,f)&&(a++,!(u=A.has(e,f)&&N(t[f],e[f],n,r))))break;if(u){for(f in e)if(A.has(e,f)&&!a--)break;u=!a}}return n.pop(),r.pop(),u};A.isEqual=function(t,e){return N(t,e,[],[])},A.isEmpty=function(t){if(null==t)return!0;if(A.isArray(t)||A.isString(t))return 0===t.length;for(var e in t)if(A.has(t,e))return!1;return!0},A.isElement=function(t){return!(!t||1!==t.nodeType)},A.isArray=k||function(t){return"[object Array]"==l.call(t)},A.isObject=function(t){return t===Object(t)},O(["Arguments","Function","String","Number","Date","RegExp"],function(t){A["is"+t]=function(e){return l.call(e)=="[object "+t+"]"}}),A.isArguments(arguments)||(A.isArguments=function(t){return!(!t||!A.has(t,"callee"))}),"function"!=typeof/./&&(A.isFunction=function(t){return"function"==typeof t}),A.isFinite=function(t){return isFinite(t)&&!isNaN(parseFloat(t))},A.isNaN=function(t){return A.isNumber(t)&&t!=+t},A.isBoolean=function(t){return t===!0||t===!1||"[object Boolean]"==l.call(t)},A.isNull=function(t){return null===t},A.isUndefined=function(t){return void 0===t},A.has=function(t,e){return h.call(t,e)},A.noConflict=function(){return t._=r,this},A.identity=function(t){return t},A.times=function(t,e,n){for(var r=Array(t),i=0;t>i;i++)r[i]=e.call(n,i);return r},A.random=function(t,e){return null==e&&(e=t,t=0),t+Math.floor(Math.random()*(e-t+1))};var P={escape:{"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"}};P.unescape=A.invert(P.escape);var T={escape:new RegExp("["+A.keys(P.escape).join("")+"]","g"),unescape:new RegExp("("+A.keys(P.unescape).join("|")+")","g")};A.each(["escape","unescape"],function(t){A[t]=function(e){return null==e?"":(""+e).replace(T[t],function(e){return P[t][e]})}}),A.result=function(t,e){if(null==t)return null;var n=t[e];return A.isFunction(n)?n.call(t):n},A.mixin=function(t){O(A.functions(t),function(e){var n=A[e]=t[e];A.prototype[e]=function(){var t=[this._wrapped];return s.apply(t,arguments),R.call(this,n.apply(A,t))}})};var C=0;A.uniqueId=function(t){var e=++C+"";return t?t+e:e},A.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var M=/(.)^/,B={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"},F=/\\|'|\r|\n|\t|\u2028|\u2029/g;A.template=function(t,e,n){var r;n=A.defaults({},n,A.templateSettings);var i=new RegExp([(n.escape||M).source,(n.interpolate||M).source,(n.evaluate||M).source].join("|")+"|$","g"),o=0,a="__p+='";t.replace(i,function(e,n,r,i,u){return a+=t.slice(o,u).replace(F,function(t){return"\\"+B[t]}),n&&(a+="'+\n((__t=("+n+"))==null?'':_.escape(__t))+\n'"),r&&(a+="'+\n((__t=("+r+"))==null?'':__t)+\n'"),i&&(a+="';\n"+i+"\n__p+='"),o=u+e.length,e}),a+="';\n",n.variable||(a="with(obj||{}){\n"+a+"}\n"),a="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+a+"return __p;\n";try{r=new Function(n.variable||"obj","_",a)}catch(u){throw u.source=a,u}if(e)return r(e,A);var s=function(t){return r.call(this,t,A)};return s.source="function("+(n.variable||"obj")+"){\n"+a+"}",s},A.chain=function(t){return A(t).chain()};var R=function(t){return this._chain?A(t).chain():t};A.mixin(A),O(["pop","push","reverse","shift","sort","splice","unshift"],function(t){var e=o[t];A.prototype[t]=function(){var n=this._wrapped;return e.apply(n,arguments),"shift"!=t&&"splice"!=t||0!==n.length||delete n[0],R.call(this,n)}}),O(["concat","join","slice"],function(t){var e=o[t];A.prototype[t]=function(){return R.call(this,e.apply(this._wrapped,arguments))}}),A.extend(A.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}})}.call(this)},{}]},{},[7])(7)}); \ No newline at end of file diff --git a/public/assets/objectid.js b/public/assets/objectid.js new file mode 100644 index 00000000..7f32db8c --- /dev/null +++ b/public/assets/objectid.js @@ -0,0 +1,120 @@ +/* +* +* Copyright (c) 2011-2014- Justin Dearing (zippy1981@gmail.com) +* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) +* and GPL (http://www.opensource.org/licenses/gpl-license.php) version 2 licenses. +* This software is not distributed under version 3 or later of the GPL. +* +* Version 1.0.2 +* +*/ + +if (!document) var document = { cookie: '' }; // fix crashes on node + +/** + * Javascript class that mimics how WCF serializes a object of type MongoDB.Bson.ObjectId + * and converts between that format and the standard 24 character representation. +*/ +var ObjectId = (function () { + var increment = Math.floor(Math.random() * (16777216)); + var pid = Math.floor(Math.random() * (65536)); + var machine = Math.floor(Math.random() * (16777216)); + + var setMachineCookie = function() { + var cookieList = document.cookie.split('; '); + for (var i in cookieList) { + var cookie = cookieList[i].split('='); + var cookieMachineId = parseInt(cookie[1], 10); + if (cookie[0] == 'mongoMachineId' && cookieMachineId && cookieMachineId >= 0 && cookieMachineId <= 16777215) { + machine = cookieMachineId; + break; + } + } + document.cookie = 'mongoMachineId=' + machine + ';expires=Tue, 19 Jan 2038 05:00:00 GMT;path=/'; + }; + if (typeof (localStorage) != 'undefined') { + try { + var mongoMachineId = parseInt(localStorage['mongoMachineId']); + if (mongoMachineId >= 0 && mongoMachineId <= 16777215) { + machine = Math.floor(localStorage['mongoMachineId']); + } + // Just always stick the value in. + localStorage['mongoMachineId'] = machine; + } catch (e) { + setMachineCookie(); + } + } + else { + setMachineCookie(); + } + + function ObjId() { + if (!(this instanceof ObjectId)) { + return new ObjectId(arguments[0], arguments[1], arguments[2], arguments[3]).toString(); + } + + if (typeof (arguments[0]) == 'object') { + this.timestamp = arguments[0].timestamp; + this.machine = arguments[0].machine; + this.pid = arguments[0].pid; + this.increment = arguments[0].increment; + } + else if (typeof (arguments[0]) == 'string' && arguments[0].length == 24) { + this.timestamp = Number('0x' + arguments[0].substr(0, 8)), + this.machine = Number('0x' + arguments[0].substr(8, 6)), + this.pid = Number('0x' + arguments[0].substr(14, 4)), + this.increment = Number('0x' + arguments[0].substr(18, 6)) + } + else if (arguments.length == 4 && arguments[0] != null) { + this.timestamp = arguments[0]; + this.machine = arguments[1]; + this.pid = arguments[2]; + this.increment = arguments[3]; + } + else { + this.timestamp = Math.floor(new Date().valueOf() / 1000); + this.machine = machine; + this.pid = pid; + this.increment = increment++; + if (increment > 0xffffff) { + increment = 0; + } + } + }; + return ObjId; +})(); + +ObjectId.prototype.getDate = function () { + return new Date(this.timestamp * 1000); +}; + +ObjectId.prototype.toArray = function () { + var strOid = this.toString(); + var array = []; + var i; + for(i = 0; i < 12; i++) { + array[i] = parseInt(strOid.slice(i*2, i*2+2), 16); + } + return array; +}; + +/** +* Turns a WCF representation of a BSON ObjectId into a 24 character string representation. +*/ +ObjectId.prototype.toString = function () { + if (this.timestamp === undefined + || this.machine === undefined + || this.pid === undefined + || this.increment === undefined) { + return 'Invalid ObjectId'; + } + + var timestamp = this.timestamp.toString(16); + var machine = this.machine.toString(16); + var pid = this.pid.toString(16); + var increment = this.increment.toString(16); + return '00000000'.substr(0, 8 - timestamp.length) + timestamp + + '000000'.substr(0, 6 - machine.length) + machine + + '0000'.substr(0, 4 - pid.length) + pid + + '000000'.substr(0, 6 - increment.length) + increment; +}; diff --git a/public/assets/peer.min.js b/public/assets/peer.min.js new file mode 100644 index 00000000..0aa06e93 --- /dev/null +++ b/public/assets/peer.min.js @@ -0,0 +1,2 @@ +/*! peerjs build:0.3.14, production. Copyright(c) 2013 Michelle Bu */!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;gd.chunkedMTU)return void this._sendChunks(e);d.supports.sctp?d.supports.binaryBlob?this._bufferedSend(e):d.blobToArrayBuffer(e,function(a){c._bufferedSend(a)}):d.blobToBinaryString(e,function(a){c._bufferedSend(a)})}else this._bufferedSend(a)},c.prototype._bufferedSend=function(a){(this._buffering||!this._trySend(a))&&(this._buffer.push(a),this.bufferSize=this._buffer.length)},c.prototype._trySend=function(a){try{this._dc.send(a)}catch(b){this._buffering=!0;var c=this;return setTimeout(function(){c._buffering=!1,c._tryBuffer()},100),!1}return!0},c.prototype._tryBuffer=function(){if(0!==this._buffer.length){var a=this._buffer[0];this._trySend(a)&&(this._buffer.shift(),this.bufferSize=this._buffer.length,this._tryBuffer())}},c.prototype._sendChunks=function(a){for(var b=d.chunk(a),c=0,e=b.length;e>c;c+=1){var a=b[c];this.send(a,!0)}},c.prototype.handleMessage=function(a){var b=a.payload;switch(a.type){case"ANSWER":this._peerBrowser=b.browser,f.handleSDP(a.type,this,b.sdp);break;case"CANDIDATE":f.handleCandidate(this,b.candidate);break;default:d.warn("Unrecognized message type:",a.type,"from peer:",this.peer)}},b.exports=c},{"./negotiator":5,"./util":8,eventemitter3:9,reliable:12}],3:[function(a){window.Socket=a("./socket"),window.MediaConnection=a("./mediaconnection"),window.DataConnection=a("./dataconnection"),window.Peer=a("./peer"),window.RTCPeerConnection=a("./adapter").RTCPeerConnection,window.RTCSessionDescription=a("./adapter").RTCSessionDescription,window.RTCIceCandidate=a("./adapter").RTCIceCandidate,window.Negotiator=a("./negotiator"),window.util=a("./util"),window.BinaryPack=a("js-binarypack")},{"./adapter":1,"./dataconnection":2,"./mediaconnection":4,"./negotiator":5,"./peer":6,"./socket":7,"./util":8,"js-binarypack":10}],4:[function(a,b){function c(a,b,g){return this instanceof c?(e.call(this),this.options=d.extend({},g),this.open=!1,this.type="media",this.peer=a,this.provider=b,this.metadata=this.options.metadata,this.localStream=this.options._stream,this.id=this.options.connectionId||c._idPrefix+d.randomToken(),void(this.localStream&&f.startConnection(this,{_stream:this.localStream,originator:!0}))):new c(a,b,g)}var d=a("./util"),e=a("eventemitter3"),f=a("./negotiator");d.inherits(c,e),c._idPrefix="mc_",c.prototype.addStream=function(a){d.log("Receiving stream",a),this.remoteStream=a,this.emit("stream",a)},c.prototype.handleMessage=function(a){var b=a.payload;switch(a.type){case"ANSWER":f.handleSDP(a.type,this,b.sdp),this.open=!0;break;case"CANDIDATE":f.handleCandidate(this,b.candidate);break;default:d.warn("Unrecognized message type:",a.type,"from peer:",this.peer)}},c.prototype.answer=function(a){if(this.localStream)return void d.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");this.options._payload._stream=a,this.localStream=a,f.startConnection(this,this.options._payload);for(var b=this.provider._getMessages(this.id),c=0,e=b.length;e>c;c+=1)this.handleMessage(b[c]);this.open=!0},c.prototype.close=function(){this.open&&(this.open=!1,f.cleanup(this),this.emit("close"))},b.exports=c},{"./negotiator":5,"./util":8,eventemitter3:9}],5:[function(a,b){var c=a("./util"),d=a("./adapter").RTCPeerConnection,e=a("./adapter").RTCSessionDescription,f=a("./adapter").RTCIceCandidate,g={pcs:{data:{},media:{}},queue:[]};g._idPrefix="pc_",g.startConnection=function(a,b){var d=g._getPeerConnection(a,b);if("media"===a.type&&b._stream&&d.addStream(b._stream),a.pc=a.peerConnection=d,b.originator){if("data"===a.type){var e={};c.supports.sctp||(e={reliable:b.reliable});var f=d.createDataChannel(a.label,e);a.initialize(f)}c.supports.onnegotiationneeded||g._makeOffer(a)}else g.handleSDP("OFFER",a,b.sdp)},g._getPeerConnection=function(a,b){g.pcs[a.type]||c.error(a.type+" is not a valid connection type. Maybe you overrode the `type` property somewhere."),g.pcs[a.type][a.peer]||(g.pcs[a.type][a.peer]={});{var d;g.pcs[a.type][a.peer]}return b.pc&&(d=g.pcs[a.type][a.peer][b.pc]),d&&"stable"===d.signalingState||(d=g._startPeerConnection(a)),d},g._startPeerConnection=function(a){c.log("Creating RTCPeerConnection.");var b=g._idPrefix+c.randomToken(),e={};"data"!==a.type||c.supports.sctp?"media"===a.type&&(e={optional:[{DtlsSrtpKeyAgreement:!0}]}):e={optional:[{RtpDataChannels:!0}]};var f=new d(a.provider.options.config,e);return g.pcs[a.type][a.peer][b]=f,g._setupListeners(a,f,b),f},g._setupListeners=function(a,b){var d=a.peer,e=a.id,f=a.provider;c.log("Listening for ICE candidates."),b.onicecandidate=function(b){b.candidate&&(c.log("Received ICE candidates for:",a.peer),f.socket.send({type:"CANDIDATE",payload:{candidate:b.candidate,type:a.type,connectionId:a.id},dst:d}))},b.oniceconnectionstatechange=function(){switch(b.iceConnectionState){case"disconnected":case"failed":c.log("iceConnectionState is disconnected, closing connections to "+d),a.close();break;case"completed":b.onicecandidate=c.noop}},b.onicechange=b.oniceconnectionstatechange,c.log("Listening for `negotiationneeded`"),b.onnegotiationneeded=function(){c.log("`negotiationneeded` triggered"),"stable"==b.signalingState?g._makeOffer(a):c.log("onnegotiationneeded triggered when not stable. Is another connection being established?")},c.log("Listening for data channel"),b.ondatachannel=function(a){c.log("Received data channel");var b=a.channel,g=f.getConnection(d,e);g.initialize(b)},c.log("Listening for remote stream"),b.onaddstream=function(a){c.log("Received remote stream");var b=a.stream,g=f.getConnection(d,e);"media"===g.type&&g.addStream(b)}},g.cleanup=function(a){c.log("Cleaning up PeerConnection to "+a.peer);var b=a.pc;!b||"closed"===b.readyState&&"closed"===b.signalingState||(b.close(),a.pc=null)},g._makeOffer=function(a){var b=a.pc;b.createOffer(function(d){c.log("Created offer."),!c.supports.sctp&&"data"===a.type&&a.reliable&&(d.sdp=Reliable.higherBandwidthSDP(d.sdp)),b.setLocalDescription(d,function(){c.log("Set localDescription: offer","for:",a.peer),a.provider.socket.send({type:"OFFER",payload:{sdp:d,type:a.type,label:a.label,connectionId:a.id,reliable:a.reliable,serialization:a.serialization,metadata:a.metadata,browser:c.browser},dst:a.peer})},function(b){a.provider.emitError("webrtc",b),c.log("Failed to setLocalDescription, ",b)})},function(b){a.provider.emitError("webrtc",b),c.log("Failed to createOffer, ",b)},a.options.constraints)},g._makeAnswer=function(a){var b=a.pc;b.createAnswer(function(d){c.log("Created answer."),!c.supports.sctp&&"data"===a.type&&a.reliable&&(d.sdp=Reliable.higherBandwidthSDP(d.sdp)),b.setLocalDescription(d,function(){c.log("Set localDescription: answer","for:",a.peer),a.provider.socket.send({type:"ANSWER",payload:{sdp:d,type:a.type,connectionId:a.id,browser:c.browser},dst:a.peer})},function(b){a.provider.emitError("webrtc",b),c.log("Failed to setLocalDescription, ",b)})},function(b){a.provider.emitError("webrtc",b),c.log("Failed to create answer, ",b)})},g.handleSDP=function(a,b,d){d=new e(d);var f=b.pc;c.log("Setting remote description",d),f.setRemoteDescription(d,function(){c.log("Set remoteDescription:",a,"for:",b.peer),"OFFER"===a&&g._makeAnswer(b)},function(a){b.provider.emitError("webrtc",a),c.log("Failed to setRemoteDescription, ",a)})},g.handleCandidate=function(a,b){var d=b.candidate,e=b.sdpMLineIndex;a.pc.addIceCandidate(new f({sdpMLineIndex:e,candidate:d})),c.log("Added ICE candidate for:",a.peer)},b.exports=g},{"./adapter":1,"./util":8}],6:[function(a,b){function c(a,b){return this instanceof c?(e.call(this),a&&a.constructor==Object?(b=a,a=void 0):a&&(a=a.toString()),b=d.extend({debug:0,host:d.CLOUD_HOST,port:d.CLOUD_PORT,key:"peerjs",path:"/",token:d.randomToken(),config:d.defaultConfig},b),this.options=b,"/"===b.host&&(b.host=window.location.hostname),"/"!==b.path[0]&&(b.path="/"+b.path),"/"!==b.path[b.path.length-1]&&(b.path+="/"),void 0===b.secure&&b.host!==d.CLOUD_HOST&&(b.secure=d.isSecure()),b.logFunction&&d.setLogFunction(b.logFunction),d.setLogLevel(b.debug),d.supports.audioVideo||d.supports.data?d.validateId(a)?d.validateKey(b.key)?b.secure&&"0.peerjs.com"===b.host?void this._delayedAbort("ssl-unavailable","The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS."):(this.destroyed=!1,this.disconnected=!1,this.open=!1,this.connections={},this._lostMessages={},this._initializeServerConnection(),void(a?this._initialize(a):this._retrieveId())):void this._delayedAbort("invalid-key",'API KEY "'+b.key+'" is invalid'):void this._delayedAbort("invalid-id",'ID "'+a+'" is invalid'):void this._delayedAbort("browser-incompatible","The current browser does not support WebRTC")):new c(a,b)}var d=a("./util"),e=a("eventemitter3"),f=a("./socket"),g=a("./mediaconnection"),h=a("./dataconnection");d.inherits(c,e),c.prototype._initializeServerConnection=function(){var a=this;this.socket=new f(this.options.secure,this.options.host,this.options.port,this.options.path,this.options.key),this.socket.on("message",function(b){a._handleMessage(b)}),this.socket.on("error",function(b){a._abort("socket-error",b)}),this.socket.on("disconnected",function(){a.disconnected||(a.emitError("network","Lost connection to server."),a.disconnect())}),this.socket.on("close",function(){a.disconnected||a._abort("socket-closed","Underlying socket is already closed.")})},c.prototype._retrieveId=function(){var a=this,b=new XMLHttpRequest,c=this.options.secure?"https://":"http://",e=c+this.options.host+":"+this.options.port+this.options.path+this.options.key+"/id",f="?ts="+(new Date).getTime()+Math.random();e+=f,b.open("get",e,!0),b.onerror=function(b){d.error("Error retrieving ID",b);var c="";"/"===a.options.path&&a.options.host!==d.CLOUD_HOST&&(c=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),a._abort("server-error","Could not get an ID from the server."+c)},b.onreadystatechange=function(){return 4===b.readyState?200!==b.status?void b.onerror():void a._initialize(b.responseText):void 0},b.send(null)},c.prototype._initialize=function(a){this.id=a,this.socket.start(this.id,this.options.token)},c.prototype._handleMessage=function(a){var b,c=a.type,e=a.payload,f=a.src;switch(c){case"OPEN":this.emit("open",this.id),this.open=!0;break;case"ERROR":this._abort("server-error",e.msg);break;case"ID-TAKEN":this._abort("unavailable-id","ID `"+this.id+"` is taken");break;case"INVALID-KEY":this._abort("invalid-key",'API KEY "'+this.options.key+'" is invalid');break;case"LEAVE":d.log("Received leave message from",f),this._cleanupPeer(f);break;case"EXPIRE":this.emitError("peer-unavailable","Could not connect to peer "+f);break;case"OFFER":var i=e.connectionId;if(b=this.getConnection(f,i))d.warn("Offer received for existing Connection ID:",i);else{if("media"===e.type)b=new g(f,this,{connectionId:i,_payload:e,metadata:e.metadata}),this._addConnection(f,b),this.emit("call",b);else{if("data"!==e.type)return void d.warn("Received malformed connection type:",e.type);b=new h(f,this,{connectionId:i,_payload:e,metadata:e.metadata,label:e.label,serialization:e.serialization,reliable:e.reliable}),this._addConnection(f,b),this.emit("connection",b)}for(var j=this._getMessages(i),k=0,l=j.length;l>k;k+=1)b.handleMessage(j[k])}break;default:if(!e)return void d.warn("You received a malformed message from "+f+" of type "+c);var m=e.connectionId;b=this.getConnection(f,m),b&&b.pc?b.handleMessage(a):m?this._storeMessage(m,a):d.warn("You received an unrecognized message:",a)}},c.prototype._storeMessage=function(a,b){this._lostMessages[a]||(this._lostMessages[a]=[]),this._lostMessages[a].push(b)},c.prototype._getMessages=function(a){var b=this._lostMessages[a];return b?(delete this._lostMessages[a],b):[]},c.prototype.connect=function(a,b){if(this.disconnected)return d.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."),void this.emitError("disconnected","Cannot connect to new Peer after disconnecting from server.");var c=new h(a,this,b);return this._addConnection(a,c),c},c.prototype.call=function(a,b,c){if(this.disconnected)return d.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),void this.emitError("disconnected","Cannot connect to new Peer after disconnecting from server.");if(!b)return void d.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");c=c||{},c._stream=b;var e=new g(a,this,c);return this._addConnection(a,e),e},c.prototype._addConnection=function(a,b){this.connections[a]||(this.connections[a]=[]),this.connections[a].push(b)},c.prototype.getConnection=function(a,b){var c=this.connections[a];if(!c)return null;for(var d=0,e=c.length;e>d;d++)if(c[d].id===b)return c[d];return null},c.prototype._delayedAbort=function(a,b){var c=this;d.setZeroTimeout(function(){c._abort(a,b)})},c.prototype._abort=function(a,b){d.error("Aborting!"),this._lastServerId?this.disconnect():this.destroy(),this.emitError(a,b)},c.prototype.emitError=function(a,b){d.error("Error:",b),"string"==typeof b&&(b=new Error(b)),b.type=a,this.emit("error",b)},c.prototype.destroy=function(){this.destroyed||(this._cleanup(),this.disconnect(),this.destroyed=!0)},c.prototype._cleanup=function(){if(this.connections)for(var a=Object.keys(this.connections),b=0,c=a.length;c>b;b++)this._cleanupPeer(a[b]);this.emit("close")},c.prototype._cleanupPeer=function(a){for(var b=this.connections[a],c=0,d=b.length;d>c;c+=1)b[c].close()},c.prototype.disconnect=function(){var a=this;d.setZeroTimeout(function(){a.disconnected||(a.disconnected=!0,a.open=!1,a.socket&&a.socket.close(),a.emit("disconnected",a.id),a._lastServerId=a.id,a.id=null)})},c.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)d.log("Attempting reconnection to server with ID "+this._lastServerId),this.disconnected=!1,this._initializeServerConnection(),this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(this.disconnected||this.open)throw new Error("Peer "+this.id+" cannot reconnect because it is not disconnected from the server!");d.error("In a hurry? We're still trying to make the initial connection!")}},c.prototype.listAllPeers=function(a){a=a||function(){};var b=this,c=new XMLHttpRequest,e=this.options.secure?"https://":"http://",f=e+this.options.host+":"+this.options.port+this.options.path+this.options.key+"/peers",g="?ts="+(new Date).getTime()+Math.random();f+=g,c.open("get",f,!0),c.onerror=function(){b._abort("server-error","Could not get peers from the server."),a([])},c.onreadystatechange=function(){if(4===c.readyState){if(401===c.status){var e="";throw e=b.options.host!==d.CLOUD_HOST?"It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":"You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",a([]),new Error("It doesn't look like you have permission to list peers IDs. "+e)}a(200!==c.status?[]:JSON.parse(c.responseText))}},c.send(null)},b.exports=c},{"./dataconnection":2,"./mediaconnection":4,"./socket":7,"./util":8,eventemitter3:9}],7:[function(a,b){function c(a,b,d,f,g){if(!(this instanceof c))return new c(a,b,d,f,g);e.call(this),this.disconnected=!1,this._queue=[];var h=a?"https://":"http://",i=a?"wss://":"ws://";this._httpUrl=h+b+":"+d+f+g,this._wsUrl=i+b+":"+d+f+"peerjs?key="+g}var d=a("./util"),e=a("eventemitter3");d.inherits(c,e),c.prototype.start=function(a,b){this.id=a,this._httpUrl+="/"+a+"/"+b,this._wsUrl+="&id="+a+"&token="+b,this._startXhrStream(),this._startWebSocket()},c.prototype._startWebSocket=function(){var a=this;this._socket||(this._socket=new WebSocket(this._wsUrl),this._socket.onmessage=function(b){try{var c=JSON.parse(b.data)}catch(e){return void d.log("Invalid server message",b.data)}a.emit("message",c)},this._socket.onclose=function(){d.log("Socket closed."),a.disconnected=!0,a.emit("disconnected")},this._socket.onopen=function(){a._timeout&&(clearTimeout(a._timeout),setTimeout(function(){a._http.abort(),a._http=null},5e3)),a._sendQueuedMessages(),d.log("Socket open")})},c.prototype._startXhrStream=function(a){try{var b=this;this._http=new XMLHttpRequest,this._http._index=1,this._http._streamIndex=a||0,this._http.open("post",this._httpUrl+"/id?i="+this._http._streamIndex,!0),this._http.onerror=function(){clearTimeout(b._timeout),b.emit("disconnected")},this._http.onreadystatechange=function(){2==this.readyState&&this.old?(this.old.abort(),delete this.old):this.readyState>2&&200===this.status&&this.responseText&&b._handleStream(this)},this._http.send(null),this._setHTTPTimeout()}catch(c){d.log("XMLHttpRequest not available; defaulting to WebSockets")}},c.prototype._handleStream=function(a){var b=a.responseText.split("\n");if(a._buffer)for(;a._buffer.length>0;){var c=a._buffer.shift(),e=b[c];try{e=JSON.parse(e)}catch(f){a._buffer.shift(c);break}this.emit("message",e)}var g=b[a._index];if(g)if(a._index+=1,a._index===b.length)a._buffer||(a._buffer=[]),a._buffer.push(a._index-1);else{try{g=JSON.parse(g)}catch(f){return void d.log("Invalid server message",g)}this.emit("message",g)}},c.prototype._setHTTPTimeout=function(){var a=this;this._timeout=setTimeout(function(){var b=a._http;a._wsOpen()?b.abort():(a._startXhrStream(b._streamIndex+1),a._http.old=b)},25e3)},c.prototype._wsOpen=function(){return this._socket&&1==this._socket.readyState},c.prototype._sendQueuedMessages=function(){for(var a=0,b=this._queue.length;b>a;a+=1)this.send(this._queue[a])},c.prototype.send=function(a){if(!this.disconnected){if(!this.id)return void this._queue.push(a);if(!a.type)return void this.emit("error","Invalid message");var b=JSON.stringify(a);if(this._wsOpen())this._socket.send(b);else{var c=new XMLHttpRequest,d=this._httpUrl+"/"+a.type.toLowerCase();c.open("post",d,!0),c.setRequestHeader("Content-Type","application/json"),c.send(b)}}},c.prototype.close=function(){!this.disconnected&&this._wsOpen()&&(this._socket.close(),this.disconnected=!0)},b.exports=c},{"./util":8,eventemitter3:9}],8:[function(a,b){var c={iceServers:[{url:"stun:stun.l.google.com:19302"}]},d=1,e=a("js-binarypack"),f=a("./adapter").RTCPeerConnection,g={noop:function(){},CLOUD_HOST:"0.peerjs.com",CLOUD_PORT:9e3,chunkedBrowsers:{Chrome:1},chunkedMTU:16300,logLevel:0,setLogLevel:function(a){var b=parseInt(a,10);g.logLevel=isNaN(parseInt(a,10))?a?3:0:b,g.log=g.warn=g.error=g.noop,g.logLevel>0&&(g.error=g._printWith("ERROR")),g.logLevel>1&&(g.warn=g._printWith("WARNING")),g.logLevel>2&&(g.log=g._print)},setLogFunction:function(a){a.constructor!==Function?g.warn("The log function you passed in is not a function. Defaulting to regular logs."):g._print=a},_printWith:function(a){return function(){var b=Array.prototype.slice.call(arguments);b.unshift(a),g._print.apply(g,b)}},_print:function(){var a=!1,b=Array.prototype.slice.call(arguments);b.unshift("PeerJS: ");for(var c=0,d=b.length;d>c;c++)b[c]instanceof Error&&(b[c]="("+b[c].name+") "+b[c].message,a=!0);a?console.error.apply(console,b):console.log.apply(console,b)},defaultConfig:c,browser:function(){return window.mozRTCPeerConnection?"Firefox":window.webkitRTCPeerConnection?"Chrome":window.RTCPeerConnection?"Supported":"Unsupported"}(),supports:function(){if("undefined"==typeof f)return{};var a,b,d=!0,e=!0,h=!1,i=!1,j=!!window.webkitRTCPeerConnection;try{a=new f(c,{optional:[{RtpDataChannels:!0}]})}catch(k){d=!1,e=!1}if(d)try{b=a.createDataChannel("_PEERJSTEST")}catch(k){d=!1}if(d){try{b.binaryType="blob",h=!0}catch(k){}var l=new f(c,{});try{var m=l.createDataChannel("_PEERJSRELIABLETEST",{});i=m.reliable}catch(k){}l.close()}if(e&&(e=!!a.addStream),!j&&d){var n=new f(c,{optional:[{RtpDataChannels:!0}]});n.onnegotiationneeded=function(){j=!0,g&&g.supports&&(g.supports.onnegotiationneeded=!0)},n.createDataChannel("_PEERJSNEGOTIATIONTEST"),setTimeout(function(){n.close()},1e3)}return a&&a.close(),{audioVideo:e,data:d,binaryBlob:h,binary:i,reliable:i,sctp:i,onnegotiationneeded:j}}(),validateId:function(a){return!a||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(a)},validateKey:function(a){return!a||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(a)},debug:!1,inherits:function(a,b){a.super_=b,a.prototype=Object.create(b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}})},extend:function(a,b){for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a},pack:e.pack,unpack:e.unpack,log:function(){if(g.debug){var a=!1,b=Array.prototype.slice.call(arguments);b.unshift("PeerJS: ");for(var c=0,d=b.length;d>c;c++)b[c]instanceof Error&&(b[c]="("+b[c].name+") "+b[c].message,a=!0);a?console.error.apply(console,b):console.log.apply(console,b)}},setZeroTimeout:function(a){function b(b){d.push(b),a.postMessage(e,"*")}function c(b){b.source==a&&b.data==e&&(b.stopPropagation&&b.stopPropagation(),d.length&&d.shift()())}var d=[],e="zero-timeout-message";return a.addEventListener?a.addEventListener("message",c,!0):a.attachEvent&&a.attachEvent("onmessage",c),b}(window),chunk:function(a){for(var b=[],c=a.size,e=index=0,f=Math.ceil(c/g.chunkedMTU);c>e;){var h=Math.min(c,e+g.chunkedMTU),i=a.slice(e,h),j={__peerData:d,n:index,data:i,total:f};b.push(j),e=h,index+=1}return d+=1,b},blobToArrayBuffer:function(a,b){var c=new FileReader;c.onload=function(a){b(a.target.result)},c.readAsArrayBuffer(a)},blobToBinaryString:function(a,b){var c=new FileReader;c.onload=function(a){b(a.target.result)},c.readAsBinaryString(a)},binaryStringToArrayBuffer:function(a){for(var b=new Uint8Array(a.length),c=0;cb;b++)d.push(this._events[a][b].fn);return d},d.prototype.emit=function(a,b,c,d,e,f){if(!this._events||!this._events[a])return!1;var g,h,i,j=this._events[a],k=j.length,l=arguments.length,m=j[0];if(1===k){switch(m.once&&this.removeListener(a,m.fn,!0),l){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,b),!0;case 3:return m.fn.call(m.context,b,c),!0;case 4:return m.fn.call(m.context,b,c,d),!0;case 5:return m.fn.call(m.context,b,c,d,e),!0;case 6:return m.fn.call(m.context,b,c,d,e,f),!0}for(h=1,g=new Array(l-1);l>h;h++)g[h-1]=arguments[h];m.fn.apply(m.context,g)}else for(h=0;k>h;h++)switch(j[h].once&&this.removeListener(a,j[h].fn,!0),l){case 1:j[h].fn.call(j[h].context);break;case 2:j[h].fn.call(j[h].context,b);break;case 3:j[h].fn.call(j[h].context,b,c);break;default:if(!g)for(i=1,g=new Array(l-1);l>i;i++)g[i-1]=arguments[i];j[h].fn.apply(j[h].context,g)}return!0},d.prototype.on=function(a,b,d){return this._events||(this._events={}),this._events[a]||(this._events[a]=[]),this._events[a].push(new c(b,d||this)),this},d.prototype.once=function(a,b,d){return this._events||(this._events={}),this._events[a]||(this._events[a]=[]),this._events[a].push(new c(b,d||this,!0)),this},d.prototype.removeListener=function(a,b,c){if(!this._events||!this._events[a])return this;var d=this._events[a],e=[];if(b)for(var f=0,g=d.length;g>f;f++)d[f].fn!==b&&d[f].once!==c&&e.push(d[f]);return this._events[a]=e.length?e:null,this},d.prototype.removeAllListeners=function(a){return this._events?(a?this._events[a]=null:this._events={},this):this},d.prototype.off=d.prototype.removeListener,d.prototype.addListener=d.prototype.on,d.prototype.setMaxListeners=function(){return this},d.EventEmitter=d,d.EventEmitter2=d,d.EventEmitter3=d,"object"==typeof b&&b.exports&&(b.exports=d)},{}],10:[function(a,b){function c(a){this.index=0,this.dataBuffer=a,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}function d(){this.bufferBuilder=new g}function e(a){var b=a.charCodeAt(0);return 2047>=b?"00":65535>=b?"000":2097151>=b?"0000":67108863>=b?"00000":"000000"}function f(a){return a.length>600?new Blob([a]).size:a.replace(/[^\u0000-\u007F]/g,e).length}var g=a("./bufferbuilder").BufferBuilder,h=a("./bufferbuilder").binaryFeatures,i={unpack:function(a){var b=new c(a);return b.unpack()},pack:function(a){var b=new d;b.pack(a);var c=b.getBuffer();return c}};b.exports=i,c.prototype.unpack=function(){var a=this.unpack_uint8();if(128>a){var b=a;return b}if(32>(224^a)){var c=(224^a)-32;return c}var d;if((d=160^a)<=15)return this.unpack_raw(d);if((d=176^a)<=15)return this.unpack_string(d);if((d=144^a)<=15)return this.unpack_array(d);if((d=128^a)<=15)return this.unpack_map(d);switch(a){case 192:return null;case 193:return void 0;case 194:return!1;case 195:return!0;case 202:return this.unpack_float();case 203:return this.unpack_double();case 204:return this.unpack_uint8();case 205:return this.unpack_uint16();case 206:return this.unpack_uint32();case 207:return this.unpack_uint64();case 208:return this.unpack_int8();case 209:return this.unpack_int16();case 210:return this.unpack_int32();case 211:return this.unpack_int64();case 212:return void 0;case 213:return void 0;case 214:return void 0;case 215:return void 0;case 216:return d=this.unpack_uint16(),this.unpack_string(d);case 217:return d=this.unpack_uint32(),this.unpack_string(d);case 218:return d=this.unpack_uint16(),this.unpack_raw(d);case 219:return d=this.unpack_uint32(),this.unpack_raw(d);case 220:return d=this.unpack_uint16(),this.unpack_array(d);case 221:return d=this.unpack_uint32(),this.unpack_array(d);case 222:return d=this.unpack_uint16(),this.unpack_map(d);case 223:return d=this.unpack_uint32(),this.unpack_map(d)}},c.prototype.unpack_uint8=function(){var a=255&this.dataView[this.index];return this.index++,a},c.prototype.unpack_uint16=function(){var a=this.read(2),b=256*(255&a[0])+(255&a[1]);return this.index+=2,b},c.prototype.unpack_uint32=function(){var a=this.read(4),b=256*(256*(256*a[0]+a[1])+a[2])+a[3];return this.index+=4,b},c.prototype.unpack_uint64=function(){var a=this.read(8),b=256*(256*(256*(256*(256*(256*(256*a[0]+a[1])+a[2])+a[3])+a[4])+a[5])+a[6])+a[7];return this.index+=8,b},c.prototype.unpack_int8=function(){var a=this.unpack_uint8();return 128>a?a:a-256},c.prototype.unpack_int16=function(){var a=this.unpack_uint16();return 32768>a?a:a-65536},c.prototype.unpack_int32=function(){var a=this.unpack_uint32();return ae;)b=d[e],128>b?(f+=String.fromCharCode(b),e++):32>(192^b)?(c=(192^b)<<6|63&d[e+1],f+=String.fromCharCode(c),e+=2):(c=(15&b)<<12|(63&d[e+1])<<6|63&d[e+2],f+=String.fromCharCode(c),e+=3);return this.index+=a,f},c.prototype.unpack_array=function(a){for(var b=new Array(a),c=0;a>c;c++)b[c]=this.unpack();return b},c.prototype.unpack_map=function(a){for(var b={},c=0;a>c;c++){var d=this.unpack(),e=this.unpack();b[d]=e}return b},c.prototype.unpack_float=function(){var a=this.unpack_uint32(),b=a>>31,c=(a>>23&255)-127,d=8388607&a|8388608;return(0==b?1:-1)*d*Math.pow(2,c-23)},c.prototype.unpack_double=function(){var a=this.unpack_uint32(),b=this.unpack_uint32(),c=a>>31,d=(a>>20&2047)-1023,e=1048575&a|1048576,f=e*Math.pow(2,d-20)+b*Math.pow(2,d-52);return(0==c?1:-1)*f},c.prototype.read=function(a){var b=this.index;if(b+a<=this.length)return this.dataView.subarray(b,b+a);throw new Error("BinaryPackFailure: read index out of range")},d.prototype.getBuffer=function(){return this.bufferBuilder.getBuffer()},d.prototype.pack=function(a){var b=typeof a;if("string"==b)this.pack_string(a);else if("number"==b)Math.floor(a)===a?this.pack_integer(a):this.pack_double(a);else if("boolean"==b)a===!0?this.bufferBuilder.append(195):a===!1&&this.bufferBuilder.append(194);else if("undefined"==b)this.bufferBuilder.append(192);else{if("object"!=b)throw new Error('Type "'+b+'" not yet supported');if(null===a)this.bufferBuilder.append(192);else{var c=a.constructor;if(c==Array)this.pack_array(a);else if(c==Blob||c==File)this.pack_bin(a); +else if(c==ArrayBuffer)this.pack_bin(h.useArrayBufferView?new Uint8Array(a):a);else if("BYTES_PER_ELEMENT"in a)this.pack_bin(h.useArrayBufferView?new Uint8Array(a.buffer):a.buffer);else if(c==Object)this.pack_object(a);else if(c==Date)this.pack_string(a.toString());else{if("function"!=typeof a.toBinaryPack)throw new Error('Type "'+c.toString()+'" not yet supported');this.bufferBuilder.append(a.toBinaryPack())}}}this.bufferBuilder.flush()},d.prototype.pack_bin=function(a){var b=a.length||a.byteLength||a.size;if(15>=b)this.pack_uint8(160+b);else if(65535>=b)this.bufferBuilder.append(218),this.pack_uint16(b);else{if(!(4294967295>=b))throw new Error("Invalid length");this.bufferBuilder.append(219),this.pack_uint32(b)}this.bufferBuilder.append(a)},d.prototype.pack_string=function(a){var b=f(a);if(15>=b)this.pack_uint8(176+b);else if(65535>=b)this.bufferBuilder.append(216),this.pack_uint16(b);else{if(!(4294967295>=b))throw new Error("Invalid length");this.bufferBuilder.append(217),this.pack_uint32(b)}this.bufferBuilder.append(a)},d.prototype.pack_array=function(a){var b=a.length;if(15>=b)this.pack_uint8(144+b);else if(65535>=b)this.bufferBuilder.append(220),this.pack_uint16(b);else{if(!(4294967295>=b))throw new Error("Invalid length");this.bufferBuilder.append(221),this.pack_uint32(b)}for(var c=0;b>c;c++)this.pack(a[c])},d.prototype.pack_integer=function(a){if(a>=-32&&127>=a)this.bufferBuilder.append(255&a);else if(a>=0&&255>=a)this.bufferBuilder.append(204),this.pack_uint8(a);else if(a>=-128&&127>=a)this.bufferBuilder.append(208),this.pack_int8(a);else if(a>=0&&65535>=a)this.bufferBuilder.append(205),this.pack_uint16(a);else if(a>=-32768&&32767>=a)this.bufferBuilder.append(209),this.pack_int16(a);else if(a>=0&&4294967295>=a)this.bufferBuilder.append(206),this.pack_uint32(a);else if(a>=-2147483648&&2147483647>=a)this.bufferBuilder.append(210),this.pack_int32(a);else if(a>=-0x8000000000000000&&0x8000000000000000>=a)this.bufferBuilder.append(211),this.pack_int64(a);else{if(!(a>=0&&0x10000000000000000>=a))throw new Error("Invalid integer");this.bufferBuilder.append(207),this.pack_uint64(a)}},d.prototype.pack_double=function(a){var b=0;0>a&&(b=1,a=-a);var c=Math.floor(Math.log(a)/Math.LN2),d=a/Math.pow(2,c)-1,e=Math.floor(d*Math.pow(2,52)),f=Math.pow(2,32),g=b<<31|c+1023<<20|e/f&1048575,h=e%f;this.bufferBuilder.append(203),this.pack_int32(g),this.pack_int32(h)},d.prototype.pack_object=function(a){var b=Object.keys(a),c=b.length;if(15>=c)this.pack_uint8(128+c);else if(65535>=c)this.bufferBuilder.append(222),this.pack_uint16(c);else{if(!(4294967295>=c))throw new Error("Invalid length");this.bufferBuilder.append(223),this.pack_uint32(c)}for(var d in a)a.hasOwnProperty(d)&&(this.pack(d),this.pack(a[d]))},d.prototype.pack_uint8=function(a){this.bufferBuilder.append(a)},d.prototype.pack_uint16=function(a){this.bufferBuilder.append(a>>8),this.bufferBuilder.append(255&a)},d.prototype.pack_uint32=function(a){var b=4294967295&a;this.bufferBuilder.append((4278190080&b)>>>24),this.bufferBuilder.append((16711680&b)>>>16),this.bufferBuilder.append((65280&b)>>>8),this.bufferBuilder.append(255&b)},d.prototype.pack_uint64=function(a){var b=a/Math.pow(2,32),c=a%Math.pow(2,32);this.bufferBuilder.append((4278190080&b)>>>24),this.bufferBuilder.append((16711680&b)>>>16),this.bufferBuilder.append((65280&b)>>>8),this.bufferBuilder.append(255&b),this.bufferBuilder.append((4278190080&c)>>>24),this.bufferBuilder.append((16711680&c)>>>16),this.bufferBuilder.append((65280&c)>>>8),this.bufferBuilder.append(255&c)},d.prototype.pack_int8=function(a){this.bufferBuilder.append(255&a)},d.prototype.pack_int16=function(a){this.bufferBuilder.append((65280&a)>>8),this.bufferBuilder.append(255&a)},d.prototype.pack_int32=function(a){this.bufferBuilder.append(a>>>24&255),this.bufferBuilder.append((16711680&a)>>>16),this.bufferBuilder.append((65280&a)>>>8),this.bufferBuilder.append(255&a)},d.prototype.pack_int64=function(a){var b=Math.floor(a/Math.pow(2,32)),c=a%Math.pow(2,32);this.bufferBuilder.append((4278190080&b)>>>24),this.bufferBuilder.append((16711680&b)>>>16),this.bufferBuilder.append((65280&b)>>>8),this.bufferBuilder.append(255&b),this.bufferBuilder.append((4278190080&c)>>>24),this.bufferBuilder.append((16711680&c)>>>16),this.bufferBuilder.append((65280&c)>>>8),this.bufferBuilder.append(255&c)}},{"./bufferbuilder":11}],11:[function(a,b){function c(){this._pieces=[],this._parts=[]}var d={};d.useBlobBuilder=function(){try{return new Blob([]),!1}catch(a){return!0}}(),d.useArrayBufferView=!d.useBlobBuilder&&function(){try{return 0===new Blob([new Uint8Array([])]).size}catch(a){return!0}}(),b.exports.binaryFeatures=d;var e=b.exports.BlobBuilder;"undefined"!=typeof window&&(e=b.exports.BlobBuilder=window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder||window.BlobBuilder),c.prototype.append=function(a){"number"==typeof a?this._pieces.push(a):(this.flush(),this._parts.push(a))},c.prototype.flush=function(){if(this._pieces.length>0){var a=new Uint8Array(this._pieces);d.useArrayBufferView||(a=a.buffer),this._parts.push(a),this._pieces=[]}},c.prototype.getBuffer=function(){if(this.flush(),d.useBlobBuilder){for(var a=new e,b=0,c=this._parts.length;c>b;b++)a.append(this._parts[b]);return a.getBlob()}return new Blob(this._parts)},b.exports.BufferBuilder=c},{}],12:[function(a,b){function c(a,b){return this instanceof c?(this._dc=a,d.debug=b,this._outgoing={},this._incoming={},this._received={},this._window=1e3,this._mtu=500,this._interval=0,this._count=0,this._queue=[],void this._setupDC()):new c(a)}var d=a("./util");c.prototype.send=function(a){var b=d.pack(a);return b.sizec;c+=1)a._intervalSend(b[c]);else a._intervalSend(b)},this._interval)},c.prototype._intervalSend=function(a){var b=this;a=d.pack(a),d.blobToBinaryString(a,function(a){b._dc.send(a)}),0===b._queue.length&&(clearTimeout(b._timeout),b._timeout=null)},c.prototype._processAcks=function(){for(var a in this._outgoing)this._outgoing.hasOwnProperty(a)&&this._sendWindowedChunks(a)},c.prototype._handleSend=function(a){for(var b=!0,c=0,d=this._queue.length;d>c;c+=1){var e=this._queue[c];e===a?b=!1:e._multiple&&-1!==e.indexOf(a)&&(b=!1)}b&&(this._queue.push(a),this._timeout||this._setupInterval())},c.prototype._setupDC=function(){var a=this;this._dc.onmessage=function(b){var c=b.data,e=c.constructor;if(e===String){var f=d.binaryStringToArrayBuffer(c);c=d.unpack(f),a._handleMessage(c)}}},c.prototype._handleMessage=function(a){var b,c=a[1],e=this._incoming[c],f=this._outgoing[c];switch(a[0]){case"no":var g=c;g&&this.onmessage(d.unpack(g));break;case"end":if(b=e,this._received[c]=a[2],!b)break;this._ack(c);break;case"ack":if(b=f){var h=a[2];b.ack=Math.max(h,b.ack),b.ack>=b.chunks.length?(d.log("Time: ",new Date-b.timer),delete this._outgoing[c]):this._processAcks()}break;case"chunk":if(b=e,!b){var i=this._received[c];if(i===!0)break;b={ack:["ack",c,0],chunks:[]},this._incoming[c]=b}var j=a[2],k=a[3];b.chunks[j]=new Uint8Array(k),j===b.ack[2]&&this._calculateNextAck(c),this._ack(c);break;default:this._handleSend(a)}},c.prototype._chunk=function(a){for(var b=[],c=a.size,e=0;c>e;){var f=Math.min(c,e+this._mtu),g=a.slice(e,f),h={payload:g};b.push(h),e=f}return d.log("Created",b.length,"chunks."),b},c.prototype._ack=function(a){var b=this._incoming[a].ack;this._received[a]===b[2]&&(this._complete(a),this._received[a]=!0),this._handleSend(b)},c.prototype._calculateNextAck=function(a){for(var b=this._incoming[a],c=b.chunks,d=0,e=c.length;e>d;d+=1)if(void 0===c[d])return void(b.ack[2]=d);b.ack[2]=c.length},c.prototype._sendWindowedChunks=function(a){d.log("sendWindowedChunks for: ",a);for(var b=this._outgoing[a],c=b.chunks,e=[],f=Math.min(b.ack+this._window,c.length),g=b.ack;f>g;g+=1)c[g].sent&&g!==b.ack||(c[g].sent=!0,e.push(["chunk",a,g,c[g].payload]));b.ack+this._window>=c.length&&e.push(["end",a,c.length]),e._multiple=!0,this._handleSend(e)},c.prototype._complete=function(a){d.log("Completed called for",a);var b=this,c=this._incoming[a].chunks,e=new Blob(c);d.blobToArrayBuffer(e,function(a){b.onmessage(d.unpack(a))}),delete this._incoming[a]},c.higherBandwidthSDP=function(a){var b=navigator.appVersion.match(/Chrome\/(.*?) /);if(b&&(b=parseInt(b[1].split(".").shift()),31>b)){var c=a.split("b=AS:30"),d="b=AS:102400";if(c.length>1)return c[0]+d+c[1]}return a},c.prototype.onmessage=function(){},b.exports.Reliable=c},{"./util":13}],13:[function(a,b){var c=a("js-binarypack"),d={debug:!1,inherits:function(a,b){a.super_=b,a.prototype=Object.create(b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}})},extend:function(a,b){for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a},pack:c.pack,unpack:c.unpack,log:function(){if(d.debug){for(var a=[],b=0;b type pairs - class2type = {}, +var class2type = {}; - // List of deleted data cache ids, so we can reuse them - core_deletedIds = [], +var toString = class2type.toString; - core_version = "1.10.2", +var hasOwn = class2type.hasOwnProperty; - // Save a reference to some core methods - core_concat = core_deletedIds.concat, - core_push = core_deletedIds.push, - core_slice = core_deletedIds.slice, - core_indexOf = core_deletedIds.indexOf, - core_toString = class2type.toString, - core_hasOwn = class2type.hasOwnProperty, - core_trim = core_version.trim, +var support = {}; + + + +var + version = "2.2.2", // Define a local copy of jQuery jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init( selector, context, rootjQuery ); + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); }, - // Used for matching numbers - core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, - - // Used for splitting on whitespace - core_rnotwhite = /\S+/g, - - // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) + // Support: Android<4.1 + // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, - // A simple way to check for HTML strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - // Strict HTML recognition (#11290: must start with <) - rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, - - // Match a standalone tag - rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, - - // JSON RegExp - rvalidchars = /^[\],:{}\s]*$/, - rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, - rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, - rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, - // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, @@ -93,134 +86,14 @@ var // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); - }, - - // The ready event handler - completed = function( event ) { - - // readyState === "complete" is good enough for us to call the dom ready in oldIE - if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { - detach(); - jQuery.ready(); - } - }, - // Clean-up method for dom ready events - detach = function() { - if ( document.addEventListener ) { - document.removeEventListener( "DOMContentLoaded", completed, false ); - window.removeEventListener( "load", completed, false ); - - } else { - document.detachEvent( "onreadystatechange", completed ); - window.detachEvent( "onload", completed ); - } }; jQuery.fn = jQuery.prototype = { + // The current version of jQuery being used - jquery: core_version, + jquery: version, constructor: jQuery, - init: function( selector, context, rootjQuery ) { - var match, elem; - - // HANDLE: $(""), $(null), $(undefined), $(false) - if ( !selector ) { - return this; - } - - // Handle HTML strings - if ( typeof selector === "string" ) { - if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = rquickExpr.exec( selector ); - } - - // Match html or make sure no context is specified for #id - if ( match && (match[1] || !context) ) { - - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - context = context instanceof jQuery ? context[0] : context; - - // scripts is true for back-compat - jQuery.merge( this, jQuery.parseHTML( - match[1], - context && context.nodeType ? context.ownerDocument || context : document, - true - ) ); - - // HANDLE: $(html, props) - if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { - for ( match in context ) { - // Properties of context are called as methods if possible - if ( jQuery.isFunction( this[ match ] ) ) { - this[ match ]( context[ match ] ); - - // ...and otherwise set as attributes - } else { - this.attr( match, context[ match ] ); - } - } - } - - return this; - - // HANDLE: $(#id) - } else { - elem = document.getElementById( match[2] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id !== match[2] ) { - return rootjQuery.find( selector ); - } - - // Otherwise, we inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || rootjQuery ).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(DOMElement) - } else if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return rootjQuery.ready( selector ); - } - - if ( selector.selector !== undefined ) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray( selector, this ); - }, // Start with an empty selector selector: "", @@ -229,19 +102,19 @@ jQuery.fn = jQuery.prototype = { length: 0, toArray: function() { - return core_slice.call( this ); + return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { - return num == null ? + return num != null ? - // Return a 'clean' array - this.toArray() : + // Return just the one element from the set + ( num < 0 ? this[ num + this.length ] : this[ num ] ) : - // Return just the object - ( num < 0 ? this[ this.length + num ] : this[ num ] ); + // Return all the elements in a clean array + slice.call( this ); }, // Take an array of elements and push it onto the stack @@ -260,21 +133,18 @@ jQuery.fn = jQuery.prototype = { }, // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - return jQuery.each( this, callback, args ); + each: function( callback ) { + return jQuery.each( this, callback ); }, - ready: function( fn ) { - // Add the callback - jQuery.ready.promise().done( fn ); - - return this; + map: function( callback ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); }, slice: function() { - return this.pushStack( core_slice.apply( this, arguments ) ); + return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { @@ -288,32 +158,23 @@ jQuery.fn = jQuery.prototype = { eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); - return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map(this, function( elem, i ) { - return callback.call( elem, i, elem ); - })); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { - return this.prevObject || this.constructor(null); + return this.prevObject || this.constructor(); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. - push: core_push, - sort: [].sort, - splice: [].splice + push: push, + sort: arr.sort, + splice: arr.splice }; -// Give the init function the jQuery prototype for later instantiation -jQuery.fn.init.prototype = jQuery.fn; - jQuery.extend = jQuery.fn.extend = function() { - var src, copyIsArray, copy, name, options, clone, - target = arguments[0] || {}, + var options, name, src, copy, copyIsArray, clone, + target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; @@ -321,25 +182,28 @@ jQuery.extend = jQuery.fn.extend = function() { // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; } // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { target = {}; } - // extend jQuery itself if only one argument is passed - if ( length === i ) { + // Extend jQuery itself if only one argument is passed + if ( i === length ) { target = this; - --i; + i--; } for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { + if ( ( options = arguments[ i ] ) != null ) { + // Extend the base object for ( name in options ) { src = target[ name ]; @@ -351,13 +215,15 @@ jQuery.extend = jQuery.fn.extend = function() { } // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = jQuery.isArray( copy ) ) ) ) { + if ( copyIsArray ) { copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; + clone = src && jQuery.isArray( src ) ? src : []; } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; + clone = src && jQuery.isPlainObject( src ) ? src : {}; } // Never move original objects, clone them @@ -375,133 +241,63 @@ jQuery.extend = jQuery.fn.extend = function() { return target; }; -jQuery.extend({ - // Unique for each copy of jQuery on the page - // Non-digits removed to match rinlinejQuery - expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), - - noConflict: function( deep ) { - if ( window.$ === jQuery ) { - window.$ = _$; - } - - if ( deep && window.jQuery === jQuery ) { - window.jQuery = _jQuery; - } - - return jQuery; - }, +jQuery.extend( { - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, + // Assume jQuery is ready without the ready module + isReady: true, - // Hold (or release) the ready event - holdReady: function( hold ) { - if ( hold ) { - jQuery.readyWait++; - } else { - jQuery.ready( true ); - } + error: function( msg ) { + throw new Error( msg ); }, - // Handle when the DOM is ready - ready: function( wait ) { - - // Abort if there are pending holds or we're already ready - if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { - return; - } - - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( !document.body ) { - return setTimeout( jQuery.ready ); - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.trigger ) { - jQuery( document ).trigger("ready").off("ready"); - } - }, + noop: function() {}, - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { - return jQuery.type(obj) === "function"; + return jQuery.type( obj ) === "function"; }, - isArray: Array.isArray || function( obj ) { - return jQuery.type(obj) === "array"; - }, + isArray: Array.isArray, isWindow: function( obj ) { - /* jshint eqeqeq: false */ - return obj != null && obj == obj.window; + return obj != null && obj === obj.window; }, isNumeric: function( obj ) { - return !isNaN( parseFloat(obj) ) && isFinite( obj ); - }, - type: function( obj ) { - if ( obj == null ) { - return String( obj ); - } - return typeof obj === "object" || typeof obj === "function" ? - class2type[ core_toString.call(obj) ] || "object" : - typeof obj; + // parseFloat NaNs numeric-cast false positives (null|true|false|"") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + // adding 1 corrects loss of precision from parseFloat (#15100) + var realStringObj = obj && obj.toString(); + return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0; }, isPlainObject: function( obj ) { var key; - // Must be an Object. - // Because of IE, we also have to check the presence of the constructor property. - // Make sure that DOM nodes and window objects don't pass through, as well - if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + // Not plain objects: + // - Any object or value whose internal [[Class]] property is not "[object Object]" + // - DOM nodes + // - window + if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } - try { - // Not own constructor property must be Object - if ( obj.constructor && - !core_hasOwn.call(obj, "constructor") && - !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { - return false; - } - } catch ( e ) { - // IE8,9 Will throw exceptions on certain host objects #9897 + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call( obj, "constructor" ) && + !hasOwn.call( obj.constructor.prototype || {}, "isPrototypeOf" ) ) { return false; } - // Support: IE<9 - // Handle iteration over inherited properties before own properties. - if ( jQuery.support.ownLast ) { - for ( key in obj ) { - return core_hasOwn.call( obj, key ); - } - } - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. + // if last one is own, then all properties are own for ( key in obj ) {} - return key === undefined || core_hasOwn.call( obj, key ); + return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { @@ -512,109 +308,45 @@ jQuery.extend({ return true; }, - error: function( msg ) { - throw new Error( msg ); - }, - - // data: string of html - // context (optional): If specified, the fragment will be created in this context, defaults to document - // keepScripts (optional): If true, will include scripts passed in the html string - parseHTML: function( data, context, keepScripts ) { - if ( !data || typeof data !== "string" ) { - return null; - } - if ( typeof context === "boolean" ) { - keepScripts = context; - context = false; - } - context = context || document; - - var parsed = rsingleTag.exec( data ), - scripts = !keepScripts && []; - - // Single tag - if ( parsed ) { - return [ context.createElement( parsed[1] ) ]; + type: function( obj ) { + if ( obj == null ) { + return obj + ""; } - parsed = jQuery.buildFragment( [ data ], context, scripts ); - if ( scripts ) { - jQuery( scripts ).remove(); - } - return jQuery.merge( [], parsed.childNodes ); + // Support: Android<4.0, iOS<6 (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; }, - parseJSON: function( data ) { - // Attempt to parse using the native JSON parser first - if ( window.JSON && window.JSON.parse ) { - return window.JSON.parse( data ); - } - - if ( data === null ) { - return data; - } - - if ( typeof data === "string" ) { + // Evaluates a script in a global context + globalEval: function( code ) { + var script, + indirect = eval; - // Make sure leading/trailing whitespace is removed (IE can't handle it) - data = jQuery.trim( data ); + code = jQuery.trim( code ); - if ( data ) { - // Make sure the incoming data is actual JSON - // Logic borrowed from http://json.org/json2.js - if ( rvalidchars.test( data.replace( rvalidescape, "@" ) - .replace( rvalidtokens, "]" ) - .replace( rvalidbraces, "")) ) { + if ( code ) { - return ( new Function( "return " + data ) )(); - } - } - } + // If the code includes a valid, prologue position + // strict mode pragma, execute code by injecting a + // script tag into the document. + if ( code.indexOf( "use strict" ) === 1 ) { + script = document.createElement( "script" ); + script.text = code; + document.head.appendChild( script ).parentNode.removeChild( script ); + } else { - jQuery.error( "Invalid JSON: " + data ); - }, + // Otherwise, avoid the DOM node creation, insertion + // and removal by using an indirect global eval - // Cross-browser xml parsing - parseXML: function( data ) { - var xml, tmp; - if ( !data || typeof data !== "string" ) { - return null; - } - try { - if ( window.DOMParser ) { // Standard - tmp = new DOMParser(); - xml = tmp.parseFromString( data , "text/xml" ); - } else { // IE - xml = new ActiveXObject( "Microsoft.XMLDOM" ); - xml.async = "false"; - xml.loadXML( data ); + indirect( code ); } - } catch( e ) { - xml = undefined; - } - if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { - jQuery.error( "Invalid XML: " + data ); - } - return xml; - }, - - noop: function() {}, - - // Evaluates a script in a global context - // Workarounds based on findings by Jim Driscoll - // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context - globalEval: function( data ) { - if ( data && jQuery.trim( data ) ) { - // We use execScript on Internet Explorer - // We use an anonymous function so that context is window - // rather than jQuery in Firefox - ( window.execScript || function( data ) { - window[ "eval" ].call( window, data ); - } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules + // Support: IE9-11+ // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); @@ -624,49 +356,20 @@ jQuery.extend({ return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, - // args is for internal usage only - each: function( obj, callback, args ) { - var value, - i = 0, - length = obj.length, - isArray = isArraylike( obj ); - - if ( args ) { - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback.apply( obj[ i ], args ); - - if ( value === false ) { - break; - } - } - } else { - for ( i in obj ) { - value = callback.apply( obj[ i ], args ); + each: function( obj, callback ) { + var length, i = 0; - if ( value === false ) { - break; - } + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; } } - - // A special, fast, case for the most common use of each } else { - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback.call( obj[ i ], i, obj[ i ] ); - - if ( value === false ) { - break; - } - } - } else { - for ( i in obj ) { - value = callback.call( obj[ i ], i, obj[ i ] ); - - if ( value === false ) { - break; - } + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; } } } @@ -674,33 +377,25 @@ jQuery.extend({ return obj; }, - // Use native String.trim function wherever possible - trim: core_trim && !core_trim.call("\uFEFF\xA0") ? - function( text ) { - return text == null ? - "" : - core_trim.call( text ); - } : - - // Otherwise use our own trimming functionality - function( text ) { - return text == null ? - "" : - ( text + "" ).replace( rtrim, "" ); - }, + // Support: Android<4.1 + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { - if ( isArraylike( Object(arr) ) ) { + if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { - core_push.call( ret, arr ); + push.call( ret, arr ); } } @@ -708,40 +403,16 @@ jQuery.extend({ }, inArray: function( elem, arr, i ) { - var len; - - if ( arr ) { - if ( core_indexOf ) { - return core_indexOf.call( arr, elem, i ); - } - - len = arr.length; - i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; - - for ( ; i < len; i++ ) { - // Skip accessing in sparse arrays - if ( i in arr && arr[ i ] === elem ) { - return i; - } - } - } - - return -1; + return arr == null ? -1 : indexOf.call( arr, elem, i ); }, merge: function( first, second ) { - var l = second.length, - i = first.length, - j = 0; + var len = +second.length, + j = 0, + i = first.length; - if ( typeof l === "number" ) { - for ( ; j < l; j++ ) { - first[ i++ ] = second[ j ]; - } - } else { - while ( second[j] !== undefined ) { - first[ i++ ] = second[ j++ ]; - } + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; } first.length = i; @@ -749,40 +420,39 @@ jQuery.extend({ return first; }, - grep: function( elems, callback, inv ) { - var retVal, - ret = [], + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], i = 0, - length = elems.length; - inv = !!inv; + length = elems.length, + callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { - retVal = !!callback( elems[ i ], i ); - if ( inv !== retVal ) { - ret.push( elems[ i ] ); + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); } } - return ret; + return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { - var value, + var length, value, i = 0, - length = elems.length, - isArray = isArraylike( elems ), ret = []; - // Go through the array, translating each of the items to their - if ( isArray ) { + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { - ret[ ret.length ] = value; + ret.push( value ); } } @@ -792,13 +462,13 @@ jQuery.extend({ value = callback( elems[ i ], i, arg ); if ( value != null ) { - ret[ ret.length ] = value; + ret.push( value ); } } } // Flatten any nested arrays - return core_concat.apply( [], ret ); + return concat.apply( [], ret ); }, // A global GUID counter for objects @@ -807,7 +477,7 @@ jQuery.extend({ // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { - var args, proxy, tmp; + var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; @@ -822,9 +492,9 @@ jQuery.extend({ } // Simulated bind - args = core_slice.call( arguments, 2 ); + args = slice.call( arguments, 2 ); proxy = function() { - return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed @@ -833,193 +503,69 @@ jQuery.extend({ return proxy; }, - // Multifunctional method to get and set values of a collection - // The value/s can optionally be executed if it's a function - access: function( elems, fn, key, value, chainable, emptyGet, raw ) { - var i = 0, - length = elems.length, - bulk = key == null; - - // Sets many values - if ( jQuery.type( key ) === "object" ) { - chainable = true; - for ( i in key ) { - jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); - } - - // Sets one value - } else if ( value !== undefined ) { - chainable = true; - - if ( !jQuery.isFunction( value ) ) { - raw = true; - } - - if ( bulk ) { - // Bulk operations run against the entire set - if ( raw ) { - fn.call( elems, value ); - fn = null; - - // ...except when executing function values - } else { - bulk = fn; - fn = function( elem, key, value ) { - return bulk.call( jQuery( elem ), value ); - }; - } - } - - if ( fn ) { - for ( ; i < length; i++ ) { - fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); - } - } - } - - return chainable ? - elems : - - // Gets - bulk ? - fn.call( elems ) : - length ? fn( elems[0], key ) : emptyGet; - }, - - now: function() { - return ( new Date() ).getTime(); - }, - - // A method for quickly swapping in/out CSS properties to get correct calculations. - // Note: this method belongs to the css module but it's needed here for the support module. - // If support gets modularized, this method should be moved back to the css module. - swap: function( elem, options, callback, args ) { - var ret, name, - old = {}; - - // Remember the old values, and insert the new ones - for ( name in options ) { - old[ name ] = elem.style[ name ]; - elem.style[ name ] = options[ name ]; - } - - ret = callback.apply( elem, args || [] ); - - // Revert the old values - for ( name in options ) { - elem.style[ name ] = old[ name ]; - } - - return ret; - } -}); - -jQuery.ready.promise = function( obj ) { - if ( !readyList ) { - - readyList = jQuery.Deferred(); - - // Catch cases where $(document).ready() is called after the browser event has already occurred. - // we once tried to use readyState "interactive" here, but it caused issues like the one - // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 - if ( document.readyState === "complete" ) { - // Handle it asynchronously to allow scripts the opportunity to delay ready - setTimeout( jQuery.ready ); - - // Standards-based browsers support DOMContentLoaded - } else if ( document.addEventListener ) { - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", completed, false ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", completed, false ); - - // If IE event model is used - } else { - // Ensure firing before onload, maybe late but safe also for iframes - document.attachEvent( "onreadystatechange", completed ); - - // A fallback to window.onload, that will always work - window.attachEvent( "onload", completed ); - - // If IE and not a frame - // continually check to see if the document is ready - var top = false; - - try { - top = window.frameElement == null && document.documentElement; - } catch(e) {} - - if ( top && top.doScroll ) { - (function doScrollCheck() { - if ( !jQuery.isReady ) { - - try { - // Use the trick by Diego Perini - // http://javascript.nwbox.com/IEContentLoaded/ - top.doScroll("left"); - } catch(e) { - return setTimeout( doScrollCheck, 50 ); - } + now: Date.now, - // detach all dom ready events - detach(); + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); - // and execute any waiting functions - jQuery.ready(); - } - })(); - } - } - } - return readyList.promise( obj ); -}; +// JSHint would error on this code due to the Symbol not being defined in ES5. +// Defining this global in .jshintrc would create a danger of using the global +// unguarded in another place, it seems safer to just disable JSHint for these +// three lines. +/* jshint ignore: start */ +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} +/* jshint ignore: end */ // Populate the class2type map -jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), +function( i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); -}); +} ); -function isArraylike( obj ) { - var length = obj.length, +function isArrayLike( obj ) { + + // Support: iOS 8.2 (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, type = jQuery.type( obj ); - if ( jQuery.isWindow( obj ) ) { + if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } - if ( obj.nodeType === 1 && length ) { - return true; - } - - return type === "array" || type !== "function" && - ( length === 0 || - typeof length === "number" && length > 0 && ( length - 1 ) in obj ); + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; } - -// All jQuery objects should point back to these -rootjQuery = jQuery(document); +var Sizzle = /*! - * Sizzle CSS Selector Engine v1.10.2 + * Sizzle CSS Selector Engine v2.2.1 * http://sizzlejs.com/ * - * Copyright 2013 jQuery Foundation, Inc. and other contributors + * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * - * Date: 2013-07-03 + * Date: 2015-10-17 */ -(function( window, undefined ) { +(function( window ) { var i, support, - cachedruns, Expr, getText, isXML, + tokenize, compile, + select, outermostContext, sortInput, + hasDuplicate, // Local document vars setDocument, @@ -1032,24 +578,21 @@ var i, contains, // Instance-specific data - expando = "sizzle" + -(new Date()), + expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), - hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; - return 0; } return 0; }, // General-purpose constants - strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods @@ -1059,12 +602,13 @@ var i, push_native = arr.push, push = arr.push, slice = arr.slice, - // Use a stripped-down indexOf if we can't use a native one - indexOf = arr.indexOf || function( elem ) { + // Use a stripped-down indexOf as it's faster than native + // http://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { var i = 0, - len = this.length; + len = list.length; for ( ; i < len; i++ ) { - if ( this[i] === elem ) { + if ( list[i] === elem ) { return i; } } @@ -1075,44 +619,46 @@ var i, // Regular expressions - // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", - // http://www.w3.org/TR/css3-syntax/#characters - characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", - - // Loosely modeled on CSS identifier characters - // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors - // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier - identifier = characterEncoding.replace( "w", "w#" ), - - // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors - attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + - "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", - - // Prefer arguments quoted, - // then not containing pseudos/brackets, - // then attribute selectors/non-parenthetical expressions, - // then anything else - // These preferences are here to reduce the number of selectors - // needing tokenize in the PSEUDO preFilter - pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", + + // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + identifier + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), - rsibling = new RegExp( whitespace + "*[+~]" ), - rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { - "ID": new RegExp( "^#(" + characterEncoding + ")" ), - "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), - "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ID": new RegExp( "^#(" + identifier + ")" ), + "CLASS": new RegExp( "^\\.(" + identifier + ")" ), + "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + @@ -1125,14 +671,15 @@ var i, whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, - rinputs = /^(?:input|select|textarea|button)$/i, - rheader = /^h\d$/i, - + rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters @@ -1140,15 +687,23 @@ var i, funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint - // Support: Firefox + // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : - // BMP codepoint high < 0 ? + // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); }; // Optimize for push.apply( _, NodeList ) @@ -1181,104 +736,129 @@ try { } function Sizzle( selector, context, results, seed ) { - var match, elem, m, nodeType, - // QSA vars - i, groups, old, nid, newContext, newSelector; + var m, i, elem, nid, nidselect, match, groups, newSelector, + newContext = context && context.ownerDocument, - if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { - setDocument( context ); - } + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; - context = context || document; results = results || []; - if ( !selector || typeof selector !== "string" ) { + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + return results; } - if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { - return []; - } + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { - if ( documentIsHTML && !seed ) { + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + context = context || document; - // Shortcuts - if ( (match = rquickExpr.exec( selector )) ) { - // Speed-up: Sizzle("#ID") - if ( (m = match[1]) ) { - if ( nodeType === 9 ) { - elem = context.getElementById( m ); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE, Opera, and Webkit return items - // by name instead of ID - if ( elem.id === m ) { - results.push( elem ); + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { + + // ID selector + if ( (m = match[1]) ) { + + // Document context + if ( nodeType === 9 ) { + if ( (elem = context.getElementById( m )) ) { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { return results; } + + // Element context } else { - return results; - } - } else { - // Context is not a document - if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && - contains( context, elem ) && elem.id === m ) { - results.push( elem ); - return results; + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( newContext && (elem = newContext.getElementById( m )) && + contains( context, elem ) && + elem.id === m ) { + + results.push( elem ); + return results; + } } - } - // Speed-up: Sizzle("TAG") - } else if ( match[2] ) { - push.apply( results, context.getElementsByTagName( selector ) ); - return results; + // Type selector + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; - // Speed-up: Sizzle(".CLASS") - } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { - push.apply( results, context.getElementsByClassName( m ) ); - return results; + // Class selector + } else if ( (m = match[3]) && support.getElementsByClassName && + context.getElementsByClassName ) { + + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } } - } - // QSA path - if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { - nid = old = expando; - newContext = context; - newSelector = nodeType === 9 && selector; + // Take advantage of querySelectorAll + if ( support.qsa && + !compilerCache[ selector + " " ] && + (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - groups = tokenize( selector ); + if ( nodeType !== 1 ) { + newContext = context; + newSelector = selector; - if ( (old = context.getAttribute("id")) ) { - nid = old.replace( rescape, "\\$&" ); - } else { - context.setAttribute( "id", nid ); - } - nid = "[id='" + nid + "'] "; + // qSA looks outside Element context, which is not what we want + // Thanks to Andrew Dupont for this workaround technique + // Support: IE <=8 + // Exclude object elements + } else if ( context.nodeName.toLowerCase() !== "object" ) { - i = groups.length; - while ( i-- ) { - groups[i] = nid + toSelector( groups[i] ); + // Capture the context ID, setting it first if necessary + if ( (nid = context.getAttribute( "id" )) ) { + nid = nid.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", (nid = expando) ); + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']"; + while ( i-- ) { + groups[i] = nidselect + " " + toSelector( groups[i] ); + } + newSelector = groups.join( "," ); + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; } - newContext = rsibling.test( selector ) && context.parentNode || context; - newSelector = groups.join(","); - } - if ( newSelector ) { - try { - push.apply( results, - newContext.querySelectorAll( newSelector ) - ); - return results; - } catch(qsaError) { - } finally { - if ( !old ) { - context.removeAttribute("id"); + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); + } } } } @@ -1291,7 +871,7 @@ function Sizzle( selector, context, results, seed ) { /** * Create key-value caches of limited size - * @returns {Function(string, Object)} Returns the Object data after storing it on itself with + * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ @@ -1300,11 +880,11 @@ function createCache() { function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) - if ( keys.push( key += " " ) > Expr.cacheLength ) { + if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } - return (cache[ key ] = value); + return (cache[ key + " " ] = value); } return cache; } @@ -1346,7 +926,7 @@ function assert( fn ) { */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), - i = attrs.length; + i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; @@ -1427,8 +1007,21 @@ function createPositionalPseudo( fn ) { } /** - * Detect xml + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== "undefined" && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist @@ -1437,45 +1030,44 @@ isXML = Sizzle.isXML = function( elem ) { return documentElement ? documentElement.nodeName !== "HTML" : false; }; -// Expose support vars for convenience -support = Sizzle.support = {}; - /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { - var doc = node ? node.ownerDocument || node : preferredDoc, - parent = doc.defaultView; + var hasCompare, parent, + doc = node ? node.ownerDocument || node : preferredDoc; - // If no document and documentElement is available, return + // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } - // Set our document + // Update global variables document = doc; - docElem = doc.documentElement; - - // Support tests - documentIsHTML = !isXML( doc ); - - // Support: IE>8 - // If iframe document is assigned to "document" variable and if iframe has been reloaded, - // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 - // IE6-8 do not support the defaultView property so parent will be undefined - if ( parent && parent.attachEvent && parent !== parent.top ) { - parent.attachEvent( "onbeforeunload", function() { - setDocument(); - }); + docElem = document.documentElement; + documentIsHTML = !isXML( document ); + + // Support: IE 9-11, Edge + // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) + if ( (parent = document.defaultView) && parent.top !== parent ) { + // Support: IE 11 + if ( parent.addEventListener ) { + parent.addEventListener( "unload", unloadHandler, false ); + + // Support: IE 9 - 10 only + } else if ( parent.attachEvent ) { + parent.attachEvent( "onunload", unloadHandler ); + } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 - // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) + // Verify that getAttribute really returns attributes and not properties + // (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); @@ -1486,21 +1078,12 @@ setDocument = Sizzle.setDocument = function( node ) { // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { - div.appendChild( doc.createComment("") ); + div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }); - // Check if getElementsByClassName can be trusted - support.getElementsByClassName = assert(function( div ) { - div.innerHTML = "
"; - - // Support: Safari<4 - // Catch class over-caching - div.firstChild.className = "i"; - // Support: Opera<10 - // Catch gEBCN failure to find non-leading classes - return div.getElementsByClassName("i").length === 2; - }); + // Support: IE<9 + support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name @@ -1508,17 +1091,15 @@ setDocument = Sizzle.setDocument = function( node ) { // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; - return !doc.getElementsByName || !doc.getElementsByName( expando ).length; + return !document.getElementsByName || !document.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { - if ( typeof context.getElementById !== strundefined && documentIsHTML ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var m = context.getElementById( id ); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [m] : []; + return m ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { @@ -1535,7 +1116,8 @@ setDocument = Sizzle.setDocument = function( node ) { Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { - var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); + var node = typeof elem.getAttributeNode !== "undefined" && + elem.getAttributeNode("id"); return node && node.value === attrId; }; }; @@ -1544,14 +1126,20 @@ setDocument = Sizzle.setDocument = function( node ) { // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { - if ( typeof context.getElementsByTagName !== strundefined ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); + + // DocumentFragment nodes don't have gEBTN + } else if ( support.qsa ) { + return context.querySelectorAll( tag ); } } : + function( tag, context ) { var elem, tmp = [], i = 0, + // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments @@ -1569,7 +1157,7 @@ setDocument = Sizzle.setDocument = function( node ) { // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { - if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { + if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; @@ -1589,7 +1177,7 @@ setDocument = Sizzle.setDocument = function( node ) { // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; - if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { + if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { @@ -1598,7 +1186,17 @@ setDocument = Sizzle.setDocument = function( node ) { // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 - div.innerHTML = ""; + docElem.appendChild( div ).innerHTML = "" + + ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( div.querySelectorAll("[msallowcapture^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } // Support: IE8 // Boolean attributes and "value" are not treated correctly @@ -1606,27 +1204,37 @@ setDocument = Sizzle.setDocument = function( node ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } + // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ + if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push("~="); + } + // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } + + // Support: Safari 8+, iOS 8+ + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibing-combinator selector` fails + if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push(".#.+[+~]"); + } }); assert(function( div ) { - - // Support: Opera 10-12/IE8 - // ^= $= *= and empty values - // Should not select anything // Support: Windows 8 Native Apps - // The type attribute is restricted during .innerHTML assignment - var input = doc.createElement("input"); + // The type and name attributes are restricted during .innerHTML assignment + var input = document.createElement("input"); input.setAttribute( "type", "hidden" ); - div.appendChild( input ).setAttribute( "t", "" ); + div.appendChild( input ).setAttribute( "name", "D" ); - if ( div.querySelectorAll("[t^='']").length ) { - rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( div.querySelectorAll("[name=d]").length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) @@ -1641,7 +1249,8 @@ setDocument = Sizzle.setDocument = function( node ) { }); } - if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || + if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || + docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { @@ -1663,11 +1272,12 @@ setDocument = Sizzle.setDocument = function( node ) { /* Contains ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another - // Purposefully does not implement inclusive descendent + // Purposefully self-exclusive // As in, an element does not contain itself - contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? + contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; @@ -1692,7 +1302,7 @@ setDocument = Sizzle.setDocument = function( node ) { ---------------------------------------------------------------------- */ // Document order sorting - sortOrder = docElem.compareDocumentPosition ? + sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal @@ -1701,34 +1311,46 @@ setDocument = Sizzle.setDocument = function( node ) { return 0; } - var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); - + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { - // Disconnected nodes - if ( compare & 1 || - (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + return compare; + } - // Choose the first element that is related to our preferred document - if ( a === doc || contains(preferredDoc, a) ) { - return -1; - } - if ( b === doc || contains(preferredDoc, b) ) { - return 1; - } + // Calculate position if both inputs belong to the same document + compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : - // Maintain original order - return sortInput ? - ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : - 0; + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { + return -1; + } + if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { + return 1; } - return compare & 4 ? -1 : 1; + // Maintain original order + return sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; } - // Not directly comparable, sort on existence of method - return a.compareDocumentPosition ? -1 : 1; + return compare & 4 ? -1 : 1; } : function( a, b ) { + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + var cur, i = 0, aup = a.parentNode, @@ -1736,19 +1358,14 @@ setDocument = Sizzle.setDocument = function( node ) { ap = [ a ], bp = [ b ]; - // Exit early if the nodes are identical - if ( a === b ) { - hasDuplicate = true; - return 0; - // Parentless nodes are either documents or disconnected - } else if ( !aup || !bup ) { - return a === doc ? -1 : - b === doc ? 1 : + if ( !aup || !bup ) { + return a === document ? -1 : + b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? - ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check @@ -1781,7 +1398,7 @@ setDocument = Sizzle.setDocument = function( node ) { 0; }; - return doc; + return document; }; Sizzle.matches = function( expr, elements ) { @@ -1798,6 +1415,7 @@ Sizzle.matchesSelector = function( elem, expr ) { expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && + !compilerCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { @@ -1811,10 +1429,10 @@ Sizzle.matchesSelector = function( elem, expr ) { elem.document && elem.document.nodeType !== 11 ) { return ret; } - } catch(e) {} + } catch (e) {} } - return Sizzle( expr, document, null, [elem] ).length > 0; + return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { @@ -1837,13 +1455,13 @@ Sizzle.attr = function( elem, name ) { fn( elem, name, !documentIsHTML ) : undefined; - return val === undefined ? + return val !== undefined ? + val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : - null : - val; + null; }; Sizzle.error = function( msg ) { @@ -1876,6 +1494,10 @@ Sizzle.uniqueSort = function( results ) { } } + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + return results; }; @@ -1891,13 +1513,13 @@ getText = Sizzle.getText = function( elem ) { if ( !nodeType ) { // If no nodeType, this is expected to be an array - for ( ; (node = elem[i]); i++ ) { + while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements - // innerText usage removed for consistency of new lines (see #11153) + // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { @@ -1939,7 +1561,7 @@ Expr = Sizzle.selectors = { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted - match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); + match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; @@ -1982,15 +1604,15 @@ Expr = Sizzle.selectors = { "PSEUDO": function( match ) { var excess, - unquoted = !match[5] && match[2]; + unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is - if ( match[3] && match[4] !== undefined ) { - match[2] = match[4]; + if ( match[3] ) { + match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && @@ -2026,7 +1648,7 @@ Expr = Sizzle.selectors = { return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { - return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, @@ -2048,7 +1670,7 @@ Expr = Sizzle.selectors = { operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : - operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; @@ -2067,11 +1689,12 @@ Expr = Sizzle.selectors = { } : function( elem, context, xml ) { - var cache, outerCache, node, diff, nodeIndex, start, + var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), - useCache = !xml && !ofType; + useCache = !xml && !ofType, + diff = false; if ( parent ) { @@ -2080,7 +1703,10 @@ Expr = Sizzle.selectors = { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { - if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + if ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) { + return false; } } @@ -2094,11 +1720,21 @@ Expr = Sizzle.selectors = { // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { + // Seek `elem` from a previously-cached index - outerCache = parent[ expando ] || (parent[ expando ] = {}); - cache = outerCache[ type ] || []; - nodeIndex = cache[0] === dirruns && cache[1]; - diff = cache[0] === dirruns && cache[2]; + + // ...in a gzip-friendly way + node = parent; + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || @@ -2108,29 +1744,55 @@ Expr = Sizzle.selectors = { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { - outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } - // Use previously-cached element index if available - } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { - diff = cache[1]; - - // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { - // Use the same loop as above to seek `elem` from the start - while ( (node = ++nodeIndex && node && node[ dir ] || - (diff = nodeIndex = 0) || start.pop()) ) { + // Use previously-cached element index if available + if ( useCache ) { + // ...in a gzip-friendly way + node = elem; + outerCache = node[ expando ] || (node[ expando ] = {}); - if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { - // Cache the index of each encountered element - if ( useCache ) { - (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; - } + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); - if ( node === elem ) { - break; + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex; + } + + // xml :nth-child(...) + // or :nth-last-child(...) or :nth(-last)?-of-type(...) + if ( diff === false ) { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) && + ++diff ) { + + // Cache the index of each encountered element + if ( useCache ) { + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + uniqueCache[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } } } } @@ -2168,7 +1830,7 @@ Expr = Sizzle.selectors = { matched = fn( seed, argument ), i = matched.length; while ( i-- ) { - idx = indexOf.call( seed, matched[i] ); + idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : @@ -2207,6 +1869,8 @@ Expr = Sizzle.selectors = { function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); + // Don't keep the element (issue #299) + input[0] = null; return !results.pop(); }; }), @@ -2218,6 +1882,7 @@ Expr = Sizzle.selectors = { }), "contains": markFunction(function( text ) { + text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; @@ -2294,12 +1959,11 @@ Expr = Sizzle.selectors = { // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo - // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), - // not comment, processing instructions, or others - // Thanks to Diego Perini for the nodeName shortcut - // Greater than "@" means alpha characters (specifically not starting with "#" or "?") + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { + if ( elem.nodeType < 6 ) { return false; } } @@ -2326,11 +1990,12 @@ Expr = Sizzle.selectors = { "text": function( elem ) { var attr; - // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) - // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && - ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection @@ -2395,7 +2060,7 @@ function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); -function tokenize( selector, parseOnly ) { +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; @@ -2416,7 +2081,7 @@ function tokenize( selector, parseOnly ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } - groups.push( tokens = [] ); + groups.push( (tokens = []) ); } matched = false; @@ -2460,7 +2125,7 @@ function tokenize( selector, parseOnly ) { Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); -} +}; function toSelector( tokens ) { var i = 0, @@ -2489,10 +2154,10 @@ function addCombinator( matcher, combinator, base ) { // Check against all ancestor/preceding elements function( elem, context, xml ) { - var data, cache, outerCache, - dirkey = dirruns + " " + doneName; + var oldCache, uniqueCache, outerCache, + newCache = [ dirruns, doneName ]; - // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { @@ -2505,14 +2170,22 @@ function addCombinator( matcher, combinator, base ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); - if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { - if ( (data = cache[1]) === true || data === cachedruns ) { - return data === true; - } + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); + + if ( (oldCache = uniqueCache[ dir ]) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return (newCache[ 2 ] = oldCache[ 2 ]); } else { - cache = outerCache[ dir ] = [ dirkey ]; - cache[1] = matcher( elem, context, xml ) || cachedruns; - if ( cache[1] === true ) { + // Reuse newcache so results back-propagate to previous elements + uniqueCache[ dir ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } @@ -2536,6 +2209,15 @@ function elementMatcher( matchers ) { matchers[0]; } +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], @@ -2627,7 +2309,7 @@ function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postS i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && - (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { + (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } @@ -2662,13 +2344,16 @@ function matcherFromTokens( tokens ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { - return indexOf.call( checkContext, elem ) > -1; + return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { - return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); + // Avoid hanging onto element (issue #299) + checkContext = null; + return ret; } ]; for ( ; i < len; i++ ) { @@ -2706,42 +2391,43 @@ function matcherFromTokens( tokens ) { } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { - // A counter to specify which element is currently being matched - var matcherCachedRuns = 0, - bySet = setMatchers.length > 0, + var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, - superMatcher = function( seed, context, xml, results, expandContext ) { + superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, - setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], - outermost = expandContext != null, + setMatched = [], contextBackup = outermostContext, - // We must always have either seed elements or context - elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher - dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), + len = elems.length; if ( outermost ) { - outermostContext = context !== document && context; - cachedruns = matcherCachedRuns; + outermostContext = context === document || context || outermost; } // Add elements passing elementMatchers directly to results - // Keep `i` a string if there are no elements so `matchedCount` will be "00" below - for ( ; (elem = elems[i]) != null; i++ ) { + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; + if ( !context && elem.ownerDocument !== document ) { + setDocument( elem ); + xml = !documentIsHTML; + } while ( (matcher = elementMatchers[j++]) ) { - if ( matcher( elem, context, xml ) ) { + if ( matcher( elem, context || document, xml) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; - cachedruns = ++matcherCachedRuns; } } @@ -2759,8 +2445,17 @@ function matcherFromGroupMatchers( elementMatchers, setMatchers ) { } } - // Apply set filters to unmatched elements + // `i` is now the count of elements visited above, and adding it to `matchedCount` + // makes the latter nonnegative. matchedCount += i; + + // Apply set filters to unmatched elements + // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` + // equals `i`), unless we didn't visit _any_ elements in the above loop because we have + // no element matchers and no seed. + // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that + // case, which will result in a "00" `matchedCount` that differs from `i` but is also + // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { @@ -2806,7 +2501,7 @@ function matcherFromGroupMatchers( elementMatchers, setMatchers ) { superMatcher; } -compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], @@ -2814,12 +2509,12 @@ compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { if ( !cached ) { // Generate a function of recursive functions that can be used to check each element - if ( !group ) { - group = tokenize( selector ); + if ( !match ) { + match = tokenize( selector ); } - i = group.length; + i = match.length; while ( i-- ) { - cached = matcherFromTokens( group[i] ); + cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { @@ -2829,91 +2524,101 @@ compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + + // Save selector and tokenization + cached.selector = selector; } return cached; }; -function multipleContexts( selector, contexts, results ) { - var i = 0, - len = contexts.length; - for ( ; i < len; i++ ) { - Sizzle( selector, contexts[i], results ); - } - return results; -} - -function select( selector, context, results, seed ) { +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, - match = tokenize( selector ); + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( (selector = compiled.selector || selector) ); - if ( !seed ) { - // Try to minimize operations if there is only one group - if ( match.length === 1 ) { + results = results || []; - // Take a shortcut and set the context if the root selector is an ID - tokens = match[0] = match[0].slice( 0 ); - if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && - support.getById && context.nodeType === 9 && documentIsHTML && - Expr.relative[ tokens[1].type ] ) { + // Try to minimize operations if there is only one selector in the list and no seed + // (the latter of which guarantees us context) + if ( match.length === 1 ) { - context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; - if ( !context ) { - return results; - } - selector = selector.slice( tokens.shift().value.length ); - } + // Reduce context if the leading compound selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + support.getById && context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { - // Fetch a seed set for right-to-left matching - i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; - while ( i-- ) { - token = tokens[i]; + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; - // Abort if we hit a combinator - if ( Expr.relative[ (type = token.type) ] ) { - break; - } - if ( (find = Expr.find[ type ]) ) { - // Search, expanding context for leading sibling combinators - if ( (seed = find( - token.matches[0].replace( runescape, funescape ), - rsibling.test( tokens[0].type ) && context.parentNode || context - )) ) { - - // If seed is empty or no tokens remain, we can return early - tokens.splice( i, 1 ); - selector = seed.length && toSelector( tokens ); - if ( !selector ) { - push.apply( results, seed ); - return results; - } + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } - break; + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; } + + break; } } } } - // Compile and execute a filtering function + // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above - compile( selector, match )( + ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, - rsibling.test( selector ) + !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; -} +}; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; -// Support: Chrome<14 +// Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function -support.detectDuplicates = hasDuplicate; +support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); @@ -2961,3164 +2666,2812 @@ if ( !assert(function( div ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { - return (val = elem.getAttributeNode( name )) && val.specified ? - val.value : - elem[ name ] === true ? name.toLowerCase() : null; + return elem[ name ] === true ? name.toLowerCase() : + (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + null; } }); } +return Sizzle; + +})( window ); + + + jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.pseudos; -jQuery.unique = Sizzle.uniqueSort; +jQuery.expr[ ":" ] = jQuery.expr.pseudos; +jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; -})( window ); -// String to Object options format cache -var optionsCache = {}; -// Convert String-formatted options into Object-formatted ones and store in cache -function createOptions( options ) { - var object = optionsCache[ options ] = {}; - jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { - object[ flag ] = true; - }); - return object; -} +var dir = function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; -/* - * Create a callback list using the following parameters: - * - * options: an optional list of space-separated options that will change how - * the callback list behaves or a more traditional option object - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible options: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ -jQuery.Callbacks = function( options ) { + while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; +}; - // Convert options from String-formatted to Object-formatted if needed - // (we check in cache first) - options = typeof options === "string" ? - ( optionsCache[ options ] || createOptions( options ) ) : - jQuery.extend( {}, options ); - var // Flag to know if list is currently firing - firing, - // Last fire value (for non-forgettable lists) - memory, - // Flag to know if list was already fired - fired, - // End of the loop when firing - firingLength, - // Index of currently firing callback (modified by remove if needed) - firingIndex, - // First callback to fire (used internally by add and fireWith) - firingStart, - // Actual callback list - list = [], - // Stack of fire calls for repeatable lists - stack = !options.once && [], - // Fire callbacks - fire = function( data ) { - memory = options.memory && data; - fired = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - firing = true; - for ( ; list && firingIndex < firingLength; firingIndex++ ) { - if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { - memory = false; // To prevent further calls using add - break; - } - } - firing = false; - if ( list ) { - if ( stack ) { - if ( stack.length ) { - fire( stack.shift() ); - } - } else if ( memory ) { - list = []; - } else { - self.disable(); - } - } - }, - // Actual Callbacks object - self = { - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - // First, we save the current length - var start = list.length; - (function add( args ) { - jQuery.each( args, function( _, arg ) { - var type = jQuery.type( arg ); - if ( type === "function" ) { - if ( !options.unique || !self.has( arg ) ) { - list.push( arg ); - } - } else if ( arg && arg.length && type !== "string" ) { - // Inspect recursively - add( arg ); - } - }); - })( arguments ); - // Do we need to add the callbacks to the - // current firing batch? - if ( firing ) { - firingLength = list.length; - // With memory, if we're not firing then - // we should call right away - } else if ( memory ) { - firingStart = start; - fire( memory ); - } - } - return this; - }, - // Remove a callback from the list - remove: function() { - if ( list ) { - jQuery.each( arguments, function( _, arg ) { - var index; - while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { - list.splice( index, 1 ); - // Handle firing indexes - if ( firing ) { - if ( index <= firingLength ) { - firingLength--; - } - if ( index <= firingIndex ) { - firingIndex--; - } - } - } - }); - } - return this; - }, - // Check if a given callback is in the list. - // If no argument is given, return whether or not list has callbacks attached. - has: function( fn ) { - return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); - }, - // Remove all callbacks from the list - empty: function() { - list = []; - firingLength = 0; - return this; - }, - // Have the list do nothing anymore - disable: function() { - list = stack = memory = undefined; - return this; - }, - // Is it disabled? - disabled: function() { - return !list; - }, - // Lock the list in its current state - lock: function() { - stack = undefined; - if ( !memory ) { - self.disable(); - } - return this; - }, - // Is it locked? - locked: function() { - return !stack; - }, - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - if ( list && ( !fired || stack ) ) { - args = args || []; - args = [ context, args.slice ? args.slice() : args ]; - if ( firing ) { - stack.push( args ); - } else { - fire( args ); - } - } - return this; - }, - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; - } - }; +var siblings = function( n, elem ) { + var matched = []; - return self; + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; }; -jQuery.extend({ - Deferred: function( func ) { - var tuples = [ - // action, add listener, listener list, final state - [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], - [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], - [ "notify", "progress", jQuery.Callbacks("memory") ] - ], - state = "pending", - promise = { - state: function() { - return state; - }, - always: function() { - deferred.done( arguments ).fail( arguments ); - return this; - }, - then: function( /* fnDone, fnFail, fnProgress */ ) { - var fns = arguments; - return jQuery.Deferred(function( newDefer ) { - jQuery.each( tuples, function( i, tuple ) { - var action = tuple[ 0 ], - fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; - // deferred[ done | fail | progress ] for forwarding actions to newDefer - deferred[ tuple[1] ](function() { - var returned = fn && fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise() - .done( newDefer.resolve ) - .fail( newDefer.reject ) - .progress( newDefer.notify ); - } else { - newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); - } - }); - }); - fns = null; - }).promise(); - }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - return obj != null ? jQuery.extend( obj, promise ) : promise; - } - }, - deferred = {}; - // Keep pipe for back-compat - promise.pipe = promise.then; +var rneedsContext = jQuery.expr.match.needsContext; - // Add list-specific methods - jQuery.each( tuples, function( i, tuple ) { - var list = tuple[ 2 ], - stateString = tuple[ 3 ]; +var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ ); - // promise[ done | fail | progress ] = list.add - promise[ tuple[1] ] = list.add; - // Handle state - if ( stateString ) { - list.add(function() { - // state = [ resolved | rejected ] - state = stateString; - // [ reject_list | resolve_list ].disable; progress_list.lock - }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); - } +var risSimple = /^.[^:#\[\.,]*$/; - // deferred[ resolve | reject | notify ] - deferred[ tuple[0] ] = function() { - deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); - return this; - }; - deferred[ tuple[0] + "With" ] = list.fireWith; - }); +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + /* jshint -W018 */ + return !!qualifier.call( elem, i, elem ) !== not; + } ); - // Make the deferred a promise - promise.promise( deferred ); + } - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + } ); + + } + + if ( typeof qualifier === "string" ) { + if ( risSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); } - // All done! - return deferred; - }, + qualifier = jQuery.filter( qualifier, elements ); + } - // Deferred helper - when: function( subordinate /* , ..., subordinateN */ ) { - var i = 0, - resolveValues = core_slice.call( arguments ), - length = resolveValues.length, + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not; + } ); +} - // the count of uncompleted subordinates - remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; - // the master Deferred. If resolveValues consist of only a single Deferred, just use that. - deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + if ( not ) { + expr = ":not(" + expr + ")"; + } - // Update function for both resolve and progress values - updateFunc = function( i, contexts, values ) { - return function( value ) { - contexts[ i ] = this; - values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; - if( values === progressValues ) { - deferred.notifyWith( contexts, values ); - } else if ( !( --remaining ) ) { - deferred.resolveWith( contexts, values ); - } - }; - }, + return elems.length === 1 && elem.nodeType === 1 ? + jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : + jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); +}; - progressValues, progressContexts, resolveContexts; +jQuery.fn.extend( { + find: function( selector ) { + var i, + len = this.length, + ret = [], + self = this; - // add listeners to Deferred subordinates; treat others as resolved - if ( length > 1 ) { - progressValues = new Array( length ); - progressContexts = new Array( length ); - resolveContexts = new Array( length ); - for ( ; i < length; i++ ) { - if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { - resolveValues[ i ].promise() - .done( updateFunc( i, resolveContexts, resolveValues ) ) - .fail( deferred.reject ) - .progress( updateFunc( i, progressContexts, progressValues ) ); - } else { - --remaining; + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter( function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } } - } + } ) ); } - // if we're not waiting on anything, resolve the master - if ( !remaining ) { - deferred.resolveWith( resolveContexts, resolveValues ); + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); } - return deferred.promise(); - } -}); -jQuery.support = (function( support ) { - - var all, a, input, select, fragment, opt, eventName, isSupported, i, - div = document.createElement("div"); - - // Setup - div.setAttribute( "className", "t" ); - div.innerHTML = "
a"; + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = this.selector ? this.selector + " " + selector : selector; + return ret; + }, + filter: function( selector ) { + return this.pushStack( winnow( this, selector || [], false ) ); + }, + not: function( selector ) { + return this.pushStack( winnow( this, selector || [], true ) ); + }, + is: function( selector ) { + return !!winnow( + this, - // Finish early in limited (non-browser) environments - all = div.getElementsByTagName("*") || []; - a = div.getElementsByTagName("a")[ 0 ]; - if ( !a || !a.style || !all.length ) { - return support; + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; } +} ); - // First batch of tests - select = document.createElement("select"); - opt = select.appendChild( document.createElement("option") ); - input = div.getElementsByTagName("input")[ 0 ]; - - a.style.cssText = "top:1px;float:left;opacity:.5"; - // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) - support.getSetAttribute = div.className !== "t"; +// Initialize a jQuery object - // IE strips leading whitespace when .innerHTML is used - support.leadingWhitespace = div.firstChild.nodeType === 3; - // Make sure that tbody elements aren't automatically inserted - // IE will insert them into empty tables - support.tbody = !div.getElementsByTagName("tbody").length; +// A central reference to the root jQuery(document) +var rootjQuery, - // Make sure that link elements get serialized correctly by innerHTML - // This requires a wrapper element in IE - support.htmlSerialize = !!div.getElementsByTagName("link").length; + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, - // Get the style information from getAttribute - // (IE uses .cssText instead) - support.style = /top/.test( a.getAttribute("style") ); + init = jQuery.fn.init = function( selector, context, root ) { + var match, elem; - // Make sure that URLs aren't manipulated - // (IE normalizes it by default) - support.hrefNormalized = a.getAttribute("href") === "/a"; + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } - // Make sure that element opacity exists - // (IE uses filter instead) - // Use a regex to work around a WebKit issue. See #5145 - support.opacity = /^0.5/.test( a.style.opacity ); + // Method init() accepts an alternate rootjQuery + // so migrate can support jQuery.sub (gh-2101) + root = root || rootjQuery; - // Verify style float existence - // (IE uses styleFloat instead of cssFloat) - support.cssFloat = !!a.style.cssFloat; + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector[ 0 ] === "<" && + selector[ selector.length - 1 ] === ">" && + selector.length >= 3 ) { - // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) - support.checkOn = !!input.value; + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; - // Make sure that a selected-by-default option has a working selected property. - // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) - support.optSelected = opt.selected; + } else { + match = rquickExpr.exec( selector ); + } - // Tests for enctype support on a form (#6743) - support.enctype = !!document.createElement("form").enctype; + // Match html or make sure no context is specified for #id + if ( match && ( match[ 1 ] || !context ) ) { - // Makes sure cloning an html5 element does not cause problems - // Where outerHTML is undefined, this still works - support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>"; + // HANDLE: $(html) -> $(array) + if ( match[ 1 ] ) { + context = context instanceof jQuery ? context[ 0 ] : context; - // Will be defined later - support.inlineBlockNeedsLayout = false; - support.shrinkWrapBlocks = false; - support.pixelPosition = false; - support.deleteExpando = true; - support.noCloneEvent = true; - support.reliableMarginRight = true; - support.boxSizingReliable = true; + // Option to run scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[ 1 ], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); - // Make sure checked status is properly cloned - input.checked = true; - support.noCloneChecked = input.cloneNode( true ).checked; + // HANDLE: $(html, props) + if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { - // Make sure that the options inside disabled selects aren't marked as disabled - // (WebKit marks them as disabled) - select.disabled = true; - support.optDisabled = !opt.disabled; + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); - // Support: IE<9 - try { - delete div.test; - } catch( e ) { - support.deleteExpando = false; - } + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } - // Check if we can trust getAttribute("value") - input = document.createElement("input"); - input.setAttribute( "value", "" ); - support.input = input.getAttribute( "value" ) === ""; + return this; - // Check if an input maintains its value after becoming a radio - input.value = "t"; - input.setAttribute( "type", "radio" ); - support.radioValue = input.value === "t"; + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[ 2 ] ); - // #11217 - WebKit loses check when the name is after the checked attribute - input.setAttribute( "checked", "t" ); - input.setAttribute( "name", "t" ); + // Support: Blackberry 4.6 + // gEBID returns nodes no longer in the document (#6963) + if ( elem && elem.parentNode ) { - fragment = document.createDocumentFragment(); - fragment.appendChild( input ); + // Inject the element directly into the jQuery object + this.length = 1; + this[ 0 ] = elem; + } - // Check if a disconnected checkbox will retain its checked - // value of true after appended to the DOM (IE6/7) - support.appendChecked = input.checked; + this.context = document; + this.selector = selector; + return this; + } - // WebKit doesn't clone checked state correctly in fragments - support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || root ).find( selector ); - // Support: IE<9 - // Opera does not clone events (and typeof div.attachEvent === undefined). - // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() - if ( div.attachEvent ) { - div.attachEvent( "onclick", function() { - support.noCloneEvent = false; - }); + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } - div.cloneNode( true ).click(); - } + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[ 0 ] = selector; + this.length = 1; + return this; - // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) - // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) - for ( i in { submit: true, change: true, focusin: true }) { - div.setAttribute( eventName = "on" + i, "t" ); + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return root.ready !== undefined ? + root.ready( selector ) : - support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; - } + // Execute immediately if ready is not present + selector( jQuery ); + } - div.style.backgroundClip = "content-box"; - div.cloneNode( true ).style.backgroundClip = ""; - support.clearCloneStyle = div.style.backgroundClip === "content-box"; + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } - // Support: IE<9 - // Iteration over object's inherited properties before its own. - for ( i in jQuery( support ) ) { - break; - } - support.ownLast = i !== "0"; + return jQuery.makeArray( selector, this ); + }; - // Run tests that need a body at doc ready - jQuery(function() { - var container, marginDiv, tds, - divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", - body = document.getElementsByTagName("body")[0]; +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; - if ( !body ) { - // Return for frameset docs that don't have a body - return; - } +// Initialize central reference +rootjQuery = jQuery( document ); - container = document.createElement("div"); - container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; - body.appendChild( container ).appendChild( div ); +var rparentsprev = /^(?:parents|prev(?:Until|All))/, - // Support: IE8 - // Check if table cells still have offsetWidth/Height when they are set - // to display:none and there are still other visible table cells in a - // table row; if so, offsetWidth/Height are not reliable for use when - // determining if an element has been hidden directly using - // display:none (it is still safe to use offsets if a parent element is - // hidden; don safety goggles and see bug #4512 for more information). - div.innerHTML = "
t
"; - tds = div.getElementsByTagName("td"); - tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; - isSupported = ( tds[ 0 ].offsetHeight === 0 ); + // Methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; - tds[ 0 ].style.display = ""; - tds[ 1 ].style.display = "none"; +jQuery.fn.extend( { + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; - // Support: IE8 - // Check if empty table cells still have offsetWidth/Height - support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + return this.filter( function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[ i ] ) ) { + return true; + } + } + } ); + }, - // Check box-sizing and margin behavior. - div.innerHTML = ""; - div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; - // Workaround failing boxSizing test due to offsetWidth returning wrong value - // with some non-1 values of body zoom, ticket #13543 - jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { - support.boxSizing = div.offsetWidth === 4; - }); + for ( ; i < l; i++ ) { + for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { - // Use window.getComputedStyle because jsdom on node.js will break without it. - if ( window.getComputedStyle ) { - support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; - support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; + // Always skip document fragments + if ( cur.nodeType < 11 && ( pos ? + pos.index( cur ) > -1 : - // Check if div with explicit width and no margin-right incorrectly - // gets computed margin-right based on width of container. (#3333) - // Fails in WebKit before Feb 2011 nightlies - // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right - marginDiv = div.appendChild( document.createElement("div") ); - marginDiv.style.cssText = div.style.cssText = divReset; - marginDiv.style.marginRight = marginDiv.style.width = "0"; - div.style.width = "1px"; + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector( cur, selectors ) ) ) { - support.reliableMarginRight = - !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); - } - - if ( typeof div.style.zoom !== core_strundefined ) { - // Support: IE<8 - // Check if natively block-level elements act like inline-block - // elements when setting their display to 'inline' and giving - // them layout - div.innerHTML = ""; - div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; - support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); - - // Support: IE6 - // Check if elements with layout shrink-wrap their children - div.style.display = "block"; - div.innerHTML = "
"; - div.firstChild.style.width = "5px"; - support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); - - if ( support.inlineBlockNeedsLayout ) { - // Prevent IE 6 from affecting layout for positioned elements #11048 - // Prevent IE from shrinking the body in IE 7 mode #12869 - // Support: IE<8 - body.style.zoom = 1; + matched.push( cur ); + break; + } } } - body.removeChild( container ); - - // Null elements to avoid leaks in IE - container = div = tds = marginDiv = null; - }); - - // Null elements to avoid leaks in IE - all = select = fragment = opt = a = input = null; - - return support; -})({}); + return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); + }, -var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, - rmultiDash = /([A-Z])/g; + // Determine the position of an element within the set + index: function( elem ) { -function internalData( elem, name, data, pvt /* Internal Use Only */ ){ - if ( !jQuery.acceptData( elem ) ) { - return; - } + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } - var ret, thisCache, - internalKey = jQuery.expando, + // Index in selector + if ( typeof elem === "string" ) { + return indexOf.call( jQuery( elem ), this[ 0 ] ); + } - // We have to handle DOM nodes and JS objects differently because IE6-7 - // can't GC object references properly across the DOM-JS boundary - isNode = elem.nodeType, + // Locate the position of the desired element + return indexOf.call( this, - // Only DOM nodes need the global jQuery cache; JS object data is - // attached directly to the object so GC can occur automatically - cache = isNode ? jQuery.cache : elem, + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, - // Only defining an ID for JS objects if its cache already exists allows - // the code to shortcut on the same path as a DOM node with no cache - id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; + add: function( selector, context ) { + return this.pushStack( + jQuery.uniqueSort( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, - // Avoid doing any more work than we need to when trying to get data on an - // object that has no data at all - if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { - return; + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter( selector ) + ); } +} ); - if ( !id ) { - // Only DOM nodes need a new unique ID for each element since their data - // ends up in the global cache - if ( isNode ) { - id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++; - } else { - id = internalKey; - } - } +function sibling( cur, dir ) { + while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} + return cur; +} - if ( !cache[ id ] ) { - // Avoid exposing jQuery metadata on plain JS objects when the object - // is serialized using JSON.stringify - cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; +jQuery.each( { + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return siblings( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return siblings( elem.firstChild ); + }, + contents: function( elem ) { + return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); - // An object can be passed to jQuery.data instead of a key/value pair; this gets - // shallow copied over onto the existing cache - if ( typeof name === "object" || typeof name === "function" ) { - if ( pvt ) { - cache[ id ] = jQuery.extend( cache[ id ], name ); - } else { - cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + if ( name.slice( -5 ) !== "Until" ) { + selector = until; } - } - thisCache = cache[ id ]; - - // jQuery data() is stored in a separate object inside the object's internal data - // cache in order to avoid key collisions between internal data and user-defined - // data. - if ( !pvt ) { - if ( !thisCache.data ) { - thisCache.data = {}; + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); } - thisCache = thisCache.data; - } - - if ( data !== undefined ) { - thisCache[ jQuery.camelCase( name ) ] = data; - } - - // Check for both converted-to-camel and non-converted data property names - // If a data property was specified - if ( typeof name === "string" ) { - - // First Try to find as-is property data - ret = thisCache[ name ]; + if ( this.length > 1 ) { - // Test for null|undefined property data - if ( ret == null ) { + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.uniqueSort( matched ); + } - // Try to find the camelCased property - ret = thisCache[ jQuery.camelCase( name ) ]; + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } } - } else { - ret = thisCache; - } - - return ret; -} - -function internalRemoveData( elem, name, pvt ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var thisCache, i, - isNode = elem.nodeType, - - // See jQuery.data for more information - cache = isNode ? jQuery.cache : elem, - id = isNode ? elem[ jQuery.expando ] : jQuery.expando; - - // If there is already no cache entry for this object, there is no - // purpose in continuing - if ( !cache[ id ] ) { - return; - } - - if ( name ) { - thisCache = pvt ? cache[ id ] : cache[ id ].data; + return this.pushStack( matched ); + }; +} ); +var rnotwhite = ( /\S+/g ); - if ( thisCache ) { - // Support array or space separated string names for data keys - if ( !jQuery.isArray( name ) ) { - // try the string as a key before any manipulation - if ( name in thisCache ) { - name = [ name ]; - } else { +// Convert String-formatted options into Object-formatted ones +function createOptions( options ) { + var object = {}; + jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + } ); + return object; +} - // split the camel cased version by spaces unless a key with the spaces exists - name = jQuery.camelCase( name ); - if ( name in thisCache ) { - name = [ name ]; - } else { - name = name.split(" "); - } - } - } else { - // If "name" is an array of keys... - // When data is initially created, via ("key", "val") signature, - // keys will be converted to camelCase. - // Since there is no way to tell _how_ a key was added, remove - // both plain key and camelCase key. #12786 - // This will only penalize the array argument path. - name = name.concat( jQuery.map( name, jQuery.camelCase ) ); - } +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { - i = name.length; - while ( i-- ) { - delete thisCache[ name[i] ]; - } + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + createOptions( options ) : + jQuery.extend( {}, options ); - // If there is no data left in the cache, we want to continue - // and let the cache object itself get destroyed - if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { - return; - } - } - } + var // Flag to know if list is currently firing + firing, - // See jQuery.data for more information - if ( !pvt ) { - delete cache[ id ].data; + // Last fire value for non-forgettable lists + memory, - // Don't destroy the parent cache unless the internal data object - // had been the only thing left in it - if ( !isEmptyDataObject( cache[ id ] ) ) { - return; - } - } + // Flag to know if list was already fired + fired, - // Destroy the cache - if ( isNode ) { - jQuery.cleanData( [ elem ], true ); + // Flag to prevent firing + locked, - // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) - /* jshint eqeqeq: false */ - } else if ( jQuery.support.deleteExpando || cache != cache.window ) { - /* jshint eqeqeq: true */ - delete cache[ id ]; + // Actual callback list + list = [], - // When all else fails, null - } else { - cache[ id ] = null; - } -} + // Queue of execution data for repeatable lists + queue = [], -jQuery.extend({ - cache: {}, + // Index of currently firing callback (modified by add/remove as needed) + firingIndex = -1, - // The following elements throw uncatchable exceptions if you - // attempt to add expando properties to them. - noData: { - "applet": true, - "embed": true, - // Ban all objects except for Flash (which handle expandos) - "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" - }, + // Fire callbacks + fire = function() { - hasData: function( elem ) { - elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; - return !!elem && !isEmptyDataObject( elem ); - }, + // Enforce single-firing + locked = options.once; - data: function( elem, name, data ) { - return internalData( elem, name, data ); - }, + // Execute callbacks for all pending executions, + // respecting firingIndex overrides and runtime changes + fired = firing = true; + for ( ; queue.length; firingIndex = -1 ) { + memory = queue.shift(); + while ( ++firingIndex < list.length ) { - removeData: function( elem, name ) { - return internalRemoveData( elem, name ); - }, + // Run callback and check for early termination + if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && + options.stopOnFalse ) { - // For internal use only. - _data: function( elem, name, data ) { - return internalData( elem, name, data, true ); - }, + // Jump to end and forget the data so .add doesn't re-fire + firingIndex = list.length; + memory = false; + } + } + } - _removeData: function( elem, name ) { - return internalRemoveData( elem, name, true ); - }, + // Forget the data if we're done with it + if ( !options.memory ) { + memory = false; + } - // A method for determining if a DOM node can handle the data expando - acceptData: function( elem ) { - // Do not set data on non-element because it will not be cleared (#8335). - if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { - return false; - } + firing = false; - var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; + // Clean up if we're done firing for good + if ( locked ) { - // nodes accept data unless otherwise specified; rejection can be conditional - return !noData || noData !== true && elem.getAttribute("classid") === noData; - } -}); + // Keep an empty list if we have data for future add calls + if ( memory ) { + list = []; -jQuery.fn.extend({ - data: function( key, value ) { - var attrs, name, - data = null, - i = 0, - elem = this[0]; + // Otherwise, this object is spent + } else { + list = ""; + } + } + }, - // Special expections of .data basically thwart jQuery.access, - // so implement the relevant behavior ourselves + // Actual Callbacks object + self = { - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = jQuery.data( elem ); + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + + // If we have memory from a past run, we should fire after adding + if ( memory && !firing ) { + firingIndex = list.length - 1; + queue.push( memory ); + } + + ( function add( args ) { + jQuery.each( args, function( _, arg ) { + if ( jQuery.isFunction( arg ) ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { - if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { - attrs = elem.attributes; - for ( ; i < attrs.length; i++ ) { - name = attrs[i].name; + // Inspect recursively + add( arg ); + } + } ); + } )( arguments ); - if ( name.indexOf("data-") === 0 ) { - name = jQuery.camelCase( name.slice(5) ); + if ( memory && !firing ) { + fire(); + } + } + return this; + }, - dataAttr( elem, name, data[ name ] ); + // Remove a callback from the list + remove: function() { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + + // Handle firing indexes + if ( index <= firingIndex ) { + firingIndex--; } } - jQuery._data( elem, "parsedAttrs", true ); + } ); + return this; + }, + + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? + jQuery.inArray( fn, list ) > -1 : + list.length > 0; + }, + + // Remove all callbacks from the list + empty: function() { + if ( list ) { + list = []; } - } + return this; + }, - return data; - } + // Disable .fire and .add + // Abort any current/pending executions + // Clear all callbacks and values + disable: function() { + locked = queue = []; + list = memory = ""; + return this; + }, + disabled: function() { + return !list; + }, - // Sets multiple values - if ( typeof key === "object" ) { - return this.each(function() { - jQuery.data( this, key ); - }); - } + // Disable .fire + // Also disable .add unless we have memory (since it would have no effect) + // Abort any pending executions + lock: function() { + locked = queue = []; + if ( !memory ) { + list = memory = ""; + } + return this; + }, + locked: function() { + return !!locked; + }, - return arguments.length > 1 ? + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( !locked ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + queue.push( args ); + if ( !firing ) { + fire(); + } + } + return this; + }, - // Sets one value - this.each(function() { - jQuery.data( this, key, value ); - }) : + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, - // Gets one value - // Try to fetch any internally stored data first - elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; - }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; - removeData: function( key ) { - return this.each(function() { - jQuery.removeData( this, key ); - }); - } -}); + return self; +}; -function dataAttr( elem, key, data ) { - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); +jQuery.extend( { - data = elem.getAttribute( name ); + Deferred: function( func ) { + var tuples = [ - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - // Only convert to a number if it doesn't change the string - +data + "" === data ? +data : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks( "once memory" ), "resolved" ], + [ "reject", "fail", jQuery.Callbacks( "once memory" ), "rejected" ], + [ "notify", "progress", jQuery.Callbacks( "memory" ) ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred( function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; - // Make sure we set the data so it isn't changed later - jQuery.data( elem, key, data ); + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[ 1 ] ]( function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .progress( newDefer.notify ) + .done( newDefer.resolve ) + .fail( newDefer.reject ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( + this === promise ? newDefer.promise() : this, + fn ? [ returned ] : arguments + ); + } + } ); + } ); + fns = null; + } ).promise(); + }, - } else { - data = undefined; - } - } + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; - return data; -} + // Keep pipe for back-compat + promise.pipe = promise.then; -// checks a cache object for emptiness -function isEmptyDataObject( obj ) { - var name; - for ( name in obj ) { + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; - // if the public data object is empty, the private is still empty - if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { - continue; - } - if ( name !== "toJSON" ) { - return false; - } - } + // promise[ done | fail | progress ] = list.add + promise[ tuple[ 1 ] ] = list.add; - return true; -} -jQuery.extend({ - queue: function( elem, type, data ) { - var queue; + // Handle state + if ( stateString ) { + list.add( function() { - if ( elem ) { - type = ( type || "fx" ) + "queue"; - queue = jQuery._data( elem, type ); + // state = [ resolved | rejected ] + state = stateString; - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !queue || jQuery.isArray(data) ) { - queue = jQuery._data( elem, type, jQuery.makeArray(data) ); - } else { - queue.push( data ); - } + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } - return queue || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - var queue = jQuery.queue( elem, type ), - startLength = queue.length, - fn = queue.shift(), - hooks = jQuery._queueHooks( elem, type ), - next = function() { - jQuery.dequeue( elem, type ); + // deferred[ resolve | reject | notify ] + deferred[ tuple[ 0 ] ] = function() { + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? promise : this, arguments ); + return this; }; + deferred[ tuple[ 0 ] + "With" ] = list.fireWith; + } ); - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - startLength--; + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); } - if ( fn ) { + // All done! + return deferred; + }, - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = slice.call( arguments ), + length = resolveValues.length, - // clear up the last queue stop function - delete hooks.stop; - fn.call( elem, next, hooks ); + // the count of uncompleted subordinates + remaining = length !== 1 || + ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. + // If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( values === progressValues ) { + deferred.notifyWith( contexts, values ); + } else if ( !( --remaining ) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // Add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .progress( updateFunc( i, progressContexts, progressValues ) ) + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ); + } else { + --remaining; + } + } } - if ( !startLength && hooks ) { - hooks.empty.fire(); + // If we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); } - }, - // not intended for public consumption - generates a queueHooks object, or returns the current one - _queueHooks: function( elem, type ) { - var key = type + "queueHooks"; - return jQuery._data( elem, key ) || jQuery._data( elem, key, { - empty: jQuery.Callbacks("once memory").add(function() { - jQuery._removeData( elem, type + "queue" ); - jQuery._removeData( elem, key ); - }) - }); + return deferred.promise(); } -}); +} ); -jQuery.fn.extend({ - queue: function( type, data ) { - var setter = 2; - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } +// The deferred used on DOM ready +var readyList; - if ( arguments.length < setter ) { - return jQuery.queue( this[0], type ); - } +jQuery.fn.ready = function( fn ) { - return data === undefined ? - this : - this.each(function() { - var queue = jQuery.queue( this, type, data ); + // Add the callback + jQuery.ready.promise().done( fn ); - // ensure a hooks for this queue - jQuery._queueHooks( this, type ); + return this; +}; - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - // Based off of the plugin by Clint Helfers, with permission. - // http://blindsignals.com/index.php/2009/07/jquery-delay/ - delay: function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; - type = type || "fx"; +jQuery.extend( { - return this.queue( type, function( next, hooks ) { - var timeout = setTimeout( next, time ); - hooks.stop = function() { - clearTimeout( timeout ); - }; - }); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, obj ) { - var tmp, - count = 1, - defer = jQuery.Deferred(), - elements = this, - i = this.length, - resolve = function() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - }; + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, - if ( typeof type !== "string" ) { - obj = type; - type = undefined; - } - type = type || "fx"; + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, - while( i-- ) { - tmp = jQuery._data( elements[ i ], type + "queueHooks" ); - if ( tmp && tmp.empty ) { - count++; - tmp.empty.add( resolve ); - } + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); } - resolve(); - return defer.promise( obj ); - } -}); -var nodeHook, boolHook, - rclass = /[\t\r\n\f]/g, - rreturn = /\r/g, - rfocusable = /^(?:input|select|textarea|button|object)$/i, - rclickable = /^(?:a|area)$/i, - ruseDefault = /^(?:checked|selected)$/i, - getSetAttribute = jQuery.support.getSetAttribute, - getSetInput = jQuery.support.input; - -jQuery.fn.extend({ - attr: function( name, value ) { - return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, - removeAttr: function( name ) { - return this.each(function() { - jQuery.removeAttr( this, name ); - }); - }, + // Handle when the DOM is ready + ready: function( wait ) { - prop: function( name, value ) { - return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); - }, + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } - removeProp: function( name ) { - name = jQuery.propFix[ name ] || name; - return this.each(function() { - // try/catch handles cases where IE balks (such as removing a property on window) - try { - this[ name ] = undefined; - delete this[ name ]; - } catch( e ) {} - }); - }, + // Remember that the DOM is ready + jQuery.isReady = true; - addClass: function( value ) { - var classes, elem, cur, clazz, j, - i = 0, - len = this.length, - proceed = typeof value === "string" && value; + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).addClass( value.call( this, j, this.className ) ); - }); + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.triggerHandler ) { + jQuery( document ).triggerHandler( "ready" ); + jQuery( document ).off( "ready" ); } + } +} ); - if ( proceed ) { - // The disjunction here is for better compressibility (see removeClass) - classes = ( value || "" ).match( core_rnotwhite ) || []; +/** + * The ready event handler and self cleanup method + */ +function completed() { + document.removeEventListener( "DOMContentLoaded", completed ); + window.removeEventListener( "load", completed ); + jQuery.ready(); +} - for ( ; i < len; i++ ) { - elem = this[ i ]; - cur = elem.nodeType === 1 && ( elem.className ? - ( " " + elem.className + " " ).replace( rclass, " " ) : - " " - ); +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { - if ( cur ) { - j = 0; - while ( (clazz = classes[j++]) ) { - if ( cur.indexOf( " " + clazz + " " ) < 0 ) { - cur += clazz + " "; - } - } - elem.className = jQuery.trim( cur ); + readyList = jQuery.Deferred(); - } - } - } + // Catch cases where $(document).ready() is called + // after the browser event has already occurred. + // Support: IE9-10 only + // Older IE sometimes signals "interactive" too soon + if ( document.readyState === "complete" || + ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { - return this; - }, + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); - removeClass: function( value ) { - var classes, elem, cur, clazz, j, - i = 0, - len = this.length, - proceed = arguments.length === 0 || typeof value === "string" && value; + } else { - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).removeClass( value.call( this, j, this.className ) ); - }); + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); } - if ( proceed ) { - classes = ( value || "" ).match( core_rnotwhite ) || []; + } + return readyList.promise( obj ); +}; - for ( ; i < len; i++ ) { - elem = this[ i ]; - // This expression is here for better compressibility (see addClass) - cur = elem.nodeType === 1 && ( elem.className ? - ( " " + elem.className + " " ).replace( rclass, " " ) : - "" - ); +// Kick off the DOM ready check even if the user does not +jQuery.ready.promise(); - if ( cur ) { - j = 0; - while ( (clazz = classes[j++]) ) { - // Remove *all* instances - while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { - cur = cur.replace( " " + clazz + " ", " " ); - } - } - elem.className = value ? jQuery.trim( cur ) : ""; - } - } - } - return this; - }, - toggleClass: function( value, stateVal ) { - var type = typeof value; - if ( typeof stateVal === "boolean" && type === "string" ) { - return stateVal ? this.addClass( value ) : this.removeClass( value ); +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + access( elems, fn, i, key[ i ], true, emptyGet, raw ); } - if ( jQuery.isFunction( value ) ) { - return this.each(function( i ) { - jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); - }); + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; } - return this.each(function() { - if ( type === "string" ) { - // toggle individual class names - var className, - i = 0, - self = jQuery( this ), - classNames = value.match( core_rnotwhite ) || []; - - while ( (className = classNames[ i++ ]) ) { - // check each className given, space separated list - if ( self.hasClass( className ) ) { - self.removeClass( className ); - } else { - self.addClass( className ); - } - } + if ( bulk ) { - // Toggle whole class name - } else if ( type === core_strundefined || type === "boolean" ) { - if ( this.className ) { - // store className if set - jQuery._data( this, "__className__", this.className ); - } + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; - // If the element has a class name or if we're passed "false", - // then remove the whole classname (if there was one, the above saved it). - // Otherwise bring back whatever was previously saved (if anything), - // falling back to the empty string if nothing was stored. - this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; } - }); - }, + } - hasClass: function( selector ) { - var className = " " + selector + " ", - i = 0, - l = this.length; - for ( ; i < l; i++ ) { - if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { - return true; + if ( fn ) { + for ( ; i < len; i++ ) { + fn( + elems[ i ], key, raw ? + value : + value.call( elems[ i ], i, fn( elems[ i ], key ) ) + ); } } + } - return false; - }, - - val: function( value ) { - var ret, hooks, isFunction, - elem = this[0]; + return chainable ? + elems : - 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; + // Gets + bulk ? + fn.call( elems ) : + len ? fn( elems[ 0 ], key ) : emptyGet; +}; +var acceptData = function( owner ) { + + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + /* jshint -W018 */ + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +}; - return typeof ret === "string" ? - // handle most common string cases - ret.replace(rreturn, "") : - // handle cases where value is null/undef or number - ret == null ? "" : ret; - } - return; - } - isFunction = jQuery.isFunction( value ); - return this.each(function( i ) { - var val; +function Data() { + this.expando = jQuery.expando + Data.uid++; +} - if ( this.nodeType !== 1 ) { - return; - } +Data.uid = 1; - if ( isFunction ) { - val = value.call( this, i, jQuery( this ).val() ); - } else { - val = value; - } +Data.prototype = { - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - } else if ( typeof val === "number" ) { - val += ""; - } else if ( jQuery.isArray( val ) ) { - val = jQuery.map(val, function ( value ) { - return value == null ? "" : value + ""; - }); - } + register: function( owner, initial ) { + var value = initial || {}; - hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; - // If set returns undefined, fall back to normal setting - if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - }); - } -}); + // Otherwise secure it in a non-enumerable, non-writable property + // configurability must be true to allow the property to be + // deleted with the delete operator + } else { + Object.defineProperty( owner, this.expando, { + value: value, + writable: true, + configurable: true + } ); + } + return owner[ this.expando ]; + }, + cache: function( owner ) { -jQuery.extend({ - valHooks: { - option: { - get: function( elem ) { - // Use proper attribute retrieval(#6932, #12072) - var val = jQuery.find.attr( elem, "value" ); - return val != null ? - val : - elem.text; - } - }, - select: { - get: function( elem ) { - var value, option, - options = elem.options, - index = elem.selectedIndex, - one = elem.type === "select-one" || index < 0, - values = one ? null : [], - max = one ? index + 1 : options.length, - i = index < 0 ? - max : - one ? index : 0; + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return an empty object. + if ( !acceptData( owner ) ) { + return {}; + } - // Loop through all the selected options - for ( ; i < max; i++ ) { - option = options[ i ]; + // Check if the owner object already has a cache + var value = owner[ this.expando ]; - // oldIE doesn't update selected after form reset (#2551) - if ( ( option.selected || i === index ) && - // Don't return options that are disabled or in a disabled optgroup - ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && - ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { + // If not, create one + if ( !value ) { + value = {}; - // Get the specific value for the option - value = jQuery( option ).val(); + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return an empty object. + if ( acceptData( owner ) ) { - // We don't need an array for one selects - if ( one ) { - return value; - } + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; - // Multi-Selects return an array - values.push( value ); - } + // Otherwise secure it in a non-enumerable property + // configurable must be true to allow the property to be + // deleted when data is removed + } else { + Object.defineProperty( owner, this.expando, { + value: value, + configurable: true + } ); } + } + } - return values; - }, + return value; + }, + set: function( owner, data, value ) { + var prop, + cache = this.cache( owner ); - set: function( elem, value ) { - var optionSet, option, - options = elem.options, - values = jQuery.makeArray( value ), - i = options.length; + // Handle: [ owner, key, value ] args + if ( typeof data === "string" ) { + cache[ data ] = value; - while ( i-- ) { - option = options[ i ]; - if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { - optionSet = true; - } - } + // Handle: [ owner, { properties } ] args + } else { - // force browsers to behave consistently when non-matching value is set - if ( !optionSet ) { - elem.selectedIndex = -1; - } - return values; + // Copy the properties one-by-one to the cache object + for ( prop in data ) { + cache[ prop ] = data[ prop ]; } } + return cache; }, + get: function( owner, key ) { + return key === undefined ? + this.cache( owner ) : + owner[ this.expando ] && owner[ this.expando ][ key ]; + }, + access: function( owner, key, value ) { + var stored; - attr: function( elem, name, value ) { - var hooks, ret, - nType = elem.nodeType; - - // don't get/set attributes on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ( ( key && typeof key === "string" ) && value === undefined ) ) { - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === core_strundefined ) { - return jQuery.prop( elem, name, value ); - } + stored = this.get( owner, key ); - // All attributes are lowercase - // Grab necessary hook if one is defined - if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { - name = name.toLowerCase(); - hooks = jQuery.attrHooks[ name ] || - ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); + return stored !== undefined ? + stored : this.get( owner, jQuery.camelCase( key ) ); } - if ( value !== undefined ) { - - if ( value === null ) { - jQuery.removeAttr( elem, name ); + // When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); - } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, name, camel, + cache = owner[ this.expando ]; - } else { - elem.setAttribute( name, value + "" ); - return value; - } + if ( cache === undefined ) { + return; + } - } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { - return ret; + if ( key === undefined ) { + this.register( owner ); } else { - ret = jQuery.find.attr( elem, name ); - - // Non-existent attributes return null, we normalize to undefined - return ret == null ? - undefined : - ret; - } - }, - - removeAttr: function( elem, value ) { - var name, propName, - i = 0, - attrNames = value && value.match( core_rnotwhite ); - if ( attrNames && elem.nodeType === 1 ) { - while ( (name = attrNames[i++]) ) { - propName = jQuery.propFix[ name ] || name; + // Support array or space separated string of keys + if ( jQuery.isArray( key ) ) { - // Boolean attributes get special treatment (#10870) - if ( jQuery.expr.match.bool.test( name ) ) { - // Set corresponding property to false - if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { - elem[ propName ] = false; - // Support: IE<9 - // Also clear defaultChecked/defaultSelected (if appropriate) - } else { - elem[ jQuery.camelCase( "default-" + name ) ] = - elem[ propName ] = false; - } + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = key.concat( key.map( jQuery.camelCase ) ); + } else { + camel = jQuery.camelCase( key ); - // See #9699 for explanation of this approach (setting first, then removal) + // Try the string as a key before any manipulation + if ( key in cache ) { + name = [ key, camel ]; } else { - jQuery.attr( elem, name, "" ); + + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + name = camel; + name = name in cache ? + [ name ] : ( name.match( rnotwhite ) || [] ); } + } + + i = name.length; - elem.removeAttribute( getSetAttribute ? name : propName ); + while ( i-- ) { + delete cache[ name[ i ] ]; } } - }, - attrHooks: { - type: { - set: function( elem, value ) { - if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { - // Setting the type on a radio button after the value resets the value in IE6-9 - // Reset value to default in case type is set after value during creation - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } + // Remove the expando if there's no more data + if ( key === undefined || jQuery.isEmptyObject( cache ) ) { + + // Support: Chrome <= 35-45+ + // Webkit & Blink performance suffers when deleting properties + // from DOM nodes, so set to undefined instead + // https://code.google.com/p/chromium/issues/detail?id=378607 + if ( owner.nodeType ) { + owner[ this.expando ] = undefined; + } else { + delete owner[ this.expando ]; } } }, + hasData: function( owner ) { + var cache = owner[ this.expando ]; + return cache !== undefined && !jQuery.isEmptyObject( cache ); + } +}; +var dataPriv = new Data(); - propFix: { - "for": "htmlFor", - "class": "className" - }, +var dataUser = new Data(); - prop: function( elem, name, value ) { - var ret, hooks, notxml, - nType = elem.nodeType; - // don't get/set properties on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 - if ( notxml ) { - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /[A-Z]/g; - if ( value !== undefined ) { - return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? - ret : - ( elem[ name ] = value ); +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch ( e ) {} + // Make sure we set the data so it isn't changed later + dataUser.set( elem, key, data ); } else { - return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? - ret : - elem[ name ]; + data = undefined; } + } + return data; +} + +jQuery.extend( { + hasData: function( elem ) { + return dataUser.hasData( elem ) || dataPriv.hasData( elem ); }, - propHooks: { - tabIndex: { - get: function( elem ) { - // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set - // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - // Use proper attribute retrieval(#12072) - var tabindex = jQuery.find.attr( elem, "tabindex" ); + data: function( elem, name, data ) { + return dataUser.access( elem, name, data ); + }, - return tabindex ? - parseInt( tabindex, 10 ) : - rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? - 0 : - -1; - } - } + removeData: function( elem, name ) { + dataUser.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to dataPriv methods, these can be deprecated. + _data: function( elem, name, data ) { + return dataPriv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + dataPriv.remove( elem, name ); } -}); +} ); -// Hooks for boolean attributes -boolHook = { - set: function( elem, value, name ) { - if ( value === false ) { - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { - // IE<8 needs the *property* name - elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); +jQuery.fn.extend( { + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; - // Use defaultChecked and defaultSelected for oldIE - } else { - elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; - } + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = dataUser.get( elem ); - return name; - } -}; -jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { - var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; - - jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? - function( elem, name, isXML ) { - var fn = jQuery.expr.attrHandle[ name ], - ret = isXML ? - undefined : - /* jshint eqeqeq: false */ - (jQuery.expr.attrHandle[ name ] = undefined) != - getter( elem, name, isXML ) ? - - name.toLowerCase() : - null; - jQuery.expr.attrHandle[ name ] = fn; - return ret; - } : - function( elem, name, isXML ) { - return isXML ? - undefined : - elem[ jQuery.camelCase( "default-" + name ) ] ? - name.toLowerCase() : - null; - }; -}); + if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { -// fix oldIE attroperties -if ( !getSetInput || !getSetAttribute ) { - jQuery.attrHooks.value = { - set: function( elem, value, name ) { - if ( jQuery.nodeName( elem, "input" ) ) { - // Does not return so that setAttribute is also used - elem.defaultValue = value; - } else { - // Use nodeHook if defined (#1954); otherwise setAttribute is fine - return nodeHook && nodeHook.set( elem, value, name ); + // Support: IE11+ + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.slice( 5 ) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + dataPriv.set( elem, "hasDataAttrs", true ); + } } + + return data; } - }; -} -// IE6/7 do not support getting/setting some attributes with get/setAttribute -if ( !getSetAttribute ) { - - // Use this for any attribute in IE6/7 - // This fixes almost every IE6/7 issue - nodeHook = { - set: function( elem, value, name ) { - // Set the existing or create a new attribute node - var ret = elem.getAttributeNode( name ); - if ( !ret ) { - elem.setAttributeNode( - (ret = elem.ownerDocument.createAttribute( name )) - ); - } + // Sets multiple values + if ( typeof key === "object" ) { + return this.each( function() { + dataUser.set( this, key ); + } ); + } - ret.value = value += ""; + return access( this, function( value ) { + var data, camelKey; - // Break association with cloned elements by also using setAttribute (#9646) - return name === "value" || value === elem.getAttribute( name ) ? - value : - undefined; - } - }; - jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = - // Some attributes are constructed with empty-string values when not defined - function( elem, name, isXML ) { - var ret; - return isXML ? - undefined : - (ret = elem.getAttributeNode( name )) && ret.value !== "" ? - ret.value : - null; - }; - jQuery.valHooks.button = { - get: function( elem, name ) { - var ret = elem.getAttributeNode( name ); - return ret && ret.specified ? - ret.value : - undefined; - }, - set: nodeHook.set - }; + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { - // Set contenteditable to false on removals(#10429) - // Setting to empty string throws an error as an invalid value - jQuery.attrHooks.contenteditable = { - set: function( elem, value, name ) { - nodeHook.set( elem, value === "" ? false : value, name ); - } - }; + // Attempt to get data from the cache + // with the key as-is + data = dataUser.get( elem, key ) || - // Set width and height to auto instead of 0 on empty string( Bug #8150 ) - // This is for removals - jQuery.each([ "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = { - set: function( elem, value ) { - if ( value === "" ) { - elem.setAttribute( name, "auto" ); - return value; + // Try to find dashed key if it exists (gh-2779) + // This is for 2.2.x only + dataUser.get( elem, key.replace( rmultiDash, "-$&" ).toLowerCase() ); + + if ( data !== undefined ) { + return data; } - } - }; - }); -} + camelKey = jQuery.camelCase( key ); -// Some attributes require a special call on IE -// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx -if ( !jQuery.support.hrefNormalized ) { - // href/src property should get the full normalized URL (#10299/#12915) - jQuery.each([ "href", "src" ], function( i, name ) { - jQuery.propHooks[ name ] = { - get: function( elem ) { - return elem.getAttribute( name, 4 ); + // Attempt to get data from the cache + // with the key camelized + data = dataUser.get( elem, camelKey ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, camelKey, undefined ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; } - }; - }); -} -if ( !jQuery.support.style ) { - jQuery.attrHooks.style = { - get: function( elem ) { - // Return undefined in the case of empty string - // Note: IE uppercases css property names, but if we were to .toLowerCase() - // .cssText, that would destroy case senstitivity in URL's, like in "background" - return elem.style.cssText || undefined; - }, - set: function( elem, value ) { - return ( elem.style.cssText = value + "" ); - } - }; -} + // Set the data... + camelKey = jQuery.camelCase( key ); + this.each( function() { -// Safari mis-reports the default selected property of an option -// Accessing the parent's selectedIndex property fixes it -if ( !jQuery.support.optSelected ) { - jQuery.propHooks.selected = { - get: function( elem ) { - var parent = elem.parentNode; + // First, attempt to store a copy or reference of any + // data that might've been store with a camelCased key. + var data = dataUser.get( this, camelKey ); - if ( parent ) { - parent.selectedIndex; + // For HTML5 data-* attribute interop, we have to + // store property names with dashes in a camelCase form. + // This might not apply to all properties...* + dataUser.set( this, camelKey, value ); - // Make sure that it also works with optgroups, see #5701 - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; + // *... In the case of properties that might _actually_ + // have dashes, we need to also store a copy of that + // unchanged property. + if ( key.indexOf( "-" ) > -1 && data !== undefined ) { + dataUser.set( this, key, value ); } - } - return null; - } - }; -} + } ); + }, null, value, arguments.length > 1, null, true ); + }, -jQuery.each([ - "tabIndex", - "readOnly", - "maxLength", - "cellSpacing", - "cellPadding", - "rowSpan", - "colSpan", - "useMap", - "frameBorder", - "contentEditable" -], function() { - jQuery.propFix[ this.toLowerCase() ] = this; -}); + removeData: function( key ) { + return this.each( function() { + dataUser.remove( this, key ); + } ); + } +} ); -// IE6/7 call enctype encoding -if ( !jQuery.support.enctype ) { - jQuery.propFix.enctype = "encoding"; -} -// Radios and checkboxes getter/setter -jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - set: function( elem, value ) { - if ( jQuery.isArray( value ) ) { - return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); +jQuery.extend( { + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = dataPriv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray( data ) ) { + queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); + } else { + queue.push( data ); + } } + return queue || []; } - }; - if ( !jQuery.support.checkOn ) { - jQuery.valHooks[ this ].get = function( elem ) { - // Support: Webkit - // "" is returned instead of "on" if a value isn't specified - return elem.getAttribute("value") === null ? "on" : elem.value; - }; - } -}); -var rformElems = /^(?:input|select|textarea)$/i, - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|contextmenu)|click/, - rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; - -function returnTrue() { - return true; -} + }, -function returnFalse() { - return false; -} + dequeue: function( elem, type ) { + type = type || "fx"; -function safeActiveElement() { - try { - return document.activeElement; - } catch ( err ) { } -} + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } - global: {}, + if ( fn ) { - add: function( elem, types, handler, data, selector ) { - var tmp, events, t, handleObjIn, - special, eventHandle, handleObj, - handlers, type, namespaces, origType, - elemData = jQuery._data( elem ); + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } - // Don't attach events to noData or text/comment nodes (but allow plain objects) - if ( !elemData ) { - return; + // Clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); } - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; + if ( !startLength && hooks ) { + hooks.empty.fire(); } + }, - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; + // Not public - generate a queueHooks object, or return the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { + empty: jQuery.Callbacks( "once memory" ).add( function() { + dataPriv.remove( elem, [ type + "queue", key ] ); + } ) + } ); + } +} ); + +jQuery.fn.extend( { + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; } - // Init the element's event structure and main handler, if this is the first - if ( !(events = elemData.events) ) { - events = elemData.events = {}; + if ( arguments.length < setter ) { + return jQuery.queue( this[ 0 ], type ); } - if ( !(eventHandle = elemData.handle) ) { - eventHandle = elemData.handle = function( e ) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? - jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : - undefined; + + return data === undefined ? + this : + this.each( function() { + var queue = jQuery.queue( this, type, data ); + + // Ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + } ); + }, + dequeue: function( type ) { + return this.each( function() { + jQuery.dequeue( this, type ); + } ); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } }; - // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events - eventHandle.elem = elem; - } - // Handle multiple events separated by a space - types = ( types || "" ).match( core_rnotwhite ) || [""]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[t] ) || []; - type = origType = tmp[1]; - namespaces = ( tmp[2] || "" ).split( "." ).sort(); + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; - // There *must* be a type, no attaching namespace-only handlers - if ( !type ) { - continue; + while ( i-- ) { + tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); } + } + resolve(); + return defer.promise( obj ); + } +} ); +var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; +var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; - // handleObj is passed to all event handlers - handleObj = jQuery.extend({ - type: type, - origType: origType, - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - needsContext: selector && jQuery.expr.match.needsContext.test( selector ), - namespace: namespaces.join(".") - }, handleObjIn ); +var isHidden = function( elem, el ) { - // Init the event handler queue if we're the first - if ( !(handlers = events[ type ]) ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || + !jQuery.contains( elem.ownerDocument, elem ); + }; - // Only use addEventListener/attachEvent if the special events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - // Bind the global event handler to the element - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); - } else if ( elem.attachEvent ) { - elem.attachEvent( "on" + type, eventHandle ); - } - } - } - if ( special.add ) { - special.add.call( elem, handleObj ); +function adjustCSS( elem, prop, valueParts, tween ) { + var adjusted, + scale = 1, + maxIterations = 20, + currentValue = tween ? + function() { return tween.cur(); } : + function() { return jQuery.css( elem, prop, "" ); }, + initial = currentValue(), + unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } + // Starting value computation is required for potential unit mismatches + initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && + rcssNum.exec( jQuery.css( elem, prop ) ); - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } + if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } + // Trust units reported by jQuery.css + unit = unit || initialInUnit[ 3 ]; - // Nullify elem to prevent memory leaks in IE - elem = null; - }, + // Make sure we update the tween properties later on + valueParts = valueParts || []; - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - var j, handleObj, tmp, - origCount, t, events, - special, handlers, type, - namespaces, origType, - elemData = jQuery.hasData( elem ) && jQuery._data( elem ); + // Iteratively approximate from a nonzero starting point + initialInUnit = +initial || 1; - if ( !elemData || !(events = elemData.events) ) { - return; - } + do { - // Once for each type.namespace in types; type may be omitted - types = ( types || "" ).match( core_rnotwhite ) || [""]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[t] ) || []; - type = origType = tmp[1]; - namespaces = ( tmp[2] || "" ).split( "." ).sort(); + // If previous iteration zeroed out, double until we get *something*. + // Use string for doubling so we don't accidentally see scale as unchanged below + scale = scale || ".5"; - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector ? special.delegateType : special.bindType ) || type; - handlers = events[ type ] || []; - tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); + // Adjust and apply + initialInUnit = initialInUnit / scale; + jQuery.style( elem, prop, initialInUnit + unit ); - // Remove matching events - origCount = j = handlers.length; - while ( j-- ) { - handleObj = handlers[ j ]; + // Update scale, tolerating zero or NaN from tween.cur() + // Break the loop if scale is unchanged or perfect, or if we've just had enough. + } while ( + scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations + ); + } - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !tmp || tmp.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { - handlers.splice( j, 1 ); + if ( valueParts ) { + initialInUnit = +initialInUnit || +initial || 0; - if ( handleObj.selector ) { - handlers.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } + // Apply relative offset (+=/-=) if specified + adjusted = valueParts[ 1 ] ? + initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : + +valueParts[ 2 ]; + if ( tween ) { + tween.unit = unit; + tween.start = initialInUnit; + tween.end = adjusted; + } + } + return adjusted; +} +var rcheckableType = ( /^(?:checkbox|radio)$/i ); - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( origCount && !handlers.length ) { - if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } +var rtagName = ( /<([\w:-]+)/ ); - delete events[ type ]; - } - } +var rscriptType = ( /^$|\/(?:java|ecma)script/i ); - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - delete elemData.handle; - // removeData also checks for emptiness and clears the expando if empty - // so use it instead of delete - jQuery._removeData( elem, "events" ); - } - }, - trigger: function( event, data, elem, onlyHandlers ) { - var handle, ontype, cur, - bubbleType, special, tmp, i, - eventPath = [ elem || document ], - type = core_hasOwn.call( event, "type" ) ? event.type : event, - namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; +// We have to close these tags to support XHTML (#13200) +var wrapMap = { - cur = tmp = elem = elem || document; + // Support: IE9 + option: [ 1, "" ], - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } + // XHTML parsers do not magically insert elements in the + // same way that tag soup parsers do. So we cannot shorten + // this by omitting or other required elements. + thead: [ 1, "", "
" ], + col: [ 2, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } + _default: [ 0, "", "" ] +}; - if ( type.indexOf(".") >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - ontype = type.indexOf(":") < 0 && "on" + type; +// Support: IE9 +wrapMap.optgroup = wrapMap.option; - // Caller can pass in a jQuery.Event object, Object, or just an event type string - event = event[ jQuery.expando ] ? - event : - new jQuery.Event( type, typeof event === "object" && event ); +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; - // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) - event.isTrigger = onlyHandlers ? 2 : 3; - event.namespace = namespaces.join("."); - event.namespace_re = event.namespace ? - new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : - null; - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } +function getAll( context, tag ) { - // Clone any incoming data and prepend the event, creating the handler arg list - data = data == null ? - [ event ] : - jQuery.makeArray( data, [ event ] ); + // Support: IE9-11+ + // Use typeof to avoid zero-argument method invocation on host objects (#15151) + var ret = typeof context.getElementsByTagName !== "undefined" ? + context.getElementsByTagName( tag || "*" ) : + typeof context.querySelectorAll !== "undefined" ? + context.querySelectorAll( tag || "*" ) : + []; - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], ret ) : + ret; +} - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { - bubbleType = special.delegateType || type; - if ( !rfocusMorph.test( bubbleType + type ) ) { - cur = cur.parentNode; - } - for ( ; cur; cur = cur.parentNode ) { - eventPath.push( cur ); - tmp = cur; - } +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( tmp === (elem.ownerDocument || document) ) { - eventPath.push( tmp.defaultView || tmp.parentWindow || window ); - } - } + for ( ; i < l; i++ ) { + dataPriv.set( + elems[ i ], + "globalEval", + !refElements || dataPriv.get( refElements[ i ], "globalEval" ) + ); + } +} - // Fire handlers on the event path - i = 0; - while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { - event.type = i > 1 ? - bubbleType : - special.bindType || type; +var rhtml = /<|&#?\w+;/; - // jQuery handler - handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } +function buildFragment( elems, context, scripts, selection, ignored ) { + var elem, tmp, tag, wrap, contains, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; - // Native handler - handle = ontype && cur[ ontype ]; - if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { - event.preventDefault(); - } - } - event.type = type; + for ( ; i < l; i++ ) { + elem = elems[ i ]; - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { + if ( elem || elem === 0 ) { - if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && - jQuery.acceptData( elem ) ) { + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { - // Call a native DOM method on the target with the same name name as the event. - // Can't use an .isFunction() check here because IE6/7 fails that test. - // Don't do default actions on window, that's where global variables be (#6170) - if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { + // Support: Android<4.1, PhantomJS<2 + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); - // Don't re-trigger an onFOO event when we call its FOO() method - tmp = elem[ ontype ]; + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); - if ( tmp ) { - elem[ ontype ] = null; - } + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - try { - elem[ type ](); - } catch ( e ) { - // IE<9 dies on focus/blur to hidden element (#1486,#12518) - // only reproducible on winXP IE8 native, not IE9 in IE8 mode - } - jQuery.event.triggered = undefined; + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; - if ( tmp ) { - elem[ ontype ] = tmp; - } + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; } + + // Support: Android<4.1, PhantomJS<2 + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (#12392) + tmp.textContent = ""; } } + } - return event.result; - }, + // Remove wrapper from fragment + fragment.textContent = ""; - dispatch: function( event ) { + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( event ); + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } + continue; + } - var i, ret, handleObj, matched, j, - handlerQueue = [], - args = core_slice.call( arguments ), - handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], - special = jQuery.event.special[ event.type ] || {}; + contains = jQuery.contains( elem.ownerDocument, elem ); - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[0] = event; - event.delegateTarget = this; + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); } - // Determine handlers - handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } - // Run delegates first; they may want to stop propagation beneath us - i = 0; - while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { - event.currentTarget = matched.elem; + return fragment; +} - j = 0; - while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { - // Triggered event must either 1) have no namespace, or - // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). - if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { +( function() { + var fragment = document.createDocumentFragment(), + div = fragment.appendChild( document.createElement( "div" ) ), + input = document.createElement( "input" ); - event.handleObj = handleObj; - event.data = handleObj.data; + // Support: Android 4.0-4.3, Safari<=5.1 + // Check state lost if the name is set (#11217) + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (#14901) + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); - ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) - .apply( matched.elem, args ); + div.appendChild( input ); - if ( ret !== undefined ) { - if ( (event.result = ret) === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } + // Support: Safari<=5.1, Android<4.2 + // Older WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } + // Support: IE<=11+ + // Make sure textarea (and checkbox) defaultValue is properly cloned + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; +} )(); - return event.result; - }, - handlers: function( event, handlers ) { - var sel, handleObj, matches, i, - handlerQueue = [], - delegateCount = handlers.delegateCount, - cur = event.target; +var + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)/; - // Find delegate handlers - // Black-hole SVG instance trees (#13180) - // Avoid non-left-click bubbling in Firefox (#3861) - if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { +function returnTrue() { + return true; +} - /* jshint eqeqeq: false */ - for ( ; cur != this; cur = cur.parentNode || this ) { - /* jshint eqeqeq: true */ +function returnFalse() { + return false; +} - // Don't check non-elements (#13208) - // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) - if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { - matches = []; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; +// Support: IE9 +// See #13393 for more info +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} - // Don't conflict with Object.prototype properties (#13203) - sel = handleObj.selector + " "; +function on( elem, types, selector, data, fn, one ) { + var origFn, type; - if ( matches[ sel ] === undefined ) { - matches[ sel ] = handleObj.needsContext ? - jQuery( sel, this ).index( cur ) >= 0 : - jQuery.find( sel, this, null, [ cur ] ).length; - } - if ( matches[ sel ] ) { - matches.push( handleObj ); - } - } - if ( matches.length ) { - handlerQueue.push({ elem: cur, handlers: matches }); - } - } - } - } + // Types can be a map of types/handlers + if ( typeof types === "object" ) { - // Add the remaining (directly-bound) handlers - if ( delegateCount < handlers.length ) { - handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + + // ( types-Object, data ) + data = data || selector; + selector = undefined; } + for ( type in types ) { + on( elem, type, selector, data, types[ type ], one ); + } + return elem; + } - return handlerQueue; - }, + if ( data == null && fn == null ) { - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { - // Create a writable copy of the event object and normalize some properties - var i, prop, copy, - type = event.type, - originalEvent = event, - fixHook = this.fixHooks[ type ]; + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { - if ( !fixHook ) { - this.fixHooks[ type ] = fixHook = - rmouseEvent.test( type ) ? this.mouseHooks : - rkeyEvent.test( type ) ? this.keyHooks : - {}; + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; } - copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return elem; + } - event = new jQuery.Event( originalEvent ); + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { - i = copy.length; - while ( i-- ) { - prop = copy[ i ]; - event[ prop ] = originalEvent[ prop ]; - } + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; - // Support: IE<9 - // Fix target property (#1925) - if ( !event.target ) { - event.target = originalEvent.srcElement || document; - } + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return elem.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + } ); +} - // Support: Chrome 23+, Safari? - // Target should not be a text node (#504, #13143) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { - // Support: IE<9 - // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) - event.metaKey = !!event.metaKey; + global: {}, - return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; - }, + add: function( elem, types, handler, data, selector ) { - // Includes some event props shared by KeyEvent and MouseEvent - props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.get( elem ); - fixHooks: {}, + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } - keyHooks: { - props: "char charCode key keyCode".split(" "), - filter: function( event, original ) { + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } - // Add which for key events - if ( event.which == null ) { - event.which = original.charCode != null ? original.charCode : original.keyCode; - } + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } - return event; + // Init the element's event structure and main handler, if this is the first + if ( !( events = elemData.events ) ) { + events = elemData.events = {}; } - }, + if ( !( eventHandle = elemData.handle ) ) { + eventHandle = elemData.handle = function( e ) { - mouseHooks: { - props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), - filter: function( event, original ) { - var body, eventDoc, doc, - button = original.button, - fromElement = original.fromElement; + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && original.clientX != null ) { - eventDoc = event.target.ownerDocument || document; - doc = eventDoc.documentElement; - body = eventDoc.body; + // Handle multiple events separated by a space + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - 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 ); + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; } - // Add relatedTarget, if necessary - if ( !event.relatedTarget && fromElement ) { - event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; - } + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && button !== undefined ) { - event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); - } + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; - return event; - } - }, + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; - special: { - load: { - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - focus: { - // Fire native event if possible so blur/focus sequence is correct - trigger: function() { - if ( this !== safeActiveElement() && this.focus ) { - try { - this.focus(); - return false; - } catch ( e ) { - // Support: IE<9 - // If we error on focus to hidden element (#1486, #12518), - // let .trigger() run the handlers + // handleObj is passed to all event handlers + handleObj = jQuery.extend( { + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join( "." ) + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !( handlers = events[ type ] ) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || + special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle ); } } - }, - delegateType: "focusin" - }, - blur: { - trigger: function() { - if ( this === safeActiveElement() && this.blur ) { - this.blur(); - return false; - } - }, - delegateType: "focusout" - }, - click: { - // For checkbox, fire native event so checked state will be right - trigger: function() { - if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { - this.click(); - return false; - } - }, - - // For cross-browser consistency, don't fire native .click() on links - _default: function( event ) { - return jQuery.nodeName( event.target, "a" ); } - }, - beforeunload: { - postDispatch: function( event ) { + if ( special.add ) { + special.add.call( elem, handleObj ); - // Even when returnValue equals to undefined Firefox will still show alert - if ( event.result !== undefined ) { - event.originalEvent.returnValue = event.result; + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; } } - } - }, - simulate: function( type, elem, event, bubble ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - var e = jQuery.extend( - new jQuery.Event(), - event, - { - type: type, - isSimulated: true, - originalEvent: {} + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); } - ); - if ( bubble ) { - jQuery.event.trigger( e, null, elem ); - } else { - jQuery.event.dispatch.call( elem, e ); - } - if ( e.isDefaultPrevented() ) { - event.preventDefault(); - } - } -}; -jQuery.removeEvent = document.removeEventListener ? - function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; } - } : - function( elem, type, handle ) { - var name = "on" + type; - if ( elem.detachEvent ) { + }, - // #8545, #7054, preventing memory leaks for custom events in IE6-8 - // detachEvent needed property on element, by name of that event, to properly expose it to GC - if ( typeof elem[ name ] === core_strundefined ) { - elem[ name ] = null; - } + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { - elem.detachEvent( name, handle ); - } - }; + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); -jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !(this instanceof jQuery.Event) ) { - return new jQuery.Event( src, props ); - } + if ( !elemData || !( events = elemData.events ) ) { + return; + } - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || - src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } - // Event type - } else { - this.type = src; - } + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[ 2 ] && + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || + selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); - // Mark it as fixed - this[ jQuery.expando ] = true; -}; + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse, + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || + special.teardown.call( elem, namespaces, elemData.handle ) === false ) { - preventDefault: function() { - var e = this.originalEvent; + jQuery.removeEvent( elem, type, elemData.handle ); + } - this.isDefaultPrevented = returnTrue; - if ( !e ) { - return; + delete events[ type ]; + } } - // If preventDefault exists, run it on the original event - if ( e.preventDefault ) { - e.preventDefault(); - - // Support: IE - // Otherwise set the returnValue property of the original event to false - } else { - e.returnValue = false; + // Remove data and the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + dataPriv.remove( elem, "handle events" ); } }, - stopPropagation: function() { - var e = this.originalEvent; - this.isPropagationStopped = returnTrue; - if ( !e ) { - return; - } - // If stopPropagation exists, run it on the original event - if ( e.stopPropagation ) { - e.stopPropagation(); - } + dispatch: function( event ) { - // Support: IE - // Set the cancelBubble property of the original event to true - e.cancelBubble = true; - }, - stopImmediatePropagation: function() { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - } -}; + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); -// Create mouseenter/leave events using mouseover/out and event-time checks -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, + var i, j, ret, matched, handleObj, + handlerQueue = [], + args = slice.call( arguments ), + handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; - handle: function( event ) { - var ret, - target = this, - related = event.relatedTarget, - handleObj = event.handleObj; + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + event.delegateTarget = this; - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !jQuery.contains( target, related )) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; } - }; -}); -// IE submit delegation -if ( !jQuery.support.submitBubbles ) { + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); - jQuery.event.special.submit = { - setup: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; - // Lazy-add a submit handler when a descendant form may potentially be submitted - jQuery.event.add( this, "click._submit keypress._submit", function( e ) { - // Node name check avoids a VML-related crash in IE (#9807) - var elem = e.target, - form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; - if ( form && !jQuery._data( form, "submitBubbles" ) ) { - jQuery.event.add( form, "submit._submit", function( event ) { - event._submit_bubble = true; - }); - jQuery._data( form, "submitBubbles", true ); - } - }); - // return undefined since we don't need an event listener - }, + j = 0; + while ( ( handleObj = matched.handlers[ j++ ] ) && + !event.isImmediatePropagationStopped() ) { - postDispatch: function( event ) { - // If form was submitted by the user, bubble the event up the tree - if ( event._submit_bubble ) { - delete event._submit_bubble; - if ( this.parentNode && !event.isTrigger ) { - jQuery.event.simulate( "submit", this.parentNode, event, true ); - } - } - }, + // Triggered event must either 1) have no namespace, or 2) have namespace(s) + // a subset or equal to those in the bound event (both can have no namespace). + if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { - teardown: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || + handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( ( event.result = ret ) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } } + } - // Remove delegated handlers; cleanData eventually reaps submit handlers attached above - jQuery.event.remove( this, "._submit" ); + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); } - }; -} -// IE change delegation and checkbox/radio fix -if ( !jQuery.support.changeBubbles ) { + return event.result; + }, + + handlers: function( event, handlers ) { + var i, matches, sel, handleObj, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Support (at least): Chrome, IE9 + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // + // Support: Firefox<=42+ + // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343) + if ( delegateCount && cur.nodeType && + ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { - jQuery.event.special.change = { + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; - setup: function() { + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; - if ( rformElems.test( this.nodeName ) ) { - // IE doesn't fire change on a check/radio until blur; trigger it on click - // after a propertychange. Eat the blur-change in special.change.handle. - // This still fires onchange a second time for check/radio after blur. - if ( this.type === "checkbox" || this.type === "radio" ) { - jQuery.event.add( this, "propertychange._change", function( event ) { - if ( event.originalEvent.propertyName === "checked" ) { - this._just_changed = true; + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; } - }); - jQuery.event.add( this, "click._change", function( event ) { - if ( this._just_changed && !event.isTrigger ) { - this._just_changed = false; + if ( matches[ sel ] ) { + matches.push( handleObj ); } - // Allow triggered, simulated change events (#11500) - jQuery.event.simulate( "change", this, event, true ); - }); + } + if ( matches.length ) { + handlerQueue.push( { elem: cur, handlers: matches } ); + } } - return false; } - // Delegated event; lazy-add a change handler on descendant inputs - jQuery.event.add( this, "beforeactivate._change", function( e ) { - var elem = e.target; - - if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { - jQuery.event.add( elem, "change._change", function( event ) { - if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { - jQuery.event.simulate( "change", this.parentNode, event, true ); - } - }); - jQuery._data( elem, "changeBubbles", true ); - } - }); - }, - - handle: function( event ) { - var elem = event.target; + } - // Swallow native change events from checkbox/radio, we already triggered them above - if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { - return event.handleObj.handler.apply( this, arguments ); - } - }, + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } ); + } - teardown: function() { - jQuery.event.remove( this, "._change" ); + return handlerQueue; + }, - return !rformElems.test( this.nodeName ); - } - }; -} + // Includes some event props shared by KeyEvent and MouseEvent + props: ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " + + "metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ), -// Create "bubbling" focus and blur events -if ( !jQuery.support.focusinBubbles ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + fixHooks: {}, - // Attach a single capturing handler while someone wants focusin/focusout - var attaches = 0, - handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); - }; + keyHooks: { + props: "char charCode key keyCode".split( " " ), + filter: function( event, original ) { - jQuery.event.special[ fix ] = { - setup: function() { - if ( attaches++ === 0 ) { - document.addEventListener( orig, handler, true ); - } - }, - teardown: function() { - if ( --attaches === 0 ) { - document.removeEventListener( orig, handler, true ); - } + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; } - }; - }); -} -jQuery.fn.extend({ + return event; + } + }, - on: function( types, selector, data, fn, /*INTERNAL*/ one ) { - var type, origFn; + mouseHooks: { + props: ( "button buttons clientX clientY offsetX offsetY pageX pageY " + + "screenX screenY toElement" ).split( " " ), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button; - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - this.on( type, selector, data, types[ type ], one ); - } - return this; - } + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; - if ( data == null && fn == null ) { - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; + 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 ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return this; - } - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return this.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - }); - }, - one: function( types, selector, data, fn ) { - return this.on( types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - var handleObj, type; - if ( types && types.preventDefault && types.handleObj ) { - // ( event ) dispatched jQuery.Event - handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - // ( types-object [, selector] ) - for ( type in types ) { - this.off( type, selector, types[ type ] ); + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } - return this; - } - if ( selector === false || typeof selector === "function" ) { - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; + + return event; } - return this.each(function() { - jQuery.event.remove( this, types, fn, selector ); - }); }, - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - triggerHandler: function( type, data ) { - var elem = this[0]; - if ( elem ) { - return jQuery.event.trigger( type, data, elem, true ); + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; } - } -}); -var isSimple = /^.[^:#\[\.,]*$/, - rparentsprev = /^(?:parents|prev(?:Until|All))/, - rneedsContext = jQuery.expr.match.needsContext, - // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; -jQuery.fn.extend({ - find: function( selector ) { - var i, - ret = [], - self = this, - len = self.length; + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; - if ( typeof selector !== "string" ) { - return this.pushStack( jQuery( selector ).filter(function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - }) ); + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; - for ( i = 0; i < len; i++ ) { - jQuery.find( selector, self[ i ], ret ); + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; } - // Needed because $( selector, context ) becomes $( context ).find( selector ) - ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); - ret.selector = this.selector ? this.selector + " " + selector : selector; - return ret; - }, + // Support: Cordova 2.5 (WebKit) (#13255) + // All events should have a target; Cordova deviceready doesn't + if ( !event.target ) { + event.target = document; + } - has: function( target ) { - var i, - targets = jQuery( target, this ), - len = targets.length; + // Support: Safari 6.0+, Chrome<28 + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } - return this.filter(function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, - not: function( selector ) { - return this.pushStack( winnow(this, selector || [], true) ); - }, - - filter: function( selector ) { - return this.pushStack( winnow(this, selector || [], false) ); - }, + special: { + load: { - is: function( selector ) { - return !!winnow( - this, + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { - // If this is a positional/relative selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - typeof selector === "string" && rneedsContext.test( selector ) ? - jQuery( selector ) : - selector || [], - false - ).length; - }, + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + this.focus(); + return false; + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { - closest: function( selectors, context ) { - var cur, - i = 0, - l = this.length, - ret = [], - pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { + this.click(); + return false; + } + }, - for ( ; i < l; i++ ) { - for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { - // Always skip document fragments - if ( cur.nodeType < 11 && (pos ? - pos.index(cur) > -1 : + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return jQuery.nodeName( event.target, "a" ); + } + }, - // Don't pass non-elements to Sizzle - cur.nodeType === 1 && - jQuery.find.matchesSelector(cur, selectors)) ) { + beforeunload: { + postDispatch: function( event ) { - cur = ret.push( cur ); - break; + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; } } } + } +}; - return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); - }, +jQuery.removeEvent = function( elem, type, handle ) { - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle ); + } +}; - // No argument, return index in parent - if ( !elem ) { - return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; - } +jQuery.Event = function( src, props ) { - // index in selector - if ( typeof elem === "string" ) { - return jQuery.inArray( this[0], jQuery( elem ) ); - } + // Allow instantiation without the 'new' keyword + if ( !( this instanceof jQuery.Event ) ) { + return new jQuery.Event( src, props ); + } - // Locate the position of the desired element - return jQuery.inArray( - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem, this ); - }, + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; - 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 ); + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && - return this.pushStack( jQuery.unique(all) ); - }, + // Support: Android<4.0 + src.returnValue === false ? + returnTrue : + returnFalse; - addBack: function( selector ) { - return this.add( selector == null ? - this.prevObject : this.prevObject.filter(selector) - ); + // Event type + } else { + this.type = src; } -}); - -function sibling( cur, dir ) { - do { - cur = cur[ dir ]; - } while ( cur && cur.nodeType !== 1 ); - return cur; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return sibling( elem, "nextSibling" ); - }, - prev: function( elem ) { - return sibling( elem, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return jQuery.nodeName( elem, "iframe" ) ? - elem.contentDocument || elem.contentWindow.document : - jQuery.merge( [], elem.childNodes ); + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var ret = jQuery.map( this, fn, until ); - - if ( name.slice( -5 ) !== "Until" ) { - selector = until; - } - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); - if ( this.length > 1 ) { - // Remove duplicates - if ( !guaranteedUnique[ name ] ) { - ret = jQuery.unique( ret ); - } + // Mark it as fixed + this[ jQuery.expando ] = true; +}; - // Reverse order for parents* and prev-derivatives - if ( rparentsprev.test( name ) ) { - ret = ret.reverse(); - } - } +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + constructor: jQuery.Event, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, - return this.pushStack( ret ); - }; -}); + preventDefault: function() { + var e = this.originalEvent; -jQuery.extend({ - filter: function( expr, elems, not ) { - var elem = elems[ 0 ]; + this.isDefaultPrevented = returnTrue; - if ( not ) { - expr = ":not(" + expr + ")"; + if ( e ) { + e.preventDefault(); } - - return elems.length === 1 && elem.nodeType === 1 ? - jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : - jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { - return elem.nodeType === 1; - })); }, + stopPropagation: function() { + var e = this.originalEvent; - dir: function( elem, dir, until ) { - var matched = [], - cur = elem[ dir ]; + this.isPropagationStopped = returnTrue; - while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { - if ( cur.nodeType === 1 ) { - matched.push( cur ); - } - cur = cur[dir]; + if ( e ) { + e.stopPropagation(); } - return matched; }, + stopImmediatePropagation: function() { + var e = this.originalEvent; - sibling: function( n, elem ) { - var r = []; + this.isImmediatePropagationStopped = returnTrue; - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - r.push( n ); - } + if ( e ) { + e.stopImmediatePropagation(); } - return r; + this.stopPropagation(); } -}); +}; -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, not ) { - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep( elements, function( elem, i ) { - /* jshint -W018 */ - return !!qualifier.call( elem, i, elem ) !== not; - }); +// Create mouseenter/leave events using mouseover/out and event-time checks +// so that event delegation works in jQuery. +// Do the same for pointerenter/pointerleave and pointerover/pointerout +// +// Support: Safari 7 only +// Safari sends mouseenter too often; see: +// https://code.google.com/p/chromium/issues/detail?id=470258 +// for the description of the bug (it existed in older Chrome versions as well). +jQuery.each( { + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, - } + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; - if ( qualifier.nodeType ) { - return jQuery.grep( elements, function( elem ) { - return ( elem === qualifier ) !== not; - }); + // For mouseenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +} ); - } +jQuery.fn.extend( { + on: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn ); + }, + one: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { - if ( typeof qualifier === "string" ) { - if ( isSimple.test( qualifier ) ) { - return jQuery.filter( qualifier, elements, not ); + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? + handleObj.origType + "." + handleObj.namespace : + handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; } + if ( typeof types === "object" ) { - qualifier = jQuery.filter( qualifier, elements ); - } + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { - return jQuery.grep( elements, function( elem ) { - return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; - }); -} -function createSafeFragment( document ) { - var list = nodeNames.split( "|" ), - safeFrag = document.createDocumentFragment(); - - if ( safeFrag.createElement ) { - while ( list.length ) { - safeFrag.createElement( - list.pop() - ); + // ( types [, fn] ) + fn = selector; + selector = undefined; } + if ( fn === false ) { + fn = returnFalse; + } + return this.each( function() { + jQuery.event.remove( this, types, fn, selector ); + } ); } - return safeFrag; -} +} ); + + +var + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi, + + // Support: IE 10-11, Edge 10240+ + // In IE/Edge using regex groups here causes severe slowdowns. + // See https://connect.microsoft.com/IE/feedback/details/1736512/ + rnoInnerhtml = /]", "i"), - rleadingWhitespace = /^\s+/, - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, - rtagName = /<([\w:]+)/, - rtbody = /\s*$/g, - - // We have to close these tags to support XHTML (#13200) - wrapMap = { - option: [ 1, "" ], - legend: [ 1, "
", "
" ], - area: [ 1, "", "" ], - param: [ 1, "", "" ], - thead: [ 1, "", "
" ], - tr: [ 2, "", "
" ], - col: [ 2, "", "
" ], - td: [ 3, "", "
" ], - - // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, - // unless wrapped in a div with non-breaking characters in front of it. - _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
", "
" ] - }, - safeFragment = createSafeFragment( document ), - fragmentDiv = safeFragment.appendChild( document.createElement("div") ); + rcleanScript = /^\s*\s*$/g; -wrapMap.optgroup = wrapMap.option; -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; +// Manipulating tables requires a tbody +function manipulationTarget( elem, content ) { + return jQuery.nodeName( elem, "table" ) && + jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? + + elem.getElementsByTagName( "tbody" )[ 0 ] || + elem.appendChild( elem.ownerDocument.createElement( "tbody" ) ) : + elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + + if ( match ) { + elem.type = match[ 1 ]; + } else { + elem.removeAttribute( "type" ); + } + + return elem; +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( dataPriv.hasData( src ) ) { + pdataOld = dataPriv.access( src ); + pdataCur = dataPriv.set( dest, pdataOld ); + events = pdataOld.events; + + if ( events ) { + delete pdataCur.handle; + pdataCur.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( dataUser.hasData( src ) ) { + udataOld = dataUser.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + dataUser.set( dest, udataCur ); + } +} + +// Fix IE bugs, see support tests +function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +function domManip( collection, args, callback, ignored ) { + + // Flatten any nested arrays + args = concat.apply( [], args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = collection.length, + iNoClone = l - 1, + value = args[ 0 ], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return collection.each( function( index ) { + var self = collection.eq( index ); + if ( isFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + domManip( self, args, callback, ignored ); + } ); + } + + if ( l ) { + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item + // instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + + // Support: Android<4.1, PhantomJS<2 + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( collection[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !dataPriv.access( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { + + if ( node.src ) { + + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl ) { + jQuery._evalUrl( node.src ); + } + } else { + jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); + } + } + } + } + } + } + + return collection; +} + +function remove( elem, selector, keepData ) { + var node, + nodes = selector ? jQuery.filter( selector, elem ) : elem, + i = 0; + + for ( ; ( node = nodes[ i ] ) != null; i++ ) { + if ( !keepData && node.nodeType === 1 ) { + jQuery.cleanData( getAll( node ) ); + } + + if ( node.parentNode ) { + if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { + setGlobalEval( getAll( node, "script" ) ); + } + node.parentNode.removeChild( node ); + } + } + + return elem; +} + +jQuery.extend( { + htmlPrefilter: function( html ) { + return html.replace( rxhtmlTag, "<$1>" ); + }, + + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = jQuery.contains( elem.ownerDocument, elem ); + + // Fix IE cloning issues + if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && + !jQuery.isXMLDoc( elem ) ) { + + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], destElements[ i ] ); + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + cleanData: function( elems ) { + var data, elem, type, + special = jQuery.event.special, + i = 0; + + for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { + if ( acceptData( elem ) ) { + if ( ( data = elem[ dataPriv.expando ] ) ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Support: Chrome <= 35-45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataPriv.expando ] = undefined; + } + if ( elem[ dataUser.expando ] ) { + + // Support: Chrome <= 35-45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataUser.expando ] = undefined; + } + } + } + } +} ); + +jQuery.fn.extend( { + + // Keep domManip exposed until 3.0 (gh-2225) + domManip: domManip, + + detach: function( selector ) { + return remove( this, selector, true ); + }, + + remove: function( selector ) { + return remove( this, selector ); + }, -jQuery.fn.extend({ text: function( value ) { - return jQuery.access( this, function( value ) { + return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : - this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); + this.empty().each( function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + } ); }, null, value, arguments.length ); }, append: function() { - return this.domManip( arguments, function( elem ) { + return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } - }); + } ); }, prepend: function() { - return this.domManip( arguments, function( elem ) { + return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } - }); + } ); }, before: function() { - return this.domManip( arguments, function( elem ) { + return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } - }); + } ); }, after: function() { - return this.domManip( arguments, function( elem ) { + return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } - }); - }, - - // keepData is for internal use only--do not document - remove: function( selector, keepData ) { - var elem, - elems = selector ? jQuery.filter( selector, this ) : this, - i = 0; - - for ( ; (elem = elems[i]) != null; i++ ) { - - if ( !keepData && elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem ) ); - } - - if ( elem.parentNode ) { - if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { - setGlobalEval( getAll( elem, "script" ) ); - } - elem.parentNode.removeChild( elem ); - } - } - - return this; + } ); }, empty: function() { var elem, i = 0; - for ( ; (elem = this[i]) != null; i++ ) { - // Remove element nodes and prevent memory leaks + for ( ; ( elem = this[ i ] ) != null; i++ ) { if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - } - // Remove any remaining nodes - while ( elem.firstChild ) { - elem.removeChild( elem.firstChild ); - } + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); - // If this is a select, ensure that it displays empty (#12336) - // Support: IE<9 - if ( elem.options && jQuery.nodeName( elem, "select" ) ) { - elem.options.length = 0; + // Remove any remaining nodes + elem.textContent = ""; } } @@ -6129,35 +5482,32 @@ jQuery.fn.extend({ dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; - return this.map( function () { + return this.map( function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); - }); + } ); }, html: function( value ) { - return jQuery.access( this, function( value ) { - var elem = this[0] || {}, + return access( this, function( value ) { + var elem = this[ 0 ] || {}, i = 0, l = this.length; - if ( value === undefined ) { - return elem.nodeType === 1 ? - elem.innerHTML.replace( rinlinejQuery, "" ) : - undefined; + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && - ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && - ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && - !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { - value = value.replace( rxhtmlTag, "<$1>" ); + value = jQuery.htmlPrefilter( value ); try { - for (; i < l; i++ ) { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + // Remove element nodes and prevent memory leaks - elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; @@ -6167,7 +5517,7 @@ jQuery.fn.extend({ elem = 0; // If using innerHTML throws an exception, use the fallback method - } catch(e) {} + } catch ( e ) {} } if ( elem ) { @@ -6177,670 +5527,488 @@ jQuery.fn.extend({ }, replaceWith: function() { - var - // Snapshot the DOM in case .domManip sweeps something relevant into its fragment - args = jQuery.map( this, function( elem ) { - return [ elem.nextSibling, elem.parentNode ]; - }), - i = 0; + var ignored = []; - // Make the changes, replacing each context element with the new content - this.domManip( arguments, function( elem ) { - var next = args[ i++ ], - parent = args[ i++ ]; + // Make the changes, replacing each non-ignored context element with the new content + return domManip( this, arguments, function( elem ) { + var parent = this.parentNode; - if ( parent ) { - // Don't use the snapshot next if it has moved (#13810) - if ( next && next.parentNode !== parent ) { - next = this.nextSibling; + if ( jQuery.inArray( this, ignored ) < 0 ) { + jQuery.cleanData( getAll( this ) ); + if ( parent ) { + parent.replaceChild( elem, this ); } - jQuery( this ).remove(); - parent.insertBefore( elem, next ); } - // Allow new content to include elements from the context set - }, true ); - // Force removal if there was no new content (e.g., from empty arguments) - return i ? this : this.remove(); - }, - - detach: function( selector ) { - return this.remove( selector, true ); - }, + // Force callback invocation + }, ignored ); + } +} ); - domManip: function( args, callback, allowIntersection ) { +jQuery.each( { + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; - // Flatten any nested arrays - args = core_concat.apply( [], args ); + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); - var first, node, hasScripts, - scripts, doc, fragment, - i = 0, - l = this.length, - set = this, - iNoClone = l - 1, - value = args[0], - isFunction = jQuery.isFunction( value ); - - // We can't cloneNode fragments that contain checked, in WebKit - if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { - return this.each(function( index ) { - var self = set.eq( index ); - if ( isFunction ) { - args[0] = value.call( this, index, self.html() ); - } - self.domManip( args, callback, allowIntersection ); - }); + // Support: QtWebKit + // .get() because push.apply(_, arraylike) throws + push.apply( ret, elems.get() ); } - if ( l ) { - fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); - first = fragment.firstChild; + return this.pushStack( ret ); + }; +} ); + - if ( fragment.childNodes.length === 1 ) { - fragment = first; - } +var iframe, + elemdisplay = { + + // Support: Firefox + // We have to pre-define these values for FF (#10227) + HTML: "block", + BODY: "block" + }; + +/** + * Retrieve the actual display of a element + * @param {String} name nodeName of the element + * @param {Object} doc Document object + */ - if ( first ) { - scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); - hasScripts = scripts.length; +// Called only from within defaultDisplay +function actualDisplay( name, doc ) { + var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), - // Use the original fragment for the last item instead of the first because it can end up - // being emptied incorrectly in certain situations (#8070). - for ( ; i < l; i++ ) { - node = fragment; + display = jQuery.css( elem[ 0 ], "display" ); - if ( i !== iNoClone ) { - node = jQuery.clone( node, true, true ); + // We don't have any data stored on the element, + // so use "detach" method as fast way to get rid of the element + elem.detach(); - // Keep references to cloned scripts for later restoration - if ( hasScripts ) { - jQuery.merge( scripts, getAll( node, "script" ) ); - } - } + return display; +} - callback.call( this[i], node, i ); - } +/** + * Try to determine the default display value of an element + * @param {String} nodeName + */ +function defaultDisplay( nodeName ) { + var doc = document, + display = elemdisplay[ nodeName ]; - if ( hasScripts ) { - doc = scripts[ scripts.length - 1 ].ownerDocument; + if ( !display ) { + display = actualDisplay( nodeName, doc ); - // Reenable scripts - jQuery.map( scripts, restoreScript ); + // If the simple way fails, read from inside an iframe + if ( display === "none" || !display ) { - // Evaluate executable scripts on first document insertion - for ( i = 0; i < hasScripts; i++ ) { - node = scripts[ i ]; - if ( rscriptType.test( node.type || "" ) && - !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { + // Use the already-created iframe if possible + iframe = ( iframe || jQuery( "