target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
app/src/common/LoadingModal.js
skunkmb/Ablo
import React, { Component } from 'react'; import { Text, View, ViewPropTypes, Image, Modal } from 'react-native'; import PropTypes from 'prop-types'; import { darkTheme } from '../themes.js'; import Spinner from 'react-native-spinkit'; let styles = darkTheme.styleSheet; let styleOptions = darkTheme.options; let abloA = require('../res/ablo-a.png'); export default class LoadingModal extends Component { render() { return ( <Modal visible={this.props.visible} transparent={true} > <View style={styles.loadingModalContainer}> <View style={styles.loadingModalView}> <Spinner color={styleOptions.loadingModalSpinnerColor} size={styleOptions.loadingModalSpinnerSize} type={styleOptions.loadingModalSpinnerType} /> <Text style={styles.loadingModalText}> {(this.props.text || 'Loading') + '…'} </Text> </View> </View> </Modal> ); } } LoadingModal.propTypes = { visible: PropTypes.bool, text: PropTypes.string, };
files/babel/5.4.1/browser-polyfill.js
Teino1978-Corp/Teino1978-Corp-jsdelivr
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ (function (global){ "use strict"; require("core-js/shim"); require("regenerator/runtime"); if (global._babelPolyfill) { throw new Error("only one instance of babel/polyfill is allowed"); } global._babelPolyfill = true; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"core-js/shim":78,"regenerator/runtime":79}],2:[function(require,module,exports){ 'use strict'; // false -> Array#indexOf // true -> Array#includes var $ = require('./$'); module.exports = function(IS_INCLUDES){ return function(el /*, fromIndex = 0 */){ var O = $.toObject(this) , length = $.toLength(O.length) , index = $.toIndex(arguments[1], length) , value; if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index; } return !IS_INCLUDES && -1; }; }; },{"./$":21}],3:[function(require,module,exports){ 'use strict'; // 0 -> Array#forEach // 1 -> Array#map // 2 -> Array#filter // 3 -> Array#some // 4 -> Array#every // 5 -> Array#find // 6 -> Array#findIndex var $ = require('./$') , ctx = require('./$.ctx'); module.exports = function(TYPE){ var IS_MAP = TYPE == 1 , IS_FILTER = TYPE == 2 , IS_SOME = TYPE == 3 , IS_EVERY = TYPE == 4 , IS_FIND_INDEX = TYPE == 6 , NO_HOLES = TYPE == 5 || IS_FIND_INDEX; return function(callbackfn/*, that = undefined */){ var O = Object($.assertDefined(this)) , self = $.ES5Object(O) , f = ctx(callbackfn, arguments[1], 3) , length = $.toLength(self.length) , index = 0 , result = IS_MAP ? Array(length) : IS_FILTER ? [] : undefined , val, res; for(;length > index; index++)if(NO_HOLES || index in self){ val = self[index]; res = f(val, index, O); if(TYPE){ if(IS_MAP)result[index] = res; // map else if(res)switch(TYPE){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(IS_EVERY)return false; // every } } return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; }; }; },{"./$":21,"./$.ctx":11}],4:[function(require,module,exports){ var $ = require('./$'); function assert(condition, msg1, msg2){ if(!condition)throw TypeError(msg2 ? msg1 + msg2 : msg1); } assert.def = $.assertDefined; assert.fn = function(it){ if(!$.isFunction(it))throw TypeError(it + ' is not a function!'); return it; }; assert.obj = function(it){ if(!$.isObject(it))throw TypeError(it + ' is not an object!'); return it; }; assert.inst = function(it, Constructor, name){ if(!(it instanceof Constructor))throw TypeError(name + ": use the 'new' operator!"); return it; }; module.exports = assert; },{"./$":21}],5:[function(require,module,exports){ var $ = require('./$') , enumKeys = require('./$.enum-keys'); // 19.1.2.1 Object.assign(target, source, ...) /* eslint-disable no-unused-vars */ module.exports = Object.assign || function assign(target, source){ /* eslint-enable no-unused-vars */ var T = Object($.assertDefined(target)) , l = arguments.length , i = 1; while(l > i){ var S = $.ES5Object(arguments[i++]) , keys = enumKeys(S) , length = keys.length , j = 0 , key; while(length > j)T[key = keys[j++]] = S[key]; } return T; }; },{"./$":21,"./$.enum-keys":13}],6:[function(require,module,exports){ var $ = require('./$') , TAG = require('./$.wks')('toStringTag') , toString = {}.toString; function cof(it){ return toString.call(it).slice(8, -1); } cof.classof = function(it){ var O, T; return it == undefined ? it === undefined ? 'Undefined' : 'Null' : typeof (T = (O = Object(it))[TAG]) == 'string' ? T : cof(O); }; cof.set = function(it, tag, stat){ if(it && !$.has(it = stat ? it : it.prototype, TAG))$.hide(it, TAG, tag); }; module.exports = cof; },{"./$":21,"./$.wks":32}],7:[function(require,module,exports){ 'use strict'; var $ = require('./$') , ctx = require('./$.ctx') , safe = require('./$.uid').safe , assert = require('./$.assert') , forOf = require('./$.for-of') , step = require('./$.iter').step , has = $.has , set = $.set , isObject = $.isObject , hide = $.hide , isFrozen = Object.isFrozen || $.core.Object.isFrozen , ID = safe('id') , O1 = safe('O1') , LAST = safe('last') , FIRST = safe('first') , ITER = safe('iter') , SIZE = $.DESC ? safe('size') : 'size' , id = 0; function fastKey(it, create){ // return primitive with prefix if(!isObject(it))return (typeof it == 'string' ? 'S' : 'P') + it; // can't set id to frozen object if(isFrozen(it))return 'F'; if(!has(it, ID)){ // not necessary to add id if(!create)return 'E'; // add missing object id hide(it, ID, ++id); // return object id with prefix } return 'O' + it[ID]; } function getEntry(that, key){ // fast case var index = fastKey(key), entry; if(index != 'F')return that[O1][index]; // frozen object case for(entry = that[FIRST]; entry; entry = entry.n){ if(entry.k == key)return entry; } } module.exports = { getConstructor: function(NAME, IS_MAP, ADDER){ function C(){ var that = assert.inst(this, C, NAME) , iterable = arguments[0]; set(that, O1, $.create(null)); set(that, SIZE, 0); set(that, LAST, undefined); set(that, FIRST, undefined); if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); } $.mix(C.prototype, { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function clear(){ for(var that = this, data = that[O1], entry = that[FIRST]; entry; entry = entry.n){ entry.r = true; if(entry.p)entry.p = entry.p.n = undefined; delete data[entry.i]; } that[FIRST] = that[LAST] = undefined; that[SIZE] = 0; }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var that = this , entry = getEntry(that, key); if(entry){ var next = entry.n , prev = entry.p; delete that[O1][entry.i]; entry.r = true; if(prev)prev.n = next; if(next)next.p = prev; if(that[FIRST] == entry)that[FIRST] = next; if(that[LAST] == entry)that[LAST] = prev; that[SIZE]--; } return !!entry; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function forEach(callbackfn /*, that = undefined */){ var f = ctx(callbackfn, arguments[1], 3) , entry; while(entry = entry ? entry.n : this[FIRST]){ f(entry.v, entry.k, this); // revert to the last existing entry while(entry && entry.r)entry = entry.p; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function has(key){ return !!getEntry(this, key); } }); if($.DESC)$.setDesc(C.prototype, 'size', { get: function(){ return assert.def(this[SIZE]); } }); return C; }, def: function(that, key, value){ var entry = getEntry(that, key) , prev, index; // change existing entry if(entry){ entry.v = value; // create new entry } else { that[LAST] = entry = { i: index = fastKey(key, true), // <- index k: key, // <- key v: value, // <- value p: prev = that[LAST], // <- previous entry n: undefined, // <- next entry r: false // <- removed }; if(!that[FIRST])that[FIRST] = entry; if(prev)prev.n = entry; that[SIZE]++; // add to index if(index != 'F')that[O1][index] = entry; } return that; }, getEntry: getEntry, // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 setIter: function(C, NAME, IS_MAP){ require('./$.iter-define')(C, NAME, function(iterated, kind){ set(this, ITER, {o: iterated, k: kind}); }, function(){ var iter = this[ITER] , kind = iter.k , entry = iter.l; // revert to the last existing entry while(entry && entry.r)entry = entry.p; // get next entry if(!iter.o || !(iter.l = entry = entry ? entry.n : iter.o[FIRST])){ // or finish the iteration iter.o = undefined; return step(1); } // return step by kind if(kind == 'keys' )return step(0, entry.k); if(kind == 'values')return step(0, entry.v); return step(0, [entry.k, entry.v]); }, IS_MAP ? 'entries' : 'values' , !IS_MAP, true); } }; },{"./$":21,"./$.assert":4,"./$.ctx":11,"./$.for-of":14,"./$.iter":20,"./$.iter-define":18,"./$.uid":30}],8:[function(require,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $def = require('./$.def') , forOf = require('./$.for-of'); module.exports = function(NAME){ $def($def.P, NAME, { toJSON: function toJSON(){ var arr = []; forOf(this, false, arr.push, arr); return arr; } }); }; },{"./$.def":12,"./$.for-of":14}],9:[function(require,module,exports){ 'use strict'; var $ = require('./$') , safe = require('./$.uid').safe , assert = require('./$.assert') , forOf = require('./$.for-of') , _has = $.has , isObject = $.isObject , hide = $.hide , isFrozen = Object.isFrozen || $.core.Object.isFrozen , id = 0 , ID = safe('id') , WEAK = safe('weak') , LEAK = safe('leak') , method = require('./$.array-methods') , find = method(5) , findIndex = method(6); function findFrozen(store, key){ return find.call(store.array, function(it){ return it[0] === key; }); } // fallback for frozen keys function leakStore(that){ return that[LEAK] || hide(that, LEAK, { array: [], get: function(key){ var entry = findFrozen(this, key); if(entry)return entry[1]; }, has: function(key){ return !!findFrozen(this, key); }, set: function(key, value){ var entry = findFrozen(this, key); if(entry)entry[1] = value; else this.array.push([key, value]); }, 'delete': function(key){ var index = findIndex.call(this.array, function(it){ return it[0] === key; }); if(~index)this.array.splice(index, 1); return !!~index; } })[LEAK]; } module.exports = { getConstructor: function(NAME, IS_MAP, ADDER){ function C(){ $.set(assert.inst(this, C, NAME), ID, id++); var iterable = arguments[0]; if(iterable != undefined)forOf(iterable, IS_MAP, this[ADDER], this); } $.mix(C.prototype, { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function(key){ if(!isObject(key))return false; if(isFrozen(key))return leakStore(this)['delete'](key); return _has(key, WEAK) && _has(key[WEAK], this[ID]) && delete key[WEAK][this[ID]]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: function has(key){ if(!isObject(key))return false; if(isFrozen(key))return leakStore(this).has(key); return _has(key, WEAK) && _has(key[WEAK], this[ID]); } }); return C; }, def: function(that, key, value){ if(isFrozen(assert.obj(key))){ leakStore(that).set(key, value); } else { _has(key, WEAK) || hide(key, WEAK, {}); key[WEAK][that[ID]] = value; } return that; }, leakStore: leakStore, WEAK: WEAK, ID: ID }; },{"./$":21,"./$.array-methods":3,"./$.assert":4,"./$.for-of":14,"./$.uid":30}],10:[function(require,module,exports){ 'use strict'; var $ = require('./$') , $def = require('./$.def') , BUGGY = require('./$.iter').BUGGY , forOf = require('./$.for-of') , species = require('./$.species') , assertInstance = require('./$.assert').inst; module.exports = function(NAME, methods, common, IS_MAP, IS_WEAK){ var Base = $.g[NAME] , C = Base , ADDER = IS_MAP ? 'set' : 'add' , proto = C && C.prototype , O = {}; function fixMethod(KEY, CHAIN){ var method = proto[KEY]; if($.FW)proto[KEY] = function(a, b){ var result = method.call(this, a === 0 ? 0 : a, b); return CHAIN ? this : result; }; } if(!$.isFunction(C) || !(IS_WEAK || !BUGGY && proto.forEach && proto.entries)){ // create collection constructor C = common.getConstructor(NAME, IS_MAP, ADDER); $.mix(C.prototype, methods); } else { var inst = new C , chain = inst[ADDER](IS_WEAK ? {} : -0, 1) , buggyZero; // wrap for init collections from iterable if(!require('./$.iter-detect')(function(iter){ new C(iter); })){ // eslint-disable-line no-new C = function(){ assertInstance(this, C, NAME); var that = new Base , iterable = arguments[0]; if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); return that; }; C.prototype = proto; if($.FW)proto.constructor = C; } IS_WEAK || inst.forEach(function(val, key){ buggyZero = 1 / key === -Infinity; }); // fix converting -0 key to +0 if(buggyZero){ fixMethod('delete'); fixMethod('has'); IS_MAP && fixMethod('get'); } // + fix .add & .set for chaining if(buggyZero || chain !== inst)fixMethod(ADDER, true); } require('./$.cof').set(C, NAME); O[NAME] = C; $def($def.G + $def.W + $def.F * (C != Base), O); species(C); species($.core[NAME]); // for wrapper if(!IS_WEAK)common.setIter(C, NAME, IS_MAP); return C; }; },{"./$":21,"./$.assert":4,"./$.cof":6,"./$.def":12,"./$.for-of":14,"./$.iter":20,"./$.iter-detect":19,"./$.species":27}],11:[function(require,module,exports){ // Optional / simple context binding var assertFunction = require('./$.assert').fn; module.exports = function(fn, that, length){ assertFunction(fn); if(~length && that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; },{"./$.assert":4}],12:[function(require,module,exports){ var $ = require('./$') , global = $.g , core = $.core , isFunction = $.isFunction; function ctx(fn, that){ return function(){ return fn.apply(that, arguments); }; } global.core = core; // type bitmap $def.F = 1; // forced $def.G = 2; // global $def.S = 4; // static $def.P = 8; // proto $def.B = 16; // bind $def.W = 32; // wrap function $def(type, name, source){ var key, own, out, exp , isGlobal = type & $def.G , target = isGlobal ? global : type & $def.S ? global[name] : (global[name] || {}).prototype , exports = isGlobal ? core : core[name] || (core[name] = {}); if(isGlobal)source = name; for(key in source){ // contains in native own = !(type & $def.F) && target && key in target; // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context if(type & $def.B && own)exp = ctx(out, global); else exp = type & $def.P && isFunction(out) ? ctx(Function.call, out) : out; // extend global if(target && !own){ if(isGlobal)target[key] = out; else delete target[key] && $.hide(target, key, out); } // export if(exports[key] != out)$.hide(exports, key, exp); } } module.exports = $def; },{"./$":21}],13:[function(require,module,exports){ var $ = require('./$'); module.exports = function(it){ var keys = $.getKeys(it) , getDesc = $.getDesc , getSymbols = $.getSymbols; if(getSymbols)$.each.call(getSymbols(it), function(key){ if(getDesc(it, key).enumerable)keys.push(key); }); return keys; }; },{"./$":21}],14:[function(require,module,exports){ var ctx = require('./$.ctx') , get = require('./$.iter').get , call = require('./$.iter-call'); module.exports = function(iterable, entries, fn, that){ var iterator = get(iterable) , f = ctx(fn, that, entries ? 2 : 1) , step; while(!(step = iterator.next()).done){ if(call(iterator, f, step.value, entries) === false){ return call.close(iterator); } } }; },{"./$.ctx":11,"./$.iter":20,"./$.iter-call":17}],15:[function(require,module,exports){ module.exports = function($){ $.FW = true; $.path = $.g; return $; }; },{}],16:[function(require,module,exports){ // Fast apply // http://jsperf.lnkit.com/fast-apply/5 module.exports = function(fn, args, that){ var un = that === undefined; switch(args.length){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); case 5: return un ? fn(args[0], args[1], args[2], args[3], args[4]) : fn.call(that, args[0], args[1], args[2], args[3], args[4]); } return fn.apply(that, args); }; },{}],17:[function(require,module,exports){ var assertObject = require('./$.assert').obj; function close(iterator){ var ret = iterator['return']; if(ret !== undefined)assertObject(ret.call(iterator)); } function call(iterator, fn, value, entries){ try { return entries ? fn(assertObject(value)[0], value[1]) : fn(value); } catch(e){ close(iterator); throw e; } } call.close = close; module.exports = call; },{"./$.assert":4}],18:[function(require,module,exports){ var $def = require('./$.def') , $ = require('./$') , cof = require('./$.cof') , $iter = require('./$.iter') , SYMBOL_ITERATOR = require('./$.wks')('iterator') , FF_ITERATOR = '@@iterator' , VALUES = 'values' , Iterators = $iter.Iterators; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCE){ $iter.create(Constructor, NAME, next); function createMethod(kind){ return function(){ return new Constructor(this, kind); }; } var TAG = NAME + ' Iterator' , proto = Base.prototype , _native = proto[SYMBOL_ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , _default = _native || createMethod(DEFAULT) , methods, key; // Fix native if(_native){ var IteratorPrototype = $.getProto(_default.call(new Base)); // Set @@toStringTag to native iterators cof.set(IteratorPrototype, TAG, true); // FF fix if($.FW && $.has(proto, FF_ITERATOR))$iter.set(IteratorPrototype, $.that); } // Define iterator if($.FW)$iter.set(proto, _default); // Plug for library Iterators[NAME] = _default; Iterators[TAG] = $.that; if(DEFAULT){ methods = { keys: IS_SET ? _default : createMethod('keys'), values: DEFAULT == VALUES ? _default : createMethod(VALUES), entries: DEFAULT != VALUES ? _default : createMethod('entries') }; if(FORCE)for(key in methods){ if(!(key in proto))$.hide(proto, key, methods[key]); } else $def($def.P + $def.F * $iter.BUGGY, NAME, methods); } }; },{"./$":21,"./$.cof":6,"./$.def":12,"./$.iter":20,"./$.wks":32}],19:[function(require,module,exports){ var SYMBOL_ITERATOR = require('./$.wks')('iterator') , SAFE_CLOSING = false; try { var riter = [7][SYMBOL_ITERATOR](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } module.exports = function(exec){ if(!SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[SYMBOL_ITERATOR](); iter.next = function(){ safe = true; }; arr[SYMBOL_ITERATOR] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; },{"./$.wks":32}],20:[function(require,module,exports){ 'use strict'; var $ = require('./$') , cof = require('./$.cof') , assertObject = require('./$.assert').obj , SYMBOL_ITERATOR = require('./$.wks')('iterator') , FF_ITERATOR = '@@iterator' , Iterators = {} , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() setIterator(IteratorPrototype, $.that); function setIterator(O, value){ $.hide(O, SYMBOL_ITERATOR, value); // Add iterator for FF iterator protocol if(FF_ITERATOR in [])$.hide(O, FF_ITERATOR, value); } module.exports = { // Safari has buggy iterators w/o `next` BUGGY: 'keys' in [] && !('next' in [].keys()), Iterators: Iterators, step: function(done, value){ return {value: value, done: !!done}; }, is: function(it){ var O = Object(it) , Symbol = $.g.Symbol , SYM = Symbol && Symbol.iterator || FF_ITERATOR; return SYM in O || SYMBOL_ITERATOR in O || $.has(Iterators, cof.classof(O)); }, get: function(it){ var Symbol = $.g.Symbol , ext = it[Symbol && Symbol.iterator || FF_ITERATOR] , getIter = ext || it[SYMBOL_ITERATOR] || Iterators[cof.classof(it)]; return assertObject(getIter.call(it)); }, set: setIterator, create: function(Constructor, NAME, next, proto){ Constructor.prototype = $.create(proto || IteratorPrototype, {next: $.desc(1, next)}); cof.set(Constructor, NAME + ' Iterator'); } }; },{"./$":21,"./$.assert":4,"./$.cof":6,"./$.wks":32}],21:[function(require,module,exports){ 'use strict'; var global = typeof self != 'undefined' ? self : Function('return this')() , core = {} , defineProperty = Object.defineProperty , hasOwnProperty = {}.hasOwnProperty , ceil = Math.ceil , floor = Math.floor , max = Math.max , min = Math.min; // The engine works fine with descriptors? Thank's IE8 for his funny defineProperty. var DESC = !!function(){ try { return defineProperty({}, 'a', {get: function(){ return 2; }}).a == 2; } catch(e){ /* empty */ } }(); var hide = createDefiner(1); // 7.1.4 ToInteger function toInteger(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); } function desc(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; } function simpleSet(object, key, value){ object[key] = value; return object; } function createDefiner(bitmap){ return DESC ? function(object, key, value){ return $.setDesc(object, key, desc(bitmap, value)); } : simpleSet; } function isObject(it){ return it !== null && (typeof it == 'object' || typeof it == 'function'); } function isFunction(it){ return typeof it == 'function'; } function assertDefined(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; } var $ = module.exports = require('./$.fw')({ g: global, core: core, html: global.document && document.documentElement, // http://jsperf.com/core-js-isobject isObject: isObject, isFunction: isFunction, it: function(it){ return it; }, that: function(){ return this; }, // 7.1.4 ToInteger toInteger: toInteger, // 7.1.15 ToLength toLength: function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }, toIndex: function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }, has: function(it, key){ return hasOwnProperty.call(it, key); }, create: Object.create, getProto: Object.getPrototypeOf, DESC: DESC, desc: desc, getDesc: Object.getOwnPropertyDescriptor, setDesc: defineProperty, setDescs: Object.defineProperties, getKeys: Object.keys, getNames: Object.getOwnPropertyNames, getSymbols: Object.getOwnPropertySymbols, assertDefined: assertDefined, // Dummy, fix for not array-like ES3 string in es5 module ES5Object: Object, toObject: function(it){ return $.ES5Object(assertDefined(it)); }, hide: hide, def: createDefiner(0), set: global.Symbol ? simpleSet : hide, mix: function(target, src){ for(var key in src)hide(target, key, src[key]); return target; }, each: [].forEach }); /* eslint-disable no-undef */ if(typeof __e != 'undefined')__e = core; if(typeof __g != 'undefined')__g = global; },{"./$.fw":15}],22:[function(require,module,exports){ var $ = require('./$'); module.exports = function(object, el){ var O = $.toObject(object) , keys = $.getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; },{"./$":21}],23:[function(require,module,exports){ var $ = require('./$') , assertObject = require('./$.assert').obj; module.exports = function ownKeys(it){ assertObject(it); var keys = $.getNames(it) , getSymbols = $.getSymbols; return getSymbols ? keys.concat(getSymbols(it)) : keys; }; },{"./$":21,"./$.assert":4}],24:[function(require,module,exports){ 'use strict'; var $ = require('./$') , invoke = require('./$.invoke') , assertFunction = require('./$.assert').fn; module.exports = function(/* ...pargs */){ var fn = assertFunction(this) , length = arguments.length , pargs = Array(length) , i = 0 , _ = $.path._ , holder = false; while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true; return function(/* ...args */){ var that = this , _length = arguments.length , j = 0, k = 0, args; if(!holder && !_length)return invoke(fn, pargs, that); args = pargs.slice(); if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++]; while(_length > k)args.push(arguments[k++]); return invoke(fn, args, that); }; }; },{"./$":21,"./$.assert":4,"./$.invoke":16}],25:[function(require,module,exports){ 'use strict'; module.exports = function(regExp, replace, isStatic){ var replacer = replace === Object(replace) ? function(part){ return replace[part]; } : replace; return function(it){ return String(isStatic ? it : this).replace(regExp, replacer); }; }; },{}],26:[function(require,module,exports){ // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var $ = require('./$') , assert = require('./$.assert'); function check(O, proto){ assert.obj(O); assert(proto === null || $.isObject(proto), proto, ": can't set as prototype!"); } module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} // eslint-disable-line ? function(buggy, set){ try { set = require('./$.ctx')(Function.call, $.getDesc(Object.prototype, '__proto__').set, 2); set({}, []); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }() : undefined), check: check }; },{"./$":21,"./$.assert":4,"./$.ctx":11}],27:[function(require,module,exports){ var $ = require('./$') , SPECIES = require('./$.wks')('species'); module.exports = function(C){ if($.DESC && !(SPECIES in C))$.setDesc(C, SPECIES, { configurable: true, get: $.that }); }; },{"./$":21,"./$.wks":32}],28:[function(require,module,exports){ 'use strict'; // true -> String#at // false -> String#codePointAt var $ = require('./$'); module.exports = function(TO_STRING){ return function(pos){ var s = String($.assertDefined(this)) , i = $.toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; },{"./$":21}],29:[function(require,module,exports){ 'use strict'; var $ = require('./$') , ctx = require('./$.ctx') , cof = require('./$.cof') , invoke = require('./$.invoke') , global = $.g , isFunction = $.isFunction , html = $.html , document = global.document , process = global.process , setTask = global.setImmediate , clearTask = global.clearImmediate , postMessage = global.postMessage , addEventListener = global.addEventListener , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , ONREADYSTATECHANGE = 'onreadystatechange' , defer, channel, port; function run(){ var id = +this; if($.has(queue, id)){ var fn = queue[id]; delete queue[id]; fn(); } } function listner(event){ run.call(event.data); } // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if(!isFunction(setTask) || !isFunction(clearTask)){ setTask = function(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(isFunction(fn) ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function(id){ delete queue[id]; }; // Node.js 0.8- if(cof(process) == 'process'){ defer = function(id){ process.nextTick(ctx(run, id, 1)); }; // Modern browsers, skip implementation for WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is object } else if(addEventListener && isFunction(postMessage) && !global.importScripts){ defer = function(id){ postMessage(id, '*'); }; addEventListener('message', listner, false); // WebWorkers } else if(isFunction(MessageChannel)){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listner; defer = ctx(port.postMessage, port, 1); // IE8- } else if(document && ONREADYSTATECHANGE in document.createElement('script')){ defer = function(id){ html.appendChild(document.createElement('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function(id){ setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; },{"./$":21,"./$.cof":6,"./$.ctx":11,"./$.invoke":16}],30:[function(require,module,exports){ var sid = 0; function uid(key){ return 'Symbol(' + key + ')_' + (++sid + Math.random()).toString(36); } uid.safe = require('./$').g.Symbol || uid; module.exports = uid; },{"./$":21}],31:[function(require,module,exports){ // 22.1.3.31 Array.prototype[@@unscopables] var $ = require('./$') , UNSCOPABLES = require('./$.wks')('unscopables'); if($.FW && !(UNSCOPABLES in []))$.hide(Array.prototype, UNSCOPABLES, {}); module.exports = function(key){ if($.FW)[][UNSCOPABLES][key] = true; }; },{"./$":21,"./$.wks":32}],32:[function(require,module,exports){ var global = require('./$').g , store = {}; module.exports = function(name){ return store[name] || (store[name] = global.Symbol && global.Symbol[name] || require('./$.uid').safe('Symbol.' + name)); }; },{"./$":21,"./$.uid":30}],33:[function(require,module,exports){ var $ = require('./$') , cof = require('./$.cof') , $def = require('./$.def') , invoke = require('./$.invoke') , arrayMethod = require('./$.array-methods') , IE_PROTO = require('./$.uid').safe('__proto__') , assert = require('./$.assert') , assertObject = assert.obj , ObjectProto = Object.prototype , A = [] , slice = A.slice , indexOf = A.indexOf , classof = cof.classof , has = $.has , defineProperty = $.setDesc , getOwnDescriptor = $.getDesc , defineProperties = $.setDescs , isFunction = $.isFunction , toObject = $.toObject , toLength = $.toLength , IE8_DOM_DEFINE = false; if(!$.DESC){ try { IE8_DOM_DEFINE = defineProperty(document.createElement('div'), 'x', {get: function(){ return 8; }} ).x == 8; } catch(e){ /* empty */ } $.setDesc = function(O, P, Attributes){ if(IE8_DOM_DEFINE)try { return defineProperty(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)assertObject(O)[P] = Attributes.value; return O; }; $.getDesc = function(O, P){ if(IE8_DOM_DEFINE)try { return getOwnDescriptor(O, P); } catch(e){ /* empty */ } if(has(O, P))return $.desc(!ObjectProto.propertyIsEnumerable.call(O, P), O[P]); }; $.setDescs = defineProperties = function(O, Properties){ assertObject(O); var keys = $.getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)$.setDesc(O, P = keys[i++], Properties[P]); return O; }; } $def($def.S + $def.F * !$.DESC, 'Object', { // 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $.getDesc, // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) defineProperty: $.setDesc, // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) defineProperties: defineProperties }); // IE 8- don't enum bug keys var keys1 = ('constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,' + 'toLocaleString,toString,valueOf').split(',') // Additional keys for getOwnPropertyNames , keys2 = keys1.concat('length', 'prototype') , keysLen1 = keys1.length; // Create object with `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = document.createElement('iframe') , i = keysLen1 , gt = '>' , iframeDocument; iframe.style.display = 'none'; $.html.appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write('<script>document.F=Object</script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict.prototype[keys1[i]]; return createDict(); }; function createGetKeys(names, length){ return function(object){ var O = toObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(length > i)if(has(O, key = names[i++])){ ~indexOf.call(result, key) || result.push(key); } return result; }; } function isPrimitive(it){ return !$.isObject(it); } function Empty(){} $def($def.S, 'Object', { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) getPrototypeOf: $.getProto = $.getProto || function(O){ O = Object(assert.def(O)); if(has(O, IE_PROTO))return O[IE_PROTO]; if(isFunction(O.constructor) && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }, // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) getOwnPropertyNames: $.getNames = $.getNames || createGetKeys(keys2, keys2.length, true), // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) create: $.create = $.create || function(O, /*?*/Properties){ var result; if(O !== null){ Empty.prototype = assertObject(O); result = new Empty(); Empty.prototype = null; // add "__proto__" for Object.getPrototypeOf shim result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : defineProperties(result, Properties); }, // 19.1.2.14 / 15.2.3.14 Object.keys(O) keys: $.getKeys = $.getKeys || createGetKeys(keys1, keysLen1, false), // 19.1.2.17 / 15.2.3.8 Object.seal(O) seal: $.it, // <- cap // 19.1.2.5 / 15.2.3.9 Object.freeze(O) freeze: $.it, // <- cap // 19.1.2.15 / 15.2.3.10 Object.preventExtensions(O) preventExtensions: $.it, // <- cap // 19.1.2.13 / 15.2.3.11 Object.isSealed(O) isSealed: isPrimitive, // <- cap // 19.1.2.12 / 15.2.3.12 Object.isFrozen(O) isFrozen: isPrimitive, // <- cap // 19.1.2.11 / 15.2.3.13 Object.isExtensible(O) isExtensible: $.isObject // <- cap }); // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) $def($def.P, 'Function', { bind: function(that /*, args... */){ var fn = assert.fn(this) , partArgs = slice.call(arguments, 1); function bound(/* args... */){ var args = partArgs.concat(slice.call(arguments)); return invoke(fn, args, this instanceof bound ? $.create(fn.prototype) : that); } if(fn.prototype)bound.prototype = fn.prototype; return bound; } }); // Fix for not array-like ES3 string function arrayMethodFix(fn){ return function(){ return fn.apply($.ES5Object(this), arguments); }; } if(!(0 in Object('z') && 'z'[0] == 'z')){ $.ES5Object = function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; } $def($def.P + $def.F * ($.ES5Object != Object), 'Array', { slice: arrayMethodFix(slice), join: arrayMethodFix(A.join) }); // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) $def($def.S, 'Array', { isArray: function(arg){ return cof(arg) == 'Array'; } }); function createArrayReduce(isRight){ return function(callbackfn, memo){ assert.fn(callbackfn); var O = toObject(this) , length = toLength(O.length) , index = isRight ? length - 1 : 0 , i = isRight ? -1 : 1; if(arguments.length < 2)for(;;){ if(index in O){ memo = O[index]; index += i; break; } index += i; assert(isRight ? index >= 0 : length > index, 'Reduce of empty array with no initial value'); } for(;isRight ? index >= 0 : length > index; index += i)if(index in O){ memo = callbackfn(memo, O[index], index, this); } return memo; }; } $def($def.P, 'Array', { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: $.each = $.each || arrayMethod(0), // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: arrayMethod(1), // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: arrayMethod(2), // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: arrayMethod(3), // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: arrayMethod(4), // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: createArrayReduce(false), // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) reduceRight: createArrayReduce(true), // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: indexOf = indexOf || require('./$.array-includes')(false), // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function(el, fromIndex /* = @[*-1] */){ var O = toObject(this) , length = toLength(O.length) , index = length - 1; if(arguments.length > 1)index = Math.min(index, $.toInteger(fromIndex)); if(index < 0)index = toLength(length + index); for(;index >= 0; index--)if(index in O)if(O[index] === el)return index; return -1; } }); // 21.1.3.25 / 15.5.4.20 String.prototype.trim() $def($def.P, 'String', {trim: require('./$.replacer')(/^\s*([\s\S]*\S)?\s*$/, '$1')}); // 20.3.3.1 / 15.9.4.4 Date.now() $def($def.S, 'Date', {now: function(){ return +new Date; }}); function lz(num){ return num > 9 ? num : '0' + num; } // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() // PhantomJS and old webkit had a broken Date implementation. var date = new Date(-5e13 - 1) , brokenDate = !(date.toISOString && date.toISOString() == '0385-07-25T07:06:39.999Z'); $def($def.P + $def.F * brokenDate, 'Date', {toISOString: function(){ if(!isFinite(this))throw RangeError('Invalid time value'); var d = this , y = d.getUTCFullYear() , m = d.getUTCMilliseconds() , s = y < 0 ? '-' : y > 9999 ? '+' : ''; return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; }}); if(classof(function(){ return arguments; }()) == 'Object')cof.classof = function(it){ var tag = classof(it); return tag == 'Object' && isFunction(it.callee) ? 'Arguments' : tag; }; },{"./$":21,"./$.array-includes":2,"./$.array-methods":3,"./$.assert":4,"./$.cof":6,"./$.def":12,"./$.invoke":16,"./$.replacer":25,"./$.uid":30}],34:[function(require,module,exports){ 'use strict'; var $ = require('./$') , $def = require('./$.def') , toIndex = $.toIndex; $def($def.P, 'Array', { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) copyWithin: function copyWithin(target/* = 0 */, start /* = 0, end = @length */){ var O = Object($.assertDefined(this)) , len = $.toLength(O.length) , to = toIndex(target, len) , from = toIndex(start, len) , end = arguments[2] , fin = end === undefined ? len : toIndex(end, len) , count = Math.min(fin - from, len - to) , inc = 1; if(from < to && to < from + count){ inc = -1; from = from + count - 1; to = to + count - 1; } while(count-- > 0){ if(from in O)O[to] = O[from]; else delete O[to]; to += inc; from += inc; } return O; } }); require('./$.unscope')('copyWithin'); },{"./$":21,"./$.def":12,"./$.unscope":31}],35:[function(require,module,exports){ 'use strict'; var $ = require('./$') , $def = require('./$.def') , toIndex = $.toIndex; $def($def.P, 'Array', { // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) fill: function fill(value /*, start = 0, end = @length */){ var O = Object($.assertDefined(this)) , length = $.toLength(O.length) , index = toIndex(arguments[1], length) , end = arguments[2] , endPos = end === undefined ? length : toIndex(end, length); while(endPos > index)O[index++] = value; return O; } }); require('./$.unscope')('fill'); },{"./$":21,"./$.def":12,"./$.unscope":31}],36:[function(require,module,exports){ var $def = require('./$.def'); $def($def.P, 'Array', { // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) findIndex: require('./$.array-methods')(6) }); require('./$.unscope')('findIndex'); },{"./$.array-methods":3,"./$.def":12,"./$.unscope":31}],37:[function(require,module,exports){ var $def = require('./$.def'); $def($def.P, 'Array', { // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) find: require('./$.array-methods')(5) }); require('./$.unscope')('find'); },{"./$.array-methods":3,"./$.def":12,"./$.unscope":31}],38:[function(require,module,exports){ var $ = require('./$') , ctx = require('./$.ctx') , $def = require('./$.def') , $iter = require('./$.iter') , call = require('./$.iter-call'); $def($def.S + $def.F * !require('./$.iter-detect')(function(iter){ Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = Object($.assertDefined(arrayLike)) , mapfn = arguments[1] , mapping = mapfn !== undefined , f = mapping ? ctx(mapfn, arguments[2], 2) : undefined , index = 0 , length, result, step, iterator; if($iter.is(O)){ iterator = $iter.get(O); // strange IE quirks mode bug -> use typeof instead of isFunction result = new (typeof this == 'function' ? this : Array); for(; !(step = iterator.next()).done; index++){ result[index] = mapping ? call(iterator, f, [step.value, index], true) : step.value; } } else { // strange IE quirks mode bug -> use typeof instead of isFunction result = new (typeof this == 'function' ? this : Array)(length = $.toLength(O.length)); for(; length > index; index++){ result[index] = mapping ? f(O[index], index) : O[index]; } } result.length = index; return result; } }); },{"./$":21,"./$.ctx":11,"./$.def":12,"./$.iter":20,"./$.iter-call":17,"./$.iter-detect":19}],39:[function(require,module,exports){ var $ = require('./$') , setUnscope = require('./$.unscope') , ITER = require('./$.uid').safe('iter') , $iter = require('./$.iter') , step = $iter.step , Iterators = $iter.Iterators; // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() require('./$.iter-define')(Array, 'Array', function(iterated, kind){ $.set(this, ITER, {o: $.toObject(iterated), i: 0, k: kind}); // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , kind = iter.k , index = iter.i++; if(!O || index >= O.length){ iter.o = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; setUnscope('keys'); setUnscope('values'); setUnscope('entries'); },{"./$":21,"./$.iter":20,"./$.iter-define":18,"./$.uid":30,"./$.unscope":31}],40:[function(require,module,exports){ var $def = require('./$.def'); $def($def.S, 'Array', { // 22.1.2.3 Array.of( ...items) of: function of(/* ...args */){ var index = 0 , length = arguments.length // strange IE quirks mode bug -> use typeof instead of isFunction , result = new (typeof this == 'function' ? this : Array)(length); while(length > index)result[index] = arguments[index++]; result.length = length; return result; } }); },{"./$.def":12}],41:[function(require,module,exports){ require('./$.species')(Array); },{"./$.species":27}],42:[function(require,module,exports){ 'use strict'; var $ = require('./$') , NAME = 'name' , setDesc = $.setDesc , FunctionProto = Function.prototype; // 19.2.4.2 name NAME in FunctionProto || $.FW && $.DESC && setDesc(FunctionProto, NAME, { configurable: true, get: function(){ var match = String(this).match(/^\s*function ([^ (]*)/) , name = match ? match[1] : ''; $.has(this, NAME) || setDesc(this, NAME, $.desc(5, name)); return name; }, set: function(value){ $.has(this, NAME) || setDesc(this, NAME, $.desc(0, value)); } }); },{"./$":21}],43:[function(require,module,exports){ 'use strict'; var strong = require('./$.collection-strong'); // 23.1 Map Objects require('./$.collection')('Map', { // 23.1.3.6 Map.prototype.get(key) get: function get(key){ var entry = strong.getEntry(this, key); return entry && entry.v; }, // 23.1.3.9 Map.prototype.set(key, value) set: function set(key, value){ return strong.def(this, key === 0 ? 0 : key, value); } }, strong, true); },{"./$.collection":10,"./$.collection-strong":7}],44:[function(require,module,exports){ var Infinity = 1 / 0 , $def = require('./$.def') , E = Math.E , pow = Math.pow , abs = Math.abs , exp = Math.exp , log = Math.log , sqrt = Math.sqrt , ceil = Math.ceil , floor = Math.floor , EPSILON = pow(2, -52) , EPSILON32 = pow(2, -23) , MAX32 = pow(2, 127) * (2 - EPSILON32) , MIN32 = pow(2, -126); function roundTiesToEven(n){ return n + 1 / EPSILON - 1 / EPSILON; } // 20.2.2.28 Math.sign(x) function sign(x){ return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; } // 20.2.2.5 Math.asinh(x) function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : log(x + sqrt(x * x + 1)); } // 20.2.2.14 Math.expm1(x) function expm1(x){ return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : exp(x) - 1; } $def($def.S, 'Math', { // 20.2.2.3 Math.acosh(x) acosh: function acosh(x){ return (x = +x) < 1 ? NaN : isFinite(x) ? log(x / E + sqrt(x + 1) * sqrt(x - 1) / E) + 1 : x; }, // 20.2.2.5 Math.asinh(x) asinh: asinh, // 20.2.2.7 Math.atanh(x) atanh: function atanh(x){ return (x = +x) == 0 ? x : log((1 + x) / (1 - x)) / 2; }, // 20.2.2.9 Math.cbrt(x) cbrt: function cbrt(x){ return sign(x = +x) * pow(abs(x), 1 / 3); }, // 20.2.2.11 Math.clz32(x) clz32: function clz32(x){ return (x >>>= 0) ? 31 - floor(log(x + 0.5) * Math.LOG2E) : 32; }, // 20.2.2.12 Math.cosh(x) cosh: function cosh(x){ return (exp(x = +x) + exp(-x)) / 2; }, // 20.2.2.14 Math.expm1(x) expm1: expm1, // 20.2.2.16 Math.fround(x) fround: function fround(x){ var $abs = abs(x) , $sign = sign(x) , a, result; if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; a = (1 + EPSILON32 / EPSILON) * $abs; result = a - (a - $abs); if(result > MAX32 || result != result)return $sign * Infinity; return $sign * result; }, // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars var sum = 0 , len1 = arguments.length , len2 = len1 , args = Array(len1) , larg = -Infinity , arg; while(len1--){ arg = args[len1] = +arguments[len1]; if(arg == Infinity || arg == -Infinity)return Infinity; if(arg > larg)larg = arg; } larg = arg || 1; while(len2--)sum += pow(args[len2] / larg, 2); return larg * sqrt(sum); }, // 20.2.2.18 Math.imul(x, y) imul: function imul(x, y){ var UInt16 = 0xffff , xn = +x , yn = +y , xl = UInt16 & xn , yl = UInt16 & yn; return 0 | xl * yl + ((UInt16 & xn >>> 16) * yl + xl * (UInt16 & yn >>> 16) << 16 >>> 0); }, // 20.2.2.20 Math.log1p(x) log1p: function log1p(x){ return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : log(1 + x); }, // 20.2.2.21 Math.log10(x) log10: function log10(x){ return log(x) / Math.LN10; }, // 20.2.2.22 Math.log2(x) log2: function log2(x){ return log(x) / Math.LN2; }, // 20.2.2.28 Math.sign(x) sign: sign, // 20.2.2.30 Math.sinh(x) sinh: function sinh(x){ return abs(x = +x) < 1 ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (E / 2); }, // 20.2.2.33 Math.tanh(x) tanh: function tanh(x){ var a = expm1(x = +x) , b = expm1(-x); return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); }, // 20.2.2.34 Math.trunc(x) trunc: function trunc(it){ return (it > 0 ? floor : ceil)(it); } }); },{"./$.def":12}],45:[function(require,module,exports){ 'use strict'; var $ = require('./$') , isObject = $.isObject , isFunction = $.isFunction , NUMBER = 'Number' , Number = $.g[NUMBER] , Base = Number , proto = Number.prototype; function toPrimitive(it){ var fn, val; if(isFunction(fn = it.valueOf) && !isObject(val = fn.call(it)))return val; if(isFunction(fn = it.toString) && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to number"); } function toNumber(it){ if(isObject(it))it = toPrimitive(it); if(typeof it == 'string' && it.length > 2 && it.charCodeAt(0) == 48){ var binary = false; switch(it.charCodeAt(1)){ case 66 : case 98 : binary = true; case 79 : case 111 : return parseInt(it.slice(2), binary ? 2 : 8); } } return +it; } if($.FW && !(Number('0o1') && Number('0b1'))){ Number = function Number(it){ return this instanceof Number ? new Base(toNumber(it)) : toNumber(it); }; $.each.call($.DESC ? $.getNames(Base) : ( // ES3: 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + // ES6 (in case, if modules with ES6 Number statics required before): 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' ).split(','), function(key){ if($.has(Base, key) && !$.has(Number, key)){ $.setDesc(Number, key, $.getDesc(Base, key)); } } ); Number.prototype = proto; proto.constructor = Number; $.hide($.g, NUMBER, Number); } },{"./$":21}],46:[function(require,module,exports){ var $ = require('./$') , $def = require('./$.def') , abs = Math.abs , floor = Math.floor , _isFinite = $.g.isFinite , MAX_SAFE_INTEGER = 0x1fffffffffffff; // pow(2, 53) - 1 == 9007199254740991; function isInteger(it){ return !$.isObject(it) && _isFinite(it) && floor(it) === it; } $def($def.S, 'Number', { // 20.1.2.1 Number.EPSILON EPSILON: Math.pow(2, -52), // 20.1.2.2 Number.isFinite(number) isFinite: function isFinite(it){ return typeof it == 'number' && _isFinite(it); }, // 20.1.2.3 Number.isInteger(number) isInteger: isInteger, // 20.1.2.4 Number.isNaN(number) isNaN: function isNaN(number){ return number != number; }, // 20.1.2.5 Number.isSafeInteger(number) isSafeInteger: function isSafeInteger(number){ return isInteger(number) && abs(number) <= MAX_SAFE_INTEGER; }, // 20.1.2.6 Number.MAX_SAFE_INTEGER MAX_SAFE_INTEGER: MAX_SAFE_INTEGER, // 20.1.2.10 Number.MIN_SAFE_INTEGER MIN_SAFE_INTEGER: -MAX_SAFE_INTEGER, // 20.1.2.12 Number.parseFloat(string) parseFloat: parseFloat, // 20.1.2.13 Number.parseInt(string, radix) parseInt: parseInt }); },{"./$":21,"./$.def":12}],47:[function(require,module,exports){ // 19.1.3.1 Object.assign(target, source) var $def = require('./$.def'); $def($def.S, 'Object', {assign: require('./$.assign')}); },{"./$.assign":5,"./$.def":12}],48:[function(require,module,exports){ // 19.1.3.10 Object.is(value1, value2) var $def = require('./$.def'); $def($def.S, 'Object', { is: function is(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; } }); },{"./$.def":12}],49:[function(require,module,exports){ // 19.1.3.19 Object.setPrototypeOf(O, proto) var $def = require('./$.def'); $def($def.S, 'Object', {setPrototypeOf: require('./$.set-proto').set}); },{"./$.def":12,"./$.set-proto":26}],50:[function(require,module,exports){ var $ = require('./$') , $def = require('./$.def') , isObject = $.isObject , toObject = $.toObject; function wrapObjectMethod(METHOD, MODE){ var fn = ($.core.Object || {})[METHOD] || Object[METHOD] , f = 0 , o = {}; o[METHOD] = MODE == 1 ? function(it){ return isObject(it) ? fn(it) : it; } : MODE == 2 ? function(it){ return isObject(it) ? fn(it) : true; } : MODE == 3 ? function(it){ return isObject(it) ? fn(it) : false; } : MODE == 4 ? function getOwnPropertyDescriptor(it, key){ return fn(toObject(it), key); } : MODE == 5 ? function getPrototypeOf(it){ return fn(Object($.assertDefined(it))); } : function(it){ return fn(toObject(it)); }; try { fn('z'); } catch(e){ f = 1; } $def($def.S + $def.F * f, 'Object', o); } wrapObjectMethod('freeze', 1); wrapObjectMethod('seal', 1); wrapObjectMethod('preventExtensions', 1); wrapObjectMethod('isFrozen', 2); wrapObjectMethod('isSealed', 2); wrapObjectMethod('isExtensible', 3); wrapObjectMethod('getOwnPropertyDescriptor', 4); wrapObjectMethod('getPrototypeOf', 5); wrapObjectMethod('keys'); wrapObjectMethod('getOwnPropertyNames'); },{"./$":21,"./$.def":12}],51:[function(require,module,exports){ 'use strict'; // 19.1.3.6 Object.prototype.toString() var $ = require('./$') , cof = require('./$.cof') , tmp = {}; tmp[require('./$.wks')('toStringTag')] = 'z'; if($.FW && cof(tmp) != 'z')$.hide(Object.prototype, 'toString', function toString(){ return '[object ' + cof.classof(this) + ']'; }); },{"./$":21,"./$.cof":6,"./$.wks":32}],52:[function(require,module,exports){ 'use strict'; var $ = require('./$') , ctx = require('./$.ctx') , cof = require('./$.cof') , $def = require('./$.def') , assert = require('./$.assert') , forOf = require('./$.for-of') , setProto = require('./$.set-proto').set , species = require('./$.species') , SPECIES = require('./$.wks')('species') , RECORD = require('./$.uid').safe('record') , PROMISE = 'Promise' , global = $.g , process = global.process , asap = process && process.nextTick || require('./$.task').set , P = global[PROMISE] , isFunction = $.isFunction , isObject = $.isObject , assertFunction = assert.fn , assertObject = assert.obj , test; var useNative = isFunction(P) && isFunction(P.resolve) && P.resolve(test = new P(function(){})) == test; // actual Firefox has broken subclass support, test that function P2(x){ var self = new P(x); setProto(self, P2.prototype); return self; } if(useNative){ try { // protect against bad/buggy Object.setPrototype setProto(P2, P); P2.prototype = $.create(P.prototype, {constructor: {value: P2}}); if(!(P2.resolve(5).then(function(){}) instanceof P2)){ useNative = false; } } catch(e){ useNative = false; } } // helpers function getConstructor(C){ var S = assertObject(C)[SPECIES]; return S != undefined ? S : C; } function isThenable(it){ var then; if(isObject(it))then = it.then; return isFunction(then) ? then : false; } function notify(record){ var chain = record.c; if(chain.length)asap(function(){ var value = record.v , ok = record.s == 1 , i = 0; while(chain.length > i)!function(react){ var cb = ok ? react.ok : react.fail , ret, then; try { if(cb){ if(!ok)record.h = true; ret = cb === true ? value : cb(value); if(ret === react.P){ react.rej(TypeError('Promise-chain cycle')); } else if(then = isThenable(ret)){ then.call(ret, react.res, react.rej); } else react.res(ret); } else react.rej(value); } catch(err){ react.rej(err); } }(chain[i++]); chain.length = 0; }); } function isUnhandled(promise){ var record = promise[RECORD] , chain = record.a , i = 0 , react; if(record.h)return false; while(chain.length > i){ react = chain[i++]; if(react.fail || !isUnhandled(react.P))return false; } return true; } function $reject(value){ var record = this , promise; if(record.d)return; record.d = true; record = record.r || record; // unwrap record.v = value; record.s = 2; asap(function(){ setTimeout(function(){ if(isUnhandled(promise = record.p)){ if(cof(process) == 'process'){ process.emit('unhandledRejection', value, promise); } else if(global.console && isFunction(console.error)){ console.error('Unhandled promise rejection', value); } } }, 1); }); notify(record); } function $resolve(value){ var record = this , then, wrapper; if(record.d)return; record.d = true; record = record.r || record; // unwrap try { if(then = isThenable(value)){ wrapper = {r: record, d: false}; // wrap then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } else { record.v = value; record.s = 1; notify(record); } } catch(err){ $reject.call(wrapper || {r: record, d: false}, err); // wrap } } // constructor polyfill if(!useNative){ // 25.4.3.1 Promise(executor) P = function Promise(executor){ assertFunction(executor); var record = { p: assert.inst(this, P, PROMISE), // <- promise c: [], // <- awaiting reactions a: [], // <- all reactions s: 0, // <- state d: false, // <- done v: undefined, // <- value h: false // <- handled rejection }; $.hide(this, RECORD, record); try { executor(ctx($resolve, record, 1), ctx($reject, record, 1)); } catch(err){ $reject.call(record, err); } }; $.mix(P.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var S = assertObject(assertObject(this).constructor)[SPECIES]; var react = { ok: isFunction(onFulfilled) ? onFulfilled : true, fail: isFunction(onRejected) ? onRejected : false }; var promise = react.P = new (S != undefined ? S : P)(function(res, rej){ react.res = assertFunction(res); react.rej = assertFunction(rej); }); var record = this[RECORD]; record.a.push(react); record.c.push(react); record.s && notify(record); return promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); } // export $def($def.G + $def.W + $def.F * !useNative, {Promise: P}); cof.set(P, PROMISE); species(P); species($.core[PROMISE]); // for wrapper // statics $def($def.S + $def.F * !useNative, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ return new (getConstructor(this))(function(res, rej){ rej(r); }); }, // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ return isObject(x) && RECORD in x && $.getProto(x) === this.prototype ? x : new (getConstructor(this))(function(res){ res(x); }); } }); $def($def.S + $def.F * !(useNative && require('./$.iter-detect')(function(iter){ P.all(iter)['catch'](function(){}); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = getConstructor(this) , values = []; return new C(function(res, rej){ forOf(iterable, false, values.push, values); var remaining = values.length , results = Array(remaining); if(remaining)$.each.call(values, function(promise, index){ C.resolve(promise).then(function(value){ results[index] = value; --remaining || res(results); }, rej); }); else res(results); }); }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = getConstructor(this); return new C(function(res, rej){ forOf(iterable, false, function(promise){ C.resolve(promise).then(res, rej); }); }); } }); },{"./$":21,"./$.assert":4,"./$.cof":6,"./$.ctx":11,"./$.def":12,"./$.for-of":14,"./$.iter-detect":19,"./$.set-proto":26,"./$.species":27,"./$.task":29,"./$.uid":30,"./$.wks":32}],53:[function(require,module,exports){ var $ = require('./$') , $def = require('./$.def') , setProto = require('./$.set-proto') , $iter = require('./$.iter') , ITER = require('./$.uid').safe('iter') , step = $iter.step , assert = require('./$.assert') , isObject = $.isObject , getDesc = $.getDesc , setDesc = $.setDesc , getProto = $.getProto , apply = Function.apply , assertObject = assert.obj , _isExtensible = Object.isExtensible || $.it; function Enumerate(iterated){ $.set(this, ITER, {o: iterated, k: undefined, i: 0}); } $iter.create(Enumerate, 'Object', function(){ var iter = this[ITER] , keys = iter.k , key; if(keys == undefined){ iter.k = keys = []; for(key in iter.o)keys.push(key); } do { if(iter.i >= keys.length)return step(1); } while(!((key = keys[iter.i++]) in iter.o)); return step(0, key); }); function wrap(fn){ return function(it){ assertObject(it); try { fn.apply(undefined, arguments); return true; } catch(e){ return false; } }; } function get(target, propertyKey/*, receiver*/){ var receiver = arguments.length < 3 ? target : arguments[2] , desc = getDesc(assertObject(target), propertyKey), proto; if(desc)return $.has(desc, 'value') ? desc.value : desc.get === undefined ? undefined : desc.get.call(receiver); return isObject(proto = getProto(target)) ? get(proto, propertyKey, receiver) : undefined; } function set(target, propertyKey, V/*, receiver*/){ var receiver = arguments.length < 4 ? target : arguments[3] , ownDesc = getDesc(assertObject(target), propertyKey) , existingDescriptor, proto; if(!ownDesc){ if(isObject(proto = getProto(target))){ return set(proto, propertyKey, V, receiver); } ownDesc = $.desc(0); } if($.has(ownDesc, 'value')){ if(ownDesc.writable === false || !isObject(receiver))return false; existingDescriptor = getDesc(receiver, propertyKey) || $.desc(0); existingDescriptor.value = V; setDesc(receiver, propertyKey, existingDescriptor); return true; } return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); } var reflect = { // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) apply: require('./$.ctx')(Function.call, apply, 3), // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) construct: function construct(target, argumentsList /*, newTarget*/){ var proto = assert.fn(arguments.length < 3 ? target : arguments[2]).prototype , instance = $.create(isObject(proto) ? proto : Object.prototype) , result = apply.call(target, instance, argumentsList); return isObject(result) ? result : instance; }, // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) defineProperty: wrap(setDesc), // 26.1.4 Reflect.deleteProperty(target, propertyKey) deleteProperty: function deleteProperty(target, propertyKey){ var desc = getDesc(assertObject(target), propertyKey); return desc && !desc.configurable ? false : delete target[propertyKey]; }, // 26.1.5 Reflect.enumerate(target) enumerate: function enumerate(target){ return new Enumerate(assertObject(target)); }, // 26.1.6 Reflect.get(target, propertyKey [, receiver]) get: get, // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){ return getDesc(assertObject(target), propertyKey); }, // 26.1.8 Reflect.getPrototypeOf(target) getPrototypeOf: function getPrototypeOf(target){ return getProto(assertObject(target)); }, // 26.1.9 Reflect.has(target, propertyKey) has: function has(target, propertyKey){ return propertyKey in target; }, // 26.1.10 Reflect.isExtensible(target) isExtensible: function isExtensible(target){ return !!_isExtensible(assertObject(target)); }, // 26.1.11 Reflect.ownKeys(target) ownKeys: require('./$.own-keys'), // 26.1.12 Reflect.preventExtensions(target) preventExtensions: wrap(Object.preventExtensions || $.it), // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) set: set }; // 26.1.14 Reflect.setPrototypeOf(target, proto) if(setProto)reflect.setPrototypeOf = function setPrototypeOf(target, proto){ setProto.check(target, proto); try { setProto.set(target, proto); return true; } catch(e){ return false; } }; $def($def.G, {Reflect: {}}); $def($def.S, 'Reflect', reflect); },{"./$":21,"./$.assert":4,"./$.ctx":11,"./$.def":12,"./$.iter":20,"./$.own-keys":23,"./$.set-proto":26,"./$.uid":30}],54:[function(require,module,exports){ var $ = require('./$') , cof = require('./$.cof') , RegExp = $.g.RegExp , Base = RegExp , proto = RegExp.prototype; function regExpBroken() { try { var a = /a/g; // "new" creates a new object if (a === new RegExp(a)) { return true; } // RegExp allows a regex with flags as the pattern return RegExp(/a/g, 'i') != '/a/i'; } catch(e) { return true; } } if($.FW && $.DESC){ if(regExpBroken()) { RegExp = function RegExp(pattern, flags){ return new Base(cof(pattern) == 'RegExp' ? pattern.source : pattern, flags === undefined ? pattern.flags : flags); }; $.each.call($.getNames(Base), function(key){ key in RegExp || $.setDesc(RegExp, key, { configurable: true, get: function(){ return Base[key]; }, set: function(it){ Base[key] = it; } }); }); proto.constructor = RegExp; RegExp.prototype = proto; $.hide($.g, 'RegExp', RegExp); } // 21.2.5.3 get RegExp.prototype.flags() if(/./g.flags != 'g')$.setDesc(proto, 'flags', { configurable: true, get: require('./$.replacer')(/^.*\/(\w*)$/, '$1') }); } require('./$.species')(RegExp); },{"./$":21,"./$.cof":6,"./$.replacer":25,"./$.species":27}],55:[function(require,module,exports){ 'use strict'; var strong = require('./$.collection-strong'); // 23.2 Set Objects require('./$.collection')('Set', { // 23.2.3.1 Set.prototype.add(value) add: function add(value){ return strong.def(this, value = value === 0 ? 0 : value, value); } }, strong); },{"./$.collection":10,"./$.collection-strong":7}],56:[function(require,module,exports){ var $def = require('./$.def'); $def($def.P, 'String', { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: require('./$.string-at')(false) }); },{"./$.def":12,"./$.string-at":28}],57:[function(require,module,exports){ 'use strict'; var $ = require('./$') , cof = require('./$.cof') , $def = require('./$.def') , toLength = $.toLength; $def($def.P, 'String', { // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) endsWith: function endsWith(searchString /*, endPosition = @length */){ if(cof(searchString) == 'RegExp')throw TypeError(); var that = String($.assertDefined(this)) , endPosition = arguments[1] , len = toLength(that.length) , end = endPosition === undefined ? len : Math.min(toLength(endPosition), len); searchString += ''; return that.slice(end - searchString.length, end) === searchString; } }); },{"./$":21,"./$.cof":6,"./$.def":12}],58:[function(require,module,exports){ var $def = require('./$.def') , toIndex = require('./$').toIndex , fromCharCode = String.fromCharCode; $def($def.S, 'String', { // 21.1.2.2 String.fromCodePoint(...codePoints) fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars var res = [] , len = arguments.length , i = 0 , code; while(len > i){ code = +arguments[i++]; if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point'); res.push(code < 0x10000 ? fromCharCode(code) : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) ); } return res.join(''); } }); },{"./$":21,"./$.def":12}],59:[function(require,module,exports){ 'use strict'; var $ = require('./$') , cof = require('./$.cof') , $def = require('./$.def'); $def($def.P, 'String', { // 21.1.3.7 String.prototype.includes(searchString, position = 0) includes: function includes(searchString /*, position = 0 */){ if(cof(searchString) == 'RegExp')throw TypeError(); return !!~String($.assertDefined(this)).indexOf(searchString, arguments[1]); } }); },{"./$":21,"./$.cof":6,"./$.def":12}],60:[function(require,module,exports){ var set = require('./$').set , at = require('./$.string-at')(true) , ITER = require('./$.uid').safe('iter') , $iter = require('./$.iter') , step = $iter.step; // 21.1.3.27 String.prototype[@@iterator]() require('./$.iter-define')(String, 'String', function(iterated){ set(this, ITER, {o: String(iterated), i: 0}); // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var iter = this[ITER] , O = iter.o , index = iter.i , point; if(index >= O.length)return step(1); point = at.call(O, index); iter.i += point.length; return step(0, point); }); },{"./$":21,"./$.iter":20,"./$.iter-define":18,"./$.string-at":28,"./$.uid":30}],61:[function(require,module,exports){ var $ = require('./$') , $def = require('./$.def'); $def($def.S, 'String', { // 21.1.2.4 String.raw(callSite, ...substitutions) raw: function raw(callSite){ var tpl = $.toObject(callSite.raw) , len = $.toLength(tpl.length) , sln = arguments.length , res = [] , i = 0; while(len > i){ res.push(String(tpl[i++])); if(i < sln)res.push(String(arguments[i])); } return res.join(''); } }); },{"./$":21,"./$.def":12}],62:[function(require,module,exports){ 'use strict'; var $ = require('./$') , $def = require('./$.def'); $def($def.P, 'String', { // 21.1.3.13 String.prototype.repeat(count) repeat: function repeat(count){ var str = String($.assertDefined(this)) , res = '' , n = $.toInteger(count); if(n < 0 || n == Infinity)throw RangeError("Count can't be negative"); for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str; return res; } }); },{"./$":21,"./$.def":12}],63:[function(require,module,exports){ 'use strict'; var $ = require('./$') , cof = require('./$.cof') , $def = require('./$.def'); $def($def.P, 'String', { // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) startsWith: function startsWith(searchString /*, position = 0 */){ if(cof(searchString) == 'RegExp')throw TypeError(); var that = String($.assertDefined(this)) , index = $.toLength(Math.min(arguments[1], that.length)); searchString += ''; return that.slice(index, index + searchString.length) === searchString; } }); },{"./$":21,"./$.cof":6,"./$.def":12}],64:[function(require,module,exports){ 'use strict'; // ECMAScript 6 symbols shim var $ = require('./$') , setTag = require('./$.cof').set , uid = require('./$.uid') , $def = require('./$.def') , keyOf = require('./$.keyof') , enumKeys = require('./$.enum-keys') , assertObject = require('./$.assert').obj , has = $.has , $create = $.create , getDesc = $.getDesc , setDesc = $.setDesc , desc = $.desc , getNames = $.getNames , toObject = $.toObject , Symbol = $.g.Symbol , setter = false , TAG = uid('tag') , HIDDEN = uid('hidden') , SymbolRegistry = {} , AllSymbols = {} , useNative = $.isFunction(Symbol); function wrap(tag){ var sym = AllSymbols[tag] = $.set($create(Symbol.prototype), TAG, tag); $.DESC && setter && setDesc(Object.prototype, tag, { configurable: true, set: function(value){ if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setDesc(this, tag, desc(1, value)); } }); return sym; } function defineProperty(it, key, D){ if(D && has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))setDesc(it, HIDDEN, desc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D.enumerable = false; } } return setDesc(it, key, D); } function defineProperties(it, P){ assertObject(it); var keys = enumKeys(P = toObject(P)) , i = 0 , l = keys.length , key; while(l > i)defineProperty(it, key = keys[i++], P[key]); return it; } function create(it, P){ return P === undefined ? $create(it) : defineProperties($create(it), P); } function getOwnPropertyDescriptor(it, key){ var D = getDesc(it = toObject(it), key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; } function getOwnPropertyNames(it){ var names = getNames(toObject(it)) , result = [] , i = 0 , key; while(names.length > i)if(!has(AllSymbols, key = names[i++]) && key != HIDDEN)result.push(key); return result; } function getOwnPropertySymbols(it){ var names = getNames(toObject(it)) , result = [] , i = 0 , key; while(names.length > i)if(has(AllSymbols, key = names[i++]))result.push(AllSymbols[key]); return result; } // 19.4.1.1 Symbol([description]) if(!useNative){ Symbol = function Symbol(description){ if(this instanceof Symbol)throw TypeError('Symbol is not a constructor'); return wrap(uid(description)); }; $.hide(Symbol.prototype, 'toString', function(){ return this[TAG]; }); $.create = create; $.setDesc = defineProperty; $.getDesc = getOwnPropertyDescriptor; $.setDescs = defineProperties; $.getNames = getOwnPropertyNames; $.getSymbols = getOwnPropertySymbols; } var symbolStatics = { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ return keyOf(SymbolRegistry, key); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }; // 19.4.2.2 Symbol.hasInstance // 19.4.2.3 Symbol.isConcatSpreadable // 19.4.2.4 Symbol.iterator // 19.4.2.6 Symbol.match // 19.4.2.8 Symbol.replace // 19.4.2.9 Symbol.search // 19.4.2.10 Symbol.species // 19.4.2.11 Symbol.split // 19.4.2.12 Symbol.toPrimitive // 19.4.2.13 Symbol.toStringTag // 19.4.2.14 Symbol.unscopables $.each.call(( 'hasInstance,isConcatSpreadable,iterator,match,replace,search,' + 'species,split,toPrimitive,toStringTag,unscopables' ).split(','), function(it){ var sym = require('./$.wks')(it); symbolStatics[it] = useNative ? sym : wrap(sym); } ); setter = true; $def($def.G + $def.W, {Symbol: Symbol}); $def($def.S, 'Symbol', symbolStatics); $def($def.S + $def.F * !useNative, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: getOwnPropertySymbols }); // 19.4.3.5 Symbol.prototype[@@toStringTag] setTag(Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setTag($.g.JSON, 'JSON', true); },{"./$":21,"./$.assert":4,"./$.cof":6,"./$.def":12,"./$.enum-keys":13,"./$.keyof":22,"./$.uid":30,"./$.wks":32}],65:[function(require,module,exports){ 'use strict'; var $ = require('./$') , weak = require('./$.collection-weak') , leakStore = weak.leakStore , ID = weak.ID , WEAK = weak.WEAK , has = $.has , isObject = $.isObject , isFrozen = Object.isFrozen || $.core.Object.isFrozen , tmp = {}; // 23.3 WeakMap Objects var WeakMap = require('./$.collection')('WeakMap', { // 23.3.3.3 WeakMap.prototype.get(key) get: function get(key){ if(isObject(key)){ if(isFrozen(key))return leakStore(this).get(key); if(has(key, WEAK))return key[WEAK][this[ID]]; } }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function set(key, value){ return weak.def(this, key, value); } }, weak, true, true); // IE11 WeakMap frozen keys fix if($.FW && new WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){ $.each.call(['delete', 'has', 'get', 'set'], function(key){ var method = WeakMap.prototype[key]; WeakMap.prototype[key] = function(a, b){ // store frozen objects on leaky map if(isObject(a) && isFrozen(a)){ var result = leakStore(this)[key](a, b); return key == 'set' ? this : result; // store all the rest on native weakmap } return method.call(this, a, b); }; }); } },{"./$":21,"./$.collection":10,"./$.collection-weak":9}],66:[function(require,module,exports){ 'use strict'; var weak = require('./$.collection-weak'); // 23.4 WeakSet Objects require('./$.collection')('WeakSet', { // 23.4.3.1 WeakSet.prototype.add(value) add: function add(value){ return weak.def(this, value, true); } }, weak, false, true); },{"./$.collection":10,"./$.collection-weak":9}],67:[function(require,module,exports){ // https://github.com/domenic/Array.prototype.includes var $def = require('./$.def'); $def($def.P, 'Array', { includes: require('./$.array-includes')(true) }); require('./$.unscope')('includes'); },{"./$.array-includes":2,"./$.def":12,"./$.unscope":31}],68:[function(require,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON require('./$.collection-to-json')('Map'); },{"./$.collection-to-json":8}],69:[function(require,module,exports){ // https://gist.github.com/WebReflection/9353781 var $ = require('./$') , $def = require('./$.def') , ownKeys = require('./$.own-keys'); $def($def.S, 'Object', { getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){ var O = $.toObject(object) , result = {}; $.each.call(ownKeys(O), function(key){ $.setDesc(result, key, $.desc(0, $.getDesc(O, key))); }); return result; } }); },{"./$":21,"./$.def":12,"./$.own-keys":23}],70:[function(require,module,exports){ // http://goo.gl/XkBrjD var $ = require('./$') , $def = require('./$.def'); function createObjectToArray(isEntries){ return function(object){ var O = $.toObject(object) , keys = $.getKeys(O) , length = keys.length , i = 0 , result = Array(length) , key; if(isEntries)while(length > i)result[i] = [key = keys[i++], O[key]]; else while(length > i)result[i] = O[keys[i++]]; return result; }; } $def($def.S, 'Object', { values: createObjectToArray(false), entries: createObjectToArray(true) }); },{"./$":21,"./$.def":12}],71:[function(require,module,exports){ // https://gist.github.com/kangax/9698100 var $def = require('./$.def'); $def($def.S, 'RegExp', { escape: require('./$.replacer')(/([\\\-[\]{}()*+?.,^$|])/g, '\\$1', true) }); },{"./$.def":12,"./$.replacer":25}],72:[function(require,module,exports){ // https://github.com/DavidBruant/Map-Set.prototype.toJSON require('./$.collection-to-json')('Set'); },{"./$.collection-to-json":8}],73:[function(require,module,exports){ // https://github.com/mathiasbynens/String.prototype.at var $def = require('./$.def'); $def($def.P, 'String', { at: require('./$.string-at')(true) }); },{"./$.def":12,"./$.string-at":28}],74:[function(require,module,exports){ // JavaScript 1.6 / Strawman array statics shim var $ = require('./$') , $def = require('./$.def') , $Array = $.core.Array || Array , statics = {}; function setStatics(keys, length){ $.each.call(keys.split(','), function(key){ if(length == undefined && key in $Array)statics[key] = $Array[key]; else if(key in [])statics[key] = require('./$.ctx')(Function.call, [][key], length); }); } setStatics('pop,reverse,shift,keys,values,entries', 1); setStatics('indexOf,every,some,forEach,map,filter,find,findIndex,includes', 3); setStatics('join,slice,concat,push,splice,unshift,sort,lastIndexOf,' + 'reduce,reduceRight,copyWithin,fill,turn'); $def($def.S, 'Array', statics); },{"./$":21,"./$.ctx":11,"./$.def":12}],75:[function(require,module,exports){ require('./es6.array.iterator'); var $ = require('./$') , Iterators = require('./$.iter').Iterators , ITERATOR = require('./$.wks')('iterator') , ArrayValues = Iterators.Array , NodeList = $.g.NodeList; if($.FW && NodeList && !(ITERATOR in NodeList.prototype)){ $.hide(NodeList.prototype, ITERATOR, ArrayValues); } Iterators.NodeList = ArrayValues; },{"./$":21,"./$.iter":20,"./$.wks":32,"./es6.array.iterator":39}],76:[function(require,module,exports){ var $def = require('./$.def') , $task = require('./$.task'); $def($def.G + $def.B, { setImmediate: $task.set, clearImmediate: $task.clear }); },{"./$.def":12,"./$.task":29}],77:[function(require,module,exports){ // ie9- setTimeout & setInterval additional parameters fix var $ = require('./$') , $def = require('./$.def') , invoke = require('./$.invoke') , partial = require('./$.partial') , navigator = $.g.navigator , MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check function wrap(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke( partial, [].slice.call(arguments, 2), $.isFunction(fn) ? fn : Function(fn) ), time); } : set; } $def($def.G + $def.B + $def.F * MSIE, { setTimeout: wrap($.g.setTimeout), setInterval: wrap($.g.setInterval) }); },{"./$":21,"./$.def":12,"./$.invoke":16,"./$.partial":24}],78:[function(require,module,exports){ require('./modules/es5'); require('./modules/es6.symbol'); require('./modules/es6.object.assign'); require('./modules/es6.object.is'); require('./modules/es6.object.set-prototype-of'); require('./modules/es6.object.to-string'); require('./modules/es6.object.statics-accept-primitives'); require('./modules/es6.function.name'); require('./modules/es6.number.constructor'); require('./modules/es6.number.statics'); require('./modules/es6.math'); require('./modules/es6.string.from-code-point'); require('./modules/es6.string.raw'); require('./modules/es6.string.iterator'); require('./modules/es6.string.code-point-at'); require('./modules/es6.string.ends-with'); require('./modules/es6.string.includes'); require('./modules/es6.string.repeat'); require('./modules/es6.string.starts-with'); require('./modules/es6.array.from'); require('./modules/es6.array.of'); require('./modules/es6.array.iterator'); require('./modules/es6.array.species'); require('./modules/es6.array.copy-within'); require('./modules/es6.array.fill'); require('./modules/es6.array.find'); require('./modules/es6.array.find-index'); require('./modules/es6.regexp'); require('./modules/es6.promise'); require('./modules/es6.map'); require('./modules/es6.set'); require('./modules/es6.weak-map'); require('./modules/es6.weak-set'); require('./modules/es6.reflect'); require('./modules/es7.array.includes'); require('./modules/es7.string.at'); require('./modules/es7.regexp.escape'); require('./modules/es7.object.get-own-property-descriptors'); require('./modules/es7.object.to-array'); require('./modules/es7.map.to-json'); require('./modules/es7.set.to-json'); require('./modules/js.array.statics'); require('./modules/web.timers'); require('./modules/web.immediate'); require('./modules/web.dom.iterable'); module.exports = require('./modules/$').core; },{"./modules/$":21,"./modules/es5":33,"./modules/es6.array.copy-within":34,"./modules/es6.array.fill":35,"./modules/es6.array.find":37,"./modules/es6.array.find-index":36,"./modules/es6.array.from":38,"./modules/es6.array.iterator":39,"./modules/es6.array.of":40,"./modules/es6.array.species":41,"./modules/es6.function.name":42,"./modules/es6.map":43,"./modules/es6.math":44,"./modules/es6.number.constructor":45,"./modules/es6.number.statics":46,"./modules/es6.object.assign":47,"./modules/es6.object.is":48,"./modules/es6.object.set-prototype-of":49,"./modules/es6.object.statics-accept-primitives":50,"./modules/es6.object.to-string":51,"./modules/es6.promise":52,"./modules/es6.reflect":53,"./modules/es6.regexp":54,"./modules/es6.set":55,"./modules/es6.string.code-point-at":56,"./modules/es6.string.ends-with":57,"./modules/es6.string.from-code-point":58,"./modules/es6.string.includes":59,"./modules/es6.string.iterator":60,"./modules/es6.string.raw":61,"./modules/es6.string.repeat":62,"./modules/es6.string.starts-with":63,"./modules/es6.symbol":64,"./modules/es6.weak-map":65,"./modules/es6.weak-set":66,"./modules/es7.array.includes":67,"./modules/es7.map.to-json":68,"./modules/es7.object.get-own-property-descriptors":69,"./modules/es7.object.to-array":70,"./modules/es7.regexp.escape":71,"./modules/es7.set.to-json":72,"./modules/es7.string.at":73,"./modules/js.array.statics":74,"./modules/web.dom.iterable":75,"./modules/web.immediate":76,"./modules/web.timers":77}],79:[function(require,module,exports){ (function (global){ /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ !(function(global) { "use strict"; var hasOwn = Object.prototype.hasOwnProperty; var undefined; // More compressible than void 0. var iteratorSymbol = typeof Symbol === "function" && Symbol.iterator || "@@iterator"; var inModule = typeof module === "object"; var runtime = global.regeneratorRuntime; if (runtime) { if (inModule) { // If regeneratorRuntime is defined globally and we're in a module, // make the exports object identical to regeneratorRuntime. module.exports = runtime; } // Don't bother evaluating the rest of this file if the runtime was // already defined globally. return; } // Define the runtime globally (as expected by generated code) as either // module.exports (if we're in a module) or a new, empty object. runtime = global.regeneratorRuntime = inModule ? module.exports : {}; function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided, then outerFn.prototype instanceof Generator. var generator = Object.create((outerFn || Generator).prototype); generator._invoke = makeInvokeMethod( innerFn, self || null, new Context(tryLocsList || []) ); return generator; } runtime.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype; GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunction.displayName = "GeneratorFunction"; runtime.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; runtime.mark = function(genFun) { genFun.__proto__ = GeneratorFunctionPrototype; genFun.prototype = Object.create(Gp); return genFun; }; runtime.async = function(innerFn, outerFn, self, tryLocsList) { return new Promise(function(resolve, reject) { var generator = wrap(innerFn, outerFn, self, tryLocsList); var callNext = step.bind(generator, "next"); var callThrow = step.bind(generator, "throw"); function step(method, arg) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); return; } var info = record.arg; if (info.done) { resolve(info.value); } else { Promise.resolve(info.value).then(callNext, callThrow); } } callNext(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } while (true) { var delegate = context.delegate; if (delegate) { if (method === "return" || (method === "throw" && delegate.iterator[method] === undefined)) { // A return or throw (when the delegate iterator has no throw // method) always terminates the yield* loop. context.delegate = null; // If the delegate iterator has a return method, give it a // chance to clean up. var returnMethod = delegate.iterator["return"]; if (returnMethod) { var record = tryCatch(returnMethod, delegate.iterator, arg); if (record.type === "throw") { // If the return method threw an exception, let that // exception prevail over the original return or throw. method = "throw"; arg = record.arg; continue; } } if (method === "return") { // Continue with the outer return, now that the delegate // iterator has been terminated. continue; } } var record = tryCatch( delegate.iterator[method], delegate.iterator, arg ); if (record.type === "throw") { context.delegate = null; // Like returning generator.throw(uncaught), but without the // overhead of an extra function call. method = "throw"; arg = record.arg; continue; } // Delegate generator ran and handled its own exceptions so // regardless of what the method was, we continue as if it is // "next" with an undefined arg. method = "next"; arg = undefined; var info = record.arg; if (info.done) { context[delegate.resultName] = info.value; context.next = delegate.nextLoc; } else { state = GenStateSuspendedYield; return info; } context.delegate = null; } if (method === "next") { if (state === GenStateSuspendedYield) { context.sent = arg; } else { delete context.sent; } } else if (method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw arg; } if (context.dispatchException(arg)) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. method = "next"; arg = undefined; } } else if (method === "return") { context.abrupt("return", arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; var info = { value: record.arg, done: context.done }; if (record.arg === ContinueSentinel) { if (context.delegate && method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. arg = undefined; } } else { return info; } } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(arg) call above. method = "throw"; arg = record.arg; } } }; } function defineGeneratorMethod(method) { Gp[method] = function(arg) { return this._invoke(method, arg); }; } defineGeneratorMethod("next"); defineGeneratorMethod("throw"); defineGeneratorMethod("return"); Gp[iteratorSymbol] = function() { return this; }; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(); } runtime.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } runtime.values = values; function doneResult() { return { value: undefined, done: true }; } Context.prototype = { constructor: Context, reset: function() { this.prev = 0; this.next = 0; this.sent = undefined; this.done = false; this.delegate = null; this.tryEntries.forEach(resetTryEntry); // Pre-initialize at least 20 temporary variables to enable hidden // class optimizations for simple generators. for (var tempIndex = 0, tempName; hasOwn.call(this, tempName = "t" + tempIndex) || tempIndex < 20; ++tempIndex) { this[tempName] = null; } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; return !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.next = finallyEntry.finallyLoc; } else { this.complete(record); } return ContinueSentinel; }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = record.arg; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { return this.complete(entry.completion, entry.afterLoc); } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; return ContinueSentinel; } }; })( // Among the various tricks for obtaining a reference to the global // object, this seems to be the most reliable technique that does not // use indirect eval (which violates Content Security Policy). typeof global === "object" ? global : typeof window === "object" ? window : typeof self === "object" ? self : this ); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}]},{},[1]);
src/app/routes/ui/containers/icons/Glyphicons.js
backpackcoder/world-in-flames
import React from 'react' import {Stats, BigBreadcrumbs, WidgetGrid, JarvisWidget} from '../../../../components' export default class Glyphicons extends React.Component { state = { search: '' }; shouldComponentUpdate(nextProps, nextState) { if (this.state.search != nextState.search) { let $container = $(this.refs.demoContainer); if (nextState.search) { $("li", $container).hide(); $("li .glyphicon", $container) .filter(function () { var r = new RegExp(nextState.search, 'i'); return r.test($(this).attr('class') + $(this).attr('alt')) }) .closest("li").show(); $(".alert, h2", $container).hide() } else { $("li", $container).show(); $(".alert, h2", $container).show() } } return true } onSearchChange = (value)=> { this.setState({ search: value }) }; render() { return ( <div id="content"> <div className="row"> <BigBreadcrumbs items={['UI Elements', 'Icons', 'Glyph Icons']} icon="fa fa-fw fa-desktop" className="col-xs-12 col-sm-7 col-md-7 col-lg-4"/> <Stats /> </div> {/* widget grid */} <WidgetGrid> <div className="well well-sm"> <div className="input-group"> <input className="form-control input-lg" value={this.state.search} onChange={event => this.onSearchChange(event.target.value)} placeholder="Search for an icon..."/> <span className="input-group-addon"><i className="fa fa-fw fa-lg fa-search"/></span> </div> </div> {/* row */} {/* row */} <div className="row"> {/* NEW WIDGET START */} <article className="col-sm-12"> {/* Widget ID (each widget will need unique ID)*/} <JarvisWidget colorbutton={false} editbutton={false} togglebutton={false} deletebutton={false} color="purple"> <header> <h2>Glyph Icons </h2> </header> {/* widget div*/} <div> {/* widget content */} <div className="widget-body" ref='demoContainer'> <ul className="bs-glyphicons"> <li> <span className="glyphicon glyphicon-adjust"/> <span className="glyphicon-class">.glyphicon .glyphicon-adjust</span> </li> <li> <span className="glyphicon glyphicon-align-center"/> <span className="glyphicon-class">.glyphicon .glyphicon-align-center</span> </li> <li> <span className="glyphicon glyphicon-align-justify"/> <span className="glyphicon-class">.glyphicon .glyphicon-align-justify</span> </li> <li> <span className="glyphicon glyphicon-align-left"/> <span className="glyphicon-class">.glyphicon .glyphicon-align-left</span> </li> <li> <span className="glyphicon glyphicon-align-right"/> <span className="glyphicon-class">.glyphicon .glyphicon-align-right</span> </li> <li> <span className="glyphicon glyphicon-arrow-down"/> <span className="glyphicon-class">.glyphicon .glyphicon-arrow-down</span> </li> <li> <span className="glyphicon glyphicon-arrow-left"/> <span className="glyphicon-class">.glyphicon .glyphicon-arrow-left</span> </li> <li> <span className="glyphicon glyphicon-arrow-right"/> <span className="glyphicon-class">.glyphicon .glyphicon-arrow-right</span> </li> <li> <span className="glyphicon glyphicon-arrow-up"/> <span className="glyphicon-class">.glyphicon .glyphicon-arrow-up</span> </li> <li> <span className="glyphicon glyphicon-asterisk"/> <span className="glyphicon-class">.glyphicon .glyphicon-asterisk</span> </li> <li> <span className="glyphicon glyphicon-backward"/> <span className="glyphicon-class">.glyphicon .glyphicon-backward</span> </li> <li> <span className="glyphicon glyphicon-ban-circle"/> <span className="glyphicon-class">.glyphicon .glyphicon-ban-circle</span> </li> <li> <span className="glyphicon glyphicon-barcode"/> <span className="glyphicon-class">.glyphicon .glyphicon-barcode</span> </li> <li> <span className="glyphicon glyphicon-bell"/> <span className="glyphicon-class">.glyphicon .glyphicon-bell</span> </li> <li> <span className="glyphicon glyphicon-bold"/> <span className="glyphicon-class">.glyphicon .glyphicon-bold</span> </li> <li> <span className="glyphicon glyphicon-book"/> <span className="glyphicon-class">.glyphicon .glyphicon-book</span> </li> <li> <span className="glyphicon glyphicon-bookmark"/> <span className="glyphicon-class">.glyphicon .glyphicon-bookmark</span> </li> <li> <span className="glyphicon glyphicon-briefcase"/> <span className="glyphicon-class">.glyphicon .glyphicon-briefcase</span> </li> <li> <span className="glyphicon glyphicon-bullhorn"/> <span className="glyphicon-class">.glyphicon .glyphicon-bullhorn</span> </li> <li> <span className="glyphicon glyphicon-calendar"/> <span className="glyphicon-class">.glyphicon .glyphicon-calendar</span> </li> <li> <span className="glyphicon glyphicon-camera"/> <span className="glyphicon-class">.glyphicon .glyphicon-camera</span> </li> <li> <span className="glyphicon glyphicon-certificate"/> <span className="glyphicon-class">.glyphicon .glyphicon-certificate</span> </li> <li> <span className="glyphicon glyphicon-check"/> <span className="glyphicon-class">.glyphicon .glyphicon-check</span> </li> <li> <span className="glyphicon glyphicon-chevron-down"/> <span className="glyphicon-class">.glyphicon .glyphicon-chevron-down</span> </li> <li> <span className="glyphicon glyphicon-chevron-left"/> <span className="glyphicon-class">.glyphicon .glyphicon-chevron-left</span> </li> <li> <span className="glyphicon glyphicon-chevron-right"/> <span className="glyphicon-class">.glyphicon .glyphicon-chevron-right</span> </li> <li> <span className="glyphicon glyphicon-chevron-up"/> <span className="glyphicon-class">.glyphicon .glyphicon-chevron-up</span> </li> <li> <span className="glyphicon glyphicon-circle-arrow-down"/> <span className="glyphicon-class">.glyphicon .glyphicon-circle-arrow-down</span> </li> <li> <span className="glyphicon glyphicon-circle-arrow-left"/> <span className="glyphicon-class">.glyphicon .glyphicon-circle-arrow-left</span> </li> <li> <span className="glyphicon glyphicon-circle-arrow-right"/> <span className="glyphicon-class">.glyphicon .glyphicon-circle-arrow-right</span> </li> <li> <span className="glyphicon glyphicon-circle-arrow-up"/> <span className="glyphicon-class">.glyphicon .glyphicon-circle-arrow-up</span> </li> <li> <span className="glyphicon glyphicon-cloud"/> <span className="glyphicon-class">.glyphicon .glyphicon-cloud</span> </li> <li> <span className="glyphicon glyphicon-cloud-download"/> <span className="glyphicon-class">.glyphicon .glyphicon-cloud-download</span> </li> <li> <span className="glyphicon glyphicon-cloud-upload"/> <span className="glyphicon-class">.glyphicon .glyphicon-cloud-upload</span> </li> <li> <span className="glyphicon glyphicon-cog"/> <span className="glyphicon-class">.glyphicon .glyphicon-cog</span> </li> <li> <span className="glyphicon glyphicon-collapse-down"/> <span className="glyphicon-class">.glyphicon .glyphicon-collapse-down</span> </li> <li> <span className="glyphicon glyphicon-collapse-up"/> <span className="glyphicon-class">.glyphicon .glyphicon-collapse-up</span> </li> <li> <span className="glyphicon glyphicon-comment"/> <span className="glyphicon-class">.glyphicon .glyphicon-comment</span> </li> <li> <span className="glyphicon glyphicon-compressed"/> <span className="glyphicon-class">.glyphicon .glyphicon-compressed</span> </li> <li> <span className="glyphicon glyphicon-copyright-mark"/> <span className="glyphicon-class">.glyphicon .glyphicon-copyright-mark</span> </li> <li> <span className="glyphicon glyphicon-credit-card"/> <span className="glyphicon-class">.glyphicon .glyphicon-credit-card</span> </li> <li> <span className="glyphicon glyphicon-cutlery"/> <span className="glyphicon-class">.glyphicon .glyphicon-cutlery</span> </li> <li> <span className="glyphicon glyphicon-dashboard"/> <span className="glyphicon-class">.glyphicon .glyphicon-dashboard</span> </li> <li> <span className="glyphicon glyphicon-download"/> <span className="glyphicon-class">.glyphicon .glyphicon-download</span> </li> <li> <span className="glyphicon glyphicon-download-alt"/> <span className="glyphicon-class">.glyphicon .glyphicon-download-alt</span> </li> <li> <span className="glyphicon glyphicon-earphone"/> <span className="glyphicon-class">.glyphicon .glyphicon-earphone</span> </li> <li> <span className="glyphicon glyphicon-edit"/> <span className="glyphicon-class">.glyphicon .glyphicon-edit</span> </li> <li> <span className="glyphicon glyphicon-eject"/> <span className="glyphicon-class">.glyphicon .glyphicon-eject</span> </li> <li> <span className="glyphicon glyphicon-envelope"/> <span className="glyphicon-class">.glyphicon .glyphicon-envelope</span> </li> <li> <span className="glyphicon glyphicon-euro"/> <span className="glyphicon-class">.glyphicon .glyphicon-euro</span> </li> <li> <span className="glyphicon glyphicon-exclamation-sign"/> <span className="glyphicon-class">.glyphicon .glyphicon-exclamation-sign</span> </li> <li> <span className="glyphicon glyphicon-expand"/> <span className="glyphicon-class">.glyphicon .glyphicon-expand</span> </li> <li> <span className="glyphicon glyphicon-export"/> <span className="glyphicon-class">.glyphicon .glyphicon-export</span> </li> <li> <span className="glyphicon glyphicon-eye-close"/> <span className="glyphicon-class">.glyphicon .glyphicon-eye-close</span> </li> <li> <span className="glyphicon glyphicon-eye-open"/> <span className="glyphicon-class">.glyphicon .glyphicon-eye-open</span> </li> <li> <span className="glyphicon glyphicon-facetime-video"/> <span className="glyphicon-class">.glyphicon .glyphicon-facetime-video</span> </li> <li> <span className="glyphicon glyphicon-fast-backward"/> <span className="glyphicon-class">.glyphicon .glyphicon-fast-backward</span> </li> <li> <span className="glyphicon glyphicon-fast-forward"/> <span className="glyphicon-class">.glyphicon .glyphicon-fast-forward</span> </li> <li> <span className="glyphicon glyphicon-file"/> <span className="glyphicon-class">.glyphicon .glyphicon-file</span> </li> <li> <span className="glyphicon glyphicon-film"/> <span className="glyphicon-class">.glyphicon .glyphicon-film</span> </li> <li> <span className="glyphicon glyphicon-filter"/> <span className="glyphicon-class">.glyphicon .glyphicon-filter</span> </li> <li> <span className="glyphicon glyphicon-fire"/> <span className="glyphicon-class">.glyphicon .glyphicon-fire</span> </li> <li> <span className="glyphicon glyphicon-flag"/> <span className="glyphicon-class">.glyphicon .glyphicon-flag</span> </li> <li> <span className="glyphicon glyphicon-flash"/> <span className="glyphicon-class">.glyphicon .glyphicon-flash</span> </li> <li> <span className="glyphicon glyphicon-floppy-disk"/> <span className="glyphicon-class">.glyphicon .glyphicon-floppy-disk</span> </li> <li> <span className="glyphicon glyphicon-floppy-open"/> <span className="glyphicon-class">.glyphicon .glyphicon-floppy-open</span> </li> <li> <span className="glyphicon glyphicon-floppy-remove"/> <span className="glyphicon-class">.glyphicon .glyphicon-floppy-remove</span> </li> <li> <span className="glyphicon glyphicon-floppy-save"/> <span className="glyphicon-class">.glyphicon .glyphicon-floppy-save</span> </li> <li> <span className="glyphicon glyphicon-floppy-saved"/> <span className="glyphicon-class">.glyphicon .glyphicon-floppy-saved</span> </li> <li> <span className="glyphicon glyphicon-folder-close"/> <span className="glyphicon-class">.glyphicon .glyphicon-folder-close</span> </li> <li> <span className="glyphicon glyphicon-folder-open"/> <span className="glyphicon-class">.glyphicon .glyphicon-folder-open</span> </li> <li> <span className="glyphicon glyphicon-font"/> <span className="glyphicon-class">.glyphicon .glyphicon-font</span> </li> <li> <span className="glyphicon glyphicon-forward"/> <span className="glyphicon-class">.glyphicon .glyphicon-forward</span> </li> <li> <span className="glyphicon glyphicon-fullscreen"/> <span className="glyphicon-class">.glyphicon .glyphicon-fullscreen</span> </li> <li> <span className="glyphicon glyphicon-gbp"/> <span className="glyphicon-class">.glyphicon .glyphicon-gbp</span> </li> <li> <span className="glyphicon glyphicon-gift"/> <span className="glyphicon-class">.glyphicon .glyphicon-gift</span> </li> <li> <span className="glyphicon glyphicon-glass"/> <span className="glyphicon-class">.glyphicon .glyphicon-glass</span> </li> <li> <span className="glyphicon glyphicon-globe"/> <span className="glyphicon-class">.glyphicon .glyphicon-globe</span> </li> <li> <span className="glyphicon glyphicon-hand-down"/> <span className="glyphicon-class">.glyphicon .glyphicon-hand-down</span> </li> <li> <span className="glyphicon glyphicon-hand-left"/> <span className="glyphicon-class">.glyphicon .glyphicon-hand-left</span> </li> <li> <span className="glyphicon glyphicon-hand-right"/> <span className="glyphicon-class">.glyphicon .glyphicon-hand-right</span> </li> <li> <span className="glyphicon glyphicon-hand-up"/> <span className="glyphicon-class">.glyphicon .glyphicon-hand-up</span> </li> <li> <span className="glyphicon glyphicon-hd-video"/> <span className="glyphicon-class">.glyphicon .glyphicon-hd-video</span> </li> <li> <span className="glyphicon glyphicon-hdd"/> <span className="glyphicon-class">.glyphicon .glyphicon-hdd</span> </li> <li> <span className="glyphicon glyphicon-header"/> <span className="glyphicon-class">.glyphicon .glyphicon-header</span> </li> <li> <span className="glyphicon glyphicon-headphones"/> <span className="glyphicon-class">.glyphicon .glyphicon-headphones</span> </li> <li> <span className="glyphicon glyphicon-heart"/> <span className="glyphicon-class">.glyphicon .glyphicon-heart</span> </li> <li> <span className="glyphicon glyphicon-heart-empty"/> <span className="glyphicon-class">.glyphicon .glyphicon-heart-empty</span> </li> <li> <span className="glyphicon glyphicon-home"/> <span className="glyphicon-class">.glyphicon .glyphicon-home</span> </li> <li> <span className="glyphicon glyphicon-import"/> <span className="glyphicon-class">.glyphicon .glyphicon-import</span> </li> <li> <span className="glyphicon glyphicon-inbox"/> <span className="glyphicon-class">.glyphicon .glyphicon-inbox</span> </li> <li> <span className="glyphicon glyphicon-indent-left"/> <span className="glyphicon-class">.glyphicon .glyphicon-indent-left</span> </li> <li> <span className="glyphicon glyphicon-indent-right"/> <span className="glyphicon-class">.glyphicon .glyphicon-indent-right</span> </li> <li> <span className="glyphicon glyphicon-info-sign"/> <span className="glyphicon-class">.glyphicon .glyphicon-info-sign</span> </li> <li> <span className="glyphicon glyphicon-italic"/> <span className="glyphicon-class">.glyphicon .glyphicon-italic</span> </li> <li> <span className="glyphicon glyphicon-leaf"/> <span className="glyphicon-class">.glyphicon .glyphicon-leaf</span> </li> <li> <span className="glyphicon glyphicon-link"/> <span className="glyphicon-class">.glyphicon .glyphicon-link</span> </li> <li> <span className="glyphicon glyphicon-list"/> <span className="glyphicon-class">.glyphicon .glyphicon-list</span> </li> <li> <span className="glyphicon glyphicon-list-alt"/> <span className="glyphicon-class">.glyphicon .glyphicon-list-alt</span> </li> <li> <span className="glyphicon glyphicon-lock"/> <span className="glyphicon-class">.glyphicon .glyphicon-lock</span> </li> <li> <span className="glyphicon glyphicon-log-in"/> <span className="glyphicon-class">.glyphicon .glyphicon-log-in</span> </li> <li> <span className="glyphicon glyphicon-log-out"/> <span className="glyphicon-class">.glyphicon .glyphicon-log-out</span> </li> <li> <span className="glyphicon glyphicon-magnet"/> <span className="glyphicon-class">.glyphicon .glyphicon-magnet</span> </li> <li> <span className="glyphicon glyphicon-map-marker"/> <span className="glyphicon-class">.glyphicon .glyphicon-map-marker</span> </li> <li> <span className="glyphicon glyphicon-minus"/> <span className="glyphicon-class">.glyphicon .glyphicon-minus</span> </li> <li> <span className="glyphicon glyphicon-minus-sign"/> <span className="glyphicon-class">.glyphicon .glyphicon-minus-sign</span> </li> <li> <span className="glyphicon glyphicon-move"/> <span className="glyphicon-class">.glyphicon .glyphicon-move</span> </li> <li> <span className="glyphicon glyphicon-music"/> <span className="glyphicon-class">.glyphicon .glyphicon-music</span> </li> <li> <span className="glyphicon glyphicon-new-window"/> <span className="glyphicon-class">.glyphicon .glyphicon-new-window</span> </li> <li> <span className="glyphicon glyphicon-off"/> <span className="glyphicon-class">.glyphicon .glyphicon-off</span> </li> <li> <span className="glyphicon glyphicon-ok"/> <span className="glyphicon-class">.glyphicon .glyphicon-ok</span> </li> <li> <span className="glyphicon glyphicon-ok-circle"/> <span className="glyphicon-class">.glyphicon .glyphicon-ok-circle</span> </li> <li> <span className="glyphicon glyphicon-ok-sign"/> <span className="glyphicon-class">.glyphicon .glyphicon-ok-sign</span> </li> <li> <span className="glyphicon glyphicon-open"/> <span className="glyphicon-class">.glyphicon .glyphicon-open</span> </li> <li> <span className="glyphicon glyphicon-paperclip"/> <span className="glyphicon-class">.glyphicon .glyphicon-paperclip</span> </li> <li> <span className="glyphicon glyphicon-pause"/> <span className="glyphicon-class">.glyphicon .glyphicon-pause</span> </li> <li> <span className="glyphicon glyphicon-pencil"/> <span className="glyphicon-class">.glyphicon .glyphicon-pencil</span> </li> <li> <span className="glyphicon glyphicon-phone"/> <span className="glyphicon-class">.glyphicon .glyphicon-phone</span> </li> <li> <span className="glyphicon glyphicon-phone-alt"/> <span className="glyphicon-class">.glyphicon .glyphicon-phone-alt</span> </li> <li> <span className="glyphicon glyphicon-picture"/> <span className="glyphicon-class">.glyphicon .glyphicon-picture</span> </li> <li> <span className="glyphicon glyphicon-plane"/> <span className="glyphicon-class">.glyphicon .glyphicon-plane</span> </li> <li> <span className="glyphicon glyphicon-play"/> <span className="glyphicon-class">.glyphicon .glyphicon-play</span> </li> <li> <span className="glyphicon glyphicon-play-circle"/> <span className="glyphicon-class">.glyphicon .glyphicon-play-circle</span> </li> <li> <span className="glyphicon glyphicon-plus"/> <span className="glyphicon-class">.glyphicon .glyphicon-plus</span> </li> <li> <span className="glyphicon glyphicon-plus-sign"/> <span className="glyphicon-class">.glyphicon .glyphicon-plus-sign</span> </li> <li> <span className="glyphicon glyphicon-print"/> <span className="glyphicon-class">.glyphicon .glyphicon-print</span> </li> <li> <span className="glyphicon glyphicon-pushpin"/> <span className="glyphicon-class">.glyphicon .glyphicon-pushpin</span> </li> <li> <span className="glyphicon glyphicon-qrcode"/> <span className="glyphicon-class">.glyphicon .glyphicon-qrcode</span> </li> <li> <span className="glyphicon glyphicon-question-sign"/> <span className="glyphicon-class">.glyphicon .glyphicon-question-sign</span> </li> <li> <span className="glyphicon glyphicon-random"/> <span className="glyphicon-class">.glyphicon .glyphicon-random</span> </li> <li> <span className="glyphicon glyphicon-record"/> <span className="glyphicon-class">.glyphicon .glyphicon-record</span> </li> <li> <span className="glyphicon glyphicon-refresh"/> <span className="glyphicon-class">.glyphicon .glyphicon-refresh</span> </li> <li> <span className="glyphicon glyphicon-registration-mark"/> <span className="glyphicon-class">.glyphicon .glyphicon-registration-mark</span> </li> <li> <span className="glyphicon glyphicon-remove"/> <span className="glyphicon-class">.glyphicon .glyphicon-remove</span> </li> <li> <span className="glyphicon glyphicon-remove-circle"/> <span className="glyphicon-class">.glyphicon .glyphicon-remove-circle</span> </li> <li> <span className="glyphicon glyphicon-remove-sign"/> <span className="glyphicon-class">.glyphicon .glyphicon-remove-sign</span> </li> <li> <span className="glyphicon glyphicon-repeat"/> <span className="glyphicon-class">.glyphicon .glyphicon-repeat</span> </li> <li> <span className="glyphicon glyphicon-resize-full"/> <span className="glyphicon-class">.glyphicon .glyphicon-resize-full</span> </li> <li> <span className="glyphicon glyphicon-resize-horizontal"/> <span className="glyphicon-class">.glyphicon .glyphicon-resize-horizontal</span> </li> <li> <span className="glyphicon glyphicon-resize-small"/> <span className="glyphicon-class">.glyphicon .glyphicon-resize-small</span> </li> <li> <span className="glyphicon glyphicon-resize-vertical"/> <span className="glyphicon-class">.glyphicon .glyphicon-resize-vertical</span> </li> <li> <span className="glyphicon glyphicon-retweet"/> <span className="glyphicon-class">.glyphicon .glyphicon-retweet</span> </li> <li> <span className="glyphicon glyphicon-road"/> <span className="glyphicon-class">.glyphicon .glyphicon-road</span> </li> <li> <span className="glyphicon glyphicon-save"/> <span className="glyphicon-class">.glyphicon .glyphicon-save</span> </li> <li> <span className="glyphicon glyphicon-saved"/> <span className="glyphicon-class">.glyphicon .glyphicon-saved</span> </li> <li> <span className="glyphicon glyphicon-screenshot"/> <span className="glyphicon-class">.glyphicon .glyphicon-screenshot</span> </li> <li> <span className="glyphicon glyphicon-sd-video"/> <span className="glyphicon-class">.glyphicon .glyphicon-sd-video</span> </li> <li> <span className="glyphicon glyphicon-search"/> <span className="glyphicon-class">.glyphicon .glyphicon-search</span> </li> <li> <span className="glyphicon glyphicon-send"/> <span className="glyphicon-class">.glyphicon .glyphicon-send</span> </li> <li> <span className="glyphicon glyphicon-share"/> <span className="glyphicon-class">.glyphicon .glyphicon-share</span> </li> <li> <span className="glyphicon glyphicon-share-alt"/> <span className="glyphicon-class">.glyphicon .glyphicon-share-alt</span> </li> <li> <span className="glyphicon glyphicon-shopping-cart"/> <span className="glyphicon-class">.glyphicon .glyphicon-shopping-cart</span> </li> <li> <span className="glyphicon glyphicon-signal"/> <span className="glyphicon-class">.glyphicon .glyphicon-signal</span> </li> <li> <span className="glyphicon glyphicon-sort"/> <span className="glyphicon-class">.glyphicon .glyphicon-sort</span> </li> <li> <span className="glyphicon glyphicon-sort-by-alphabet"/> <span className="glyphicon-class">.glyphicon .glyphicon-sort-by-alphabet</span> </li> <li> <span className="glyphicon glyphicon-sort-by-alphabet-alt"/> <span className="glyphicon-class">.glyphicon .glyphicon-sort-by-alphabet-alt</span> </li> <li> <span className="glyphicon glyphicon-sort-by-attributes"/> <span className="glyphicon-class">.glyphicon .glyphicon-sort-by-attributes</span> </li> <li> <span className="glyphicon glyphicon-sort-by-attributes-alt"/> <span className="glyphicon-class">.glyphicon .glyphicon-sort-by-attributes-alt</span> </li> <li> <span className="glyphicon glyphicon-sort-by-order"/> <span className="glyphicon-class">.glyphicon .glyphicon-sort-by-order</span> </li> <li> <span className="glyphicon glyphicon-sort-by-order-alt"/> <span className="glyphicon-class">.glyphicon .glyphicon-sort-by-order-alt</span> </li> <li> <span className="glyphicon glyphicon-sound-5-1"/> <span className="glyphicon-class">.glyphicon .glyphicon-sound-5-1</span> </li> <li> <span className="glyphicon glyphicon-sound-6-1"/> <span className="glyphicon-class">.glyphicon .glyphicon-sound-6-1</span> </li> <li> <span className="glyphicon glyphicon-sound-7-1"/> <span className="glyphicon-class">.glyphicon .glyphicon-sound-7-1</span> </li> <li> <span className="glyphicon glyphicon-sound-dolby"/> <span className="glyphicon-class">.glyphicon .glyphicon-sound-dolby</span> </li> <li> <span className="glyphicon glyphicon-sound-stereo"/> <span className="glyphicon-class">.glyphicon .glyphicon-sound-stereo</span> </li> <li> <span className="glyphicon glyphicon-star"/> <span className="glyphicon-class">.glyphicon .glyphicon-star</span> </li> <li> <span className="glyphicon glyphicon-star-empty"/> <span className="glyphicon-class">.glyphicon .glyphicon-star-empty</span> </li> <li> <span className="glyphicon glyphicon-stats"/> <span className="glyphicon-class">.glyphicon .glyphicon-stats</span> </li> <li> <span className="glyphicon glyphicon-step-backward"/> <span className="glyphicon-class">.glyphicon .glyphicon-step-backward</span> </li> <li> <span className="glyphicon glyphicon-step-forward"/> <span className="glyphicon-class">.glyphicon .glyphicon-step-forward</span> </li> <li> <span className="glyphicon glyphicon-stop"/> <span className="glyphicon-class">.glyphicon .glyphicon-stop</span> </li> <li> <span className="glyphicon glyphicon-subtitles"/> <span className="glyphicon-class">.glyphicon .glyphicon-subtitles</span> </li> <li> <span className="glyphicon glyphicon-tag"/> <span className="glyphicon-class">.glyphicon .glyphicon-tag</span> </li> <li> <span className="glyphicon glyphicon-tags"/> <span className="glyphicon-class">.glyphicon .glyphicon-tags</span> </li> <li> <span className="glyphicon glyphicon-tasks"/> <span className="glyphicon-class">.glyphicon .glyphicon-tasks</span> </li> <li> <span className="glyphicon glyphicon-text-height"/> <span className="glyphicon-class">.glyphicon .glyphicon-text-height</span> </li> <li> <span className="glyphicon glyphicon-text-width"/> <span className="glyphicon-class">.glyphicon .glyphicon-text-width</span> </li> <li> <span className="glyphicon glyphicon-th"/> <span className="glyphicon-class">.glyphicon .glyphicon-th</span> </li> <li> <span className="glyphicon glyphicon-th-large"/> <span className="glyphicon-class">.glyphicon .glyphicon-th-large</span> </li> <li> <span className="glyphicon glyphicon-th-list"/> <span className="glyphicon-class">.glyphicon .glyphicon-th-list</span> </li> <li> <span className="glyphicon glyphicon-thumbs-down"/> <span className="glyphicon-class">.glyphicon .glyphicon-thumbs-down</span> </li> <li> <span className="glyphicon glyphicon-thumbs-up"/> <span className="glyphicon-class">.glyphicon .glyphicon-thumbs-up</span> </li> <li> <span className="glyphicon glyphicon-time"/> <span className="glyphicon-class">.glyphicon .glyphicon-time</span> </li> <li> <span className="glyphicon glyphicon-tint"/> <span className="glyphicon-class">.glyphicon .glyphicon-tint</span> </li> <li> <span className="glyphicon glyphicon-tower"/> <span className="glyphicon-class">.glyphicon .glyphicon-tower</span> </li> <li> <span className="glyphicon glyphicon-transfer"/> <span className="glyphicon-class">.glyphicon .glyphicon-transfer</span> </li> <li> <span className="glyphicon glyphicon-trash"/> <span className="glyphicon-class">.glyphicon .glyphicon-trash</span> </li> <li> <span className="glyphicon glyphicon-tree-conifer"/> <span className="glyphicon-class">.glyphicon .glyphicon-tree-conifer</span> </li> <li> <span className="glyphicon glyphicon-tree-deciduous"/> <span className="glyphicon-class">.glyphicon .glyphicon-tree-deciduous</span> </li> <li> <span className="glyphicon glyphicon-unchecked"/> <span className="glyphicon-class">.glyphicon .glyphicon-unchecked</span> </li> <li> <span className="glyphicon glyphicon-upload"/> <span className="glyphicon-class">.glyphicon .glyphicon-upload</span> </li> <li> <span className="glyphicon glyphicon-usd"/> <span className="glyphicon-class">.glyphicon .glyphicon-usd</span> </li> <li> <span className="glyphicon glyphicon-user"/> <span className="glyphicon-class">.glyphicon .glyphicon-user</span> </li> <li> <span className="glyphicon glyphicon-volume-down"/> <span className="glyphicon-class">.glyphicon .glyphicon-volume-down</span> </li> <li> <span className="glyphicon glyphicon-volume-off"/> <span className="glyphicon-class">.glyphicon .glyphicon-volume-off</span> </li> <li> <span className="glyphicon glyphicon-volume-up"/> <span className="glyphicon-class">.glyphicon .glyphicon-volume-up</span> </li> <li> <span className="glyphicon glyphicon-warning-sign"/> <span className="glyphicon-class">.glyphicon .glyphicon-warning-sign</span> </li> <li> <span className="glyphicon glyphicon-wrench"/> <span className="glyphicon-class">.glyphicon .glyphicon-wrench</span> </li> <li> <span className="glyphicon glyphicon-zoom-in"/> <span className="glyphicon-class">.glyphicon .glyphicon-zoom-in</span> </li> <li> <span className="glyphicon glyphicon-zoom-out"/> <span className="glyphicon-class">.glyphicon .glyphicon-zoom-out</span> </li> </ul> </div> {/* end widget content */} </div> {/* end widget div */} </JarvisWidget> {/* end widget */} </article> {/* WIDGET END */} </div> </WidgetGrid> </div> ) } }
src/component/DeveloperOptions.js
BristolPound/cyclos-mobile-3-TownPound
import React from 'react' import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import { ListView, View, TouchableHighlight, Image } from 'react-native' import Colors from '@Colors/colors' import merge from '../util/merge' import { loadBusinessList, resetBusinesses } from '../store/reducer/business' import { loadTransactions, resetTransactions } from '../store/reducer/transaction' import DefaultText from './DefaultText' import { hideModal } from '../store/reducer/navigation' import { LOGIN_STATUSES } from '../store/reducer/login' import { selectServer, SERVER } from '../store/reducer/developerOptions' import { setSessionToken } from '../api/api' import Images from '@Assets/images' const INFO_FONT_SIZE = 14 const ACTION_FONT_SIZE = 18 const PADDING = 5 const style = { header: { container: { padding: PADDING, backgroundColor: Colors.gray4 }, text: { fontSize: INFO_FONT_SIZE } }, row: { container: { padding: PADDING }, label: { fontSize: INFO_FONT_SIZE }, value: { fontSize: INFO_FONT_SIZE }, action: { fontSize: ACTION_FONT_SIZE } } } // Render label / value pair. const DeveloperInfo = ({label, value, index, accessibilityLabel}) => <View key={index} style={style.row.container}> <View style={{flexDirection: 'row'}}> <DefaultText style={style.row.label}> {label} </DefaultText> <DefaultText style={style.row.value} accessibilityLabel={accessibilityLabel}> {value} </DefaultText> </View> </View> // Render clickable button const DeveloperAction = ({text, onPress, disabled, index, accessibilityLabel}) => <View key={index} style={style.row.container}> <TouchableHighlight onPress={() => !disabled && onPress()} activeOpacity={0.6} underlayColor={Colors.transparent} > <View> <DefaultText style={merge(style.row.action, disabled ? {opacity: 0.4} : {})} accessibilityLabel={accessibilityLabel} > {text} </DefaultText> </View> </TouchableHighlight> </View> const renderSectionHeader = (sectionData, sectionID) => <View key={sectionID} style={style.header.container}> <DefaultText style={style.row.text}>{sectionID}</DefaultText> </View> const DeveloperOptions = props => { let infoSource = new ListView.DataSource({ rowHasChanged: (a, b) => a.text !== b.text || a.disabled !== b.disabled, sectionHeaderHasChanged: (a, b) => a !== b }) let actionsSource = new ListView.DataSource({ rowHasChanged: (a, b) => a.text !== b.text || a.disabled !== b.disabled, sectionHeaderHasChanged: (a, b) => a !== b }) const infoRows = { 'App State': [ { label: 'Businesses: ', value: props.store.businessCount, accessibilityLabel: 'Business Count'}, { label: 'Business List Timestamp: ', value: `${props.store.businessTimestamp}`, accessibilityLabel: 'Business Timestamp'}, { label: 'Transactions: ', value: props.store.transactionCount, accessibilityLabel: 'Transaction Count'}, { label: 'Server: ', value: props.store.server, accessibilityLabel: 'Server'} ] } const actionRows = { 'Developer Actions': [{ text: 'Clear All Business Data', onPress: () => props.resetBusinesses(), accessibilityLabel: 'Clear Businesses' }, { text: 'Load Business Data', onPress: () => props.loadBusinessList(), accessibilityLabel: 'Load Businesses' }, { text: 'Clear All Transaction Data', onPress: () => props.resetTransactions(), disabled: props.loadingTransactions, accessibilityLabel: 'Clear Transactions' }, { text: 'Load Transaction Data', onPress: () => props.loadTransactions(), disabled: props.loadingTransactions || !props.loggedIn, accessibilityLabel: 'Load Transactions' }, { text: 'Switch Server To ' + (props.store.server === SERVER.STAGE ? 'Dev' : 'Stage'), onPress: () => props.selectServer(props.store.server === SERVER.STAGE ? 'DEV' : 'STAGE'), accessibilityLabel: 'Switch Server' }, { text: 'Corrupt session token', onPress: () => setSessionToken('not a valid session token'), accessibilityLabel: 'Corrupt session token' } ] } infoSource = infoSource.cloneWithRowsAndSections(infoRows, Object.keys(infoRows)) actionsSource = actionsSource.cloneWithRowsAndSections(actionRows, Object.keys(actionRows)) return ( <View style={{flex: 1}}> <View> <TouchableHighlight onPress={() => props.hideModal()} underlayColor={Colors.white} accessiblityLabel='Close Developer Options' > <Image source={Images.close} style={{margin: 20}}/> </TouchableHighlight> </View> <ListView style={{flex: 1}} dataSource={infoSource} renderRow={(accountOption, i) => <DeveloperInfo {...accountOption} index={i}/> } renderSectionHeader={renderSectionHeader} accessibilityLabel='Developer Info' removeClippedSubviews={false}/> <ListView style={{flex: 1}} dataSource={actionsSource} renderRow={(accountOption, i) => <DeveloperAction {...accountOption} index={i}/> } renderSectionHeader={renderSectionHeader} accessibilityLabel='Developer Actions' removeClippedSubviews={false}/> </View> ) } export const onPressChangeServer = props => () => { props.switchBaseUrl() if (props.loggedIn) { props.logout() } } const mapStateToProps = state => ({ store: { businessCount: state.business.businessList.length, businessTimestamp: state.business.businessListTimestamp, transactionCount: state.transaction.transactions.length, server: state.developerOptions.server }, loadingTransactions: state.transaction.loadingTransactions, loggedIn: state.login.loginStatus === LOGIN_STATUSES.LOGGED_IN }) const mapDispatchToProps = dispatch => bindActionCreators({ loadTransactions, resetTransactions, resetBusinesses, loadBusinessList, hideModal, selectServer }, dispatch) export default connect(mapStateToProps, mapDispatchToProps)(DeveloperOptions)
app/clients/next/components/form/button_dropdown.js
garbin/koapp
import React from 'react' import { ButtonDropdown } from 'reactstrap' export default class extends React.Component { constructor () { super() this.state = { open: false } } handleToggle () { this.setState({open: !this.state.open}) } render () { return ( <ButtonDropdown isOpen={this.state.open} toggle={this.handleToggle.bind(this)} {...this.props} /> ) } }
app/layouts/login.js
jtparrett/countcals
import React from 'react' import { StyleSheet, View, Text, Button } from 'react-native' import Header from '../components/header' import Input from '../components/input' export default class Login extends React.Component { constructor(props) { super(props) this.state = { username: '', password: '' } } submit = () => { this.props.API.post('auth', {...this.state}).then((response) => { this.props.onLogin(response.data) }).catch((error) => { console.error(error.message) }) } render() { return ( <View style={{ flex: 1 }}> <Header /> <View style={ styles.container }> <Input placeholder="Username" onChangeText={value => { this.setState({ username: value }) }} value={this.state.username} /> <Input placeholder="Password" onChangeText={value => { this.setState({ password: value }) }} value={this.state.password} secureTextEntry /> <Button title="Login" onPress={this.submit} /> </View> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, margin: 20 } })
javascript/ShareAdmin/Hosts.js
AppStateESS/stories
'use strict' import React from 'react' import PropTypes from 'prop-types' import HostRow from './HostRow' const Hosts = ({listing, deleteHost, setAuthKey}) => { if (listing.length === 0) { return <p>No guest requests in queue.</p> } let rows = listing.map((value, key) => { return <HostRow {...value} key={key} deleteHost={deleteHost.bind(null, key)} setAuthKey={setAuthKey.bind(null, key)}/> }) return ( <div> <table className="table table-striped"> <tbody> <tr> <th>Action</th> <th>Site</th> <th>Url</th> <th>Authkey</th> </tr> {rows} </tbody> </table> </div> ) } Hosts.propTypes = { listing: PropTypes.array, deleteHost: PropTypes.func, setAuthKey: PropTypes.func } export default Hosts
src/components/Developer/DeveloperList.js
iamraphson/mernmap
/** * Created by Raphson on 10/14/16. */ import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Link } from 'react-router'; export default class DeveloperList extends Component { constructor() { super(); } render(){ return ( <div className="col-lg-2 col-md-3 col-sm-4 col-xs-5 team-profile"> <div style={{textAlign: 'center'}}> <Link to={ `/mern-developers/${this.props.developer.username}`}> <img height={150} width={150} alt={this.props.developer.fullname} src={this.props.developer.user_avi} /> </Link> </div> <div className="profile-name grid3">{this.props.developer.username}</div> <ul className="profile-social-icons"> <li> <a target="_blank" href={this.props.developer.twitter_handle || '#'}> <i className="fa fa-twitter-square" /> </a> </li> <div style={{display: 'inline-block', width: 10, height: 4}}></div> <li> <a target="_blank" href={this.props.developer.github_profile || '#'}> <i className="fa fa-github-square" /> </a> </li> </ul> </div> ); } }
src/components/ShareExperience/InterviewForm/InterviewInfo/InterviewResult.js
goodjoblife/GoodJobShare
import React from 'react'; import PropTypes from 'prop-types'; import cn from 'classnames'; import ButtonGroup from 'common/button/ButtonGroup'; import TextInput from 'common/form/TextInput'; import InputTitle from '../../common/InputTitle'; import { interviewResultMap } from '../../common/optionMap'; import styles from './InterviewResult.module.css'; const OTHER_VALUE = ''; const notOtherValueMap = interviewResultMap .filter(option => option.value !== OTHER_VALUE) .map(option => option.value); const isNotOther = result => notOtherValueMap.includes(result) || result === null; const InterviewResult = ({ interviewResult, onChange, validator, submitted, }) => { const notOther = isNotOther(interviewResult); const isWarning = submitted && !validator(interviewResult); return ( <div> <InputTitle text="面試結果" must /> <div className={isWarning ? styles.warning : ''}> <ButtonGroup value={notOther ? interviewResult : OTHER_VALUE} onChange={result => { if (notOther || isNotOther(result)) { return onChange(result); } return null; }} options={interviewResultMap} /> {!notOther ? ( <section style={{ marginTop: '8px', }} > <TextInput value={interviewResult} placeholder="輸入面試結果" onChange={e => onChange(e.target.value)} /> </section> ) : null} </div> {isWarning ? ( <p className={cn(styles.warning__wording, 'pS')} style={{ marginTop: '8px', }} > 需填寫面試結果,或字數少於 100 字。 </p> ) : null} </div> ); }; InterviewResult.propTypes = { interviewResult: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), onChange: PropTypes.func, validator: PropTypes.func, submitted: PropTypes.bool, }; export default InterviewResult;
node_modules/react-icons/io/ios-basketball.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const IoIosBasketball = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m19.8 3.8c8.9 0 16.2 7.2 16.2 16.2s-7.3 16.3-16.2 16.3-16.3-7.3-16.3-16.3 7.3-16.2 16.3-16.2z m9.7 27.5c-1.7-4-4.1-7.6-6.9-10.8 0.8-1 1.6-2 2.4-3 2.6 2.1 6 3.5 9.6 3.8 0-0.4 0.1-0.9 0.1-1.3-1.7-0.2-3.5-0.5-5.1-1.2-1.4-0.7-2.7-1.4-3.8-2.3 1.6-2.4 2.9-4.8 4-7.4-0.3-0.4-0.6-0.7-0.9-0.9 0 0.1-0.1 0.1-0.1 0.2-1.1 2.5-2.5 5-4.1 7.2-0.1-0.1-0.1-0.1-0.3-0.3-1.4-1.5-2.7-3.2-3.5-5.1-0.7-1.7-1-3.4-1.2-5.1-0.3 0-0.8 0.1-1.2 0.1 0.3 4.5 2.4 8.5 5.5 11.4-0.7 1.1-1.4 2-2.3 2.9-3.7-3.9-8.2-7.1-13.2-9.3-0.3 0.3-0.5 0.7-0.8 1.1 4.6 2 8.8 4.8 12.4 8.4l0.7 0.8-0.6 0.6c-1 1-2 1.9-3.1 2.8-3.1-3.4-7.3-5.5-12.1-5.8-0.1 0.4-0.1 0.9-0.1 1.3 2 0.1 3.8 0.5 5.6 1.2 1.9 0.8 3.6 2.1 5.1 3.5l0.6 0.6c-2.5 1.9-5.2 3.4-8 4.7 0.3 0.3 0.5 0.7 0.8 1 2.9-1.3 5.5-2.9 7.9-4.8 0.9 1.1 1.7 2.4 2.2 3.7 0.8 1.8 1.2 3.6 1.3 5.5 0.4 0 0.8 0 1.2 0-0.1-3.8-1.5-7.2-3.6-10 1.3-1 2.5-2.1 3.7-3.4 2.8 3.2 5.1 6.7 6.8 10.6 0.3-0.2 0.7-0.4 1-0.7z"/></g> </Icon> ) export default IoIosBasketball
public/js/cat_source/es6/components/analyze/ChunkAnalyzeFile.js
riccio82/MateCat
import React from 'react' class ChunkAnalyzeFile extends React.Component { constructor(props) { super(props) this.dataChange = {} this.containers = {} } checkWhatChanged() { if (this.file) { this.dataChange.TOTAL_PAYABLE = !this.file .get('TOTAL_PAYABLE') .equals(this.props.file.get('TOTAL_PAYABLE')) this.dataChange.NEW = !this.file .get('NEW') .equals(this.props.file.get('NEW')) this.dataChange.REPETITIONS = !this.file .get('REPETITIONS') .equals(this.props.file.get('REPETITIONS')) this.dataChange.INTERNAL_MATCHES = !this.file .get('INTERNAL_MATCHES') .equals(this.props.file.get('INTERNAL_MATCHES')) this.dataChange.TM_50_74 = !this.file .get('TM_50_74') .equals(this.props.file.get('TM_50_74')) this.dataChange.TM_75_84 = !this.file .get('TM_75_84') .equals(this.props.file.get('TM_75_84')) this.dataChange.TM_85_94 = !this.file .get('TM_85_94') .equals(this.props.file.get('TM_85_94')) this.dataChange.TM_95_99 = !this.file .get('TM_95_99') .equals(this.props.file.get('TM_95_99')) this.dataChange.TM_100 = !this.file .get('TM_100') .equals(this.props.file.get('TM_100')) this.dataChange.TM_100_PUBLIC = !this.file .get('TM_100_PUBLIC') .equals(this.props.file.get('TM_100_PUBLIC')) this.dataChange.ICE = !this.file .get('ICE') .equals(this.props.file.get('ICE')) this.dataChange.MT = !this.file .get('MT') .equals(this.props.file.get('MT')) } this.file = this.props.file } componentDidUpdate() { let self = this let changedData = _.pick(this.dataChange, function (item) { return item === true }) if (_.size(changedData) > 0) { _.each(changedData, function (item, i) { self.containers[i].classList.add('updated-count') setTimeout(function () { self.containers[i].classList.remove('updated-count') }, 400) }) } } shouldComponentUpdate() { return true } render() { var file = this.props.file.toJS() this.checkWhatChanged() return ( <div className="chunk-detail sixteen wide column pad-right-10"> <div className="left-box"> <i className="icon-make-group icon"></i> <div className="file-title-details"> {this.props.fileInfo.filename} {/*(<span className="f-details-number">2</span>)*/} </div> </div> <div className="single-analysis"> <div className="single total"> {this.props.fileInfo.file_raw_word_count} </div> <div className="single payable-words" ref={(container) => (this.containers['TOTAL_PAYABLE'] = container)} > {file.TOTAL_PAYABLE[1]} </div> <div className="single new" ref={(container) => (this.containers['NEW'] = container)} > {file.NEW[1]} </div> <div className="single repetition" ref={(container) => (this.containers['REPETITIONS'] = container)} > {file.REPETITIONS[1]} </div> <div className="single internal-matches" ref={(container) => (this.containers['INTERNAL_MATCHES'] = container) } > {file.INTERNAL_MATCHES[1]} </div> <div className="single p-50-74" ref={(container) => (this.containers['TM_50_74'] = container)} > {file.TM_50_74[1]} </div> <div className="single p-75-84" ref={(container) => (this.containers['TM_75_84'] = container)} > {file.TM_75_84[1]} </div> <div className="single p-84-94" ref={(container) => (this.containers['TM_85_94'] = container)} > {file.TM_85_94[1]} </div> <div className="single p-95-99" ref={(container) => (this.containers['TM_95_99'] = container)} > {file.TM_95_99[1]} </div> <div className="single tm-100" ref={(container) => (this.containers['TM_100'] = container)} > {file.TM_100[1]} </div> <div className="single tm-public" ref={(container) => (this.containers['TM_100_PUBLIC'] = container)} > {file.TM_100_PUBLIC[1]} </div> <div className="single tm-context" ref={(container) => (this.containers['ICE'] = container)} > {file.ICE[1]} </div> <div className="single machine-translation" ref={(container) => (this.containers['MT'] = container)} > {file.MT[1]} </div> </div> </div> ) } } export default ChunkAnalyzeFile
packages/material-ui/src/ListItemSecondaryAction/ListItemSecondaryAction.js
Kagami/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; export const styles = { /* Styles applied to the root element. */ root: { position: 'absolute', right: 4, top: '50%', transform: 'translateY(-50%)', }, }; function ListItemSecondaryAction(props) { const { children, classes, className, ...other } = props; return ( <div className={classNames(classes.root, className)} {...other}> {children} </div> ); } ListItemSecondaryAction.propTypes = { /** * The content of the component, normally an `IconButton` or selection control. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css-api) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, }; ListItemSecondaryAction.muiName = 'ListItemSecondaryAction'; export default withStyles(styles, { name: 'MuiListItemSecondaryAction' })(ListItemSecondaryAction);
node_modules/@material-ui/core/esm/Dialog/Dialog.js
pcclarke/civ-techs
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; /* eslint-disable jsx-a11y/click-events-have-key-events */ /* eslint-disable jsx-a11y/no-noninteractive-element-interactions */ import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import { capitalize } from '../utils/helpers'; import Modal from '../Modal'; import Backdrop from '../Backdrop'; import Fade from '../Fade'; import { duration } from '../styles/transitions'; import Paper from '../Paper'; export var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: { '@media print': { position: 'absolute' } }, /* Styles applied to the root element if `scroll="paper"`. */ scrollPaper: { display: 'flex', justifyContent: 'center', alignItems: 'center' }, /* Styles applied to the root element if `scroll="body"`. */ scrollBody: { overflowY: 'auto', overflowX: 'hidden' }, /* Styles applied to the container element. */ container: { height: '100%', '@media print': { height: 'auto' }, // We disable the focus ring for mouse, touch and keyboard users. outline: 'none' }, /* Styles applied to the `Paper` component. */ paper: { display: 'flex', flexDirection: 'column', margin: 48, position: 'relative', overflowY: 'auto', // Fix IE 11 issue, to remove at some point. '@media print': { overflowY: 'visible', boxShadow: 'none' } }, /* Styles applied to the `Paper` component if `scroll="paper"`. */ paperScrollPaper: { flex: '0 1 auto', maxHeight: 'calc(100% - 96px)' }, /* Styles applied to the `Paper` component if `scroll="body"`. */ paperScrollBody: { margin: '48px auto' }, /* Styles applied to the `Paper` component if `maxWidth=false`. */ paperWidthFalse: { '&$paperScrollBody': { margin: 48 } }, /* Styles applied to the `Paper` component if `maxWidth="xs"`. */ paperWidthXs: { maxWidth: Math.max(theme.breakpoints.values.xs, 444), '&$paperScrollBody': _defineProperty({}, theme.breakpoints.down(Math.max(theme.breakpoints.values.xs, 444) + 48 * 2), { margin: 48 }) }, /* Styles applied to the `Paper` component if `maxWidth="sm"`. */ paperWidthSm: { maxWidth: theme.breakpoints.values.sm, '&$paperScrollBody': _defineProperty({}, theme.breakpoints.down(theme.breakpoints.values.sm + 48 * 2), { margin: 48 }) }, /* Styles applied to the `Paper` component if `maxWidth="md"`. */ paperWidthMd: { maxWidth: theme.breakpoints.values.md, '&$paperScrollBody': _defineProperty({}, theme.breakpoints.down(theme.breakpoints.values.md + 48 * 2), { margin: 48 }) }, /* Styles applied to the `Paper` component if `maxWidth="lg"`. */ paperWidthLg: { maxWidth: theme.breakpoints.values.lg, '&$paperScrollBody': _defineProperty({}, theme.breakpoints.down(theme.breakpoints.values.lg + 48 * 2), { margin: 48 }) }, /* Styles applied to the `Paper` component if `maxWidth="xl"`. */ paperWidthXl: { maxWidth: theme.breakpoints.values.xl, '&$paperScrollBody': _defineProperty({}, theme.breakpoints.down(theme.breakpoints.values.xl + 48 * 2), { margin: 48 }) }, /* Styles applied to the `Paper` component if `fullWidth={true}`. */ paperFullWidth: { width: '100%', '&$paperScrollBody': { width: 'initial' } }, /* Styles applied to the `Paper` component if `fullScreen={true}`. */ paperFullScreen: { margin: 0, width: '100%', maxWidth: '100%', height: '100%', maxHeight: 'none', borderRadius: 0, '&$paperScrollBody': { margin: 0 } } }; }; var defaultTransitionDuration = { enter: duration.enteringScreen, exit: duration.leavingScreen }; /** * Dialogs are overlaid modal paper based components with a backdrop. */ var Dialog = React.forwardRef(function Dialog(props, ref) { var BackdropProps = props.BackdropProps, children = props.children, classes = props.classes, className = props.className, _props$disableBackdro = props.disableBackdropClick, disableBackdropClick = _props$disableBackdro === void 0 ? false : _props$disableBackdro, _props$disableEscapeK = props.disableEscapeKeyDown, disableEscapeKeyDown = _props$disableEscapeK === void 0 ? false : _props$disableEscapeK, _props$fullScreen = props.fullScreen, fullScreen = _props$fullScreen === void 0 ? false : _props$fullScreen, _props$fullWidth = props.fullWidth, fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth, _props$maxWidth = props.maxWidth, maxWidth = _props$maxWidth === void 0 ? 'sm' : _props$maxWidth, onBackdropClick = props.onBackdropClick, onClose = props.onClose, onEnter = props.onEnter, onEntered = props.onEntered, onEntering = props.onEntering, onEscapeKeyDown = props.onEscapeKeyDown, onExit = props.onExit, onExited = props.onExited, onExiting = props.onExiting, open = props.open, _props$PaperComponent = props.PaperComponent, PaperComponent = _props$PaperComponent === void 0 ? Paper : _props$PaperComponent, _props$PaperProps = props.PaperProps, PaperProps = _props$PaperProps === void 0 ? {} : _props$PaperProps, _props$scroll = props.scroll, scroll = _props$scroll === void 0 ? 'paper' : _props$scroll, _props$TransitionComp = props.TransitionComponent, TransitionComponent = _props$TransitionComp === void 0 ? Fade : _props$TransitionComp, _props$transitionDura = props.transitionDuration, transitionDuration = _props$transitionDura === void 0 ? defaultTransitionDuration : _props$transitionDura, TransitionProps = props.TransitionProps, other = _objectWithoutProperties(props, ["BackdropProps", "children", "classes", "className", "disableBackdropClick", "disableEscapeKeyDown", "fullScreen", "fullWidth", "maxWidth", "onBackdropClick", "onClose", "onEnter", "onEntered", "onEntering", "onEscapeKeyDown", "onExit", "onExited", "onExiting", "open", "PaperComponent", "PaperProps", "scroll", "TransitionComponent", "transitionDuration", "TransitionProps"]); var mouseDownTarget = React.useRef(); var handleMouseDown = function handleMouseDown(event) { mouseDownTarget.current = event.target; }; var handleBackdropClick = function handleBackdropClick(event) { // Ignore the events not coming from the "backdrop" // We don't want to close the dialog when clicking the dialog content. if (event.target !== event.currentTarget) { return; } // Make sure the event starts and ends on the same DOM element. if (event.target !== mouseDownTarget.current) { return; } mouseDownTarget.current = null; if (onBackdropClick) { onBackdropClick(event); } if (!disableBackdropClick && onClose) { onClose(event, 'backdropClick'); } }; return React.createElement(Modal, _extends({ className: clsx(classes.root, className), BackdropComponent: Backdrop, BackdropProps: _extends({ transitionDuration: transitionDuration }, BackdropProps), closeAfterTransition: true, disableBackdropClick: disableBackdropClick, disableEscapeKeyDown: disableEscapeKeyDown, onEscapeKeyDown: onEscapeKeyDown, onClose: onClose, open: open, ref: ref, role: "dialog" }, other), React.createElement(TransitionComponent, _extends({ appear: true, in: open, timeout: transitionDuration, onEnter: onEnter, onEntering: onEntering, onEntered: onEntered, onExit: onExit, onExiting: onExiting, onExited: onExited }, TransitionProps), React.createElement("div", { className: clsx(classes.container, classes["scroll".concat(capitalize(scroll))]), onClick: handleBackdropClick, onMouseDown: handleMouseDown, role: "document" }, React.createElement(PaperComponent, _extends({ elevation: 24 }, PaperProps, { className: clsx(classes.paper, classes["paperScroll".concat(capitalize(scroll))], classes["paperWidth".concat(capitalize(String(maxWidth)))], fullScreen && classes.paperFullScreen, fullWidth && classes.paperFullWidth, PaperProps.className) }), children)))); }); process.env.NODE_ENV !== "production" ? Dialog.propTypes = { /** * @ignore */ BackdropProps: PropTypes.object, /** * Dialog children, usually the included sub-components. */ children: PropTypes.node.isRequired, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * If `true`, clicking the backdrop will not fire the `onClose` callback. */ disableBackdropClick: PropTypes.bool, /** * If `true`, hitting escape will not fire the `onClose` callback. */ disableEscapeKeyDown: PropTypes.bool, /** * If `true`, the dialog will be full-screen */ fullScreen: PropTypes.bool, /** * If `true`, the dialog stretches to `maxWidth`. */ fullWidth: PropTypes.bool, /** * Determine the max-width of the dialog. * The dialog width grows with the size of the screen. * Set to `false` to disable `maxWidth`. */ maxWidth: PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl', false]), /** * Callback fired when the backdrop is clicked. */ onBackdropClick: PropTypes.func, /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback * @param {string} reason Can be:`"escapeKeyDown"`, `"backdropClick"` */ onClose: PropTypes.func, /** * Callback fired before the dialog enters. */ onEnter: PropTypes.func, /** * Callback fired when the dialog has entered. */ onEntered: PropTypes.func, /** * Callback fired when the dialog is entering. */ onEntering: PropTypes.func, /** * Callback fired when the escape key is pressed, * `disableKeyboard` is false and the modal is in focus. */ onEscapeKeyDown: PropTypes.func, /** * Callback fired before the dialog exits. */ onExit: PropTypes.func, /** * Callback fired when the dialog has exited. */ onExited: PropTypes.func, /** * Callback fired when the dialog is exiting. */ onExiting: PropTypes.func, /** * If `true`, the Dialog is open. */ open: PropTypes.bool.isRequired, /** * The component used to render the body of the dialog. */ PaperComponent: PropTypes.elementType, /** * Properties applied to the [`Paper`](/api/paper/) element. */ PaperProps: PropTypes.object, /** * Determine the container for scrolling the dialog. */ scroll: PropTypes.oneOf(['body', 'paper']), /** * The component used for the transition. */ TransitionComponent: PropTypes.elementType, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. */ transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number })]), /** * Properties applied to the `Transition` element. */ TransitionProps: PropTypes.object } : void 0; export default withStyles(styles, { name: 'MuiDialog' })(Dialog);
src/3rdparty/v8/test/mjsunit/unicode-test.js
Distrotech/qtjsbackend
// Copyright 2008 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Texts are from the Unibrow test suite. // Note that this file is in UTF-8. smjs and testkjs do not read their // source files as UTF-8, so they will fail on this test. If you want // to run the test on them you can do so after filtering it with the // following piece of perl-based line noise: // perl -CIO -ne '$_ =~ s/([^\n -~])/"\\u" . sprintf("%04x", ord($1))/ge; print $_;' < unicode-test.js > unicode-test-ascii.js // The result is predictably illegible even for those fluent in Hindi. var chinese = "中国历史\n" + "[编辑首段]维基百科,自由的百科全书\n" + "跳转到: 导航, 搜索\n" + "中國歷史\n" + "中国历史系列条目\n" + "史前时期\n" + "传说时期\n" + "(另见三皇五帝)\n" + "夏\n" + "商\n" + "西周 周\n" + "春秋 东周\n" + "战国\n" + "秦\n" + "西汉 汉\n" + "新朝\n" + "东汉\n" + "魏 蜀 吴 三\n" + "国\n" + "西晋 晋\n" + "东晋 十六国\n" + "宋 南\n" + "朝 北魏 北\n" + "朝 南\n" + "北\n" + "朝\n" + "齐\n" + "梁 东\n" + "魏 西\n" + "魏\n" + "陈 北\n" + "齐 北\n" + "周\n" + "隋\n" + "唐\n" + "(另见武周)\n" + "五代十国\n" + "辽\n" + "(西辽) 西\n" + "夏 北宋 宋\n" + "金 南宋\n" + "元\n" + "明\n" + "清\n" + "中华民国\n" + "中华人民\n" + "共和国 中华\n" + "民国\n" + "(见台湾问题)\n" + "\n" + " * 中国历史年表\n" + " * 中国军事史\n" + " * 中国美术史\n" + " * 中国科学技术史\n" + " * 中国教育史\n" + "\n" + "中国\n" + "天坛\n" + "文化\n" + "中文 - 文学 - 哲学 - 教育\n" + "艺术 - 国画 - 戏曲 - 音乐\n" + "神话 - 宗教 - 术数 - 建筑\n" + "文物 - 电影 - 服饰 - 饮食\n" + "武术 - 书法 - 节日 - 姓名\n" + "地理\n" + "疆域 - 行政区划 - 城市\n" + "地图 - 旅游 - 环境 - 生物\n" + "人口 - 民族 - 交通 - 时区\n" + "历史\n" + "年表 - 传说时代 - 朝代\n" + "民国史 - 共和国史\n" + "文化史 - 科技史 - 教育史\n" + "人口史 - 经济史 - 政治史\n" + "政治\n" + "中华人民共和国政治 - 中华民国政治\n" + "宪法 - 外交 - 军事 - 国旗\n" + "两岸问题 - 两岸关系\n" + "一个中国 - 中国统一\n" + "经济\n" + "金融 - 农业 - 工业 - 商业\n" + "中国各省经济 - 五年计划\n" + "其他\n" + "列表 - 体育 - 人权 - 媒体\n" + "\n" + "中国历史自商朝起算约有3600年,自黄帝时代起算约有4000多年。有历史学者认为,在人类文明史中,“历史时代”的定义是指从有文字发明时起算,那之前则称为“史前”;中国历史中传说伏羲做八卦,黄帝时代仓颉造文字;近代考古发现了3600多年前(公元前1600年)商朝的甲骨文、约4000年前至7000年前的陶文、约7000年前至10000年前具有文字性貭的龟骨契刻符号。另外,目前在中国发现最早的史前人类遗址距今约200万年。\n" + "\n" + "从政治形态区分中国历史,可见夏朝以前长达3000年以上的三皇五帝是母系氏族社会到父系氏族社会的过渡时代,而夏朝开始君王世袭,周朝建立完备的封建制度至东周逐渐解构,秦朝首度一统各国政治和许多民间分歧的文字和丈量制度,并建立中央集权政治,汉朝起则以文官主治国家直至清朝,清末以降,民主政治、马克思主义等各种政治思潮流传,先促成中华民国的建立,并于其后四、五十年再出现中华人民共和国,而由于内战失败,中华民国政府退守台湾。\n" + "\n" + "由经济形态观察,中国古代人口主要由自由民构成,私有制、商业活动发达。周朝时商业主要由封建领主阶层控制的官商贸易和庶民的自由贸易构成。秦汉以后实行中央集权,人口由士、农、工、商等构成,其中以从事农业的自由民为主体,是一个君权官僚制下的以土地为主要生产资本的较为自由的商业经济社会,一些重要的行业由官商垄断。除了农业,手工业以及商业贸易也有很大的发展。早在汉朝丝路的开通,促进了东亚与中亚至欧洲的陆上交通时,国际贸易早已起步;隋唐时大运河的开通促进了南北贸易;唐朝的盛世及外交的开放、交通的建设,更使各国文化、物资得以交流;宋代时出现了纸币;元代时与中亚的商业交流十分繁荣;明清两代受到西方国家海上发展的影响,海上国际贸易发展迅猛。自中华民国成立起试图建立民主国家,实行自由经济,直到1990年代台湾落实民主制度,1950年代以后30多年迅速实现了向工业化社会的转型;而中国大陆则在1949年后采用一党制统治,起先为公有制的计划经济社会,改革开放后逐步向私有制的市场经济社会転型,同时,1980年代以来工业化发展迅猛,数亿人口在短短20多年内从农民转为产业工人(目前仅仅被称为“农民工”的产业工人就达到约2亿)。伴随经济的迅速国际化,中国经济成为全球经济中越来越重要的组成部分。\n" + "目录\n" + "[隐藏]\n" + "\n" + " * 1 史前时代\n" + " * 2 传说时代\n" + " * 3 先秦时期\n" + " o 3.1 三代\n" + " o 3.2 春秋战国\n" + " * 4 秦汉时期\n" + " * 5 魏晋南北朝时期\n" + " * 6 隋唐五代时期\n" + " * 7 宋元时期\n" + " * 8 明清时期\n" + " o 8.1 清末的内忧外患\n" + " * 9 20世纪至今\n" + " * 10 参见\n" + " * 11 其他特定主题中国史\n" + " * 12 注解\n" + " * 13 参考文献\n" + " * 14 相关著作\n" + " * 15 外部链接\n" + "\n" + "[编辑] 史前时代\n" + "大汶口文化的陶鬹,山東莒县大朱村出土\n" + "大汶口文化的陶鬹,山东莒县大朱村出土\n" + "\n" + "迄今为止发现的最早的高等灵长类中华曙猿在4500万年前生活在中国江南一带。考古证据显示224万年至25万年前,中国就有直立人居住,目前考古发现的有巫山人、元谋人、蓝田人、南京直立人、北京直立人等。这些都是目前所知较早的原始人类踪迹。\n" + "\n" + "中国史前时代的各种文化是经过了以下几个阶段:以直立猿\n" + "人为主的旧石器时代早中期(距今约50至40多万年前),接着进入了旧石器时代中晚期,以山顶洞人为代表,距今约在20至10余万年前。新石器时代早期的代表性文化是裴李岗文化,紧接着是以仰韶文化为代表的新石器时代中期。而以龙山文化为代表的新石器时代晚期,大约出现在公元前2500年到公元前1300年间。\n" + "\n" + "根据现在的考古学研究,中国的新石器时代呈现多元并立的情形:约西元前5000年到3000年前在河南省、河北省南部、甘肃省南部和山西省南部出现的仰韶文化便具备使用红陶、彩陶以及食用粟和畜养家畜的特质。而大约在同一时间,尚有在浙江省北边出现的河姆渡文化、山东省的大汶口文化。而之后发现的如二里头遗址和三星堆遗址则为青铜器时代的代表。\n" + "\n" + "[编辑] 传说时代\n" + "\n" + " 主条目:三皇五帝\n" + "\n" + "後人所繪的黄帝像\n" + "后人所绘的黄帝像\n" + "\n" + "华夏文明形成于黄河流域中原地区。早期的历史,口口相传。神话中有盘古开天地、女娲造人的说法。传说中的三皇五帝,是夏朝以前数千年杰出首领的代表,具体而言有不同的说法。一般认为,三皇是燧人、伏羲、神农以及女娲、祝融中的三人,五帝一般指黄帝、颛顼、帝喾、尧、舜。自三皇至五帝,历年无确数,最少当不下数千年。\n" + "\n" + "据现今整理出来的传说,黄帝原系炎帝部落的一个分支的首领,强大之后在阪泉之战中击败炎帝,成为新部落联盟首领,之后又与东南方的蚩尤部落发生冲突,在涿鹿之战中彻底击败对手,树立了自己的霸主地位。\n" + "\n" + "后来黄帝的孙子颛顼和玄孙帝喾继续担任部落联盟的首领。帝喾的儿子尧继位,他是一名贤君,创立了禅让制,传位给了舜。在舜时期,洪水泛滥,鲧采用堵塞的方法,结果洪水更厉害了,鲧被处决,他的儿子禹采用疏导的方法,成功治理了洪水,因此被推举为首领。然而他的儿子启破坏了禅让制方式,自立为王(但据《史记》及香港中学课本所述,启是被推举为领袖),建立了第一个世袭王朝——夏朝,夏朝持续了400多年,在最后一个夏朝君主——桀末期,东方诸侯国商首领成汤夺取了政权,建立了商朝。\n" + "\n" + "[编辑] 先秦时期\n" + "\n" + "[编辑] 三代\n" + "\n" + " 主条目:夏朝、商朝、周朝和西周\n" + "\n" + "甲骨文\n" + "甲骨文\n" + "\n" + "最早的世袭朝代夏朝约在前21世纪到前16世纪,由于这段历史目前没有发现文字性文物做印证,所以只能靠后世的记录和出土文物互相对照考证,中国学者一般认为河南洛阳二里头遗址是夏朝首都遗址,有学者对此持有疑问。根据文字记载,夏朝有了中国最早的历法--夏小正。不过之后的商朝是目前所发现的最早有文字文物的历史时期,存在于前16世纪到约前1046年。据说夏朝最后一个君主——桀,由于荒淫无道而被汤推翻。而商代时文明已经十分发达,有历法、青铜器以及成熟的文字——甲骨文等。商王朝时已经有一个完整的国家组织,并且具有了封建王朝的规模。当时的主要生产部门是农业,不过手工业,特别是青铜器的冶铸水平也已经十分高超。并且已经出现了原始的瓷器。商朝自盘庚之后,定都于殷(今河南安阳),因此也称为殷朝。商朝的王位继承制度是传子或传弟,多按年龄的长幼继承。\n" + "\n" + "与此同时,黄河上游的另一个部落周正在逐步兴起,到了大约前1046年,周武王伐纣,在牧野之战中取得决定性胜利,商朝灭亡。周朝正式建立,建都渭河流域的镐京(今陕西西安附近)。之后周朝的势力又慢慢渗透到黄河下游和淮河一带。周王朝依然是封建贵族统治,有许多贵族的封国(诸侯)。到鼎盛时,周朝的影响力已经在南方跨过长江,东北到今天的辽宁,西至甘肃,东到山东。周朝时的宗法制度已经建立,政权机构也较完善。自唐尧、虞舜至周朝皆封建时代,帝王与诸侯分而治之[1]。中国最早有确切时间的历史事件是发生于公元前841年西周的国人暴动。\n" + "\n" + "[编辑] 春秋战国\n" + "\n" + " 主条目:周朝、东周、春秋时期和战国 (中国)\n" + "\n" + "先師孔子行教像,為唐朝画家吳道子所画\n" + "先师孔子行教像,为唐朝画家吴道子所画\n" + "\n" + "前770年,由于遭到北方游牧部落犬戎的侵袭,周平王东迁黄河中游的洛邑(今河南洛阳),东周开始。此后,周王朝的影响力逐渐减弱,取而代之的是大大小小一百多个小国(诸侯国和附属国),史称春秋时期。春秋时期的大国共有十几个,其中包括了晋、秦、郑、齐及楚等。这一时期社会动荡,战争不断,先后有五个国家称霸,即齐、宋、晋、楚、秦(又有一说是齐、晋、楚、吴、越),合称春秋五霸。到了前546年左右,黄河流域的争霸基本结束,晋、楚两国平分了霸权。前403年,晋国被分成韩、赵、魏三个诸侯国,史称“三家分晋”。再加上被田氏夺去了政权的齐国,和秦、楚及燕,并称战国七雄,战国时期正式开始。大部分马克思主义史学家将战国开始划为封建社会,然而大部分西方及台湾学者却又将之划为封建社会的崩溃。前356年秦国商鞅变法开始后,秦国国力大大增强,最后终于在前221年消灭六国最后的齐国,完成统一,中国历史也进入了新时代。\n" + "\n" + "春秋战国时期学术思想比较自由,史称百家争鸣。出现了多位对之后中国有深远影响的思想家(诸子百家),例如老子、孔子、墨子、庄子、孟子、荀子、韩非等人。出现了很多学术流派,较出名的有十大家,即道家(自然)、儒家(伦理)、阴阳家(星象占卜)、法家(法治)、名家(修辞辩论)、墨家(科技)、众、杂、农家(农业)、小说家(小说)等。文化上则出现了第一个以个人名字出现在中国文学史上的诗人屈原,他著有楚辞、离骚等文学作品。孔子编成了诗经。战争史上出现了杰出的兵法家孙武、孙膑、吴起等等。科技史上出现了墨子,建筑史上有鲁班,首次发明了瓦当,奠定了中国建筑技术的基础。能制造精良的战车与骑兵,同时此时中国的冶金也十分发达,能制造精良的铁器,在农业上出现了各种灌溉机械,大大提高了生产率,从而为以后人口大大膨胀奠定了基础。历史上出现了春秋(左传),国语,战国策。中华文化的源头基本上都可以在这一时期找到。\n" + "\n" + "这一时期科技方面也取得了很大进步。夏朝发明了干支纪年,出现了十进位制。西周人用圭表测日影来确定季节;春秋时期确定了二十八宿;后期则产生了古四分历。\n" + "\n" + "[编辑] 秦汉时期\n" + "\n" + " 主条目:秦朝、汉朝、西汉、新朝和东汉\n" + "\n" + "北京八達嶺長城\n" + "北京八达岭长城\n" + "\n" + "前221年,秦并其他六国后统一了中国主体部分,成为了中国历史上第一个统一的中央集权君主统治国家,定都咸阳(今西安附近)。由于秦王嬴政自认“功盖三皇,德过五帝”,于是改用皇帝称号,自封始皇帝,人称秦始皇,传位后的皇帝称二世,直至千世万世。他对国家进行了许多项改革,包括了中央集权的确立,取代了周朝的诸侯分封制;统一了文字,方便官方行文;统一度量衡,便于工程上的计算。秦始皇还大力修筑驰道,并连接了战国时赵国、燕国和秦国的北面围城,筑成了西起临洮、东至辽东的万里长城以抵御北方来自匈奴,东胡等游牧民族的侵袭。秦始皇推崇法治,重用法家的李斯作为丞相,并听其意见,下令焚书坑儒,收缴天下兵器,役使七十万人修筑阿房宫以及自己的陵墓——包括兵马俑等。部分史学家对以上事件存有怀疑,认为由于秦始皇的一系列激进改革得罪了贵族,平民无法适应,才在史书上留此一笔。[来源请求]\n" + "\n" + "前210年,秦始皇病死于出巡途中,胡亥(即秦二世)杀害太子扶苏即位。但十个月后,陈胜、吴广在大泽乡揭竿而起,包括六国遗臣等野心家乘势作乱,前206年刘邦围攻咸阳,秦王子婴自缚出城投降,秦亡。此后,汉王刘邦与西楚霸王项羽展开了争夺天下的楚汉战争。 前202年十二月,项羽被汉军围困于垓下(今安徽灵壁),四面楚歌。项羽在乌江自刎而死。楚汉之争至此结束。汉高祖刘邦登基,定都长安(今陕西西安),西汉开始。到了汉武帝时,西汉到达鼎盛。并与罗马,安息(帕提亚),贵霜并称为四大帝国。武帝实行推恩令,彻底削弱了封国势力,强化监察制度,实现中央集权;他派遣卫青、霍去病、李广等大将北伐,成功地击溃了匈奴,控制了西域,还派遣张骞出使西域,开拓了著名的丝绸之路,发展了对外贸易,使中国真正了解了外面的世界,促进中西文化交流。儒家学说也被确立为官方的主流意识形态,成为了占统治地位的思想。其他艺术与文化也蒸蒸日上。同时期还出现了第一部通史性质的巨著——《史记》,同时这时的中国出现造纸术,大大推动了文化发展。\n" + "\n" + "西汉发展到了一世纪左右开始逐渐衰败。公元9年,外戚王莽夺权,宣布进行一系列的改革,改国号为新。然而这些改革却往往不切实际,最终导致农民纷纷起义。公元25年刘秀复辟了汉朝,定都洛阳,史称东汉,而他就是汉光武帝。东汉的发展延续了西汉的传统,此时出现了天文学家张衡。汉的文化吸取了秦的教训,显得相当开明,当时佛教通过西域到达中国,在河南洛阳修建了中国的第一座佛教寺庙——白马寺,佛教正式传入中国。\n" + "\n" + "[编辑] 魏晋南北朝时期\n" + "\n" + " 主条目:魏晋南北朝、三国、晋朝、十六国和南北朝\n" + "\n" + "赤壁\n" + "赤壁\n" + "\n" + "东汉中后期,宦官和外戚长期争权,在黄巾起义的打击下,到了公元二世纪左右时再度衰败,196年曹操控制了东汉朝廷,把汉献帝迎至许都,“挟天子以令诸侯”,220年,曹操死后,长子曹丕废汉献帝自立,建立魏国,同时尚有刘氏的汉和孙氏的吴,历史进入了三国时期。\n" + "\n" + "265年,魏权臣司马炎称帝,建立晋朝。280年三国归晋,再度统一。晋朝的文化也有一定发展,当时由于战乱纷纷,很多学士选择归隐,不问世事,典型的代表人物是陶渊明(陶潜),当时的书法艺术也十分兴盛。290年晋武帝死后不到一年,十六年的朝廷权利斗争开始,史称“八王之乱”。与此同时,中原周边的五个游牧民族(匈奴、鲜卑、羌、氐、羯)与各地流民起来反晋,史称五胡乱华。这些游牧民族纷纷建立自己的国家,从304年到409年,北部中国陆陆续续有多个国家建立,包括了汉、前赵、后赵、前燕、前凉、前秦、后秦、后燕、西秦、后凉、北凉、南凉、南燕、西凉、夏和北燕, 史称十六国。\n" + "\n" + "自东汉后期开始,为躲避战乱,北方的汉族人民大量迁居南方,造成经济重心南移;晋朝南迁,建都建康(今江苏南京),历史上称此前为西晋,南迁后为东晋。最后,拓跋鲜卑统一北方,建立北朝的第一个王朝——北魏,形成了南北朝的对立。南朝经历了宋、齐、梁、陈的更替,而北朝则有北魏、东魏、西魏、北齐和北周。南北朝时期是佛教十分盛行的时期,西方的佛教大师络绎不绝地来到中国,许多佛经被翻译成汉文。\n" + "\n" + "[编辑] 隋唐五代时期\n" + "\n" + " 主条目:隋朝、唐朝和五代十国\n" + "\n" + "唐代画家张萱作《捣练图》。\n" + "唐代画家张萱作《捣练图》。\n" + "\n" + "581年,杨坚取代北周建立了隋朝,并于589年灭掉南朝最后一个政权——陈,中国历经了三百多年的分裂之后再度实现了统一。不过隋朝也是一个短命的王朝,在修筑了巨大工程——京杭大运河后就灭亡了,只经历了两代37年。\n" + "\n" + "618年,唐高祖李渊推翻隋朝建立了唐朝,它是中国历史上延续时间最长的朝代之一。626年,唐太宗李世民即位,唐朝开始进入鼎盛时期,史称贞观之治。长安(今陕西西安)是当时世界上最大的城市,唐王朝也是当时最发达的文明。高宗李治之妻武则天迁都洛阳,并称帝,成为中国史上唯一的女皇帝,改国号周,并定佛教为国教,广修佛寺,大兴土木。隋唐时期开创的科举制是当时比较科学与公平的人材选拔制度。唐王朝与许多邻国发展了良好的关系,文成公主嫁到吐蕃,带去了大批丝织品和手工艺品。日本则不断派遣使节、学问僧和留学生到中国。唐朝的文化也处于鼎盛,特别是诗文得到较大的发展,还编撰了许多纪传体史书。唐代涌现出许多伟大的文学家,例如诗人李白、杜甫、白居易、杜牧,以及散文家韩愈、柳宗元。唐代的佛教是最兴盛的宗教,玄奘曾赴天竺取经,回国后译成1335卷的经文,并于西安修建了大雁塔以存放佛经。唐朝前期对宗教采取宽容政策,佛教外,道教、摩尼教(Manicheism)、景教和伊斯兰教等也得到了广泛传播。这一切都在李世民的曾孙唐玄宗李隆基统治时期达到顶峰,史称开元盛世。然而在755年,爆发了安史之乱,唐朝由此开始走向衰落。\n" + "\n" + "875年,黄巢起义爆发,唐朝再度分裂,并于907年灭亡,形成了五代十国的混乱局面。\n" + "\n" + "[编辑] 宋元时期\n" + "\n" + " 主条目:辽朝、金朝、西夏、宋朝和元朝\n" + "\n" + "清明上河圖局部,描繪了清明時節,北宋京城汴梁及汴河兩岸的繁華和熱鬧的景象和優美的自然風光。\n" + "清明上河图局部,描绘了清明时节,北宋京城汴梁及汴河两岸的繁华和热闹的景象和优美的自然风光。\n" + "\n" + "经过了五十多年的纷争后,960年北宋控制了中国大部分地区,但是燕云十六州在北方契丹族建立的辽朝手中(五代中的后晋太祖“儿皇帝”石敬瑭所献),河西走廊被党项族建立的西夏趁中原内乱占据,北宋初期虽然曾出兵讨还(宋太宗)但是以失败告终,木以成舟,无可奈何,不得不向日益坐大的辽和西夏交纳岁币。北宋晚期发生了分别以王安石、司马光为首的党派斗争,增加了社会的不安。到了1125年松花江流域女真族,也就是后来的满族,建立的金国势力逐渐强大,1125年,金国灭辽。金国随即开始进攻积弱的北宋,1127年(靖康元年)金国攻破北宋首都汴京(今河南开封),俘虏三千多皇族,其中包括了当时的皇帝宋钦宗和太上皇宋徽宗,因为钦宗其时的年号为靖康,史称靖康之难,北宋灭亡。同年宋钦宗的弟弟赵构在南京应天府(今河南商丘)即皇位,定都临安(今浙江杭州),史称南宋,偏安江南。\n" + "\n" + "此后金与南宋多次交战,英雄人物层出不穷(如名将岳飞)。直到1234年,蒙古南宋联合灭金。随即蒙古与南宋对抗,经历了空前绝后的大规模血腥战争(如襄樊之战, 钓鱼城之战)。1271年忽必烈建立元朝,定都大都(今北京)。元军于1279年与南宋进行了崖山海战,8岁的小皇帝赵昺被民族英雄陆秀夫背着以身殉国惨烈地跳海而死。崖山海战以元朝的胜利告终,南宋随之灭亡。另有一说, 原华夏文明至此夭折.[来源请求]\n" + "\n" + "北宋时期中国出现印刷术和火药。当时中国经济发达,中国海上贸易十分兴盛,福建泉州一带成为繁华的港口,中国当时的经济总量占世界的一半,财政收入超过一亿两白银,首都开封和杭州人口达到400到500万人口,相对当时佛罗伦萨和巴黎十几万人口来讲确实是十分繁华,各国商人云集,文化也极盛,出现了程颐、朱熹等理学家,提倡三从四德。与唐诗并驾齐驱的宋词,有苏轼等词文优秀的词人,出现了中国历史上最著名的女词人李清照,社会文化发达,出现了白蛇传,梁祝等浪漫爱情传说,以至于宋朝被西方学者称为中国的“文艺复兴”。\n" + "\n" + "元朝建立后,一方面吸收了许多中原、汉族文化,以中原的统治机构和方式来统治人民,并大力宣扬朱熹一派的理论(即程朱理学),使得程朱理学成为元朝(以及其后朝代)的官方思想,另一方面却实行了民族等级制度,第一等是蒙古人;第二等是“色目人”,包括原西夏统治区以及来自西域、中亚等地的人口;第三等是“汉人”,包括原金统治区的汉族和契丹、女真等族人;第四等是“南人”,包括原南宋统治区的汉族和其他族人。这种民族制度导致汉族的不满,许多汉族人将元朝视为外来政权,并发动多次反抗。元朝政府除了传统的农业外,也比较重视商业。元朝首都大都十分繁华,来自世界各国的商人云集。在文化上,则出现了与唐诗、宋词并称的元曲,涌现出诸如关汉卿、马致远、王实甫等著名作曲家。\n" + "\n" + "[编辑] 明清时期\n" + "紫禁城太和殿\n" + "紫禁城太和殿\n" + "\n" + " 主条目:明朝、南明、清朝和中国近代史\n" + "\n" + "1368年,农民起义军领袖朱元璋推翻元朝并建立了明朝。明朝前期建都南京,1405年曾帮助明成祖篡位的太监郑和奉命七次下西洋,曾经到达印度洋、东南亚及非洲等地,但后来明朝逐渐走向闭关锁国。1421年,明朝迁都北京。明朝文化上则出现了王阳明、李贽等思想家,以及《三国演义》、《水浒传》、《西游记》和《金瓶梅》等长篇小说。由于明朝末年行政混乱及严重自然灾害,1627年,明末农民大起义爆发,1644年,起义首领李自成攻克北京,明思宗自缢。南方大臣先后拥护福王朱由崧(弘光)、唐王朱聿键(隆武)、桂王朱由榔(永历)为帝,史称南明,最终因实力不足及政治内斗,仍为当时强盛的清朝所灭。\n" + "\n" + "明朝晚期,居住在东北地区的满族开始兴盛起来,终于在1644年李自成攻克北京后不久,驱逐李自成,进入北京,建立了清朝,当时明朝旧臣郑成功南撤到台湾岛,并驱逐了那里的荷兰殖民者,后来被清朝军队攻下。清朝在之后的半个世纪还成功地征服了许多地区,例如新疆、西藏、蒙古以及台湾。康熙年间,清廷还与沙俄在黑龙江地区发生战争,最终于1689年签订停战条约——《中俄尼布楚条约》。清朝由于取消了丁税(人头税),导致人口增加,到19世纪已达当时世界总人口的三分之一,人口的增多促进当时农业的兴盛,为当时世界上第一强国,到1820年时中国的经济总量占世界的三分之一。\n" + "\n" + "然而到了19世纪初,清朝已经走向衰落,在嘉庆年间先后爆发白莲教、天理教的大规模起义。与此同时海上强国英国、荷兰与葡萄牙等纷纷开始强制与中国进行贸易。1787年,英国商人开始向华输入鸦片,导致中国的国际贸易由顺差变为巨额逆差。清廷于1815年颁布搜查洋船鸦片章程,然而英商无视禁令依然走私大量鸦片,道光皇帝不得不于1838年派林则徐赴广州禁烟。1839年6月,将237万多斤鸦片在虎门销毁,史称虎门销烟。英国政府因此于1840年6月发动鸦片战争。一般中国大陆史学界认为这是中国近代史的开始。\n" + "\n" + "[编辑] 清末的内忧外患\n" + "一幅描繪列強瓜分中國情形的漫畫\n" + "一幅描绘列强瓜分中国情形的漫画\n" + "\n" + "鸦片战争持续了一年多,1841年8月英军到达南京,清廷恐惧英军会进逼北京,于是求和,1842年8月29日,《南京条约》签署。香港岛被割让;上海、广州、厦门、福州和宁波开放作为通商口岸,还赔偿款银(西班牙银圆)2100万元。1844年,美国与法国也与清廷分别签订了《望厦条约》和《黄埔条约》,中国的主权受到破坏。\n" + "\n" + "与此同时中国国内反抗清朝的斗争再度兴起。1851年至1864年间,受到基督教影响的秀才洪秀全建立拜上帝会,发动金田起义并创建了太平天国。太平天国曾经一度占领南方部分省份,并定都南京(改名“天京”),建立政教合一的中央政权。同一时期其它的运动还有天地会、捻军、上海小刀会起义、甘肃回民起义等。这些反抗清朝的斗争直到1860年代才基本平息下来。\n" + "\n" + "19世纪后期,英、美、法、俄、日等国多次侵入中国,强迫中国与之签定不平等条约。1858年中俄签定《瑷珲条约》,俄国割去黑龙江以北、外兴安岭以南60多万平方公里的中国领土。1860年,英法联军发动第二次鸦片战争,侵入北京,掠夺并烧毁皇家园林圆明园,并于1860年与清廷签定《北京条约》,各赔英法800万两白银,开放更多通商口岸。同年中俄《北京条约》将乌苏里江以东,包括库页岛(萨哈林岛)、海参崴(符拉迪沃斯托克)约40万平方公里的中国领土,划归俄国。1864年,《中俄勘分西北界约记》将巴尔喀什湖以东、以南和斋桑卓尔南北44万平方公里的中国领土,割给俄国。\n" + "\n" + "为了增强国力并巩固国防,清朝自1860年代开始推行洋务运动,国力有所恢复,并一度出现了同治中兴的局面。1877年清军收复新疆,1881年通过《伊犁条约》清军收复被沙俄占据多年的伊犁。中法战争后清朝还建立了当时号称亚洲第一、世界第六的近代海军舰队—北洋水师。然而在1894年爆发的中日甲午战争中,中国战败,次年被迫与日本签定《马关条约》,赔偿日本2亿两白银,并割让台湾、澎湖列岛给日本。甲午战争的失败,对当时的中国产生了很大的影响。1898年,光绪帝在亲政后同意康有为、梁启超等人提出的变法主张,从6月11日到9月21日的被称为百日维新的103天中进行了多项改革,但最终在慈禧太后发动政变后失败落幕,康有为、梁启超逃亡国外,谭嗣同、刘光第等六人被杀,史称“戊戌六君子”。\n" + "\n" + "1899年,义和团运动爆发,以“扶清灭洋”为宗旨并在慈禧太后默许下开始围攻外国驻北京使馆。于是,各国以解救驻京使馆人员的名义侵入中国,史称八国联军。1901年,清政府被迫与各国签定辛丑条约,赔款4.5亿两白银,分39年还清(本息合计9.8亿两),同时从北京到山海关铁路沿线由各国派兵驻扎,开北京东交民巷为使馆区,国人不得入内等。\n" + "\n" + "[编辑] 20世纪至今\n" + "\n" + " 主条目:中华民国历史和中华人民共和国史\n" + "\n" + "1901年,革命党开始兴起,孙中山等人在海外积极筹款,指挥国内的多次起义运动。经过十次失败的起义后,与革命党互不沟通的湖北新军在武昌起义获得成功。1912年元月,中华民国宣告成立。孙中山就任临时大总统。以清帝退位为条件,孙中山辞去总统位置,由袁世凯接任。但袁世凯妄图恢复帝制。此后,孙中山发起护法运动与护国运动讨伐袁世凯。1916年,袁世凯在称帝83天之后死去,中华民国进入北洋军阀控制中央政府统治时期,地方政府分别由各个军阀派系占据。\n" + "\n" + "孙中山之后多次试图联合南方地方军阀北伐北京中央政府未果。1921年,在共产国际的指导下中国共产党成立,并成为共产国际中国支部。1924年,孙中山提出新三民主义并确定联俄联共扶助农工的政策,国民党在共产国际帮助下改组,共产党员以个人身份加入国民党,国共两党进行第一次合作。孙中山自建立广州军政府(1923年改称大元帅府)以后,曾经三次进行北伐,均因条件不具备而未果。1925年春,孙中山病逝于北京。同年,广州国民政府为统一与巩固广东革命根据地,先后举行第一次东征第二次东征与南征,肃清广东境内的军阀势力和反革命武装,并将广东境内倾向革命的军队统一改编为国民革命军,下辖第1至第6军。不久又将广西部队改编为第7军。为北伐战争作了重要准备。1926年6月5日,国民党中央执行委员会正式通过国民革命军出师北伐案,并任命蒋介石为国民革命军总司令正式开始北伐。然而随着北伐和国民革命的深入,国民党不能容忍共产党激进的工人运动,国共两党分裂,大量共产党员及其支持者被清出国民党,有的被拘捕和杀害。1927年8月1日,以周恩来、贺龙、叶挺为首的共产党员在江西南昌发动南昌叛乱,共产党从此有自己独立的军队(中华人民共和国成立后,8月1日被定为建军节)。并于江西瑞金建立了第一个红色苏维埃地方割据政权。此后南京国民政府先后对中央苏区进行五次围剿,红军逃过了前四次围剿,在第五次战争失败,不得不离开红区。1934年开始,红军进行战略转移,在贵州遵义确立了毛泽东对红军的领导和指挥权,四渡赤水河,终于摆脱了追击,途经江西,贵州,四川,甘肃,陕西,经过二万五千里长征,最后在陕西北部与陕北红军刘志丹部会师,建立陕甘宁共产党临时政府。\n" + "毛泽東在天安门城楼上宣布中华人民共和國的成立\n" + "毛泽东在天安门城楼上宣布中华人民共和国的成立\n" + "\n" + "1931年9月18日,日本开始侵华,占领了东北全境。1936年12月12日,西安事变后国共第二次合作抗日。1937年7月7日,抗日战争全面爆发,蒋中正在庐山发表著名的“最后关头”的演说,号召全国人民一致抗日。在日军进行南京大屠杀前夕,中华民国首都从南京迁至武汉,后来迁至重庆,在八年间蒋中正为统帅的抗日力量共进行了22次大会战,和成千上万次大小战斗。1945年,二战结束后,当时的中国国民政府从日本手里获得了台湾及澎湖列岛以及其他一些领土,但也在1946年与苏联签订的条约中承认了外蒙古的独立(1951年,迁往台湾的国民党国民政府以苏联未履约为由,不承认该条约及依据该条约而独立的外蒙古的独立地位;但是,蒙古独立已为既成事实)。1946年6月,国共两党又进行了内战。中国共产党最终于1949年获得决定性胜利,中华民国中央政府迁往战后的台湾。中华人民共和国在北平成立,并将北平改名为北京,毛泽东宣布中华人民共和国政府为包括台湾在内的全中国的唯一合法政府。与此同时,蒋介石宣布台北为中华民国临时首都,宣誓三年内反攻大陆。(请参看台湾问题)\n" + "\n" + "中共执政之初,采取“土地革命”“公私合营”等手段,国内纷乱的局势暂时得到了稳定。按照中共的史观,自1956年“三大改造”完成后,中国正式进入社会主义阶段。并制订第一个五年计划,大力发展重工业,国家经济一度好转。但是1958年,毛泽东发动“大跃进”运动与人民公社话运动,各地浮夸风“放卫星”等谎报数据的情况盛行。自1959年到1961年,国家经济又陷入濒临崩溃的境地,中共称其为“三年自然灾害”。毛泽东因此退居幕后,以刘少奇为首的一批官僚着手恢复经济,国家形式得到了回稳。1966年,文化大革命爆发,刘少奇、贺龙等人被打倒,毛泽东再度成为政治领导,林彪一度成为内定接班人。在林彪阴谋败露后,四人帮成为新的重要政治势力。1976年,周恩来朱德先后去世;9月9日,毛泽东去世。华国锋接替了毛的领导地位,四人帮被打倒。但是华提出了“两个凡是”的路线,国家实质上仍然没有完全脱离文化大革命阶段。 1978年,邓小平复出,中共十一届三中全会召开,改革开放时代正式到来。中国的经济开始步入正轨。但是,由于通货膨胀与政治腐败,民间不满情绪开始酝酿。胡耀邦的去世成为愤怒爆发的导火索,终致爆发了六四事件。从此以后,改革的步伐一度停滞,直到1992年邓小平南巡后才得以改变。1997年,中国收复香港的主权,江泽民也接替邓成为了新的中国领导人。2002 年后,胡锦涛成为新的国家领导人,上海帮淡出政治中心。中共政府近几年渐渐放弃“韬光养晦”的外交方针,在外交舞台上动作频繁,并加强对台湾的攻势。经济改革依然得到了持续,但政治改革的话题仍然是禁忌。而由于贫富差距的拉大与政治腐败不见好转,民间对中共的评价与看法也日益两极。\n" + "\n" + "至于中华民国,在国府迁台后,国民党始终保持对政治与言论自由的强力控制。1986年,中华民国第一个反对党民主进步党成立,威权时代的戒严体制开始松动。1987年,中华民国政府正式宣告台湾省解严,进入了一个新的时代。之后,1996年实现了第一次民选总统;2000年更实现第一次政党和平轮替。2005年,末代国民大会召开,中华民国宪法出现了重大修改。今后,民主化的中华民国仍然充满变量。\n" + "\n" + "[编辑] 参见\n" + "\n" + " * 中国\n" + " * 中国历史年表\n" + " * 中国历史事件列表\n" + " * 诸侯会盟\n" + " * 中国历史地图\n" + "\n" + " \n" + "\n" + " * 中华人民共和国历史年表\n" + " * 中华人民共和国史\n" + " * 汉学\n" + " * 中华文明\n" + " * 中国历史大事年表\n" + "\n" + " \n" + "\n" + " * 中国文化\n" + " * 中国行政区划\n" + " * 中国朝代\n" + " * 夏商周断代工程\n" + " * 中国古都\n" + "\n" + " \n" + "\n" + " * 中国战争列表\n" + " * 中国国旗\n" + " * 中国皇帝\n" + " * 中国历代王朝君主世系表\n" + " * 中国君王诸子女列表\n" + " * 中华民国历史\n" + "\n" + "[编辑] 其他特定主题中国史\n" + "\n" + " * 中国军事史\n" + " * 中国科学技术史\n" + " * 中国文化史\n" + " * 中国文学史\n" + " * 中国艺术史\n" + " * 中国经济史\n" + " * 中国体育史\n" + " * 中国人口史\n" + " * 中国疆域史\n" + " * 中国盗墓史\n" + " * 中国酷刑史\n" + " * 中国食人史\n" + " * 中国盐业史\n" + "\n" + "[编辑] 注解\n" + "\n" + " 1. ↑ 柳翼谋:《中国文化史》\n" + "\n" + "[编辑] 参考文献\n" + "\n" + " 1. 白寿彝主编:中国通史纲要,1993年上海:人民出版社,ISBN 7208001367\n" + " 2. 周谷城著:中国通史,1995年上海:人民出版社,ISBN 7208003300\n" + " 3. 李敖著:独白下的传统,2000年香港:三联书店(香港)有限公司,ISBN 9620418913\n" + " 4. 范文澜著:中国近代史,1962年北京:人民出版社,统一书号 11001241\n" + " 5. 徐中约著:中国近代史(上册),香港2001 中文大学出版社,ISBN 9622019870\n" + " 6. Korotayev A., Malkov A., Khaltourina D. Introduction to Social Macrodynamics: Secular Cycles and Millennial Trends. Moscow: URSS, 2006. ISBN 5-484-00559-0 [1] (Chapter 2: Historical Population Dynamics in China).\n" + "\n" + "[编辑] 相关著作\n" + "\n" + " * 《二十四史》 (正史)\n" + " * 《国史要义》 柳诒徵\n" + " * 《国史大纲》 钱穆\n" + " * 《中华五千年史》 张其昀\n" + "\n" + "[编辑] 外部链接\n" + "维基共享资源中相关的多媒体资源:\n" + "中国历史\n" + "\n" + " * 中华万年网\n" + " * 一个全面专门研究中华历史的论坛:中华历史网论坛\n" + " * (正体中文 - 台湾)《中国大百科全书》:中国历史概述\n"; var cyrillic = "История Китая\n" + "[править]\n" + "Материал из Википедии — свободной энциклопедии\n" + "Перейти к: навигация, поиск\n" + "История Китая\n" + "История Китая\n" + "Три властителя и пять императоров\n" + "Династия Ся\n" + "Династия Шан\n" + "Династия Чжоу \n" + "Западное Чжоу\n" + "Восточное Чжоу Чуньцю\n" + "Чжаньго\n" + "Династия Цинь\n" + "(Династия Чу) - смутное время\n" + "Династия Хань Западная Хань\n" + "Синь, Ван Ман\n" + "Восточная Хань\n" + "Эпоха Троецарствия Вэй Шу У\n" + "Цзинь\n" + " Западная Цзинь\n" + "Шестнадцать варварских государств Восточная Цзинь\n" + "Северные и Южные Династии\n" + "Династия Суй\n" + "Династия Тан\n" + "Ляо\n" + " \n" + "5 династий и 10 царств\n" + "Северная Сун\n" + " \n" + "Сун\n" + "Цзинь\n" + " \n" + "Западная Ся\n" + " \n" + "Южная Сун\n" + "Династия Юань\n" + "Династия Мин\n" + "Династия Цин\n" + "Китайская республика\n" + "Китайская Народная Республика\n" + " Китайская республика (Тайвань)\n" + "\n" + "Китайская цивилизация — одна из старейших в мире. По утверждениям китайских учёных, её возраст может составлять пять тысяч лет, при этом имеющиеся письменные источники покрывают период не менее 3500 лет. Наличие систем административного управления, которые совершенствовались сменявшими друг друга династиями, ранняя освоенность крупнейших аграрных очагов в бассейнах рек Хуанхэ и Янцзы создавало преимущества для китайского государства, экономика которого основывалась на развитом земледелии, по сравнению с соседями-кочевниками и горцами. Ещё более укрепило китайскую цивилизацию введение конфуцианства в качестве государственной идеологии (I век до н. э.) и единой системы письма (II век до н. э.).\n" + "Содержание\n" + "[убрать]\n" + "\n" + " * 1 Древний Китай\n" + " * 2 Государство Шан-Инь\n" + " * 3 Государство Чжоу (XI—III вв. до н. э.)\n" + " * 4 Империя Цинь\n" + " * 5 Империя Хань\n" + " * 6 Государство Цзинь и период Нань-бэй чао (IV—VI вв.)\n" + " * 7 Государство Суй (581—618)\n" + " * 8 Государство Тан\n" + " * 9 Государство Сун\n" + " * 10 Монголы и государство Юань (1280—1368)\n" + " * 11 Государство Мин (1368—1644)\n" + " * 12 Государство Цин\n" + " o 12.1 Внешняя экспансия Цин\n" + " o 12.2 Цинский Китай и Россия\n" + " o 12.3 Опиумные войны\n" + " o 12.4 Японо-китайская война 1894—1895 годов\n" + " o 12.5 Тройственная интервенция\n" + " o 12.6 Успехи русской политики в Китае\n" + " o 12.7 Захват Цзяочжоу Германией\n" + " o 12.8 Сто дней реформ\n" + " * 13 XX век\n" + " o 13.1 Боксерское восстание\n" + " o 13.2 Русско-японская война\n" + " o 13.3 Смерть Цыси\n" + " o 13.4 Аннексия Кореи\n" + " o 13.5 Революция 1911 года и создание Китайской Республики\n" + " o 13.6 Первая мировая война\n" + " o 13.7 Эра милитаристов\n" + " o 13.8 Победа Гоминьдана\n" + " o 13.9 Японская оккупация и Вторая мировая война\n" + " o 13.10 Создание Китайской Народной Республики\n" + " o 13.11 Культурная революция\n" + " o 13.12 Экономическая либерализация\n" + " * 14 См. также\n" + " * 15 Литература\n" + "\n" + "[править] Древний Китай\n" + "\n" + "Китайская цивилизация (предков государствообразующего этноса хань) — группа культур (Баньпо 1, Шицзя, Баньпо 2, Мяодигоу, Чжуншаньчжай 2, Хоуган 1 и др.) среднего неолита (ок. 4500-2500 до н.э.) в бассейне реки Хуанхэ, которые традиционно объединяются общим названием Яншао. Представители этих культур выращивали зерновые (чумиза и др.) и занимались разведением скота (свиньи). Позднее в этом районе появились ближневосточные виды злаков (пшеница и ячмень) и породы домашнего скота (коровы, овцы, козы).\n" + "\n" + "[править] Государство Шан-Инь\n" + "\n" + "Первым известным государством бронзового века на территории Китая было государство Шан-Инь, сформировавшееся в XIV веке до н. э. в среднем течении реки Хуанхэ, в районе Аньяна.\n" + "\n" + "В результате войн с соседними племенами его территория расширилась и к XI веку до н. э. охватывала территории современных провинций Хэнань и Шаньси, а также часть территории провинций Шэньси и Хэбэй. Уже тогда появились зачатки лунного календаря и возникла письменность — прообраз современного иероглифического китайского письма. Иньцы значительно превосходили окружающие их племена и с военной точки зрения — у них было профессиональное войско, использовавшее бронзовое оружие, луки, копья и боевые колесницы. Иньцы практиковали человеческие жертвоприношения — чаще всего в жертву приносились пленные.\n" + "\n" + "В XI веке до н. э. государство Инь было завоёвано немногочисленным западным племенем Чжоу, которое до этого находилось в вассальных отношениях с иньцами, но постепенно укрепилось и создало коалицию племён.\n" + "\n" + "[править] Государство Чжоу (XI—III вв. до н. э.)\n" + "Китайская медная монета в виде мотыги. Провинция Лоян, V-III в. до н.э.\n" + "Китайская медная монета в виде мотыги. Провинция Лоян, V-III в. до н.э.\n" + "\n" + "Обширная территория государства Чжоу, охватывавшая практически весь бассейн Хуанхэ, со временем распалась на множество соперничающих между собой самостоятельных государственных образований — изначально, наследственных уделов на территориях, заселённых различными племенами и расположенных на удалении от столиц — Цзунчжоу (западной - около г. Сиань) и Чэнчжоу (восточной - Лои, Лоян). Эти уделы предоставлялись во владение родственникам и приближённым верховного правителя — обычно чжоусцам. В междоусобной борьбе число первоначальных уделов постепенно сокращалось, а сами уделы укреплялись и становились более самостоятельными.\n" + "\n" + "Население Чжоу было разнородным, причём наиболее крупную и развитую его часть составляли иньцы. В государстве Чжоу значительная часть иньцев была расселена на новых землях на востоке, где была построена новая столица — Чэнчжоу (современная провинция Хэнань).\n" + "\n" + "Для периода Чжоу в целом характерно активное освоение новых земель, расселение и этническое смешивание выходцев из различных районов, уделов (впоследствии — царств), что способствовало созданию фундамента будущей китайской общности.\n" + "\n" + "Период Чжоу (XI—III вв. до н. э.) делится на так называемые Западное и Восточное Чжоу, что связано с переездом правителя Чжоу в 770 до н. э. под угрозой нашествия варварских племён из Цзунчжоу — первоначальной столицы государства — в Чэнчжоу. Земли в районе старой столицы были отданы одному из союзников правителя государства, который создал здесь новый удел Цинь. Впоследствии именно этот удел станет центром единой китайской империи.\n" + "\n" + "Период Восточное Чжоу, в свою очередь, разделяется на два периода:\n" + "\n" + " * Чуньцю ( «Период Весны и Осени» VIII—V вв. до н. э.);\n" + " * Чжаньго («Период Сражающихся царств», V—III вв. до н. э.).\n" + "\n" + "В период Восточного Чжоу власть центрального правителя — вана, сына Неба (тянь-цзы), правящего Поднебесной по Мандату Неба (тянь-мин), — постепенно ослабла, а ведущую политическую роль стали играть сильные уделы, превращавшиеся в крупные царства. Большинство из них (за исключением окраинных) именовали себя «срединными государствами» (чжун-го), ведущими своё происхождение от раннечжоуских уделов.\n" + "\n" + "В период Восточного Чжоу формируются основные философские школы древнего Китая — конфуцианство (VI—V вв. до н. э.), моизм (V в. до н. э.), даосизм (IV в. до н. э.), легизм.\n" + "\n" + "В V—III вв. до н.э. (период Чжаньго) Китай вступает в железный век. Расширяются сельскохозяйственные площади, увеличиваются ирригационные системы, развиваются ремёсла, революционные изменения происходят в военном деле.\n" + "\n" + "В период Чжаньго на территории Китая сосуществовало семь крупнейших царств — Вэй, Чжао и Хань (ранее все три входили в царство Цзинь), Цинь, Ци, Янь и Чу. Постепенно в результате ожесточённого соперничества верх стало одерживать самое западное — Цинь. Присоединив одно за другим соседние царства, в 221 до н. э. правитель Цинь — будущий император Цинь Ши Хуан — объединил весь Китай под своей властью.\n" + "\n" + "Так в середине III века до н. э. завершился период Восточного Чжоу.\n" + "\n" + "[править] Империя Цинь\n" + "\n" + "Объединив древнекитайские царства, император Цинь Ши Хуан конфисковал всё оружие у населения, переселил десятки тысяч семей наследственной знати из различных царств в новую столицу — Сяньян и разделил огромную страну на 36 новых областей, которые возглавили назначаемые губернаторы.\n" + "\n" + "При Цинь Шихуанди были соединены оборонительные стены (валы) северных чжоуских царств и создана Великая китайская стена. Было сооружено несколько стратегических дорог из столицы на окраины империи. В результате успешных войн на севере гунны (сюнну) были оттеснены за Великую стену. На юге к империи были присоединены значительные территории племён юэ, в том числе северная часть современного Вьетнама.\n" + "Строительство Великой китайской стены, протянувшейся на более чем 6700 км, было начато в III веке до н. э. для защиты северных районов Китая от набегов кочевников.\n" + "Строительство Великой китайской стены, протянувшейся на более чем 6700 км, было начато в III веке до н. э. для защиты северных районов Китая от набегов кочевников.\n" + "\n" + "Цинь Шихуанди, строивший все свои реформы на основах легизма с казарменной дисциплиной и жестокими наказаниями провинившихся, преследовал конфуцианцев, предавая их казни (погребение заживо) и сжигая их сочинения — за то, что они смели выступать против установившегося в стране жесточайшего гнёта.\n" + "\n" + "Империя Цинь прекратила существование вскоре после смерти Цинь Шихуанди.\n" + "\n" + "[править] Империя Хань\n" + "\n" + "Вторую в истории Китая империю, получившую название Хань (206 до н. э.—220 н. э.) основал выходец из среднего чиновничества Лю Бан (Гао-цзу), один из военачальников возрожденного царства Чу, воевавших против Цинь после смерти императора Цинь Шихуана в 210 г. до н.э.\n" + "\n" + "Китай в это время переживал экономический и социальный кризис, вызванный потерей управляемости и войнами военачальников циньских армий с элитами уничтоженных раннее царств, пытавшихся восстановить свою государственность. Из-за переселений и войн значительно сократилась численность сельского населения в основных аграрных районах.\n" + "\n" + "Важная особенность смены династий в Китае состояла в том, что каждая новая династия приходила на смену предыдущей в обстановке социально-экономического кризиса, ослабления центральной власти и войн между военачальниками. Основателем нового государства становился тот из них, кто мог захватить столицу и насильственно отстранить правившего императора от власти.\n" + "\n" + "С правления Гао-цзу (206–195 до н.э.) начинается новый период китайской истории, который получил название Западная Хань.\n" + "\n" + "При императоре У-ди (140—87 до н. э.) была взята на вооружение иная философия — восстановленное и реформированное конфуцианство, которое стало господствующей официальной идеологией вместо дискредитировавшего себя легизма с его жёсткими нормами и бесчеловечной практикой. Именно с этого времени берёт своё начало китайская конфуцианская империя.\n" + "\n" + "При нем территория ханьской империи значительно расширяется. Были уничтожены вьетское государство Намвьет (территория современной провинции Гуандун, Гуанси-Чжуанского автономного района и север Индокитайского полуострова), вьетские государства в южных частях современных провинций Чжэцзян и Фуцзянь, корейское государство Чосон, присоеденены земли на юго-западе, сюнну оттеснены далее на севере.\n" + "\n" + "Китайский путешественник Чжан Цянь проникает далеко на запад и описывает многие страны Средней Азии (Фергана, Бактрия, Парфия и др.). Вдоль пройденного им маршрута прокладывается торговый путь через Джунгарию и Восточный Туркестан в страны Средней Азии и Ближнего Востока — так называемый «Великий шёлковый путь». Империя на некоторое время подчиняет себе оазисы-протогосударства вдоль Шёлкового пути и распространяет своё влияние до Памира.\n" + "\n" + "В I в. н. э. в Китай из Индии начинает проникать буддизм.\n" + "\n" + "В период с 8 по 23 гг. н. э. власть захватывает Ван Ман, провозглашающий себя императором и основателем государства Синь. Начинается ряд преобразований, который прерывается экологической катастрофой - река Хуанхэ изменила русло. Из-за трехлетнего голода центральная власть ослабла. В этих условиях началось движение представителей рода Лю за возвращение престола. Ван Ман был убит, столица взята, власть возвратилась династии Лю.\n" + "\n" + "Новый период получил название Восточная Хань, он продлился до 220 г. н. э.\n" + "\n" + "[править] Государство Цзинь и период Нань-бэй чао (IV—VI вв.)\n" + "\n" + "Восточную Хань сменил период Троецарствия (Вэй, Шу и У). В ходе борьбы за власть между военачальниками было основано новое государство Цзинь (265—420).\n" + "\n" + "В начале IV века Китай подвергается нашествию кочевников — сюнну (гуннов), сяньбийцев, цянов, цзе и др. Весь Северный Китай был захвачен кочевниками, которые создали здесь свои царства, так называемые 16 варварских государств Китая. Значительная часть китайской знати бежала на юг и юго-восток, основанное там государство получило название Восточная Цзинь.\n" + "\n" + "Кочевники приходят волнами, одна за другой, и после каждой из этих волн в Северном Китае возникают новые царства и правящие династии, которые, однако, принимают классические китайские названия (Чжао, Янь, Лян, Цинь, Вэй и др.).\n" + "\n" + "В это время, с одной стороны, происходит варваризация образа жизни оседлых китайцев — разгул жестокости, произвола, массовых убийств, нестабильности, казней и бесконечных переворотов. А с другой стороны, пришельцы-кочевники активно стремятся использовыть китайский опыт управления и китайскую культуру для стабилизации и упрочения своей власти — мощь китайской конфуцианской цивилизации в конечном счёте гасит волны нашествий варварских племён, которые подвергаются китаизации. К концу VI века потомки кочевников практически полностью ассимилируются с китайцами.\n" + "\n" + "На севере Китая верх в столетней борьбе между некитайскими царствами берёт сяньбийское государство Тоба Вэй (Северная Вэй), объединившее под своей властью весь Северный Китай (бассейн Хуанхэ) и к концу V века в борьбе против южнокитайского государства Сун распространившее своё влияние до берегов Янцзы. При этом уже в VI веке, как было сказано, захватчики-сяньбийцы ассимилировались с подавляющим большинством местного населения.\n" + "\n" + "С началом варварских вторжений на север Китая, сопровождавшихся массовым уничтожением и порабощением местного населения, до миллиона местных жителей — в первую очередь знатных, богатых и образованных, включая императорский двор, — перебрались на юг, в районы, сравнительно недавно присоединённые к империи. Пришельцы с севера, заселив речные долины, активно занялись выращиванием риса и постепенно превратили Южный Китай в основной земледельческий район империи. Уже в V веке здесь стали собирать по два урожая риса в год. Резко ускорилась китаизация и ассимиляция местного населения, колонизация новых земель, строительство новых городов и развитие старых. На юге сосредоточился центр китайской культуры.\n" + "\n" + "Одновременно здесь укрепляет свои позиции буддизм — на севере и юге построено уже несколько десятков тысяч монастырей с более чем 2 млн. монахов. В немалой степени распространению буддизма способствует ослабление официальной религии — конфуцианства — в связи с варварскими вторжениями и междоусобицами. Первыми китайскими буддистами, способствовавшими популяризации новой религии, были приверженцы даосизма — именно с их помощью переводились с санскрита на китайский древние буддийские тексты. Буддизм постепенно стал процветающей религией.\n" + "\n" + "[править] Государство Суй (581—618)\n" + "\n" + "Процесс китаизации варваризованного севера и колонизованного юга создаёт предпосылки для нового объединения страны. В 581 севернокитайский полководец Чжоу Ян Цзянь объединяет под своей властью весь Северный Китай и провозглашает новую династию Суй (581—618), а после уничтожения южнокитайского государства Чэнь возглавляет объединённый Китай. В начале VII века его сын Ян Ди ведёт войны против корейского государства Когурё (611 - 614) и вьетнамского государства Вансуан, строит Великий канал между Хуанхэ и Янцзы для транспортировки риса с юга в столицу, создаёт роскошные дворцы в столице Лоян, восстанавливает и строит новые участки Великой китайской стены, пришедшей в упадок за тысячу лет.\n" + "\n" + "Подданные не выдерживают тягот и лишений и восстают. Ян Ди убивают, а династию Суй сменяет династия Тан (618—907), основатель — шансийский феодал Ли Юань.\n" + "\n" + "[править] Государство Тан\n" + "\n" + "Правители из династии Лю покончили с выступлениями знати и провели ряд успешных преобразований. Происходит разделение страны на 10 провинций, была восстановлена \"надельная система\", усовершенствовано административное законодательство, укреплена вертикаль власти, оживились торговля и городская жизнь. Значительно увеличились размеры многих городов и численность городского населения.\n" + "\n" + "К концу VII века усилившееся военное могущество Танской империи приводит к расширению территории Китая за счёт Восточно-Тюркского и Западно-Тюркского каганатов. Государства, расположенные в Джунгарии и Восточном Туркестане, на некоторое время становятся данниками Китая. Корейское государство Когурё покорено и становится Аньдунским наместничеством Китая. Вновь открыт Великий шёлковый путь.\n" + "\n" + "В VIII—X вв. в Китае получают распространение новые сельскохозяйственные культуры — в частности, чай, хлопок.\n" + "\n" + "Развивается морская торговля, главным образом через Гуанчжоу (Кантон), с Индией и Ираном, Арабским Халифатом, корейским государством Силла и Японией.\n" + "\n" + "В VIII веке империю Тан ослабляют конфликты между центральной властью и военными наместниками на периферии. Окончательно господство династии Лю подрывает война Хуан Чао за престол 874—901.\n" + "\n" + "В течение долгого времени (907—960) в стране не удаётся восстановить единую государственную власть, что связано с междоусобными войнами, особенно на севере страны.\n" + "\n" + "[править] Государство Сун\n" + "\n" + "В 960 военачальник Чжао Куан-инь основывает династию Сун (960—1279). Все три столетия Сун прошли под знаком успешного давления на Китай со стороны северных степных народов.\n" + "\n" + "Ещё в начале X века усилилось развитие и консолидация протомонгольской этнической общности киданей, соседствовавшей с Китаем на северо-востоке. Государство киданей, основанное в 916 и существовавшее по 1125, получило название Ляо. Активно укрепляясь на северных рубежах, кидани отторгли часть китайских территорий (часть современных провинций Хэбэй и Шаньси). Основы управления в государстве Ляо были созданы китайцами и корейцами, на основе китайских иероглифов и из китайских элементов письма была создана письменность, развивались города, ремёсла, торговля. Не сумев справиться с соседями и вернуть утраченные территории, Сунская империя была вынуждена пойти на подписание в 1004 мирного договора и согласиться на выплату дани. В 1042 дань была увеличена, а в 1075 Китай отдал киданям ещё часть своей территории.\n" + "\n" + "В то же время на северо-западных окраинах Сунской империи, к западу от киданей, на рубеже X—XI вв. складывается сильное государство тангутов — Западное Ся. Тангуты отторгли от Китая часть современной провинции Шэньси, целиком территорию современной провинции Ганьсу и Нинся-Хуэйского автономного района. С 1047 Сунской империи пришлось и тангутам платить дань серебром и шёлком.\n" + "\n" + "Несмотря на вынужденные территориальные уступки соседям период Сун считается эпохой экономического и культурного расцвета Китая. Растёт число городов, продолжается рост численности городского населения, китайские ремесленники достигают высот в изготовлении изделий из фарфора, шёлка, лака, дерева, слоновой кости и др. Изобретены порох и компас, распространяется книгопечатание, выводятся новые высокоурожайные сорта зерновых, увеличиваются посевы хлопка. Одной из наиболее впечатляющих и эффективных из данных инноваций было вполне сознательное, систематическое и хорошо организованное внедрение и распространение новых сортов скороспелого риса из Южного Вьетнама (Чампы).\n" + "Чжан Цзэдуань. «По реке в День поминовения усопших» (XII век).\n" + "Чжан Цзэдуань. «По реке в День поминовения усопших» (XII век).\n" + "\n" + "В XII веке Китаю приходится отдать ещё большую территорию новым захватчикам — южноманьчжурским чжурчжэням, создавшим (на базе уничтоженной ими в 1125 империи киданей Ляо) государство (впоследствии — империю) Цзинь (1115—1234), границы которой проходили по р. Хуайхэ. При этом часть разбитых киданей ушла на запад, где в районе рек Талас и Чу сложилось небольшое государство кара-китаев — Западное Ляо (1124—1211).\n" + "\n" + "В 1127 чжурчжэни захватывают столицу империи Сун — Кайфын и берут в плен императорскую семью. Один из сыновей императора бежит на юг, в Ханчжоу, который впоследствии становится столицей новой — южносунской империи (1127—1280). Продвижение армии чжурчжэней на юг сдерживает лишь река Янцзы. Граница между Цзинь и южносунской империей устанавливается по междуречью Хуанхэ и Янцзы. Северный Китай вновь на длительное время оказывается под господством иноземных завоевателей.\n" + "\n" + "В 1141 подписан мирный договор, согласно которому Сунская империя признаёт себя вассалом империи Цзинь и обязуется платить ей дань.\n" + "\n" + "[править] Монголы и государство Юань (1280—1368)\n" + "\n" + "В начале XIII века в Китай вторгаются монголы. До XIII века монголы являлись частью большой степной общности, которую китайцы называли \"татарами\". Их предшественники — протомонгольские и раннемонгольские группы и народы, одним из которых были кидани, представляли собой степных кочевников, разводивших лошадей и рогатый скот, кочевавших от пастбища к пастбищу и организованных в небольшие родоплеменные коллективы, связанные общностью происхождения, языка, культуры и т. п.\n" + "\n" + "Соседство развитой китайской цивилизации способствовало ускорению процесса создания племён, а затем и мощных племенных союзов во главе с влиятельными вождями. В 1206 на всемонгольском курултае вождём всех монголов был провозглашён победивший в жестокой междоусобной борьбе Темучин, принявший имя и титул Чингисхана.\n" + "\n" + "Чингисхан создал организованную и боеспособную армию, которая и стала решающим фактором в последующих успехах сравнительно немногочисленного монгольского этноса.\n" + "\n" + "Покорив соседние народы Южной Сибири, Чингисхан в 1210 пошёл войной на чжурчжэней и в 1215 взял Пекин.\n" + "\n" + "В 1219—1221 была разорена Средняя Азия и разбито государство Хорезмшахов. В 1223 — разбиты русские князья, в 1226—1227 — уничтожено государство тангутов. В 1231 основные силы монголов вернулись в Северный Китай и к 1234 завершили разгром чжурчжэньского государства Цзинь.\n" + "\n" + "Завоевания в Южном Китае были продолжены уже в 1250-х, после походов в Европу и на Ближний и Средний Восток. Вначале монголы захватили страны, окружавшие Южно-Сунскую империю — государство Дали (1252—1253), Тибет (1253). В 1258 монгольские войска под предводительством хана Хубилая с разных сторон вторглись в Южный Китай, но осуществлению их планов помешала неожиданная смерть Великого хана Мункэ (1259). Хан Хубилай, захватив ханский престол, в 1260 перенёс столицу из Каракорума на территорию Китая (сначала в Кайпин, а в 1264 в Чжунду — современный Пекин). Столицу южносунского государства Ханчжоу монголам удалось взять лишь в 1276. К 1280 весь Китай был завоёван, а Сунская империя — уничтожена.\n" + "\n" + "После покорения Китая хан Хубилай основывает новую династию Юань (1271—1368), на службу новой власти привлекаются кидани, чжурчжэни, тюрки и даже европейцы — в частности, в это время Китай посещает венецианский купец Марко Поло.\n" + "\n" + "Тяжёлый экономический, политический и национальный гнёт, установленный монгольскими феодалами, сдерживает развитие страны. Множество китайцев было обращено в рабство. Земледелие и торговля были подорваны. Не выполнялись необходимые работы по поддержанию ирригационных сооружений (дамб и каналов), что привело в 1334 к чудовищному наводнению и гибели нескольких сот тысяч человек. Великтий Китайский канал был построен во время монгольского господства.\n" + "\n" + "Народное недовольство новыми правителями вылилось в мощное патриотическое движение и восстания, которые возглавили руководители тайного общества «Белый лотос» (Байляньцзяо).\n" + "\n" + "[править] Государство Мин (1368—1644)\n" + "\n" + "В результате длительной борьбы в середине XIV века монголы были изгнаны. К власти пришёл один из руководителей восстания — сын крестьянина Чжу Юаньчжан, основавший государствоМин (1368—1644).\n" + "\n" + "Монголы, оттеснённые на север, приступают к активному освоению степей современной Монголии. Империя Мин подчиняет себе часть чжурчжэньских племён, государство Наньчжао (современные провинции Юньнань и Гуйчжоу), часть современных провинций Цинхай и Сычуань.\n" + "\n" + "Китайский флот под командой Чжэн Хэ, состоящий из нескольких десятков многопалубных фрегатов, за период с 1405 по 1433 совершает несколько морских экспедиций в Юго-Восточную Азию, Индию и к восточному побережью Африки. Не принеся Китаю никакой экономической выгоды, экспедиции были прекращены, а корабли — разобраны.\n" + "\n" + "В XVI веке происходит первая попытка усилившейся Японии вторгнуться в Китай и Корею. В это же время в Китай проникают европейцы — португальцы, испанцы, голландцы. В 1557 Португалия овладела на правах «аренды» китайской территорией Аомынь (Макао). В Китае появляются и христианские миссионеры — иезуиты. Они привезли в Китай новые инструменты и механизмы — часы, астрономические приборы, наладили здесь производство огнестрельного оружия. В то же время они занимаются доскональным изучением Китая.\n" + "\n" + "[править] Государство Цин\n" + "\n" + "К концу XVI века северные соседи империи Мин — потомки чжурчжэньских племён, разбитых в своё время Чингисханом, — объединяются вокруг владения Маньчжоу под предводительством вождя Нурхаци (1559—1626). В 1609 Нурхаци прекращает платить дань Китаю, а затем провозглашает собственную династию Цзинь. С 1618 маньчжуры усиливают вооружённое давление на Китай. За восемь лет они выходят практически к Великой китайской стене (на крайнем востоке).\n" + "\n" + "Преемник Нурхаци Абахай провозглашает себя императором и меняет название династии на Цин. В начале XVII века маньчжуры завоевали Южную (Внутреннюю) Монголию. На всей территории Южной Маньчжурии и захваченных ханств Южной Монголии устанавливается централизованная администрация.\n" + "\n" + "Маньчжурская конница, поддержанная внутренними монголами, начинает совершать регулярные набеги на Китай, грабя и обращая в рабство сотни тысяч китайцев. Императору Мин приходится направить на северные рубежи свою лучшую армию под командованием У Саньгуя. Тем временем в Китае разгорается очередное крестьянское восстание. В 1644 крестьянские отряды под предводительством Ли Цзычэна, разгромив все остальные армии, занимают Пекин, а сам Ли Цзычэн провозглашает себя императором. У Саньгуй пропускает маньчжурскую конницу на Пекин. 6 июня 1644 маньчжуры захватывают столицу. Ли Цзычэн вскоре гибнет, а маньчжуры объявляют своего малолетнего императора Шуньчжи правителем всего Китая. У Саньгуй вместе со всей армией переходит на службу к завоевателям.\n" + "\n" + "Борьба против маньчжурских захватчиков продолжается ещё долго, но ослабленный Китай не в силах противостоять хорошо вооружённому и организованному войску. Последний оплот сопротивления — Тайвань захвачен маньчжурами в 1683.\n" + "\n" + "Маньчжурская династия в государстве Цин правила с 1644 по 1911 год. В руках маньчжурской знати находились высшие органы власти и руководство армией. Смешанные браки были запрещены, и тем не менее маньчжуры быстро китаизировались, тем более что, в отличие от монголов, они не противопоставляли себя китайской культуре.\n" + "\n" + "Начиная с Канси (годы правления 1662—1723), маньчжурские императоры были ревностными конфуцианцами, управляя страной по древним законам. Китай под властью династии Цин в XVII—XVIII вв. развивался достаточно интенсивно. К началу XIX века в Китае насчитывалось уже около 300 млн. человек — примерно в пять раз больше, чем в среднем на протяжении предыдущих двух тысяч лет. Демографическое давление привело к необходимости интенсификации сельского хозяйственного производства при активном участии государства. Маньчжуры обеспечили покорность китайского населения, но при этом заботились о процветании экономики страны и благосостоянии народа.\n" + "\n" + "[править] Внешняя экспансия Цин\n" + "\n" + "Правители государства Цин проводили политику изоляции Китая от внешнего мира. Европейская колонизация почти не затронула Китай. Католические миссионеры играли заметную роль при императорском дворе до конца XVII века, после чего христианские церкви были постепенно закрыты, а миссионеры — высланы из страны. В середине XVIII века была ликвидирована торговля с европейцами, за исключением одного порта в Кантоне (Гуанчжоу). Опорным пунктом иностранной торговли оставался остров Макао, находившийся под контролем португальцев.\n" + "\n" + "В первые два столетия цинской династии Китай, закрытый от повседневных контактов с внешним миром, проявлял себя как сильное независимое государство, осуществляющее экспансию во всех направлениях.\n" + "\n" + "Вассалом Китая была Корея. В середине XVIII века в империю вошла Северная (Внешняя) Монголия. В 1757 было уничтожено Джунгарское ханство, и территория его вместе с покорённым к 1760 Восточным Туркестаном была включена в состав Цинской империи под названием Синьцзян («Новая граница»). После ряда походов маньчжуро-китайской армии против Тибета этот район был в конце XVIII века присоединён к Цинской империи. Войны Цинской империи против Бирмы (1765—1769) и Вьетнама (1788—1789) оказались неудачными и закончились поражением цинских войск.\n" + "\n" + "Одновременно осуществлялась экспансия на север и северо-восток, что неминуемо привело к конфликту с Россией в Приамурье. В течение двух веков территория Китая увеличилась практически вдвое. Цинская империя обзавелась своего рода буферными зонами — Маньчжурией, Монголией, Тибетом, Синьцзяном — которые охраняли китайские земли.\n" + "\n" + "В цинском Китае любые официальные представители иностранных государств рассматривались исключительно как представители вассальных государств — реальных или потенциальных.\n" + "\n" + "[править] Цинский Китай и Россия\n" + "\n" + " Основная статья: Российско-китайские отношения\n" + "\n" + "Первые шаги по установлению русско-китайских отношений были предприняты Россией в конце периода Мин (миссия И. Петлина в 1618—1619), но основные миссии (Фёдора Байкова в 1654—1657, Николая Спафария в 1675—1678 и др.) последовали уже в цинский период. Параллельно с миссиями шло продвижение на восток русских казаков — походы первопроходцев Василия Пояркова (1643—1646) и Ерофея Хабарова (1649—1653) положили начало освоению русскими людьми Приамурья и привели к присоединению его к России, в то время как маньчжуры считали эти районы своей вотчиной.\n" + "\n" + "В середине XVII века на обоих берегах Амура уже существовали русские крепости-остроги (Албазинский, Кумарский и др.), крестьянские слободы и пашни. В 1656 было образовано Даурское (позднее — Албазинское) воеводство, в которое входила долина Верхнего и Среднего Амура по обоим берегам.\n" + "\n" + "Хотя граница империи Цин тогда проходила чуть севернее Ляодунского полуострова («Ивовый палисад»), в 1650-е годы и позднее Цинская империя попыталась военной силой захватить русские владения в бассейне Амура и предотвратить принятие местными племенами российского подданства. Маньчжурское войско на какое-то время вытеснило казаков из крепости Албазин. Вслед за миссиями Фёдора Байкова и Николая Спафария Россия направила в 1686 к пограничным властям на Амуре полномочное посольство Фёдора Головина для мирного урегулирования конфликта.\n" + "\n" + "Переговоры велись в окружении многотысячной маньчжурской армии. С китайской стороны в переговорах участвовали миссионеры-иезуиты, противившиеся соглашению Китая с Россией, что ещё более осложняло обстановку. Китай отказался определить русско-китайскую границу по Амуру, потребовав себе всё Албазинское воеводство, всё Забайкалье, а впоследствии — вообще все земли к востоку от Лены.\n" + "\n" + "Угрожая захватить Нерчинск штурмом, цинские представители вынудили Головина согласиться на уход русских с Верхнего и Среднего Амура. По Нерчинскому договору Россия была вынуждена уступить Цинской империи свои владения по правому берегу р. Аргунь и на части левого и правого берегов Амура. Казаки были обязаны разрушить и оставить Албазин. Вследствие разночтений в текстах договора, составленных каждой из сторон, однако, большая территория оказалась неразграниченной и фактически превратилась в буферную зону между двумя государствами. Разграничение между Россией и Китаем в пределах этой зоны завершилось в XIX веке. Окончательно граница России с Китаем на Дальнем Востоке была определена Айгуньским (1858) и Пекинским (1860) договорами; она прошла по рекам Амур и Уссури через озеро Ханка и горные хребты до р. Туманьцзян; русско-китайское территориальное разграничение в Центральной Азии было завершено к середине 1890-х.\n" + "\n" + "[править] Опиумные войны\n" + "Территория собственно Китая в 1875\n" + "Территория собственно Китая в 1875\n" + "\n" + "К концу XVIII века торговля Китая с внешним миром вновь начала расширяться. Китайский шёлк, фарфор, чай и другие товары пользовались большим спросом в Европе, но китайцы отказывались что-либо покупать у европейцев, так что тем приходилось платить серебром за китайские товары. Тогда англичане начали ввозить в Китай опиум — в основном контрабандой из Индии — и вскоре приобщили к курению опиума местное население, особенно в приморских районах. Ввоз опиума постоянно возрастал и стал подлинным бедствием для страны, что привело к серии Опиумных войн в середине XIX века. Поражение в этих войнах привело к постепенному превращению Китая в фактическую полуколонию европейских держав.\n" + "\n" + "[править] Японо-китайская война 1894—1895 годов\n" + "\n" + "В 1874 году Япония захватила Формозу, однако вынуждена была покинуть её по требованию Англии. Тогда Япония обратила свои усилия на Корею, находившуюся в вассальной зависимости от Китая и Манчжурию. В июне 1894 по просьбе корейского правительства Китай направил войска в Корею для подавления крестьянского восстания. Воспользовавшись этим предлогом, Япония также направила сюда свои войска, после чего потребовала от корейского короля проведения «реформ», означавших фактически установление в Корее японского контроля.\n" + "\n" + "В ночь на 23 июля при поддержке японских войск в Сеуле был организован правительственный переворот. Новое правительство 27 июля обратилось к Японии с «просьбой» об изгнании китайских войск из Кореи. Однако ещё 25 июля японский флот уже без объявления войны начал военные действия против Китая; официальное объявление войны последовало только 1 августа 1894. Началась Японо-китайская война\n" + "\n" + "В ходе войны превосходство японской армии и флота привело к крупным поражениям Китая на суше и на море (под Асаном, июль 1894; под Пхеньяном, сентябрь 1894; при Цзюляне, октябрь 1894).\n" + "\n" + "С 24 октября 1894 военные действия перешли на территорию Северо-Восточного Китая. К марту 1895 японские войска захватили Ляодунский полуостров, Вэйхайвэй, Инкоу, под угрозой находился Мукден.\n" + "\n" + "17 апреля 1895 в Симоносеки представители Японии и Китая подписали унизительный для Китая Симоносекский договор.\n" + "\n" + "[править] Тройственная интервенция\n" + "\n" + "Условия, навязанные Японией Китаю, привели к так называемой \"тройственной интервенции\" России, Германии и Франции - держав, которые к этому времени уже поддерживали обширные контакты с Китаем и поэтому восприняли подписанный договор как наносящий ущерб их интересам. 23 апреля 1895 Россия, Германия и Франция одновременно, но по отдельности обратились к японскому правительству с требованием отказа от аннексии Ляодунского полуострова, которая могла бы привести к установлению японского контроля над Порт-Артуром, в то время как Николай II, поддерживаемый западными союзниками, имел собственные виды на Порт-Артур как незамерзающий порт для России. Германская нота была наиболее жесткой, даже оскорбительной для Японии.\n" + "\n" + "Японии пришлось уступить. 10 мая 1895 года японское правительство заявило о возвращении Китаю Ляодунского полуострова, правда, добившись увеличения суммы китайской контрибуции на 30 миллионов таэлей.\n" + "\n" + "[править] Успехи русской политики в Китае\n" + "\n" + "В 1895 году Россия предоставила Китаю заём в 150 миллионов рублей под 4% годовых. Договор содержал обязательство Китая не соглашаться на иностранный контроль над своими финансами, если в нём не будет участвовать Россия. В конце 1895 года по инициативе Витте был основан Русско-Китайский банк. 3 июня 1896 года в Москве был подписан русско-китайский договор об оборонительном союзе против Японии. 8 сентября 1896 года между китайским правительством и Русско-Китайским банком был подписан концессионный договор о сроительстве Китайской Восточной железной дороги. Общество КВЖД получало полосу земли вдоль дороги, которая переходила под его юрисдикцию. В марте 1898 года был подписан русско-китайский договор об аренде Россией Порт-Артура и Ляодунского полуострова.\n" + "\n" + "[править] Захват Цзяочжоу Германией\n" + "\n" + "В августе 1897 года Вильгельм II посетил Николая II в Петергофе и добился согласия на устройство немецкой военно-морской базы в Цзяочжоу (в тогдашнем варианте транскрипции - \"Киао-Чао\"), на южном побережье Шаньдуна. В начале ноября в Шаньдуне китайцами были убиты германские миссионеры. 14 ноября 1897 года немцы высадили десант на побережье Цзяочжоу и захватили его. 6 марта 1898 года было подписано германо-китайское соглашение, по которому Китай арендовал Германии Цзяочжоу сроком на 99 лет. Одновременно китайское правительство предоставило Германии концессию на постройку двух железных дорог в Шаньдуне и ряд горных концессий в этой провинции.\n" + "\n" + "[править] Сто дней реформ\n" + "\n" + "Непродолжительный период реформ начался 11 июня 1898 с издания маньчжурским императором Цзай Тянем (название годов правления — Гуансюй) указа «Об установлении основной линии государственной политики». Цзай Тянь привлек группу молодых реформаторов — учеников и единомышленников Кан Ювэя для разработки серии указов о реформах. В общей сложности было издано свыше 60 указов, которые касались системы образования, строительства железных дорог, заводов и фабрик, модернизации сельского хозяйства, развития внутренней и внешней торговли, реорганизации вооружённых сил, чистки государственного аппарата и т.д. Период радикальных реформ окончился 21 сентября того же года, когда вдовствующая Императрица Цыси произвела дворцовый переворот и отменила реформы.\n" + "\n" + "[править] XX век\n" + "\n" + "[править] Боксерское восстание\n" + "\n" + "В мае 1900 года в Китае началось большое восстание, получившее название боксерского или Ихэтуаньского восстания. 20 июня в Пекине был убит германский посланник Кеттелер. Вслед за этим восставшими были осаждены дипломатические миссии, находившиеся в особом квартале Пекина. Было осаждено также здание католического кафедрального собора Петанг (Бейтанг). Начались массовые убийства \"ихэтуанями\" китайцев-христиан, в том числе было убито 222 православных китайца. 21 июня 1900 года Императрица Цыси объявила войну Великобритании, Германии, Австро-Венгрии, Франции, Италии, Японии, США и России. Великие державы согласились о совместных действиях против восставших. Главнокомандующим экспедиционными силами был назначен германский генерал Вальдерзее. Однако, когда он прибыл в Китай, Пекин был уже освобожден небольшим передовым отрядом под командованием русского генерала Линевича. Русская армия заняла Манчжурию.\n" + "\n" + "[править] Русско-японская война\n" + "\n" + "8 февраля 1904 года началась Русско-японская война за контроль над Манчжурией и Кореей. Война, шедшая на территории Китая была для России неудачной, по её результатам, Россия была вынуждена уступить Японии Порт-Артур и Ляодунский полуостров с частью построенной к тому времени КВЖД.\n" + "\n" + "[править] Смерть Цыси\n" + "\n" + "14 декабря 1908 года в один день умерли Императрица Цыси и Император Гуансюй, которого Цыси ранее отстранила от власти. Возможно, Гуансюй был отравлен, так как Цыси не хотела, чтобы он её пережил. На престол взошёл Император Пу И, которому было два года. Регентом назначен его отец князь Чунь, однако вскоре власть перешла к его брату.\n" + "\n" + "[править] Аннексия Кореи\n" + "\n" + "В 1910 году Япония аннексировала Корею, хотя японские войска там находились с начала Русско-японской войны.\n" + "\n" + "[править] Революция 1911 года и создание Китайской Республики\n" + "\n" + "В 1911 году в Китае началось Учанское восстание. Оно стало началом Синьхайской революции (1911—1913) в Китае, в результате которой было свергнута маньчжурская династия Цин и провозглашено создание Китайской республики.\n" + "\n" + "После падения монархии правитель Монголии отказался повиноваться республике и отделился от Китая. 3 ноября им было заключено соглашение с Россией. Англия воспользовалась внутренней борьбой в Китае для превращения Тибета в свою зону влияния. Тибет поднялся на борьбу и заставил китайский гарнизон покинуть страну. Все последующие попытки китайцев восстановить там свою власть пресекались Британией. Россия согласилась считать Тибет английской сферой влияния, а Англия признала русские интересы в независимой (внешней) Монголии.\n" + "\n" + "12 февраля 1912 года Император Пу И отрекся от престола. К власти пришел генерал Юань Шикай премьер-министр и главнокомандующий армией. Вскоре он был провозглашен президентом Китая.\n" + "\n" + "В 1913 году произошла \"Вторая революция\". Юань Шикай подавил разрозненные выступления в центральных и южных провинциях. В стране устанавливается военная диктатура Юань Шикая, основателя группировки бэйянских (северных) милитаристов. Сунь Ятсен вынужден эмигрировать за границу.\n" + "\n" + "[править] Первая мировая война\n" + "\n" + "После начала первой мировой войны китайское правительство объявляет о своем нейтралитете и просит воюющие державы не переносить военные действия на территорию Китая, в том числе и на \"арендованные\" державами китайские земли. Однако 22 августа 1914 года Япония объявила о своем состоянии войны с Германией и высадила 30-тысячную армию севернее Циндао - центра немецкой колонии в провинции Шаньдун. После двухмесячной военной кампании Япония захватила германские владения в Шаньдуне, а также распространила свой контроль на всю территорию провинции.\n" + "\n" + "В 1915 году китайские принцы голосуют за установленче в Китае монархии с Юанем Шикаем на императорском троне. Распускается парламент. Объявляется монархия. Это вызывает ряд восстаний в провинциях Китая. Независимость от Пекина объявляют провинции Юньнань, Гуйчжоу и Гуанси. Потом отделяются Гуандун, Чжэцзян, Сычуань и Хунань.\n" + "\n" + "22 марта 1916 года умирает Юань Шикай.\n" + "\n" + "[править] Эра милитаристов\n" + "\n" + "После смерти Юань Шикая в Китае начали оформляться многочисленные военно-феодальные вотчины различных милитаристских группировок. Наиболее крупной была бэйянская (северная), делившаяся на фэнтяньскую (маньчжурскую) во главе с бывшим главарем шайки хунхузов Чжан Цзолинем, чжилийскую во главе с генералом Фэн Гочжаном, и аньхойскую во главе с генералом Дуань Цижуем. В провинции Шаньси господствовал милитарист Янь Сишань, заигрывавший с бэйянской группировкой, а в провинции Шэньси - генерал Чэнь Шуфань. Лагерь юго-западных милитаристов состоял из двух крупных группировок: юньнаньской во главе с генералом Тан Цзияо, и гуансийской во главе с генералом Лу Жунтином.\n" + "\n" + "Под контролем фэнтяньской группировки находились провинции Хэйлунцзян, Гирин и Фэнтянь, под контролем чжилийской - Шаньдун, Цзянсу, Чжэцзян, Фуцзянь, Цзянси, Хунань, Хубэй и часть Чжили. Фэнтяньская и аньхойская клики финансировались Японией, чжилийская - Англией и США. Ли Юаньхун был ставленником юго-западных милитаристов. Вице-президент генерал Фэн Гочжан ориентировался на Англию и США, а премьер-министр генерал Дуань Цижуй держался прояпонского направления. В 1917 году Япония начала предоставлять Дуань Цижую крупные займы, получая за них все новые и новые уступки, в том числе концессии в Маньчжурии.\n" + "\n" + "[править] Победа Гоминьдана\n" + "\n" + "Партия Гоминьдан была создана в 1912 году в провинции Гуанчжоу. Примерно в тоже время, в 1921 г., была создана и Китайская коммунистическая партия, малочисленная и не пользовавшаяся в тот период особой популярностью. 8 сентября 1923 в Китай по просьбе Сунь Ятсена, который просил прислать ему человека с которым он мог бы говорить по-английски без переводчика, прибыл агент коминтерна М.М.Бородин, ставший политическим советником ЦИК Гоминьдана и советником Сунь Ятсена. Он организовал сотрудничество между Гоминьданом и КПК. 20 января 1924 г. проходит I Всекитайский съезд Гоминьдана в Гуанчжоу. На съезде был принят курс на союз с китайскими коммунистами и СССР. 16 июня учреждена Военная академия Вампу под руководством Чан Кайши. В первый набор было зачислено 400, во второй - 500, в третий - 800 и четвертый - около 2600 слушателей; при школе было создано два учебных полка. В академию Вампу прибыла большая группа советских военных советников. В октябре 1924 г. в Гуанчжоу на должность главного военного советника прибыл Василий Константинович Блюхер.\n" + "В марте 1926 Чан Кайши осуществил в Кантоне военный переворот, изгнал из города коммунистов, а спустя три месяца был избран председателем Гоминьдана и главнокомандующим вооруженными войсками. Добившись высокой власти, Чан Кайши пригласил немецких советников во главе бывшим генералом рейхсвера фон Сектом.\n" + "В качестве советников у Чан Кайши действовали офицеры Германии:\n" + "\n" + " * полковник В.Бауэр (друг Гитлера и ученик Людендорфа)\n" + " * нацист подполковник Крибель\n" + " * генерал-лейтенант Ветцель\n" + " * генерал Фалькенхаузен\n" + "\n" + "Гоминьдановцы старательно перенимали опыт нацистов по наведению порядка в стране. Китайские офицеры в организованном порядке направлялись на обучение в Германию.\n" + "В 1926 Национально-революционная армия Китая Чан Кайши предприняла так называемый Великий Северный поход. В течение шести месяцев непрерывных боев от власти местных военных правителей были освобождены центральные районы Китая.\n" + "В начале 1927 Чан Кайши пошел на открытый развал единого фронта ГМД и КПК: его войска начали разоружение шанхайских рабочих отрядов и дружин, начались массовые аресты и казни профсоюзных деятелей и коммунистов. В ответ на это коммунисты организовали 1 августа в городе Наньчан восстание части гоминьдановских войск, вошедшее в историю Китая как \"Наньчанское восстание\".\n" + "В декабре 1927 было поднято коммунистическое восстание в Кантоне, которое гоминьдановцы жесточайшим образом подавили после четырех дней кровопролитных боев.\n" + "После нескольких военных операций к 1927 году войска Гоминьдана контролировали большую часть территории Китая.\n" + "\n" + "[править] Японская оккупация и Вторая мировая война\n" + "\n" + "Осенью 1931 Япония напала на Китай. 18 сентября после серии провокаций японцы перешли в наступление, за короткое оккупировав всю Манчжурию. В марте 1932 здесь было провозглашено прояпонское марионеточное государство Маньчжоу-Го, которое возглавил Пу И – последний отпрыск маньчжурской династии Цин, свергнутой в годы Синьхайской революции.\n" + "\n" + "В этих сложных условиях Чан Кайши был вынужден бороться одновременно с тремя врагами: внешней японской агрессией, спорадическими бунтами отдельных милитаристов на местах, и вооружёнными силами КПК, претендовавшими на захват власти в стране. Он выбрал политику компромисса с японцами, с милитаристами вёл дела в зависимости от конкретных обстоятельств, с коммунистами же никакой компромисс был невозможен. В 1934 году основные силы КПК были блокированы в провинции Цзянси. В этих сложных условиях руководство КПК сумело организовать прорыв, и после многомесячного марша привело войска на Северо-Запад страны в т.н. \"особый район\" с центром в городе Яньань; эти события вошли в историю КПК как \"Великий поход\". Чан Кайши планировал продолжать борьбу с коммунистами и там, но тут взбунтовался ряд его генералов, считавших более приоритетной задачей примирение с коммунистами и совместную борьбу с японской агрессией. В результате \"Сианьского инцидента\" было подписано соглашение о создании единого фронта между КПК и Гоминьданом.\n" + "\n" + "7 июля 1937 конфликтом у моста Лугоуцяо недалеко от Пекина началась «большая» война. С этого момента, по мнению китайских историков, начинается Вторая мировая война.\n" + "\n" + "\n" + " Этот раздел не завершён. Вы можете помочь проекту, исправив и дополнив его.\n" + "Японская оккупация (1940)\n" + "Японская оккупация (1940)\n" + "\n" + "[править] Создание Китайской Народной Республики\n" + "\n" + "Разгром милитаристской Японии в августе-сентябре 1945 завершил Вторую мировую войну, освободив от порабощения страны Азиатско-Тихоокеанского региона. В Китае шла ожесточенная гражданская война.\n" + "Советская Красная Армия полностью оккупировала Манчжурию, приняв капитуляцию фактически у всей японской Квантунской армии. К тому времени на территории Манчжурии действовали лишь разрозненные партизанские отряды и разведгруппы китайских партизан.\n" + "В сентябре 1945 начала осуществляться массовая переброска вооруженных сил КПК из северного и Восточного Китая на северо-восток страны. К ноябрю туда перешли около 100 тысяч бойцов 8-ой и 4-ой армий. Из этих частей, партизанских формирований и местных жителей была сформирована Объединенная демократическая армия (ОДА) Северо-Востока, которая стала костяком Народно-освободительной армии Китая.\n" + "Советская армия находилась в Манчжурии вплоть до мая 1946. За это время советская сторона помогла китайским коммунистам организовать, обучить и вооружить новые китайские войска. В результате, когда гоминьдановские войска начали в апреле 1946 входить в Манчжурию, они, к своему удивлению, обнаружили там не разрозненные партизанские отряды, а современную дисциплинированную армию коммунистов, вовсе не намеревавшуюся самораспускаться.\n" + "Ситуация в Манчжурии стала шоком и для Белого дома. Первый отряд вооруженных сил США в составе двух дивизий морской пехоты высадился в Китае в районе Тяньцзиня еще 30 сентября 1945. К осени в Китае находилось уже свыше 100 тысяч американских военнослужащих.\n" + "Американские экспедиционные войска, главным образом части морской пехоты, старались не вмешиваться в отношения между КПК и ГМД. Однако они активно взаимодействовали с вооруженными силами легитимного китайского правительства - войсками Гоминьдана, прежде всего в приеме капитуляции японских войск в Северном и Центральном Китае, а также в поддержании порядка и охране различных важных объектов в китайских городах.\n" + "С самого начала командование войск ГМД допустило стратегическую ошибку: несмотря на успехи первых столкновений с ОДА в Манчжурии, военные действия в Северо-Восточном Китае не были доведены до конца, ГМД направил свои усилия не на борьбу с регулярными войсками КПК, а на уничтожение партизанского движения и партизанских баз в Центральном, Восточном и Северном Китае.\n" + "Укрепившись с помощью советской стороны, при поддержке местного населения, войска Мао Цзэдуна к осени 1948 достигли численности в 600 тысяч человек. С 1 ноября ОДА стала именоваться 4-й Полевой армией. возглавили ее Линь Бяо.\n" + "В ноябре 1948 4-я полевая армия перешла к решительным боевым действиям против гоминьдановцев. За короткие сроки было разбито 52 дивизии Чан Кайши, еще 26 дивизий, обученных военными инструкторами США, перешли на сторону КПК. В начале 1949 армия вошла в Северный Китай, где объединилась с войсками 8-й армии КПК. 15 января был взят Тяньцзинь, 22 января - Пекин.\n" + "К весне 1949 вооруженные силы КПК освободили от гоминьдановцев весь Китай севернее реки Янцзы и восточнее провинции Ганьсу. К концу гражданской войны Народно-освободительная армия представляла собой мощную 4-миллионую армию, крупнейшую в Азии.\n" + "24 апреля 1949 войска КПК под командованием маршала Лю Бочэна вступили в столицу гоминьдановского Китая - город Нанкин. Само гоминьдановское правительство еще в феврале переехало на юг страны, в Кантон, а затем вместе с остатками верных ему войск - бежало на остров Тайвань.\n" + "В конце года Народно-освободительная армия Китая уничтожила все основные группировки Гоминьдана на континенте, победоносно завершив тем самым третью гражданскую войну в Китае.\n" + "1 октября 1949 г. в Пекине была провозглашена Китайская Народная Республика.\n" + "На следующий же день Советский Союз первым признал КНР и заключил с ней Договор о дружбе, союзе и взаимной помощи. Таким образом, в конце 1949 года родился советско-китайский «монолит» - тот самый, который на многие годы стал кошмаром для Запада.\n" + "\n" + "[править] Культурная революция\n" + "\n" + "В 1966 году председателем КПК Мао Цзэдуном была начата культурная революция для утверждения маоизма в качестве единственной государственной идеологии и уничтожения политической оппозиции. Было организовано массовое ополчение молодёжи, называвшееся «красногвардейцы». Красногвардейцы занялись преследованием «контререволюционеров» из числа аппарата КПК, интеллигенции и вообще всех, кто мог им не понравиться.\n" + "\n" + "[править] Экономическая либерализация\n" + "\n" + "После падения \"банды четырех\" власть в стране взяли реформаторы Дэн Сяопин и Ху Яобан, которые в конце 1978 года провозгласили на 3-м пленуме ЦК КПК 11-го созыва политику \"реформ и открытости\". Реальный старт \"Экономической реформе\" был дан на XII съезде КПК (1982 г.). На XIII съезде КПК (1987 г.) было дано подробное толкование теории начального этапа социализма, согласно которой социалистический строй и социалистическая экономическая система - разные вещи, т.е. социалистический политический режим не подразумевает безусловной плановой централизации всей экономики, а позволяет использовать и рыночные механизмы, особенно в паре \"государство-предприятие\". На XIV съезде КПК (1992 г.) был провозглашен курс на построение социалистической рыночной экономической системы с китайской спецификой. Данное изменение идеологии хорошо иллюстрирует высказываение Д.Сяопина: \"Неважно какого цвета кошка - главное, чтобы ловила мышей\".\n" + "\n" + "Фактически введение \"Экономической реформы\" означало настоящую \"революцию сверху\", заключавшуюся в постепенном и частичном сворачивании тоталитарной сталинско-маоистской модели жестко централизованной экономики и переводе части отраслей народного хозяйства на рыночные рельсы, но при полностью неизменной политической надстройке в лице монопольно управляющей страной КПК. К концу 70-х исторически слабая экономика Китая \"лежала\" из-за негативных последствий авантюристических кампаний Мао Цзедуна - \"большого скачка\" и \"культурной революции\". От систематического голода в Китае ежегодно страдали практически все 800 млн. крестьян (из миллиардного населения), страна занимала последние места в мире по уровню производства товаров и продовольствия на душу населения. Для решения проблемы голода необходимо было обеспечить стабильный валовый сбор зерна в объеме не менее 400 млн. т в год. Аграрные преобразования были связаны с отменой народной коммуны и заменой ее семейным подрядом и единой коллективной собственностью. Практически все 800 млн. крестьян получили право на свободное сельскохозяйственное производство. В основном была отменена система госзаготовок, освобождены цены на большинство видов сельскохозяйственной продукции. Результатом этих мер стал выход аграрного сектора из застоя, вступление крестьянских хозяйств на путь специализации и повышения товарности. Организованные в деревне по инициативе крестьян волостно-поселковые предприятия позволили обеспечить рост занятости (120 млн. чел.) и повысить жизненный уровень крестьян.Задача обеспечения страны зерном была в основном решена в 80-х. Постепенно в деревне сформировалась двухслойная хозяйственная система на основе сочетания коллективной собственности и семейного подряда.\n" + "\n" + "В области промышленной политики правительство Китая, начиная с 1984 года сделало упор концепцию плановой товарной экономики. На практике это означало перевод части отдельных городских предприятий на самоокупаемость. Позже правительство разрешило и подразделениям армии Китая (НОАК) перейти на самообеспечение и заниматься свободным предпринимательством. В соответствии с принципом \"Чжуа Да Фан Сяо\" (\"держать в руках большие предприятия, отпустить маленькие\") многие мелкие госпредприятия получили право изменить не только механизм хозяйствования, но и форму собственности. Это позволило государству сосредоточить силы на улучшении положения крупных предприятий. Четыре города - Шэньчжэнь, Чжухай, Сямынь, Шаньтоу - были объявлены специальными экономическими зонами. Вслед за ними 14 приморских городов, четыре региона в устьях рек Янцзы и Чжуцзян, юго-восточная часть провинции Фуцзянь и регион в районе Бахайского залива стали открытыми экономическими зонами. На острове Хайнань была создана одноименная новая провинция, а сам он стал специальной экономической зоной. Все эти города и районы получили различные инвестиционные и налоговые льготы для привлечения иностранного капитала и технологий, заимствования у иностранных партнеров эффективных методов управления. Быстрое развитие их экономики способствовало эффективному росту в масштабе страны. Характерно, что значительную долю ввозимого капитала на начальном этапе обеспечила китайская диаспора (хуацяо), проживающая преимущественно в странах тихоокеанского бассейна (основные зоны компактного проживания: Гонконг, Макао, Сингапур, Малайзия, США). Успешное проведение политики либерализации в сочетании с жестко проводимой политикой ограничения рождаемости (снижение рождаемости за 20 лет составило не менее 200 млн. человек) позволило создать многоукладную экономику, в которой госпредприятия дают 48% промышленной продукции, коллективные - 38%, частные, в том числе с иностранным участием, - 13,5%. На долю государственной торговли приходится свыше 41% общего розничного оборота, коллективной - почти 28% и частной - 31%. Доля рыночных цен по потребительским товарам достигла 90%, средствам производства - 80%, по сельскохозяйственным продуктам - 85%. Доля видов промышленной продукции, производство которых регулируется государственными директивными планами, снизилась с 95% в 1978 г. до 5% в настоящее время. Удельный вес товаров, ценами которых непосредственно управляет государство, в розничном товарообороте упал с 95 до 6%. Помимо рынка товаров начали создаваться рынки капиталов, машин и оборудования, рабочей силы, других необходимых для производства элементов. ВВП Китая рос в течение 20 лет, начиная с 1985 года в среднем на 9,5% ежегодно. Страна вышла на 1-е место в мире по производству цемента, цветных металлов, хлопчатобумажных тканей, велосипедов (свыше 80 млн.), мотоциклов (21,3 млн.), телевизоров (35 млн.), угля, зерна, хлопка, рапсовых семян, мяса, яиц, на 2-е - химических удобрений, 3-е - сахара, автомобилей (7,3 млн., вкл. 4,6 млн. легковых), 4-е - электроэнергии, 5-е - сырой нефти. По объему ВВП Китай находится на 4-м месте в мире (при расчете по паритетному покупательскому курсу - на 2-м). На его долю приходится 5,4% мирового валового продукта (2006 г.). Золотовалютные резервы страны превысили в 2006 г. триллион долларов США. Положительное сальдо торгового баланса составляет 180 млрд. долларов. Правда, несмотря на такой рекордно длительный и масштабный экономический рост, среднедушевые показатели ВВП Китая остаются еще на относительно низком уровне, ВВП на душу населения в 2005 году составил 7600 долларов (109-110 место в мире рядом с Украиной). В тоже время средний доход горожанина в открытых городах на конец 2006 г. превысил 10000 юаней в месяц. В китайской деревне от 100 до 150 млн. человек не могут найти работу, еще несколько сотен миллионов заняты частично. Официальный уровень безработицы в городах 4,2% (2005 г.).\n" + "\n" + "В начале 21-го века Китай превратился в \"мировую фабрику\" куда переводится ряд производств из развитых стран Европы, Северной Америки и Японии. Бурный экономический рост во многом связан с дешевизной рабочей силы, слабым уровнем техники безопасности и низким контролем за экологией. В результате Китай уже стал вторым загрязнителем мировой атмосферы и гидросферы, после гораздо более мощной экономики США, а также вышел в \"лидеры\" по эррозии почвы (особенно в северных областях). Возросший из-за роста авто- и мотопарка уровень импорта Китаем нефти (3,2 млн. баррелей/сут. в 2005-м, 2-е место в мире) приводит в последние годы к росту ее среднемировой цены.\n" + "\n" + "В тоже время экономическое и политическое влияние страны в мире в последние годы постоянно возрастает. Так Китаю в 1997-м и 1999-и годах были возращены \"арендованные\" еще у Поднебесной империи территории Гонконг (Сянган) и Макао (Аомынь). Постоянно возрастает уровень обороноспособности страны и техническое оснащение НОАК, чему в немалой степени способствует и РФ, поставляющая в Китай самые современные виды вооружения.\n" + "\n" + "Либерализация экономики КНР пока не сопровождается смягчением политического режима. В стране продолжаются политические репрессии против оппозиции, особенно масштабно реализованные во время \"событий на площади Тяньаньмэнь\" в мае 1989-го, жестко контролируются СМИ, включая Интернет. В тоже время в последние годы предпринят ряд важных изменений устава КПК, например, в партию разрешено вступать представителям предпринимательских кругов, введена ротация высших кадров руководства Партии. Во внутренней политике сняты все ограничения на рост личных состояний и разрешено владение личными автомобилями. В тоже время страна лидирует в мире по количеству смертных казней (более 7000 в год). Несмотря на такую суровую практику, уровень преступности и коррупции постоянно возрастает.\n" + "\n" + "Политика либерализации дала сенсационно высокие результаты, перевела экономику Китая на иной качественный уровень. При этом развитие экономики идет неравномерно по регионам, накапливаются социальные диспропорции, а экологическим аспектам уделяется недостаточное внимание, что уже затрагивает не только территорию Китая, но и интересы сопредельных с ним стран.\n" + "\n" + "[править] См. также\n" + "\n" + " * Китай (цивилизация)\n" + " * События на площади Тяньаньмэнь 1989 года\n" + "\n" + "[править] Литература\n" + "\n" + " * Васильев Л.С. Древний Китай: в 3 т. Т. 3. Период Чжаньго (V–III вв. до н.э.). М.: Восточная литература, 2006. ISBN 502018103X\n" + " * Непомнин О.Е. История Китая: Эпоха Цин. XVII – начало XX века. М.: Восточная литература, 2005. ISBN 5020184004\n"; var devanagari = "भारत\n" + "विकिपीडिया, एक मुक्त ज्ञानकोष से\n" + "Jump to: navigation, search\n" + " यह लेख एक निर्वाचित लेख उम्मीदवार है। अधिक जानकारी के लिए और इस लेख को निर्वाचित लेख बनने के लिए क्या आवश्यकताएँ हैं यह जानने के लिए कृपया यहाँ देखें।\n" + "भारत गणराज्य\n" + "Flag of भारत Coat of arms of भारत\n" + "ध्वज कुलचिह्न\n" + "राष्ट्रवाक्य: \"सत्यमेव जयते\" (संस्कृत)\n" + "\n" + "सत्य ही विजयी होता है\n" + "राष्ट्रगान: जन गण मन\n" + "भारत की स्थिति\n" + "राजधानी नई दिल्ली\n" + "८७, ५९०) 28°34′ N 77°12′ E\n" + "सबसे बड़ा शहर मुम्बई\n" + "राजभाषा(एँ) हिन्दी, अंग्रेज़ी तथा अन्य भारतीय भाषाएं\n" + "सरकार\n" + "राष्ट्रपति\n" + "प्रधानमंत्री\n" + " गणराज्य\n" + "प्रतिभा पाटिल\n" + "डॉ मनमोहन सिंह\n" + "ब्रिटिश राज से स्वतंत्रता\n" + " १५ अगस्त, १९४७\n" + "क्षेत्रफल\n" + " - कुल\n" + " \n" + " - जलीय (%) \n" + "३२, ८७, ५९० km² (सातवां)\n" + "१२,२२,५५९ sq mi \n" + "९.५६\n" + "जनसंख्या\n" + " - २००५ अनुमान\n" + " - २००१ जनगणना\n" + " - जनसंख्या का घनत्व \n" + "१,१०,३३,७१,००० (द्वितीय)\n" + "१,०२,७०,१५,२४८\n" + "३२९/km² (३१ वीं)\n" + "८५२/sq mi \n" + "सकल घरेलू उत्पाद (जीडीपी) (पीपीपी)\n" + " - कुल\n" + " - प्रतिव्यत्ति २००५ estimate\n" + "$३.६३३ महासंख (चौथी GDP_PPP_per_capita = $३,३२०)\n" + "{{{GDP_PPP_per_capita}}} (१२२ वीं)\n" + "मानव विकास संकेतांक (एइचडीआइ) ०.६११ (१२६ वीं) – medium\n" + "मुद्रा भारतीय रुपया (आइएनआर)\n" + "समय मण्डल\n" + " - ग्रीष्म ऋतु (डेलाइट सेविंग टाइम) आइएसटी (UTC+५:३०)\n" + "अब्सर्व्ड नहीं है (UTC+५:३०)\n" + "इंटरनेट टॉप लेवेल डोमेन .आइएन\n" + "दूरभाष कोड +९१\n" + "\n" + "भारत गणराज्य, पौराणिक जम्बुद्वीप, दक्षिण एशिया में स्थित एक देश है। यह भारतीय उपमहाद्वीप का सबसे बड़ा देश है। भारत का भौगोलिक फैलाव 8० 4' से 37० 6' उत्तरी अक्षांश तक तथा 68० 7' से 97० 25'पूर्वी देशान्तर तक है । भारत का क्षेत्रफल ३२,८७,२६३ वर्ग कि. मी. हैं | भारत का विस्तार उत्तर से दक्षिण तक ३,२१४ कि. मी. और पूर्व से पश्चिम तक २,९३३ कि. मी. हैं । भारत की समुद्र तट रेखा ७५१६.६ किलोमीटर लम्बी है। भारत, भौगोलिक दृष्टि से विश्व का सातवाँ सबसे बड़ा और जनसँख्या के दृष्टिकोण से दूसरा बड़ा देश है | भारत के पश्चिम में पाकिस्तान , उत्तर-पूर्व मे चीन, नेपाल, और भूटान और पूर्व में बांग्लादेश और म्यांमार देश स्थित हैं। हिन्द महासागर में इसके दक्षिण पश्चिम में मालदीव, दक्षिण में श्रीलंका और दक्षिण-पूर्व में इंडोनेशिया है। भारत उत्तर-पश्चिम में अफ़्ग़ानिस्तान के साथ सीमा का दावा करता है। इसके उत्तर में हिमालय पर्वत है। दक्षिण में हिन्द महासागर है। पूर्व में बंगाल की खाड़ी है। पश्चिम में अरब सागर है। भारत में कई बड़ी नदियाँ है। गंगा नदी भारतीय सभ्यता मै बहुत पवित्र मानी जाती है। अन्य बड़ी नदियाँ ब्रह्मपुत्र, यमुना, गोदावरी, कावेरी, कृष्णा, चम्बल, सतलज, बियास हैं ।\n" + "\n" + "भारत की १०० करोड़ (१ अरब) से अधिक जनसंख्या, चीन के बाद विश्व में सबसे अधिक है। यह विश्व का सबसे बड़ा लोकतंत्र है। यहाँ ३०० से अधिक भाषाएँ बोली जाती है (साइटेसन चाहिए)। यह एक बहुत प्राचीन सभ्यता की भूमि है।\n" + "\n" + "भारत विश्व की दसवीं सबसे बड़ी अर्थव्यवस्था है, किन्तु हाल में भारत ने काफी प्रगति की है, और ताज़ा स्थिति में भारत विश्व में तीसरे, चौथे स्थान पर होने का दावा करता है (साइटेसन चाहिए)। भारत भौगोलिक क्षेत्रफल के आधार पर विश्व का सातवाँ सबसे बड़ा राष्ट्र है। यह विश्व की कुछ प्राचीनतम सभ्यताओं का पालना रहा है जैसे - सिन्धु घाटी सभ्यता , और महत्वपूर्ण ऐतिहासिक व्यापार पथों का अभिन्न अंग है। विश्व के चार प्रमुख धर्म : हिन्दू , बौध , जैन तथा सिख भारत में प्रतिपादित हुए | १९४७ में स्वतंत्रता प्राप्ति से पूर्व ब्रिटिश भारत के रूप में ब्रिटिश साम्राज्य के प्रमुख अंग भारत ने विगत २० वर्ष में सार्थक प्रगति की है, विशेष रूप से आर्थिक और सैन्य | भारतीय सेना एक क्षेत्रिय शक्ति और विश्वव्यापक शक्ति है।\n" + "\n" + "भारत की राजधानी नई दिल्ली है। भारत के अन्य बड़े महानगर मुम्बई (बम्बई), कोलकाता (कलकत्ता) और चेन्नई (मद्रास) हैं।\n" + "\n" + "\n" + "अनुक्रम\n" + "[छुपाएं]\n" + "\n" + " * १ नाम\n" + " * २ इतिहास\n" + " * ३ सरकार\n" + " * ४ राजनीति\n" + " * ५ राज्य और केन्द्रशासित प्रदेश\n" + " * ६ भूगोल और मौसम\n" + " * ७ अर्थव्यवस्था\n" + " * ८ जनवृत्त\n" + " * ९ संस्कृति\n" + " * १० यह भी देखें\n" + " * ११ बाहरी कड़ियाँ\n" + "\n" + "[संपादित करें] नाम\n" + "मुख्य लेख: भारत नाम की उत्पत्ति\n" + "\n" + "भारत के दो आधिकारिक नाम है हिन्दी में भारत और अंग्रेज़ी में इन्डिया (India)। इन्डिया नाम की उत्पत्ति सिन्धु नदी के फारसी नाम से हुई। भारत नाम एक प्राचीन हिन्दू राजा भरत, जिनकी कथा महाभारत में है, के नाम से लिया गया है। एक तीसरा नाम हिन्दुस्तान (उत्पत्ति फारसी) या हिन्दुओं की भूमि मुगल काल से प्रयोग होता है यद्यपि इसका समकालीन उपयोग कम है।\n" + "\n" + "[संपादित करें] इतिहास\n" + "मुख्य लेख: भारतीय इतिहास\n" + "\n" + "पाषाण युग भीमबेटका मध्य प्रदेश की गुफाएं भारत में मानव जीवन का प्राचीनतम प्रमाण है। प्रथम स्थाई बस्तियों ने ९००० वर्ष पूर्व स्वरुप लिया। यही आगे चल कर सिन्धु घाटी सभ्यता में विकसित हुई , जो २६०० ईसवी और १९०० ईसवी के मध्य अपने चरम पर थी। लगभग १६०० ईसापूर्व आर्य भारत आए और उत्तर भारतीय क्षेत्रों में वैदिक सभ्यता का सूत्रपात किया । इस सभ्यता के स्रोत वेद और पुराण हैं। यह परम्परा कई सहस्र वर्ष पुरानी है। इसी समय दक्षिण बारत में द्रविड़ सभ्यता का विकास होता रहा। दोनो जातियों ने एक दूसरे की खूबियों को अपनाते हुए भारत में एक मिश्रित संस्कृति का निर्माण किया।\n" + "\n" + "५०० ईसवी पूर्व कॆ बाद, कई स्वतंत्र राज्य बन गए। उत्तर में मौर्य राजवंश, जिसमें बौद्ध महाराजा अशोक सम्मिलित थे, ने भारत के सांस्कृतिक पटल पर उल्लेखनीय छाप छोड़ी। १८० ईसवी के आरम्भ से, मध्य एशिया से कई आक्रमण हुए, जिनके परिणामस्वरूप उत्तरी भारतीय उपमहाद्वीप में यूनानी, शक, पार्थी और अंततः कुषाण राजवंश स्थापित हुए | तीसरी शताब्दी के आगे का समय जब भारत पर गुप्त वंश का शासन था, भारत का \"स्वर्णिम काल\" कहलाया।\n" + "तीसरी शताब्दी में सम्राट अशोक द्वारा बनाया गया मध्य प्रदेश में साँची का स्तूप\n" + "तीसरी शताब्दी में सम्राट अशोक द्वारा बनाया गया मध्य प्रदेश में साँची का स्तूप\n" + "\n" + "दक्षिण भारत में भिन्न-भिन्न समयकाल में कई राजवंश चालुक्य, चेर, चोल, पल्लव तथा पांड्य चले | विज्ञान, कला, साहित्य, गणित, खगोल शास्त्र, प्राचीन प्रौद्योगिकी, धर्म, तथा दर्शन इन्हीं राजाओं के शासनकाल में फ़ले-फ़ूले |\n" + "\n" + "१२वीं शताब्दी के प्रारंभ में, भारत पर इस्लामी आक्रमणों के पश्चात, उत्तरी व केन्द्रीय भारत का अधिकांश भाग दिल्ली सल्तनत के शासनाधीन हो गया; और बाद में, अधिकांश उपमहाद्वीप मुगल वंश के अधीन । दक्षिण भारत में विजयनगर साम्राज्य शक्तिशाली निकला। हालांकि, विशेषतः तुलनात्मक रूप से, संरक्षित दक्षिण में अनेक राज्य शेष रहे अथवा अस्तित्व में आये।\n" + "\n" + "१७वीं शताब्दी के मध्यकाल में पुर्तगाल, डच, फ्रांस, ब्रिटेन सहित अनेकों यूरोपीय देशों, जो भारत से व्यापार करने के इच्छुक थे, उन्होनें देश की शासकीय अराजकता का लाभ प्राप्त किया। अंग्रेज दूसरे देशों से व्यापार के इच्छुक लोगों को रोकने में सफल रहे और १८४० तक लगभग संपूर्ण देश पर शासन करने में सफल हुए। १८५७ में ब्रिटिश इस्ट इंडिया कम्पनी के विरुद्ध असफल विद्रोह, जो कि भारतीय स्वतन्त्रता के प्रथम संग्राम से जाना जाता है, के बाद भारत का अधिकांश भाग सीधे अंग्रेजी शासन के प्रशासनिक नियंत्रण में आ गया।\n" + "कोणार्क चक्र - १३वीं शताब्दी में बने उड़ीसा के सूर्य मन्दिर में स्थित, यह दुनिया के सब से प्रसिद्घ ऐतिहासिक स्थानों में से एक है।\n" + "कोणार्क चक्र - १३वीं शताब्दी में बने उड़ीसा के सूर्य मन्दिर में स्थित, यह दुनिया के सब से प्रसिद्घ ऐतिहासिक स्थानों में से एक है।\n" + "\n" + "बीसवीं शताब्दी के प्रारंभ में एक लम्बे समय तक स्वतंत्रता प्राप्ति के लिये विशाल अहिंसावादी संघर्ष चला, जिसका नेतृत्‍व महात्मा गांधी, जो कि आधिकारिक रुप से आधुनिक भारत के राष्ट्रपिता से संबोधित किये जाते हैं, ने किया। ईसके साथ - साथ चंद्रशेखर आजाद, सरदार भगत सिंह, सुख देव, राजगुरू, नेताजी सुभाष चन्द्र बोस आदि के नेतृत्‍व मे चले क्रांतिकारी संघर्ष के फलस्वरुप 15 अगस्त, 1947 भारत ने अंग्रेजी शासन से पूर्णतः स्वतंत्रता प्राप्त की। तदुपरान्त 26 जनवरी, 1950 को भारत एक गणराज्य बना।\n" + "\n" + "एक बहुजातीय तथा बहुधर्मिक राष्ट्र होने के कारण भारत को समय-समय पर साम्प्रदायिक तथा जातीय विद्वेष का शिकार होना पङा है। क्षेत्रीय असंतोष तथा विद्रोह भी हालाँकि देश के अलग-अलग हिस्सों में होते रहे हैं, पर इसकी धर्मनिरपेक्षता तथा जनतांत्रिकता, केवल १९७५-७७ को छोड़, जब तत्कालीन प्रधानमंत्री इंदिरा गांधी ने आपातकाल की घोषणा कर दी थी, अक्षुण्य रही है।\n" + "\n" + "भारत के पड़ोसी राष्ट्रों के साथ अनसुलझे सीमा विवाद हैं। इसके कारण इसे छोटे पैमानों पर युद्ध का भी सामना करना पड़ा है। १९६२ में चीन के साथ, तथा १९४७, १९६५, १९७१ एवम् १९९९ में पाकिस्तान के साथ लड़ाइयाँ हो चुकी हैं।\n" + "\n" + "भारत गुटनिरपेक्ष आन्दोलन तथा संयुक्त राष्ट्र संघ के संस्थापक सदस्य देशों में से एक है।\n" + "\n" + "१९७४ में भारत ने अपना पहला परमाणु परीक्षण किया था जिसके बाद १९९८ में 5 और परीक्षण किये गये। १९९० के दशक में किये गये आर्थिक सुधारीकरण की बदौलत आज देश सबसे तेजी से विकासशील राष्ट्रों की सूची में आ गया है।\n" + "\n" + "[संपादित करें] सरकार\n" + "मुख्य लेख: भारत सरकार\n" + "\n" + "भारत का संविधान भारत को एक सार्वभौमिक, समाजवादी, धर्मनिरपेक्ष, लोकतान्त्रिक गणराज्य की उपाधि देता है। भारत एक लोकतांत्रिक गणराज्य है, जिसका द्विसदनात्मक संसद वेस्टमिन्स्टर शैली के संसदीय प्रणाली द्वारा संचालित है। इसके शासन में तीन मुख्य अंग हैं: न्यायपालिका, कार्यपालिका और व्यवस्थापिका।\n" + "\n" + "राष्ट्रपति,जो कि राष्ट्र का प्रमुख है, has a largely ceremonial role. उसके कार्यों में संविधान का अभिव्यक्तिकरण, प्रस्तावित कानूनों (विधेयक) पर अपनी सहमति देना, और अध्यादेश जारी करना। वह भारतीय सेनाओं का मुख्य सेनापति भी है। राष्ट्रपति और उपराष्ट्रपति को एक अप्रत्यक्ष मतदान विधि द्वारा ५ वर्षों के लिये चुना जाता है। प्रधानमन्त्री सरकार का प्रमुख है और कार्यपालिका की सारी शक्तियाँ उसी के पास होती हैं। इसका चुनाव राजनैतिक पार्टियों या गठबन्धन के द्वारा प्रत्यक्ष विधि से संसद में बहुमत प्राप्त करने पर होता है। बहुमत बने रहने की स्थिति में इसका कार्यकाल ५ वर्षों का होता है। संविधान में किसी उप-प्रधानमंत्री का प्रावधान नहीं है पर समय-समय पर इसमें फेरबदल होता रहा है।\n" + "\n" + "व्यवस्थापिका संसद को कहते हैं जिसके दो सदन हैं - उच्चसदन राज्यसभा, or Council of States,और निम्नसदन लोकसभा. राज्यसभा में २४५ सदस्य होते हैं जबकि लोकसभा में ५५२। राज्यसभा के सदस्यों का चुनाव, अप्रत्यक्ष विधि से ६ वर्षों के लिये होता है, जबकि लोकसभा के सदस्यों का चुनाव प्रत्यक्ष विधि से, ५ वर्षों की अवधि के लिये। १८ वर्ष से अधिक उम्र के सभी भारतीय नागरिक मतदान कर सकते हैं।\n" + "\n" + "कार्यपालिका के तीन अंग हैं - राष्ट्रपति, उपराष्ट्रपति और मंत्रीमंडल। मंत्रीमंडल का प्रमुख प्रधानमंत्री होता है। मंत्रीमंडल के प्रत्येक मंत्री को संसद का सदस्य होना अनिवार्य है। कार्यपालिका, व्यवस्थापिका से नीचे होता है।\n" + "\n" + "भारत की स्वतंत्र न्यायपालिका का शीर्ष सर्वोच्च न्यायालय है, जिसका प्रधान प्रधान न्यायाधीश होता है। सर्वोच्च न्यायालय को अपने नये मामलों तथा उच्च न्यायालयों के विवादों, दोनो को देखने का अधिकार है। भारत में 21 उच्च न्यायालय हैं, जिनके अधिकार और उत्तरदायित्व सर्वोच्च न्यायालय की अपेक्षा सीमित हैं। न्यायपालिका और व्यवस्थापिका के परस्पर मतभेद या विवाद का सुलह राष्ट्रपति करता है।\n" + "\n" + "[संपादित करें] राजनीति\n" + "मुख्य लेख: भारत की राजनीति\n" + "भारत का मानचित्र\n" + "भारत का मानचित्र\n" + "\n" + "स्वतंत्र भारत के इतिहास में उसकी सरकार मुख्य रूप से भारतीय राष्ट्रीय कान्ग्रेस पार्टी के हाथ में रही है। स्वतन्त्रतापूर्व भारत में सबसे बडे़ राजनीतिक संगठन होने के कारण काँग्रेस की, जिसका नेता मूल रूप से नेहरू - गाँधी परिवार का कोई न कोई सदस्य होता है, चालीस वर्षों तक राष्ट्रीय राजनीति में प्रमुख भूमिका रही। १९७७ में, पूर्व काँग्रेस शासन की इंदिरा गाँधी के आपातकाल लगाने के बाद एक संगठित विपक्ष जनता पार्टी ने चुनाव जीता और उसने अत्यधिक छोटी अवधि के लिये एक गैर-काँग्रेसी सरकार बनाई।\n" + "\n" + "१९९६ में, भारतीय जनता पार्टी (भाजपा), सबसे बड़े राजनीतिक संगठन के रूप में उभरी और उसने काँग्रेस के आगे इतिहास में पहली बार एक ठोस विपक्ष प्रस्तुत किया। परन्तु आगे चलकर सत्ता वास्तविक रूप से दो गठबन्धन सरकारों के हाथ में रही जिन्हें काँग्रेस का सम्पूर्ण समर्थन था। १९९९ में, भाजपा ने छोटे दलों को साथ लेकर राष्ट्रीय जनतान्त्रिक गठबन्धन (राजग) बनाया और ५ वर्षों तक कार्यकाल पूरा करने वाली वह पहली गैर-काँग्रेसी सरकार बनी। १९९९ से पूर्व का दशक अल्पावधि सरकारों का था, इन वर्षों में सात भिन्न सरकारें बनी। परन्तु १९९१ मे बनी काँग्रेस सरकार ने अपना ५ वर्ष का कार्यकाल पूरा किया और कई आर्थिक सुधार लाई।\n" + "\n" + "भारतीय आम चुनाव २००४ के फ़लस्वरूप काँग्रेस दल ने सर्वाधिक सीटें जीतीं और वह बड़े ही कम बहुमत से सत्ता में वापिस आई। काँग्रेस ने गठजोड़ द्वारा भारतीय कम्युनिस्ट पार्टी (मार्क्सवादी) और बहुत सी राज्य स्तरीय पार्टियों को साथ लेकर यूनाईटेड प्रोग्रेसिव अलायन्स (यूपीए) नामक सरकार बनाई। आज बीजेपी और उसके सहयोगी विपक्ष में मुख्य भूमिका निभाते हैं। राष्ट्रीय स्तर पर किसी विशेष पार्टी का दबदबा न होने और राज्य स्तर की कई पार्टियों के राष्ट्रीय स्तर पर उभरने के कारण १९९६ से बनी सभी सरकारों को राजनीतिक गठबन्धनों की आवश्यक्ता पड़ी है।\n" + "\n" + "[संपादित करें] राज्य और केन्द्रशासित प्रदेश\n" + "मुख्य लेख: भारत के राज्य\n" + "\n" + "वर्तमान में भारत २८ राज्यों, ६ केन्द्रशासित प्रदेशों और राजधानी दिल्ली मे बँटा हुआ है। राज्यों की चुनी हुई स्वतंत्र सरकारें हैं जबकि केन्द्रशासित प्रदेशों पर केन्द्र द्वारा नियुक्त प्रबंधन शासन करता है, हालाँकि कुछ की लोकतांत्रिक सरकार भी है।\n" + "\n" + "अन्टार्कटिका और दक्षिण गंगोत्री और मैत्री पर भी भारत के वैज्ञानिक स्थल हैं यद्यपि अभी तक कोई वास्तविक आधिपत्य स्थापित नहीं किया गया है।\n" + "\n" + "[संपादित करें] भूगोल और मौसम\n" + "मुख्य लेख: भारत का भूगोल\n" + "हिमालय उत्तर में जम्मू और काश्मीर से लेकर पूर्व में अरुणाचल प्रदेश तक भारत की अधिकतर पूर्वी सीमा बनाता है\n" + "हिमालय उत्तर में जम्मू और काश्मीर से लेकर पूर्व में अरुणाचल प्रदेश तक भारत की अधिकतर पूर्वी सीमा बनाता है\n" + "\n" + "भारत के अधिकतर उत्तरी और उत्तरपश्चिमीय प्रांत हिमालय की पहाङियों में स्थित हैं। शेष का उत्तरी, मध्य और पूर्वी भारत गंगा के उपजाऊ मैदानों से बना है। उत्तरी-पूर्वी पाकिस्तान से सटा हुआ, भारत के पश्चिम में थार का मरुस्थल है। दक्षिण भारत लगभग संपूर्ण ही दक्खन के पठार से निर्मित है। यह पठार पूर्वी और पश्चिमी घाटों के बीच स्थित है।\n" + "\n" + "कई महत्वपूर्ण और बड़ी नदियाँ जैसे गंगा, ब्रह्मपुत्र, यमुना, गोदावरी और कृष्णा भारत से होकर बहती हैं। इन नदियों के कारण उत्तर भारत की भूमि कृषि के लिए उपजाऊ है।\n" + "\n" + "भारत के विस्तार के साथ ही इसके मौसम में भी बहुत भिन्नता है। दक्षिण में जहाँ तटीय और गर्म वातावरण रहता है वहीं उत्तर में कड़ी सर्दी, पूर्व में जहाँ अधिक बरसात है वहीं पश्चिम में रेगिस्तान की शुष्कता। भारत में वर्षा मुख्यतया मानसून हवाओं से होती है।\n" + "\n" + "भारत के मुख्य शहर है - दिल्ली, मुम्बई, कोलकाता, चेन्नई, बंगलोर ( बेंगलुरु ) | ये भी देंखे - भारत के शहर\n" + "\n" + "[संपादित करें] अर्थव्यवस्था\n" + "मुख्य लेख: भारत की अर्थव्यवस्था\n" + "सूचना प्रोद्योगिकी (आईटी) भारत के सबसे अधिक विकासशील उद्योगों में से एक है, वार्षिक आय $२८५० करोड़ डालर, इन्फ़ोसिस, भारत की सबसे बडी आईटी कम्पनियों में से एक\n" + "सूचना प्रोद्योगिकी (आईटी) भारत के सबसे अधिक विकासशील उद्योगों में से एक है, वार्षिक आय $२८५० करोड़ डालर, इन्फ़ोसिस, भारत की सबसे बडी आईटी कम्पनियों में से एक\n" + "\n" + "मुद्रा स्थानांतरण की दर से भारत की अर्थव्यवस्था विश्व में दसवें और क्रयशक्ति के अनुसार चौथे स्थान पर है। वर्ष २००३ में भारत में लगभग ८% की दर से आर्थिक वृद्धि हुई है जो कि विश्व की सबसे तीव्र बढती हुई अर्थव्यवस्थओं में से एक है। परंतु भारत की अत्यधिक जनसंख्या के कारण प्रतिव्यक्ति आय क्रयशक्ति की दर से मात्र ३२६२ अमेरिकन डॉलर है जो कि विश्व बैंक के अनुसार १२५वें स्थान पर है। भारत का विदेशी मुद्रा भंडार १४३ अरब अमेरिकन डॉलर है। मुम्बई भारत की आर्थिक राजधानी है और भारतीय रिजर्व बैंक और बॉम्बे स्टॉक एक्सचेंज का मुख्यालय भी। यद्यपि एक चौथाई भारतीय अभी भी निर्धनता रेखा से नीचे हैं, तीव्रता से बढ़ती हुई सूचना प्रोद्योगिकी कंपनियों के कारण मध्यमवर्गीय लोगों में वृद्धि हुई है। १९९१ के बाद भारत मे आर्थिक सुधार की नीति ने भारत के सर्वंगीण विकास मे बडी भूमिका निभाआयी।\n" + "\n" + "१९९१ के बाद भारत मे हुए [आर्थिक सुधार। आर्थिक सुधारोँ]] ने भारत के सर्वांगीण विकास मे बड़ी भूमिका निभाई। भारतीय अर्थव्यवस्था ने कृषि पर अपनी ऐतिहासिक निर्भरता कम की है और कृषि अब भारतीय सकल घरेलू उत्पाद (जीडीपी) का केवल २५% है। दूसरे प्रमुख उद्योग हैं उत्खनन, पेट्रोलियम, बहुमूल्य रत्न, चलचित्र, टेक्स्टाईल, सूचना प्रोद्योगिकी सेवाएं, तथा सजावटी वस्तुऐं। भारत के अधिकतर औद्योगिक क्षेत्र उसके प्रमुख महानगरों के आसपास स्थित हैं। हाल ही के वर्षों में $१७२० करोड़ अमरीकी डालर वार्षिक आय २००४-२००५ के साथ भारत सॉफ़्टवेयर और बीपीओ सेवाओं का सबसे बडा केन्द्र बनकर उभरा है। इसके साथ ही कई लघु स्तर के उद्योग भी हैं जोकि छोटे भारतीय गाँव और भारतीय नगरों के कई नागरिकों को जीविका प्रदान करते हैं। पिछले वषों मंे भारत में वित्तीय संस्थानो ने विकास में बड़ी भूमिका निभाई है।\n" + "\n" + "केवल तीस लाख विदेशी पर्यटकों के प्रतिवर्ष आने के बाद भी भार्तीय पर्यटन राष्ट्रीय आय का एक अति आवश्यक परन्तु कम विकसित स्त्रोत है। पर्यटन उद्योग भारत के जीडीपी का कुल ५.३% है। पर्यटन १०% भारतीय कामगारों को आजीविका देता है। वास्तविक संख्या ४.२ करोड है। आर्थिक रूप से देखा जाए तो पर्यटन भारतीय अर्थव्यवस्था को लगभग $४०० करोड डालर प्रदान करता है। भारत के प्रमुख व्यापार सहयोगी हैं अमरीका, जापान, चीन और संयुक्त अरब अमीरात।\n" + "\n" + "भारत के निर्यातों में कृषि उत्पाद, चाय, कपड़ा, बहुमूल्य रत्न व ज्वैलरी, साफ़्टवेयर सेवायें, इंजीनियरिंग सामान, रसायन तथा चमड़ा उत्पाद प्रमुख हैं जबकि उसके आयातों में कच्चा तेल, मशीनरी, बहुमूल्य रत्न, फ़र्टिलाइज़र तथा रसायन प्रमुख हैं। वर्ष २००४ के लिये भारत के कुल निर्यात $६९१८ करोड़ डालर के थे जबकि उसके आयात $८९३३ करोड डालर के थे।\n" + "\n" + "[संपादित करें] जनवृत्त\n" + "मुख्य लेख: भारत के लोग\n" + "\n" + "भारत चीन के बाद विश्व का दूसरा सबसे बड़ी जनसंख्या वाला देश है। भारत की विभिन्नताओं से भरी जनता में भाषा, जाति और धर्म, सामाजिक और राजनीतिक संगठन के मुख्य शत्रु हैं।\n" + "हिन्दुत्व भारत का सबसे बङा धर्म है - इस चित्र मे गोआ का एक मंदिर दर्शाया गया है\n" + "हिन्दुत्व भारत का सबसे बङा धर्म है - इस चित्र मे गोआ का एक मंदिर दर्शाया गया है\n" + "\n" + "भारत में ६४.८ प्रतिशत साक्षरता है जिसमे से ७५.३ % पुरुष और ५३.७% स्त्रियाँ साक्षर है। लिंग अनुपात की दृष्टि से भारत में प्रत्येक १००० पुरुषों के पीछे मात्र ९३३ महिलायें हैं। कार्य भागीदारी दर (कुल जनसंख्या मे कार्य करने वालों का भाग) ३९.१% है। पुरुषों के लिये यह दर ५१.७% और स्त्रियों के लिये २५.६% है। भारत की १००० जनसंख्या में २२.३२ जन्मों के साथ बढती जनसंख्या के आधे लोग २२.६६ वर्ष से कम आयु के हैं।\n" + "\n" + "यद्यपि भारत की ८०.५ प्रतिशत जनसंख्या हिन्दू है, १३.४ प्रतिशत जनसंख्या के साथ भारत विश्व में मुसलमानों की संख्या में भी इंडोनेशिया के बाद दूसरे स्थान पर है। अन्य धर्मावलम्बियों में ईसाई (२.३३ %), सिख (१.८४ %), बौद्ध (०.७६ %), जैन (०.४० %), अय्यावलि (०.१२ %), यहूदी, पारसी, अहमदी और बहाई आदि सम्मिलित हैं।\n" + "\n" + "भारत दो मुख्य भाषा सूत्रों, आर्यन् और द्रविङियन्, का भी स्त्रोत है (साइटेसन चाहिए)। भारत का संविधान कुल २३ भाषाओं को मान्यता देता है। हिन्दी और अंग्रेजी केन्द्रीय सरकार द्वारा सरकारी कामकाज के लिये उपयोग की जाती है। संस्कृत और तमिल जैसी अति प्राचीन भाषाएं भारत में ही जन्मी हैं। कुल मिलाकर भारत में १६५२ से भी अधिक भाषाएं एवं बोलियाँ बोली जातीं हैं।\n" + "\n" + "[संपादित करें] संस्कृति\n" + "मुख्य लेख: भारतीय संस्कृति\n" + "ताजमहल विश्व के सबसे प्रसिद्ध पर्यटक स्थलों में गिना जाता है।\n" + "ताजमहल विश्व के सबसे प्रसिद्ध पर्यटक स्थलों में गिना जाता है।\n" + "\n" + "भारत की सांस्कृतिक धरोहर बहुत संपन्न है। यहां की संस्कृति अनोखी है, और वर्षों से इसके कई अवयव अबतक अक्षुण्य हैं। आक्रमणकारियों तथा प्रवासियों से विभिन्न चीजों को समेटकर यह एक मिश्रित संस्कृति बन गई है। आधुनिक भारत का समाज, भाषाएं, रीति-रिवाज इत्यादि इसका प्रमाण हैं। ताजमहल और अन्य उदाहरण, इस्लाम प्रभावित स्थापत्य कला के अतिसुन्दर नमूने हैं।\n" + "गुम्पा नृत्य एक तिब्बती बौद्ध समाज का सिक्किम में छिपा नृत्य है। यह बौद्ध नव बर्ष में है।\n" + "गुम्पा नृत्य एक तिब्बती बौद्ध समाज का सिक्किम में छिपा नृत्य है। यह बौद्ध नव बर्ष में है।\n" + "\n" + "भारतीय समाज बहुधर्मिक, बहुभाषी तथा मिश्र-सांस्कृतिक है। पारंपरिक भारतीय पारिवारिक मूल्यों को काफी आदर की दृष्टि से देखा जाता है।\n" + "\n" + "विभिन्न धर्मों के इस भूभाग पर कई मनभावन पर्व त्यौहार मनाए जाते हैं - दिवाली, होली, दशहरा. पोंगल तथा ओणम . ईद-उल-फितर, मुहर्रम, क्रिसमस, ईस्टर आदि भी काफ़ी लोकप्रिय हैं।\n" + "\n" + "हालाँकि हॉकी देश का राष्ट्रीय खेल है, क्रिकेट सबसे अधिक लोकप्रिय है। वर्तमान में फुटबॉल, हॉकी तथा टेनिस में भी बहुत भारतीयों की अभिरुचि है। देश की राष्ट्रीय क्रिकेट टीम में 1983 में एक बार विश्व कप भी जीता है। इसके अतिरिक्त वर्ष 2003 में वह विश्व कप के फाइनल तक पहुँचा था। 1930 तथा 40 के दशक में हाकी में भारत अपने चरम पर था। मेजर ध्यानचंद ने हॉकी में भारत को बहुत प्रसिद्धि दिलाई और एक समय भारत ने अमरीका को 24-0 से हराया था जो अब तर विश्व कीर्तिमान है। शतरंज के जनक देश भारत के खिलाड़ी शतरंज में भी अच्छा प्रदर्शन करते आए हैं।\n" + "\n" + "भारतीय खानपान बहुत ही समृद्ध है। शाकाहारी तथा मांसाहारी दोनो तरह का खाना पसन्द किया जाता है। भारतीय व्यंजन विदेशों में भी बहुत पसन्द किए जाते है।\n" + "\n" + "भारत में संगीत तथा नृत्य की अपनी शैलियां भी विकसित हुईं जो बहुत ही लोकप्रिय हैं। भरतनाट्यम, ओडिसी, कत्थक प्रसिद्ध भारतीय नृत्य शैली है। हिन्दुस्तानी संगीत तथा कर्नाटक संगीत भारतीय परंपरागत संगीत की दो मुख्य धाराएं हैं।\n" + "\n" + "वैश्वीकरण के इस युग में शेष विश्व की तरह भारतीय समाज पर भी अंग्रेजी तथा यूरोपीय प्रभाव पड़ रहा है। बाहरी लोगों की खूबियों को अपनाने की भारतीय परंपरा का नया दौर कई भारतीयों की दृष्टि में अनुचित है। एक खुले समाज के जीवन का यत्न कर रहे लोगों को मध्यमवर्गीय तथा वरिष्ठ नागरिकों की उपेक्षा का शिकार होना पड़ता है। कुछ लोग इसे भारतीय पारंपरिक मूल्यों का हनन मानते हैं। विज्ञान तथा साहित्य में अधिक प्रगति ना कर पाने की वजह से भारतीय समाज यूरोपीय लोगों पर निर्भर होता जा रहा है। ऐसे समय में लोग विदेशी अविष्कारों का भारत में प्रयोग अनुचित भी समझते हैं। हालाँकि ऐसे कई लोग है जो ऐसा विचार नहीं रखते।\n" + "\n" + "[संपादित करें] यह भी देखें\n" + "\n" + " * दक्षिण भारत\n" + " * उत्तर पूर्वी भारत\n" + " * भारत की भाषाएँ\n" + "\n" + "\n" + "[संपादित करें] बाहरी कड़ियाँ\n" + "\n" + "सरकार (हिन्दी)\n" + "\n" + " * भारत का राष्ट्रीय पोर्टल\n" + "\n" + "सरकार (अंग्रेज़ी)\n" + "\n" + " * भारतीय सरकार का सरकारी वैबसाइट\n" + " * भारतीय सरकार का वेबसाइट का सरकारी निर्देशिका\n" + "\n" + "सेनापति निर्देश (अंग्रेज़ी)\n" + "\n" + " * सीआईए में भारत निबन्ध\n" + " * एन्साक्लोपीडिया ब्रिटैनिका का भारत निबन्ध\n" + " * बीबीसी का भारत निबन्ध\n" + "\n" + "भारत का देश नक्शा\n" + "\n" + "सैटेलाइट चित्र (अंग्रेज़ी)\n" + "\n" + " * गूगल मानचित्र से भारत का सैटेलाइट चित्र\n" + "\n" + "अन्य (अंग्रेज़ी)\n" + "\n" + " * विकिभ्रमण का भारत निबन्ध\n" + " * भारत ओपेन डायरैक्टरी प्रॉजेक्ट में\n" + " * भारत यात्रा - सामूहिक यात्रा ब्लॉग\n"; var english = "English language\n" + "From Wikipedia, the free encyclopedia\n" + "• Learn more about citing Wikipedia •\n" + "Jump to: navigation, search\n" + " Editing of this article by unregistered or newly registered users is currently disabled.\n" + "If you cannot edit this article and you wish to make a change, you can discuss changes on the talk page, request unprotection, log in, or create an account.\n" + "English \n" + "Pronunciation: /ˈɪŋɡlɪʃ/[37]\n" + "Spoken in: Listed in the article\n" + "Total speakers: First language: 309[38] – 380 million[3]\n" + "Second language: 199[39] – 600 million[40]\n" + "Overall: 1.8 billion[41] \n" + "Ranking: 3 (native speakers)[9][10]\n" + "Total: 1 or 2 [11]\n" + "Language family: Indo-European\n" + " Germanic\n" + " West Germanic\n" + " Anglo–Frisian\n" + " Anglic\n" + " English \n" + "Writing system: Latin (English variant) \n" + "Official status\n" + "Official language of: 53 countries\n" + "Flag of the United Nations United Nations\n" + "Regulated by: no official regulation\n" + "Language codes\n" + "ISO 639-1: en\n" + "ISO 639-2: eng\n" + "ISO 639-3: eng \n" + "World countries, states, and provinces where English is a primary language are dark blue; countries, states and provinces where it is an official but not a primary language are light blue. English is also one of the official languages of the European Union.\n" + "Note: This page may contain IPA phonetic symbols in Unicode. See IPA chart for English for an English-​based pronunciation key.\n" + "\n" + "English is a West Germanic language originating in England, and the first language for most people in Australia, Canada, the Commonwealth Caribbean, Ireland, New Zealand, the United Kingdom and the United States of America (also commonly known as the Anglosphere). It is used extensively as a second language and as an official language throughout the world, especially in Commonwealth countries such as India, Sri Lanka, Pakistan and South Africa, and in many international organisations.\n" + "\n" + "Modern English is sometimes described as the global lingua franca.[1][2] English is the dominant international language in communications, science, business, aviation, entertainment, radio and diplomacy.[3] The influence of the British Empire is the primary reason for the initial spread of the language far beyond the British Isles.[4] Following World War II, the growing economic and cultural influence of the United States has significantly accelerated the spread of the language.\n" + "\n" + "A working knowledge of English is required in certain fields, professions, and occupations. As a result over a billion people speak English at least at a basic level (see English language learning and teaching). English is one of six official languages of the United Nations.\n" + "Contents\n" + "[hide]\n" + "\n" + " * 1 History\n" + " * 2 Classification and related languages\n" + " * 3 Geographical distribution\n" + " o 3.1 English as a global language\n" + " o 3.2 Dialects and regional varieties\n" + " o 3.3 Constructed varieties of English\n" + " * 4 Phonology\n" + " o 4.1 Vowels\n" + " + 4.1.1 See also\n" + " o 4.2 Consonants\n" + " + 4.2.1 Voicing and aspiration\n" + " o 4.3 Supra-segmental features\n" + " + 4.3.1 Tone groups\n" + " + 4.3.2 Characteristics of intonation\n" + " * 5 Grammar\n" + " * 6 Vocabulary\n" + " o 6.1 Number of words in English\n" + " o 6.2 Word origins\n" + " + 6.2.1 Dutch origins\n" + " + 6.2.2 French origins\n" + " * 7 Writing system\n" + " o 7.1 Basic sound-letter correspondence\n" + " o 7.2 Written accents\n" + " * 8 Formal written English\n" + " * 9 Basic and simplified versions\n" + " * 10 Notes\n" + " * 11 References\n" + " * 12 See also\n" + " * 13 External links\n" + " o 13.1 Dictionaries\n" + "\n" + "History\n" + "\n" + " Main article: History of the English language\n" + "\n" + "English is an Anglo-Frisian language. Germanic-speaking peoples from northwest Germany (Saxons and Angles) and Jutland (Jutes) invaded what is now known as Eastern England around the fifth century AD. It is a matter of debate whether the Old English language spread by displacement of the original population, or the native Celts gradually adopted the language and culture of a new ruling class, or a combination of both of these processes (see Sub-Roman Britain).\n" + "\n" + "Whatever their origin, these Germanic dialects eventually coalesced to a degree (there remained geographical variation) and formed what is today called Old English. Old English loosely resembles some coastal dialects in what are now northwest Germany and the Netherlands (i.e., Frisia). Throughout the history of written Old English, it retained a synthetic structure closer to that of Proto-Indo-European, largely adopting West Saxon scribal conventions, while spoken Old English became increasingly analytic in nature, losing the more complex noun case system, relying more heavily on prepositions and fixed word order to convey meaning. This is evident in the Middle English period, when literature was to an increasing extent recorded with spoken dialectal variation intact, after written Old English lost its status as the literary language of the nobility. It is postulated that the early development of the language was influenced by a Celtic substratum.[5][6] Later, it was influenced by the related North Germanic language Old Norse, spoken by the Vikings who settled mainly in the north and the east coast down to London, the area known as the Danelaw.\n" + "\n" + "The Norman Conquest of England in 1066 profoundly influenced the evolution of the language. For about 300 years after this, the Normans used Anglo-Norman, which was close to Old French, as the language of the court, law and administration. By the fourteenth century, Anglo-Norman borrowings had contributed roughly 10,000 words to English, of which 75% remain in use. These include many words pertaining to the legal and administrative fields, but also include common words for food, such as mutton[7] and beef[8]. The Norman influence gave rise to what is now referred to as Middle English. Later, during the English Renaissance, many words were borrowed directly from Latin (giving rise to a number of doublets) and Greek, leaving a parallel vocabulary that persists into modern times. By the seventeenth century there was a reaction in some circles against so-called inkhorn terms.\n" + "\n" + "During the fifteenth century, Middle English was transformed by the Great Vowel Shift, the spread of a prestigious South Eastern-based dialect in the court, administration and academic life, and the standardising effect of printing. Early Modern English can be traced back to around the Elizabethan period.\n" + "\n" + "Classification and related languages\n" + "\n" + "The English language belongs to the western sub-branch of the Germanic branch of the Indo-European family of languages.\n" + "\n" + "The question as to which is the nearest living relative of English is a matter of discussion. Apart from such English-lexified creole languages such as Tok Pisin, Scots (spoken primarily in Scotland and parts of Northern Ireland) is not a Gaelic language, but is part of the English family of languages: both Scots and modern English are descended from Old English, also known as Anglo-Saxon. The closest relative to English after Scots is Frisian, which is spoken in the Northern Netherlands and Northwest Germany. Other less closely related living West Germanic languages include German, Low Saxon, Dutch, and Afrikaans. The North Germanic languages of Scandinavia are less closely related to English than the West Germanic languages.\n" + "\n" + "Many French words are also intelligible to an English speaker (though pronunciations are often quite different) because English absorbed a large vocabulary from Norman and French, via Anglo-Norman after the Norman Conquest and directly from French in subsequent centuries. As a result, a large portion of English vocabulary is derived from French, with some minor spelling differences (word endings, use of old French spellings, etc.), as well as occasional divergences in meaning, in so-called \"faux amis\", or false friends.\n" + "\n" + "Geographical distribution\n" + "\n" + " See also: List of countries by English-speaking population\n" + "\n" + "Over 380 million people speak English as their first language. English today is probably the third largest language by number of native speakers, after Mandarin Chinese and Spanish.[9][10] However, when combining native and non-native speakers it is probably the most commonly spoken language in the world, though possibly second to a combination of the Chinese Languages, depending on whether or not distinctions in the latter are classified as \"languages\" or \"dialects.\"[11][12] Estimates that include second language speakers vary greatly from 470 million to over a billion depending on how literacy or mastery is defined.[13][14] There are some who claim that non-native speakers now outnumber native speakers by a ratio of 3 to 1.[15]\n" + "\n" + "The countries with the highest populations of native English speakers are, in descending order: United States (215 million),[16] United Kingdom (58 million),[17] Canada (17.7 million),[18] Australia (15 million),[19] Ireland (3.8 million),[17] South Africa (3.7 million),[20] and New Zealand (3.0-3.7 million).[21] Countries such as Jamaica and Nigeria also have millions of native speakers of dialect continuums ranging from an English-based creole to a more standard version of English. Of those nations where English is spoken as a second language, India has the most such speakers ('Indian English') and linguistics professor David Crystal claims that, combining native and non-native speakers, India now has more people who speak or understand English than any other country in the world.[22] Following India is the People's Republic of China.[23]\n" + "Distribution of native English speakers by country (Crystal 1997)\n" + "Distribution of native English speakers by country (Crystal 1997)\n" + " Country Native speakers\n" + "1 USA 214,809,000[16]\n" + "2 UK 58,200,000[17]\n" + "3 Canada 17,694,830[18]\n" + "4 Australia 15,013,965[19]\n" + "5 Ireland 4,200,000+ (Approx)[17]\n" + "6 South Africa 3,673,203[20]\n" + "7 New Zealand 3,500,000+ (Approx)[21]\n" + "8 Singapore 665,087[24]\n" + "\n" + "English is the primary language in Anguilla, Antigua and Barbuda, Australia (Australian English), the Bahamas, Barbados, Bermuda, Belize, the British Indian Ocean Territory, the British Virgin Islands, Canada (Canadian English), the Cayman Islands, Dominica, the Falkland Islands, Gibraltar, Grenada, Guernsey (Guernsey English), Guyana, Ireland (Hiberno-English), Isle of Man (Manx English), Jamaica (Jamaican English), Jersey, Montserrat, Nauru, New Zealand (New Zealand English), Pitcairn Islands, Saint Helena, Saint Lucia, Saint Kitts and Nevis, Saint Vincent and the Grenadines, Singapore, South Georgia and the South Sandwich Islands, Trinidad and Tobago, the Turks and Caicos Islands, the United Kingdom, the U.S. Virgin Islands, and the United States (various forms of American English).\n" + "\n" + "In many other countries, where English is not the most spoken language, it is an official language; these countries include Botswana, Cameroon, Fiji, the Federated States of Micronesia, Ghana, Gambia, Hong Kong, India, Kiribati, Lesotho, Liberia, Kenya, Madagascar, Malta, the Marshall Islands, Namibia, Nigeria, Pakistan, Papua New Guinea, the Philippines, Puerto Rico, Rwanda, the Solomon Islands, Samoa, Sierra Leone, Singapore, Sri Lanka, Swaziland, Tanzania, Uganda, Zambia, and Zimbabwe. It is also one of the 11 official languages that are given equal status in South Africa (\"South African English\"). English is also an important language in several former colonies or current dependent territories of the United Kingdom and the United States, such as in Hong Kong and Mauritius.\n" + "\n" + "English is not an official language in either the United States or the United Kingdom.[25][26] Although the United States federal government has no official languages, English has been given official status by 30 of the 50 state governments.[27]\n" + "\n" + "English as a global language\n" + "\n" + " See also: English on the Internet and global language\n" + "\n" + "Because English is so widely spoken, it has often been referred to as a \"global language\", the lingua franca of the modern era.[2] While English is not an official language in many countries, it is currently the language most often taught as a second language around the world. Some linguists believe that it is no longer the exclusive cultural sign of \"native English speakers\", but is rather a language that is absorbing aspects of cultures worldwide as it continues to grow. It is, by international treaty, the official language for aerial and maritime communications, as well as one of the official languages of the European Union, the United Nations, and most international athletic organisations, including the International Olympic Committee.\n" + "\n" + "English is the language most often studied as a foreign language in the European Union (by 89% of schoolchildren), followed by French (32%), German (18%), and Spanish (8%).[28] In the EU, a large fraction of the population reports being able to converse to some extent in English. Among non-English speaking countries, a large percentage of the population claimed to be able to converse in English in the Netherlands (87%), Sweden (85%), Denmark (83%), Luxembourg (66%), Finland (60%), Slovenia (56%), Austria (53%), Belgium (52%), and Germany (51%). [29] Norway and Iceland also have a large majority of competent English-speakers.\n" + "\n" + "Books, magazines, and newspapers written in English are available in many countries around the world. English is also the most commonly used language in the sciences.[2] In 1997, the Science Citation Index reported that 95% of its articles were written in English, even though only half of them came from authors in English-speaking countries.\n" + "\n" + "Dialects and regional varieties\n" + "\n" + " Main article: List of dialects of the English language\n" + "\n" + "The expansion of the British Empire and—since WWII—the primacy of the United States have spread English throughout the globe.[2] Because of that global spread, English has developed a host of English dialects and English-based creole languages and pidgins.\n" + "\n" + "The major varieties of English include, in most cases, several subvarieties, such as Cockney slang within British English; Newfoundland English within Canadian English; and African American Vernacular English (\"Ebonics\") and Southern American English within American English. English is a pluricentric language, without a central language authority like France's Académie française; and, although no variety is clearly considered the only standard, there are a number of accents considered to be more prestigious, such as Received Pronunciation in Britain.\n" + "\n" + "Scots developed — largely independently — from the same origins, but following the Acts of Union 1707 a process of language attrition began, whereby successive generations adopted more and more features from English causing dialectalisation. Whether it is now a separate language or a dialect of English better described as Scottish English is in dispute. The pronunciation, grammar and lexis of the traditional forms differ, sometimes substantially, from other varieties of English.\n" + "\n" + "Because of the wide use of English as a second language, English speakers have many different accents, which often signal the speaker's native dialect or language. For the more distinctive characteristics of regional accents, see Regional accents of English speakers, and for the more distinctive characteristics of regional dialects, see List of dialects of the English language.\n" + "\n" + "Just as English itself has borrowed words from many different languages over its history, English loanwords now appear in a great many languages around the world, indicative of the technological and cultural influence of its speakers. Several pidgins and creole languages have formed using an English base, such as Jamaican Creole, Nigerian Pidgin, and Tok Pisin. There are many words in English coined to describe forms of particular non-English languages that contain a very high proportion of English words. Franglais, for example, is used to describe French with a very high English word content; it is found on the Channel Islands. Another variant, spoken in the border bilingual regions of Québec in Canada, is called FrEnglish.\n" + "\n" + "Constructed varieties of English\n" + "\n" + " * Basic English is simplified for easy international use. It is used by manufacturers and other international businesses to write manuals and communicate. Some English schools in Asia teach it as a practical subset of English for use by beginners.\n" + " * Special English is a simplified version of English used by the Voice of America. It uses a vocabulary of only 1500 words.\n" + " * English reform is an attempt to improve collectively upon the English language.\n" + " * Seaspeak and the related Airspeak and Policespeak, all based on restricted vocabularies, were designed by Edward Johnson in the 1980s to aid international cooperation and communication in specific areas. There is also a tunnelspeak for use in the Channel Tunnel.\n" + " * English as a lingua franca for Europe and Euro-English are concepts of standardising English for use as a second language in continental Europe.\n" + " * Manually Coded English — a variety of systems have been developed to represent the English language with hand signals, designed primarily for use in deaf education. These should not be confused with true sign languages such as British Sign Language and American Sign Language used in Anglophone countries, which are independent and not based on English.\n" + " * E-Prime excludes forms of the verb to be.\n" + "\n" + "Euro-English (also EuroEnglish or Euro-English) terms are English translations of European concepts that are not native to English-speaking countries. Due to the United Kingdom's (and even the Republic of Ireland's) involvement in the European Union, the usage focuses on non-British concepts. This kind of Euro-English was parodied when English was \"made\" one of the constituent languages of Europanto.\n" + "\n" + "Phonology\n" + "\n" + " Main article: English phonology\n" + "\n" + "Vowels\n" + "IPA Description word\n" + "monophthongs\n" + "i/iː Close front unrounded vowel bead\n" + "ɪ Near-close near-front unrounded vowel bid\n" + "ɛ Open-mid front unrounded vowel bed\n" + "æ Near-open front unrounded vowel bad\n" + "ɒ Open back rounded vowel bod 1\n" + "ɔ Open-mid back rounded vowel pawed 2\n" + "ɑ/ɑː Open back unrounded vowel bra\n" + "ʊ Near-close near-back rounded vowel good\n" + "u/uː Close back rounded vowel booed\n" + "ʌ/ɐ Open-mid back unrounded vowel, Near-open central vowel bud\n" + "ɝ/ɜː Open-mid central unrounded vowel bird 3\n" + "ə Schwa Rosa's 4\n" + "ɨ Close central unrounded vowel roses 5\n" + "diphthongs\n" + "e(ɪ)/eɪ Close-mid front unrounded vowel\n" + "Close front unrounded vowel bayed 6\n" + "o(ʊ)/əʊ Close-mid back rounded vowel\n" + "Near-close near-back rounded vowel bode 6\n" + "aɪ Open front unrounded vowel\n" + "Near-close near-front unrounded vowel cry\n" + "aʊ Open front unrounded vowel\n" + "Near-close near-back rounded vowel bough\n" + "ɔɪ Open-mid back rounded vowel\n" + "Close front unrounded vowel boy\n" + "ʊɝ/ʊə Near-close near-back rounded vowel\n" + "Schwa boor 9\n" + "ɛɝ/ɛə Open-mid front unrounded vowel\n" + "Schwa fair 10\n" + "\n" + "Notes:\n" + "\n" + "It is the vowels that differ most from region to region.\n" + "\n" + "Where symbols appear in pairs, the first corresponds to American English, General American accent; the second corresponds to British English, Received Pronunciation.\n" + "\n" + " 1. American English lacks this sound; words with this sound are pronounced with /ɑ/ or /ɔ/.\n" + " 2. Many dialects of North American English do not have this vowel. See Cot-caught merger.\n" + " 3. The North American variation of this sound is a rhotic vowel.\n" + " 4. Many speakers of North American English do not distinguish between these two unstressed vowels. For them, roses and Rosa's are pronounced the same, and the symbol usually used is schwa /ə/.\n" + " 5. This sound is often transcribed with /i/ or with /ɪ/.\n" + " 6. The diphthongs /eɪ/ and /oʊ/ are monophthongal for many General American speakers, as /eː/ and /oː/.\n" + " 7. The letter <U> can represent either /u/ or the iotated vowel /ju/. In BRP, if this iotated vowel /ju/ occurs after /t/, /d/, /s/ or /z/, it often triggers palatalization of the preceding consonant, turning it to /ʨ/, /ʥ/, /ɕ/ and /ʑ/ respectively, as in tune, during, sugar, and azure. In American English, palatalization does not generally happen unless the /ju/ is followed by r, with the result that /(t, d,s, z)jur/ turn to /tʃɚ/, /dʒɚ/, /ʃɚ/ and /ʒɚ/ respectively, as in nature, verdure, sure, and treasure.\n" + " 8. Vowel length plays a phonetic role in the majority of English dialects, and is said to be phonemic in a few dialects, such as Australian English and New Zealand English. In certain dialects of the modern English language, for instance General American, there is allophonic vowel length: vowel phonemes are realized as long vowel allophones before voiced consonant phonemes in the coda of a syllable. Before the Great Vowel Shift, vowel length was phonemically contrastive.\n" + " 9. This sound only occurs in non-rhotic accents. In some accents, this sound may be, instead of /ʊə/, /ɔ:/. See pour-poor merger.\n" + " 10. This sound only occurs in non-rhotic accents. In some accents, the schwa offglide of /ɛə/ may be dropped, monophthising and lengthening the sound to /ɛ:/.\n" + "\n" + "See also\n" + "\n" + " * International Phonetic Alphabet for English for more vowel charts.\n" + "\n" + "Consonants\n" + "\n" + "This is the English Consonantal System using symbols from the International Phonetic Alphabet (IPA).\n" + " bilabial labio-\n" + "dental dental alveolar post-\n" + "alveolar palatal velar glottal\n" + "plosive p b t d k ɡ \n" + "nasal m n ŋ 1 \n" + "flap ɾ 2 \n" + "fricative f v θ ð 3 s z ʃ ʒ 4 ç 5 x 6 h\n" + "affricate tʃ dʒ 4 \n" + "approximant ɹ 4 j \n" + "lateral approximant l \n" + " labial-velar\n" + "approximant ʍ w 7\n" + "\n" + " 1. The velar nasal [ŋ] is a non-phonemic allophone of /n/ in some northerly British accents, appearing only before /k/ and /g/. In all other dialects it is a separate phoneme, although it only occurs in syllable codas.\n" + " 2. The alveolar flap [ɾ] is an allophone of /t/ and /d/ in unstressed syllables in North American English and Australian English.[30] This is the sound of tt or dd in the words latter and ladder, which are homophones for many speakers of North American English. In some accents such as Scottish English and Indian English it replaces /ɹ/. This is the same sound represented by single r in most varieties of Spanish.\n" + " 3. In some dialects, such as Cockney, the interdentals /θ/ and /ð/ are usually merged with /f/ and /v/, and in others, like African American Vernacular English, /ð/ is merged with dental /d/. In some Irish varieties, /θ/ and /ð/ become the corresponding dental plosives, which then contrast with the usual alveolar plosives.\n" + " 4. The sounds /ʃ/, /ʒ/, and /ɹ/ are labialised in some dialects. Labialisation is never contrastive in initial position and therefore is sometimes not transcribed. Most speakers of General American realize <r> (always rhoticized) as the retroflex approximant /ɻ/, whereas the same is realized in Scottish English, etc. as the alveolar trill.\n" + " 5. The voiceless palatal fricative /ç/ is in most accents just an allophone of /h/ before /j/; for instance human /çjuːmən/. However, in some accents (see this), the /j/ is dropped, but the initial consonant is the same.\n" + " 6. The voiceless velar fricative /x/ is used only by Scottish or Welsh speakers of English for Scots/Gaelic words such as loch /lɒx/ or by some speakers for loanwords from German and Hebrew like Bach /bax/ or Chanukah /xanuka/. In some dialects such as Scouse (Liverpool) either [x] or the affricate [kx] may be used as an allophone of /k/ in words such as docker [dɒkxə]. Most native speakers have a great deal of trouble pronouncing it correctly when learning a foreign language. Most speakers use the sounds [k] and [h] instead.\n" + " 7. Voiceless w [ʍ] is found in Scottish and Irish English, as well as in some varieties of American, New Zealand, and English English. In most other dialects it is merged with /w/, in some dialects of Scots it is merged with /f/.\n" + "\n" + "Voicing and aspiration\n" + "\n" + "Voicing and aspiration of stop consonants in English depend on dialect and context, but a few general rules can be given:\n" + "\n" + " * Voiceless plosives and affricates (/ p/, / t/, / k/, and / tʃ/) are aspirated when they are word-initial or begin a stressed syllable — compare pin [pʰɪn] and spin [spɪn], crap [kʰɹ̥æp] and scrap [skɹæp].\n" + " o In some dialects, aspiration extends to unstressed syllables as well.\n" + " o In other dialects, such as Indo-Pakistani English, all voiceless stops remain unaspirated.\n" + " * Word-initial voiced plosives may be devoiced in some dialects.\n" + " * Word-terminal voiceless plosives may be unreleased or accompanied by a glottal stop in some dialects (e.g. many varieties of American English) — examples: tap [tʰæp̚], sack [sæk̚].\n" + " * Word-terminal voiced plosives may be devoiced in some dialects (e.g. some varieties of American English) — examples: sad [sæd̥], bag [bæɡ̊]. In other dialects they are fully voiced in final position, but only partially voiced in initial position.\n" + "\n" + "Supra-segmental features\n" + "\n" + "Tone groups\n" + "\n" + "English is an intonation language. This means that the pitch of the voice is used syntactically, for example, to convey surprise and irony, or to change a statement into a question.\n" + "\n" + "In English, intonation patterns are on groups of words, which are called tone groups, tone units, intonation groups or sense groups. Tone groups are said on a single breath and, as a consequence, are of limited length, more often being on average five words long or lasting roughly two seconds. For example:\n" + "\n" + " - /duː juː niːd ˈɛnɪˌθɪŋ/ Do you need anything?\n" + " - /aɪ dəʊnt | nəʊ/ I don't, no\n" + " - /aɪ dəʊnt nəʊ/ I don't know (contracted to, for example, - /aɪ dəʊnəʊ/ or /aɪ dənəʊ/ I dunno in fast or colloquial speech that de-emphasises the pause between don't and know even further)\n" + "\n" + "Characteristics of intonation\n" + "\n" + "English is a strongly stressed language, in that certain syllables, both within words and within phrases, get a relative prominence/loudness during pronunciation while the others do not. The former kind of syllables are said to be accentuated/stressed and the latter are unaccentuated/unstressed. All good dictionaries of English mark the accentuated syllable(s) by either placing an apostrophe-like ( ˈ ) sign either before (as in IPA, Oxford English Dictionary, or Merriam-Webster dictionaries) or after (as in many other dictionaries) the syllable where the stress accent falls. In general, for a two-syllable word in English, it can be broadly said that if it is a noun or an adjective, the first syllable is accentuated; but if it is a verb, the second syllable is accentuated.\n" + "\n" + "Hence in a sentence, each tone group can be subdivided into syllables, which can either be stressed (strong) or unstressed (weak). The stressed syllable is called the nuclear syllable. For example:\n" + "\n" + " That | was | the | best | thing | you | could | have | done!\n" + "\n" + "Here, all syllables are unstressed, except the syllables/words best and done, which are stressed. Best is stressed harder and, therefore, is the nuclear syllable.\n" + "\n" + "The nuclear syllable carries the main point the speaker wishes to make. For example:\n" + "\n" + " John hadn't stolen that money. (... Someone else had.)\n" + " John hadn't stolen that money. (... You said he had. or ... Not at that time, but later he did.)\n" + " John hadn't stolen that money. (... He acquired the money by some other means.)\n" + " John hadn't stolen that money. (... He had stolen some other money.)\n" + " John hadn't stolen that money. (... He stole something else.)\n" + "\n" + "Also\n" + "\n" + " I didn't tell her that. (... Someone else told her.)\n" + " I didn't tell her that. (... You said I did. or ... But now I will!)\n" + " I didn't tell her that. (... I didn't say it; she could have inferred it, etc.)\n" + " I didn't tell her that. (... I told someone else.)\n" + " I didn't tell her that. (... I told her something else.)\n" + "\n" + "This can also be used to express emotion:\n" + "\n" + " Oh really? (...I didn't know that)\n" + " Oh really? (...I disbelieve you)\n" + "\n" + "The nuclear syllable is spoken more loudly than the others and has a characteristic change of pitch. The changes of pitch most commonly encountered in English are the rising pitch and the falling pitch, although the fall-rising pitch and/or the rise-falling pitch are sometimes used. In this opposition between falling and rising pitch, which plays a larger role in English than in most other languages, falling pitch conveys certainty and rising pitch uncertainty. This can have a crucial impact on meaning, specifically in relation to polarity, the positive–negative opposition; thus, falling pitch means \"polarity known\", while rising pitch means \"polarity unknown\". This underlies the rising pitch of yes/no questions. For example:\n" + "\n" + " When do you want to be paid?\n" + " Now? (Rising pitch. In this case, it denotes a question: \"Can I be paid now?\" or \"Do you desire to be paid now?\")\n" + " Now. (Falling pitch. In this case, it denotes a statement: \"I choose to be paid now.\")\n" + "\n" + "Grammar\n" + "\n" + " Main article: English grammar\n" + "\n" + "English grammar has minimal inflection compared with most other Indo-European languages. For example, Modern English, unlike Modern German or Dutch and the Romance languages, lacks grammatical gender and adjectival agreement. Case marking has almost disappeared from the language and mainly survives in pronouns. The patterning of strong (e.g. speak/spoke/spoken) versus weak verbs inherited from its Germanic origins has declined in importance in modern English, and the remnants of inflection (such as plural marking) have become more regular.\n" + "\n" + "At the same time, the language has become more analytic, and has developed features such as modal verbs and word order as rich resources for conveying meaning. Auxiliary verbs mark constructions such as questions, negative polarity, the passive voice and progressive tenses.\n" + "\n" + "Vocabulary\n" + "\n" + "The English vocabulary has changed considerably over the centuries.[31]\n" + "\n" + "Germanic words (generally words of Old English or to a lesser extent Norse origin) which include all the basics such as pronouns (I, my, you, it) and conjunctions (and, or, but) tend to be shorter than the Latinate words of English, and more common in ordinary speech. The longer Latinate words are often regarded as more elegant or educated. However, the excessive or superfluous use of Latinate words is considered at times to be either pretentious (as in the stereotypical policeman's talk of \"apprehending the suspect\") or an attempt to obfuscate an issue. George Orwell's essay \"Politics and the English Language\" is critical of this, as well as other perceived abuses of the language.\n" + "\n" + "An English speaker is in many cases able to choose between Germanic and Latinate synonyms: come or arrive; sight or vision; freedom or liberty. In some cases there is a choice between a Germanic derived word (oversee), a Latin derived word (supervise), and a French word derived from the same Latin word (survey). The richness of the language arises from the variety of different meanings and nuances such synonyms harbour, enabling the speaker to express fine variations or shades of thought. Familiarity with the etymology of groups of synonyms can give English speakers greater control over their linguistic register. See: List of Germanic and Latinate equivalents.\n" + "\n" + "An exception to this and a peculiarity perhaps unique to English is that the nouns for meats are commonly different from, and unrelated to, those for the animals from which they are produced, the animal commonly having a Germanic name and the meat having a French-derived one. Examples include: deer and venison; cow and beef; swine/pig and pork, or sheep and mutton. This is assumed to be a result of the aftermath of the Norman invasion, where a French-speaking elite were the consumers of the meat, produced by English-speaking lower classes.\n" + "\n" + "In everyday speech, the majority of words will normally be Germanic. If a speaker wishes to make a forceful point in an argument in a very blunt way, Germanic words will usually be chosen. A majority of Latinate words (or at least a majority of content words) will normally be used in more formal speech and writing, such as a courtroom or an encyclopedia article. However, there are other Latinate words that are used normally in everyday speech and do not sound formal; these are mainly words for concepts that no longer have Germanic words, and are generally assimilated better and in many cases do not appear Latinate. For instance, the words mountain, valley, river, aunt, uncle, move, use, push and stay are all Latinate.\n" + "\n" + "English is noted for the vast size of its active vocabulary and its fluidity.[citation needed][weasel words] English easily accepts technical terms into common usage and imports new words and phrases that often come into common usage. Examples of this phenomenon include: cookie, Internet and URL (technical terms), as well as genre, über, lingua franca and amigo (imported words/phrases from French, German, modern Latin, and Spanish, respectively). In addition, slang often provides new meanings for old words and phrases. In fact, this fluidity is so pronounced that a distinction often needs to be made between formal forms of English and contemporary usage. See also: sociolinguistics.\n" + "\n" + "Number of words in English\n" + "\n" + "English has an extraordinarily rich vocabulary and willingness to absorb new words. As the General Explanations at the beginning of the Oxford English Dictionary states:\n" + "\n" + " The Vocabulary of a widely diffused and highly cultivated living language is not a fixed quantity circumscribed by definite limits... there is absolutely no defining line in any direction: the circle of the English language has a well-defined centre but no discernible circumference.\n" + "\n" + "The vocabulary of English is undoubtedly vast, but assigning a specific number to its size is more a matter of definition than of calculation. Unlike other languages, there is no Academy to define officially accepted words. Neologisms are coined regularly in medicine, science and technology and other fields, and new slang is constantly developed. Some of these new words enter wide usage; others remain restricted to small circles. Foreign words used in immigrant communities often make their way into wider English usage. Archaic, dialectal, and regional words might or might not be widely considered as \"English\".\n" + "\n" + "The Oxford English Dictionary, 2nd edition (OED2) includes over 600,000 definitions, following a rather inclusive policy:\n" + "\n" + " It embraces not only the standard language of literature and conversation, whether current at the moment, or obsolete, or archaic, but also the main technical vocabulary, and a large measure of dialectal usage and slang (Supplement to the OED, 1933).[32]\n" + "\n" + "The editors of Webster's Third New International Dictionary, Unabridged (475,000 main headwords) in their preface, estimate the number to be much higher. It is estimated that about 25,000 words are added to the language each year.[33]\n" + "\n" + "Word origins\n" + "Influences in English vocabulary\n" + "Influences in English vocabulary\n" + "\n" + " Main article: Lists of English words of international origin\n" + "\n" + "One of the consequences of the French influence is that the vocabulary of English is, to a certain extent, divided between those words which are Germanic (mostly Old English) and those which are \"Latinate\" (Latin-derived, either directly from Norman French or other Romance languages).\n" + "\n" + "Numerous sets of statistics have been proposed to demonstrate the various origins of English vocabulary. None, as yet, are considered definitive by a majority of linguists.\n" + "\n" + "A computerised survey of about 80,000 words in the old Shorter Oxford Dictionary (3rd ed.) was published in Ordered Profusion by Thomas Finkenstaedt and Dieter Wolff (1973)[34] that estimated the origin of English words as follows:\n" + "\n" + " * Langue d'oïl, including French and Old Norman: 28.3%\n" + " * Latin, including modern scientific and technical Latin: 28.24%\n" + " * Other Germanic languages (including words directly inherited from Old English): 25%\n" + " * Greek: 5.32%\n" + " * No etymology given: 4.03%\n" + " * Derived from proper names: 3.28%\n" + " * All other languages contributed less than 1% (e.g. Arabic-English loanwords)\n" + "\n" + "A survey by Joseph M. Williams in Origins of the English Language of 10,000 words taken from several thousand business letters[35] gave this set of statistics:\n" + "\n" + " * French (langue d'oïl), 41%\n" + " * \"Native\" English, 33%\n" + " * Latin, 15%\n" + " * Danish, 2%\n" + " * Dutch, 1%\n" + " * Other, 10%\n" + "\n" + "However, 83% of the 1,000 most-common English words are Anglo-Saxon in origin. [36]\n" + "\n" + "Dutch origins\n" + "\n" + " Main article: List of English words of Dutch origin\n" + "\n" + "Words describing the navy, types of ships, and other objects or activities on the water are often from Dutch origin. Yacht (Jacht) and cruiser (kruiser) are examples.\n" + "\n" + "French origins\n" + "\n" + " Main article: List of French phrases used by English speakers\n" + "\n" + "There are many words of French origin in English, such as competition, art, table, publicity, police, role, routine, machine, force, and many others that have been and are being anglicised; they are now pronounced according to English rules of phonology, rather than French. A large portion of English vocabulary is of French or Oïl language origin, most derived from, or transmitted via, the Anglo-Norman spoken by the upper classes in England for several hundred years after the Norman Conquest.\n"; var greek = "Ελλάδα\n" + "Από τη Βικιπαίδεια, την ελεύθερη εγκυκλοπαίδεια\n" + "Ελληνική Δημοκρατία\n" + " \n" + "Σημαία Εθνόσημο\n" + "Εθνικό σύνθημα: Ελευθερία ή Θάνατος\n" + "Εθνικός ύμνος: Ὕμνος εἰς τὴν Ἐλευθερίαν\n" + "\n" + "Πρωτεύουσα Αθήνα \n" + "38.01.36N 23.44.00E\n" + "\n" + "Μεγαλύτερη πόλη Αθήνα\n" + "Επίσημες γλώσσες Ελληνική\n" + "Πολίτευμα\n" + "\n" + "Πρόεδρος της Δημοκρατίας\n" + "Πρωθυπουργός Προεδρευόμενη\n" + "Κοινοβουλευτική Δημοκρατία\n" + "Κάρολος Παπούλιας\n" + "Κωνσταντίνος Καραμανλής\n" + "Ανεξαρτησία\n" + "- Κηρύχθηκε\n" + "- Αναγνωρίστηκε\n" + "\n" + "25 Μαρτίου, 1821\n" + "1828\n" + "Έκταση\n" + " - Σύνολο\n" + " - Νερό (%) \n" + "131.940 km² (94ηη)\n" + "%0.86\n" + "Πληθυσμός\n" + " - Εκτίμηση 2006\n" + " - Απογραφή 2001\n" + " - Πυκνότητα \n" + "11.120.000 [1] (72ηη)\n" + "10.964.020\n" + "83.1 κάτ./km² (87ηη)\n" + "Α.Ε.Π.\n" + " - Ολικό\n" + " - Κατά κεφαλή Εκτίμηση 2007\n" + "$305,595 δισ. (37η)\n" + "$27,360 (27η)\n" + "Νόμισμα Ευρώ\n" + "(€)\n" + "Ζώνη ώρας\n" + " - Θερινή ώρα (UTC+2)\n" + "(UTC+3)\n" + "Internet TLD .gr\n" + "Κωδικός κλήσης +30\n" + "Η Ελλάδα (αρχαΐζουσα: Ἑλλάς, επίσημα: Ελληνική Δημοκρατία), είναι χώρα στην νοτιοανατολική Ευρώπη, στο νοτιότερο άκρο της Βαλκανικής χερσονήσου, στην Ανατολική Μεσόγειο. Συνορεύει στην ξηρά, βόρεια με την Πρώην Γιουγκοσλαβική Δημοκρατία της Μακεδονίας και την Βουλγαρία, στα βορειοδυτικά με την Αλβανία και στα βορειοανατολικά με την Τουρκία. Βρέχεται ανατολικά από το Αιγαίο Πέλαγος, στα δυτικά και νότια από το Ιόνιο και από την Μεσόγειο Θάλασσα. Είναι το λίκνο του Δυτικού πολιτισμού. Η Ελλάδα έχει μια μακρά και πλούσια ιστορία κατά την οποία άσκησε μεγάλη πολιτισμική επίδραση σε τρεις ηπείρους.\n" + "Πίνακας περιεχομένων [Απόκρυψη]\n" + "1 Ιστορία\n" + "2 Πολιτικά\n" + "2.1 Κόμματα\n" + "2.2 Κυβέρνηση\n" + "3 Περιφέρειες\n" + "3.1 Βουνά της Ελλάδας\n" + "3.2 Λίμνες της Ελλάδας\n" + "3.3 Ποτάμια της Ελλάδας\n" + "3.4 Κλίμα\n" + "4 Οικονομία\n" + "5 Δημογραφία\n" + "6 Ένοπλες δυνάμεις και Σώματα ασφαλείας\n" + "6.1 Υποχρεωτική στράτευση\n" + "7 Πολιτισμός\n" + "7.1 Αργίες\n" + "8 Σημειώσεις\n" + "9 Δείτε επίσης\n" + "10 Εξωτερικές συνδέσεις\n" + "[Επεξεργασία]\n" + "Ιστορία\n" + "\n" + "Κύριο άρθρο: Ελληνική ιστορία\n" + "Στις ακτές του Αιγαίου Πελάγους εμφανίστηκαν οι πρώτοι πολιτισμοί της Ευρώπης, ο Μινωικός και ο Μυκηναϊκός. Την εποχή των πολιτισμών αυτών, ακολούθησε μία σκοτεινή περίοδος περίπου μέχρι το 800 π.Χ., οπότε εμφανίζεται ένας καινούριος Ελληνικός πολιτισμός, βασισμένος στο μοντέλο της πόλης-κράτους. Είναι ο πολιτισμός που θα διαδοθεί με τον αποικισμό των ακτών της Μεσογείου, θα αντισταθεί στην Περσική εισβολή με τους δύο επιφανέστερους εκπροσώπους του, την κοσμοπολίτικη και δημοκρατική Αθήνα και την μιλιταριστική και ολιγαρχική Σπάρτη, θα αποτελέσει τη βάση του Ελληνιστικού πολιτισμού που δημιούργησαν οι κατακτήσεις του Μεγάλου Αλεξάνδρου, θα επηρεάσει ως ένα βαθμό την πολιτισμική φυσιογνωμία της Βυζαντινής Αυτοκρατορίας και αργότερα θα πυροδοτήσει την Αναγέννηση στην Ευρώπη.\n" + "Στρατιωτικά έχανε δύναμη σε σύγκριση με τη Ρωμαϊκή αυτοκρατορία μέχρι που κατακτήθηκε τελικά από τους Ρωμαίους το 146 π.Χ., αν και ο Ελληνικός πολιτισμός τελικά κατέκτησε το Ρωμαϊκό τρόπο ζωής. Οι Ρωμαίοι αναγνώρισαν και θαύμασαν τον πλούτο του Ελληνικού πολιτισμού, τον μελέτησαν βαθιά και έγιναv συνειδητά συνεχιστές του. Διέσωσαν επίσης και μεγάλο μέρος της αρχαιοελληνικής γραμματείας. Αν και ήταν μόνο ένα μέρος της Ρωμαϊκής αυτοκρατορίας, ο ελληνικός πολιτισμός θα συνέχιζε να δεσπόζει στην Ανατολική Μεσόγειο, και όταν τελικά η Αυτοκρατορία χωρίστηκε στα δύο, η ανατολική ή Βυζαντινή Αυτοκρατορία με πρωτεύουσα την Κωνσταντινούπολη, θα είχε κυρίως λόγω γλώσσας έντονο τον ελληνικό χαρακτήρα. Από τον 4ο μέχρι τον 15ο αιώνα, η Ανατολική Ρωμαϊκή Αυτοκρατορία επέζησε επιθέσεις 11 αιώνων από δυτικά και ανατολικά, μέχρι που η Κωνσταντινούπολη έπεσε στις 29 Μαΐου του 1453 στα χέρια της Οθωμανικής Αυτοκρατορίας. Σταδιακά το Βυζάντιο κατακτήθηκε ολόκληρο μέσα στον 15ο αιώνα.\n" + "Η Οθωμανική κυριαρχία συνεχίστηκε μέχρι το 1821 που οι Έλληνες κήρυξαν την ανεξαρτησία τους. Η Ελληνική Επανάσταση του 1821 έληξε το 1828. Το 1830 αναγνωρίζεται η ανεξαρτησία του νέου ελληνικού κράτους. Εγκαθιδρύθηκε μοναρχία το 1833. Μέσα στον 19ο και τον πρώιμο 20ό αιώνα, η Ελλάδα προσπάθησε να προσαρτήσει στα εδάφη της όλες τις περιοχές που ακόμη ανήκαν στην Οθωμανική Αυτοκρατορία και είχαν Ελληνόφωνο πληθυσμό, πράγμα που κατάφερε εν μέρει, επεκτείνοντας σταδιακά την έκτασή της, μέχρι να φτάσει το σημερινό της μέγεθος το 1947.\n" + "Μετά τον Δεύτερο Παγκόσμιο Πόλεμο στην Ελλάδα ξέσπασε εμφύλιος πόλεμος μέχρι το 1949. Αργότερα, το 1952, η Ελλάδα έγινε μέλος του ΝΑΤΟ. Στις 21 Απριλίου του 1967 ο στρατός, υποβοηθούμενος από την κυβέρνηση των ΗΠΑ, πήρε την εξουσία με πραξικόπημα. Οι δικτατορες στη συνεχεια διαχωριστηκαν και απο τον βασιλια, τον εκδίωξαν απο την χώρα και κατήργησαν τη μοναρχία. Η στρατιωτική Χούντα υπήρξε η αιτία δημιουργίας, μετά από λανθασμένους χειρισμούς που εκμεταλλεύτηκε η Τουρκική πλευρά, του Κυπριακού ζητήματος, το οποίο οδήγησε στην κατάρρευσή της το 1974. Έπειτα από δημοψήφισμα για την κατάργηση της μοναρχίας στις 8 Δεκεμβρίου 1974 το πολίτευμα της Ελλάδας μετατράπηκε ξανά σε αβασίλευτη Δημοκρατία και συντάχθηκε νέο σύνταγμα από την πέμπτη Αναθεωρητική Βουλή που τέθηκε σε ισχύ στις 11 Ιουνίου 1975, το οποίο ισχύει σήμερα όπως αναθεωρήθηκε το 1986 και το 2001. Η Ελλάδα έγινε μέλος της Ευρωπαϊκής Ένωσης το 1981 και μέλος της Ευρωπαϊκής Οικονομικής και Νομισματικής Ένωσης (ΟΝΕ) γνωστής και ως ζώνης ευρώ, το 2001.\n" + "Ελληνική ιστορία \n" + "Κυκλαδικός πολιτισμός (3η χιλιετία π.Χ.)\n" + "Μινωικός πολιτισμός (3000-1450 π.Χ.)\n" + "Μυκηναϊκός πολιτισμός (1600-1100 π.Χ.)\n" + "Γεωμετρική εποχή (1100-800 π.Χ.)\n" + "Αρχαϊκή εποχή (800-500 π.Χ.)\n" + "Κλασική εποχή (500 π.Χ.- 323 π.Χ.)\n" + "Ελληνιστική εποχή (323-146 π.Χ.)\n" + "Ρωμαϊκή περίοδος (146 π.Χ.-330 μ.Χ.)\n" + "Βυζαντινή περίοδος (330-1453)\n" + "Οθωμανική περίοδος (1453-1821)\n" + "Νεότερη Ελλάδα (1821 έως σήμερα)\n" + "Σχετικά\n" + "Αρχαία ελληνική γραμματεία\n" + "Ελληνική γλώσσα\n" + "Ονομασίες Ελλήνων\n" + "\n" + "[Επεξεργασία]\n" + "Πολιτικά\n" + "\n" + "Το Σύνταγμα του 1975 περιέχει εκτενείς εγγυήσεις των ελευθεριών και των δικαιωμάτων του πολίτη, ελευθερίες και δικαιώματα που ενισχύθηκαν περαιτέρω με την αναθεώρηση του 2001. Είναι χαρακτηριστικό ότι κατά την αναθεώρηση αυτή κατοχυρώθηκαν, για πρώτη φορά συνταγματικά, πέντε ανεξάρτητες αρχές, οι τρεις εκ των οποίων (Συνήγορος του Πολίτη, Αρχή Διασφάλισης Ατομικών Δικαιωμάτων και Αρχή Προστασίας Προσωπικών Δεδομένων) είναι ταγμένες στην προστασία και διασφάλιση των ατομικών δικαιωμάτων. Η Ελλάδα είναι επίσης μέλος της Ευρωπαϊκής Σύμβασης για τα Δικαιώματα του Ανθρώπου.\n" + "Σε πολιτειακό και οργανωτικό επίπεδο, το Σύνταγμα διακρίνει τρεις εξουσίες: τη νομοθετική, την εκτελεστική και τη δικαστική. Στη νομοθετική μετέχουν ο Πρόεδρος της Δημοκρατίας και η Βουλή· στην εκτελεστική ο Πρόεδρος της Δημοκρατίας και η Κυβέρνηση, ενώ η δικαστική εξουσία ασκείται από τα δικαστήρια στο όνομα του ελληνικού λαού.\n" + "Ο Πρόεδρος της Δημοκρατίας, ιεραρχικά, βρίσκεται στην κορυφή της εκτελεστικής εξουσίας, μετέχει στη νομοθετική με τη δημοσίευση των νόμων και τη δυνατότητα αναπομπής ψηφισμένου νομοσχεδίου, ενώ ορίζεται από το Σύνταγμα ως ρυθμιστής του πολιτεύματος [2] . Εκλέγεται έμμεσα από τη Βουλή με διαδοχικές ψηφοφορίες των μελών της, στις οποίες επιδιώκεται η εξασφάλιση πλειοψηφίας 2/3, σε πρώτη φάση, και 3/5, σε δεύτερη, του συνόλου των μελών της. Σε περίπτωση αποτυχίας συγκέντρωσης των ανωτέρω πλειοψηφιών, διαλύεται η Βουλή, προκηρύσσονται εκλογές και η νέα Βουλή εκλέγει τον Πρόεδρο της Δημοκρατίας με την απόλυτη πλειοψηφία των μελών της, ή και με σχετική αν δεν συγκεντρωθεί η απόλυτη πλειοψηφία. Οι εξουσίες του Προέδρου είναι περιορισμένες καθώς ασκεί, κυρίως, τελετουργικά καθήκοντα. Όλες, σχεδόν, οι πράξεις του, χρήζουν προσυπογραφής από τον Πρωθυπουργό ή άλλο μέλος της Κυβέρνησης (υπουργό), όπως, π.χ., τα προεδρικά διατάγματα. Από την υποχρέωση προσυπογραφής εξαιρούνται ρητά ελάχιστες πράξεις του Προέδρου που προβλέπονται από το Σύνταγμα, όπως ο διορισμός των υπαλλήλων της Προεδρίας της Δημοκρατίας. Η θητεία του είναι πενταετής με δικαίωμα επανεκλογής για μία ακόμη φορά.\n" + "Η νομοθετική εξουσία ασκείται από τη Βουλή, τα μέλη της οποίας εκλέγονται με καθολική μυστική ψηφοφορία για τετραετή θητεία. Εκλογές μπορεί να κηρυχθούν νωρίτερα για έκτακτους λόγους, όπως αυτοί ορίζονται στο Σύνταγμα. Μετά, πάντως, το 1975 η προκήρυξη πρόωρων εκλογών αποτελεί τον κανόνα, με την επίκληση, συνήθως, από τις απερχόμενες κυβερνήσεις ιδιαζούσης σημασίας εθνικού θέματος. Η Ελληνική Δημοκρατία χρησιμοποιεί για την ανάδειξη των βουλευτών ένα σύνθετο ενδυναμωμένο εκλογικό σύστημα αναλογικής εκπροσώπησης (ενισχυμένη αναλογική), που αποθαρρύνει τη δημιουργία πολυκομματικών Κυβερνήσεων συνεργασίας και επιτρέπει ισχυρή κυβέρνηση πλειοψηφίας, ακόμα και αν το πρώτο κόμμα υστερεί της πλειοψηφίας των ψήφων. Για να μπορεί να καταλάβει μία από τις 300 βουλευτικές έδρες ένα κόμμα, πρέπει να έχει λάβει τουλάχιστον το 3% του συνόλου των ψήφων, ενώ με τον εκλογικό νόμο, που θα εφαρμοστεί, για πρώτη φορά, στις μετά το 2004 βουλευτικές εκλογές, το πρώτο κόμμα εξασφαλίζει απόλυτη πλειοψηφία στη Βουλή με ποσοστό 41%.\n" + "Η εκτελεστική εξουσία ασκείται από την Κυβέρνηση, κεφαλή της οποίας είναι ο Πρωθυπουργός, το ισχυρότερο πρόσωπο του ελληνικού πολιτικού συστήματος. Η Κυβέρνηση καθορίζει και κατευθύνει τη γενική πολιτική της Χώρας [3], εφαρμόζει την πολιτική, που εγκρίνει μέσω των νομοθετικών πράξεων η Βουλή, αλλά ταυτόχρονα μετέχει στη νομοπαρασκευαστική διαδικασία, μέσω της σύνταξης και της προώθησης προς ψήφιση των νομοσχεδίων. Η Κυβέρνηση με βάση την αρχή της δεδηλωμένης οφείλει να απολαύει της εμπιστοσύνης της Βουλής, να έχει λάβει δηλαδή ψήφο εμπιστοσύνης από την πλειοψηφία των Βουλευτών. Στα πλαίσια δε της σύγχρονης κομματικής δημοκρατίας, η Κυβέρνηση κυριαρχεί και στη νομοθετική λειτουργία, καθώς προέρχεται από το Κόμμα που ελέγχει την πλειοψηφία του Κοινοβουλίου, καθιστώντας, έτσι, την ψήφιση των νόμων μια τυπική, κατά κανόνα, διαδικασία. Λόγω δε της συχνής έως καταχρηστικής επίκλησης της κομματικής πειθαρχίας, η δυνατότητα διαφωνίας κυβερνητικού βουλευτή με την Κυβέρνηση που στηρίζει θεωρείται σπάνιο φαινόμενο. Σε έκτακτες περιπτώσεις μπορεί η Κυβέρνηση να εκδίδει Πράξεις Νομοθετικού Περιεχομένου. Οι Π.Ν.Π. έχουν ισχύ νόμου και οφείλουν να εγκριθούν εντός 40 ημερών από τη Βουλή.\n" + "Ο Πρωθυπουργός αποτελεί την κεφαλή της κυβέρνησης και, με βάση το Σύνταγμα, είναι, συνήθως (αν και όχι απαραίτητα), ο αρχηγός του έχοντος την απόλυτη πλειοψηφία στη Βουλή κυβερνώντος κόμματος. Βάσει του άρθρου 82 του Συντάγματος, \"ο Πρωθυπουργός εξασφαλίζει την ενότητα της Κυβέρνησης και κατευθύνει τις ενέργειές της, καθώς και των δημοσίων γενικά υπηρεσιών για την εφαρμογή της κυβερνητικής πολιτικής μέσα στο πλαίσιο των νόμων\" [3]. Οι βασικότερες εξουσίες του είναι οι εξής:\n" + "Προεδρεύει του Υπουργικού Συμβουλίου, στο οποίο μετέχει μαζί με τους Υπουργούς.\n" + "Με δέσμια πρόταση του διορίζονται και παύονται από τον Πρόεδρο της Δημοκρατίας οι υπουργοί και οι υφυπουργοί της Κυβέρνησης.\n" + "Καθορίζει με τον οικείο Υπουργό τις αρμοδιότητες των υφυπουργών.\n" + "Προΐσταται τεσσάρων αυτοτελών υπηρεσιών και γραμματειών: του Πολιτικού Γραφείου του Πρωθυπουργού, της Γραμματείας της Κυβερνήσεως, της Κεντρικής Νομοπαρασκευαστικής Επιτροπής και της Γενικής Γραμματείας Τύπου.\n" + "Δίνει άδεια για τη δημοσίευση στην Εφημερίδα της Κυβερνήσεως οποιουδήποτε κειμένου πρέπει, κατά το νόμο, να καταχωρισθεί σε αυτήν.\n" + "[Επεξεργασία]\n" + "Κόμματα\n" + "Περισσότερα: Κατάλογος ελληνικών πολιτικών κομμάτων\n" + "Μετά την αποκατάσταση της Δημοκρατίας το 1974 (μεταπολίτευση) το πολιτικό σύστημα κυριαρχείται από το φιλελεύθερο κόμμα της Νέας Δημοκρατίας και το σοσιαλιστικό ΠΑΣΟΚ (Πανελλλήνιο Σοσιαλιστικό Κίνημα). Άλλα κόμματα είναι το Κομμουνιστικό Κόμμα Ελλάδας, ο Συνασπισμός της Αριστεράς και ο ΛΑ.Ο.Σ..\n" + "[Επεξεργασία]\n" + "Κυβέρνηση\n" + "Περισσότερα: Κυβέρνηση της Ελλάδας\n" + "Στις εκλογές της 7 Μαρτίου 2004, πρωθυπουργός εκλέχθηκε ο Κωνσταντίνος Α. Καραμανλής, πρόεδρος της Νέας Δημοκρατίας. Ήταν η πρώτη εκλογική νίκη του κόμματος μετά από 11 χρόνια. Ο Καραμανλής αντικατέστησε τον Κωνσταντίνο Σημίτη και σχημάτισε δική του κυβέρνηση. Οι επόμενες βουλευτικές εκλογές προβλέπονταν από το Σύνταγμα για το 2008, όμως διεξήχθησαν πρόωρα στις 16 Σεπτεμβρίου 2007. Τις εκλογές της 16ης κέρδισε ξανά η ΝΔ. Η Νέα βουλή είναι η πρώτη πεντακομματική Βουλή τα τελευταία χρόνια και σε αυτή συμμετέχουν η ΝΔ το ΠΑΣΟΚ, το ΚΚΕ, ο ΣΥ.ΡΙ.ΖΑ και το ΛΑ.Ο.Σ. Συγκεκριμένα η ΝΔ εξασφάλισε το 41.83% και 152 από τις 300 Έδρες. Το ΠΑΣΟΚ εξασφάλισε το 38.10 % και 102 Έδρες. Το Κ.Κ.Ε εξασφάλισε το 8.15% και 22 έδρες. Ο ΣΥ.ΡΙ.ΖΑ εξασφάλισε το 5.04% και 14 έδρες και τέλος το ΛΑ.Ο.Σ εξασφάλισε το 3.80% κερδίζοντας 10 έδρες.\n" + "[Επεξεργασία]\n" + "Περιφέρειες\n" + "\n" + "Κύριο άρθρο: Περιφέρειες της Ελλάδας\n" + "Η Ελλάδα χωρίζεται σε 13 διοικητικές περιοχές γνωστές σαν Περιφέρειες, που διαχωρίζονται περαιτέρω σε 51 Νομούς:\n" + "Αττική\n" + "Αττική\n" + "Στερεά Ελλάδα\n" + "Εύβοια\n" + "Ευρυτανία\n" + "Φωκίδα\n" + "Φθιώτιδα\n" + "Βοιωτία\n" + "Κεντρική Μακεδονία\n" + "Χαλκιδική\n" + "Ημαθία\n" + "Κιλκίς\n" + "Πέλλα\n" + "Πιερία\n" + "Σέρρες\n" + "Θεσσαλονίκη\n" + "Κρήτη\n" + "Χανιά\n" + "Ηράκλειο\n" + "Λασίθι\n" + "Ρέθυμνο\n" + "Ανατολική Μακεδονία και Θράκη\n" + "Καβάλα\n" + "Δράμα\n" + "Ξάνθη\n" + "Ροδόπη\n" + "Έβρος\n" + "Ήπειρος\n" + "Άρτα\n" + "Ιωάννινα\n" + "Πρέβεζα\n" + "Θεσπρωτία\n" + "Ιόνια νησιά\n" + "Κέρκυρα\n" + "Κεφαλονιά\n" + "Λευκάδα\n" + "Ζάκυνθος\n" + "Βόρειο Αιγαίο\n" + "Χίος\n" + "Λέσβος\n" + "Σάμος - Ικαρία\n" + "Πελοπόννησος\n" + "Αρκαδία\n" + "Αργολίδα\n" + "Κορινθία\n" + "Λακωνία\n" + "Μεσσηνία\n" + "Νότιο Αιγαίο\n" + "Κυκλάδες\n" + "Δωδεκάνησα\n" + "Θεσσαλία\n" + "Καρδίτσα\n" + "Λάρισα\n" + "Μαγνησία\n" + "Τρίκαλα\n" + "Δυτική Ελλάδα\n" + "Αχαΐα\n" + "Αιτωλοακαρνανία\n" + "Ηλεία\n" + "Δυτική Μακεδονία\n" + "Φλώρινα\n" + "Γρεβενά\n" + "Καστοριά\n" + "Κοζάνη\n" + "Επιπλέον, στη Μακεδονία υπάρχει μία αυτόνομη περιοχή, το Άγιο Όρος, μία μοναστική πολιτεία υπό Ελληνική κυριαρχία. Οι νομοί χωρίζονται σε 147 επαρχίες, που διαιρούνται σε 900 δήμους και 133 κοινότητες. Πριν το 1999, υπήρχαν 5.775 οργανισμοί τοπικής αυτοδιοίκησης: 361 δήμοι και 5.560 κοινότητες, υποδιαιρούμενες σε 12.817 οικισμούς\n" + "\n" + "\n" + "\n" + "Αλβανία\n" + "\n" + "П.Γ.Δ.Μ.\n" + "\n" + "Βουλγαρία\n" + "'\n" + "\n" + "Τουρκία\n" + "\n" + "EΛΛAΣ\n" + "AΘHNA\n" + "Θεσσαλονίκη\n" + "Καβάλα\n" + "Αλεξανδρούπολη\n" + "Κέρκυρα\n" + "Ηγουμενίτσα\n" + "Λάρισα\n" + "Βόλος\n" + "Ιωάννινα\n" + "Χαλκίδα\n" + "Πάτρα\n" + "Πειραιάς\n" + "Ελευσίνα\n" + "Λαύριο\n" + "Ηράκλειο\n" + "Μ α κ ε δ ο ν ί α\n" + "Θράκη\n" + "Ήπειρος\n" + "Θεσσαλία\n" + "Στερεά Ελλάδα\n" + "Πελοπόννησος\n" + "Όλυμπος (2917m)\n" + "Λευκάδα\n" + "Κεφαλονιά\n" + "Λήμνος\n" + "Λέσβος\n" + "Χίος\n" + "Σάμος\n" + "Τήνος\n" + "Ικαρία\n" + "Νάξος\n" + "Σαντορίνη\n" + "Κως\n" + "Ρόδος\n" + "Κάρπαθος\n" + "Κύθηρα\n" + "Γαύδος\n" + "Αιγαίον\n" + "Πέλαγος\n" + "Μυρτώον\n" + "Πέλαγος\n" + "Κρητικόν Πέλαγος\n" + "Ιόνιον\n" + "Πέλαγος\n" + "Μεσόγειος\n" + "Θάλασσα\n" + "Κρήτη\n" + "[Επεξεργασία]\n" + "Βουνά της Ελλάδας\n" + "Κύριο άρθρο: Κατάλογος βουνών της Ελλάδας\n" + "Περίπου το 80% του εδάφους της χώρας είναι ορεινό ή λοφώδες. Μεγάλο μέρος του είναι ξηρό και βραχώδες, μόνο 28% του εδάφους είναι καλλιεργήσιμο.\n" + "Όλυμπος 2917 μ. Θεσσαλία, Κεντρική Μακεδονία (Λάρισα, Πιερία)\n" + "Σμόλικας 2637 μ. Βόρεια Πίνδος (Ιωάννινα)\n" + "Βόρας 2524 μ. Κεντρική Μακεδονία (Πέλλα, Φλώρινα, Π.Γ.Δ.Μ.)\n" + "Γράμος 2520 μ. Δυτική Μακεδονία (Καστοριά, Ιωάννινα, Αλβανία)\n" + "Γκιώνα 2510 μ. Στερεά (Φωκίδα)\n" + "Τύμφη 2497 μ. Βόρεια Πίνδος (Ιωάννινα)\n" + "Βαρδούσια 2495 μ. Στερεά (Φωκίδα)\n" + "Αθαμανικά όρη 2469 μ. Νότια Πίνδος (Άρτα)\n" + "Παρνασσός 2457 μ. Στερεά (Φωκίδα, Φθιώτιδα)\n" + "Ψηλορείτης 2456 μ. Κρήτη (Ηράκλειο)\n" + "\n" + "\n" + "\n" + "\n" + "Η χώρα αποτελείται από ένα μεγάλο ηπειρωτικό τμήμα, το νότιο άκρο των Βαλκανίων, ενωμένο με την πρώην ηπειρωτική Πελοπόννησο, από τον Ισθμό της Κορίνθου, και το Ιόνιο και Αιγαίο πέλαγος. Η Πελοπόννησος πλέον μετά την κατασκευή της διώρυγας της Κορίνθου είναι στην πραγματικότητα νησί. Το Αιγαίο περιέχει πολυάριθμα νησιά, ανάμεσά τους τη Ρόδο, την Εύβοια, τη Λέσβο και τα συμπλέγματα των Κυκλάδων και Δωδεκανήσων. 180 χιλιόμετρα νότια των ακτών δεσπόζει η Κρήτη, το πέμπτο μεγαλύτερο νησί της Μεσογείου. Η Ελλάδα έχει μήκος ακτών 15.021 χιλιόμετρα, που θεωρείται εξαιρετικά μεγάλο, και οφείλεται στον πλούσιο οριζόντιο εδαφικό διαμελισμό, καθώς και στο πλήθος των αναρίθμητων νησιών, τα οποία είναι πάνω από 1500. Έχει μήκος συνόρων που πλησιάζει τα 1.181 χιλιόμετρα.\n" + "\n" + "\n" + "Δορυφορική εικόνα της Ελλάδας\n" + "Κύριο άρθρο: Γεωγραφία της Ελλάδας\n" + "[Επεξεργασία]\n" + "Λίμνες της Ελλάδας\n" + "Κύριο άρθρο: Κατάλογος λιμνών της Ελλάδας\n" + "Η Ελλάδα έχει αρκετές λίμνες, οι περισσότερες των οποίων βρίσκονται στο ηπειρωτικό της τμήμα. Οι μεγαλύτερες λίμνες στην ελληνική επικράτεια είναι:\n" + "Τριχωνίδα 96.513 τ.χλμ.\n" + "Βόλβη 75.600 τ.χλμ\n" + "Λίμνη Βεγορίτιδα 72.488 τ.χλμ\n" + "Λίμνη Βιστονίδα 45.625 τ.χλμ\n" + "Λίμνη Κορώνεια 42.823 τ.χλμ\n" + "Μικρή Πρέσπα (ελληνικό τμήμα) 43.122 τ.χλμ\n" + "Μεγάλη Πρέσπα (ελληνικό τμήμα) 38.325 τ.χλμ\n" + "Κερκίνη 37.688 τ.χλμ\n" + "Υπάρχουν επίσης και αρκετές τεχνητές λίμνες κυρίως για παραγωγή ηλεκτρικού ρεύματος, όπως η Λίμνη Κρεμαστών (68.531 τ.χλμ) και η Λίμνη Πολυφύτου (56.793 τ.χλμ).\n" + "\n" + "[Επεξεργασία]\n" + "Ποτάμια της Ελλάδας\n" + "Αρκετά ποτάμια διαρρέουν την Ελλάδα, από τα οποίο κανένα δεν είναι πλεύσιμο. Μερικά από τα μεγαλύτερα, τα Δέλτα που σχηματίζουν στην εκροή τους προς την θάλασσα αποτελούν σημαντικούς υγροβιότοπους, όπως αυτοί του Αλιάκμονα και του Έβρου. Ποταμοί όπως ο Πηνειός στην Θεσσαλία, υδροδοτούν μεγάλες γεωργικές εκτάσεις με την βοήθεια καναλιών, ενώ σε άλλα έχουν δημιουργηθεί τεχνητές λίμνες για την λειτουργία υδροηλεκτρικών εργοστασίων. Ένα αμφιλεγόμενο για οικολογικούς λόγους σχέδιο των τελευταίων δεκαετιών, είναι η εκτροπή του Αχελώου από τη νότια Πίνδο για την αντιμετώπιση του υδατικού προβλήματος της Θεσσαλίας.\n" + "Ακολουθεί κατάλογος των μεγαλύτερων σε μήκος ποταμών της Ελλάδας. Το μήκος που αναγράφεται είναι αυτό που διατρέχει την ελληνική επικράτεια.\n" + "Αλιάκμονας 297 χλμ.\n" + "Αχελώος 220 χλμ.\n" + "Πηνειός (Θεσσαλίας) 205 χλμ.\n" + "Έβρος [4] 204 χλμ.\n" + "Νέστος [4] 130 χλμ.\n" + "Στρυμόνας [4] 118 χλμ.\n" + "Θύαμις (Καλαμάς) 115 χλμ.\n" + "Αλφειός 110 χλμ.\n" + "Άραχθος 110 χλμ.\n" + "[Επεξεργασία]\n" + "Κλίμα\n" + "Η Ελλάδα χαρακτηρίζεται από τον μεσογειακό τύπο του εύκρατου κλίματος και έχει ήπιους υγρούς χειμώνες και ζεστά ξηρά καλοκαίρια. Το κλίμα της χώρας μπορεί να διαιρεθεί σε τέσσερις βασικές κατηγορίες:\n" + "- υγρό μεσογειακό (δυτική Ελλάδα, δυτική Πελοπόννησος, πεδινά και ημιορεινά της Ηπείρου) - ξηρό μεσογειακό (Κυκλάδες, παραλιακή Κρήτη, Δωδεκάνησα, ανατολική Πελοπόννησος, Αττική, πεδινές περιοχές Ανατολικής Στερεάς) - ηπειρωτικό (δυτική Μακεδονία, εσωτερικά υψίπεδα ηπειρωτικής Ελλάδας, βόρειος Έβρος) - ορεινό (ορεινές περιοχές με υψόμετρο περίπου >1500μ στη βόρεια Ελλάδα, >1800μ στην κεντρική Ελλάδα και >2000μ στην Κρήτη).\n" + "Οι θερμοκρασίες είναι σπάνια υπερβολικές στις παραθαλάσσιες περιοχές. Στις κλειστές εσωτερικές πεδιάδες και στα υψίπεδα της χώρας παρατηρούνται τα μεγαλύτερα θερμοκρασιακά εύρη -τόσο ετήσια όσο και ημερήσια. Οι χιονοπτώσεις είναι κοινές στα ορεινά από τα τέλη Σεπτεμβρίου (στη βόρεια Ελλάδα, τέλη Οκτωβρίου κατά μέσο όρο στην υπόλοιπη χώρα), ενώ στις πεδινές περιοχές χιονίζει κυρίως από τον Δεκέμβριο μέχρι τα μέσα Μαρτίου. Έχει χιονίσει, πάντως, ακόμα και κατά μήνα Μάιο στη Φλώρινα. Στις παραθαλάσσιες περιοχές των νησιωτικών περιοχών, οι χιονοπτώσεις συμβαίνουν σπανιότερα και δεν αποτελούν βασικό χαρακτηριστικό του κλίματος. Η πόλη της Ρόδου έχει μέσο όρο 0,0 μέρες χιονόπτωσης το χρόνο. Οι καύσωνες επηρεάζουν κυρίως τις πεδινές περιοχές και είναι κοινότεροι τον Ιούλιο και τον Αύγουστο. Σπάνια, πάντως, διαρκούν περισσότερες από 3 μέρες.\n" + "Η Ελλάδα βρίσκεται μεταξύ των παραλλήλων 34ου και 42oυ του βορείου ημισφαιρίου και έχει μεγάλη ηλιοφάνεια όλο σχεδόν το χρόνο. Λεπτομερέστερα στις διάφορες περιοχές της Ελλάδας παρουσιάζεται μια μεγάλη ποικιλία κλιματικών τύπων, πάντα βέβαια μέσα στα πλαίσια του μεσογειακού κλίματος. Αυτό οφείλεται στην τοπογραφική διαμόρφωση της χώρας που έχει μεγάλες διαφορές υψομέτρου (υπάρχουν μεγάλες οροσειρές κατά μήκος της κεντρικής χώρας και άλλοι ορεινοί όγκοι) και εναλλαγή ξηράς και θάλασσας. Έτσι από το ξηρό κλίμα της Αττικής και γενικά της ανατολικής Ελλάδας μεταπίπτουμε στο υγρό της βόρειας και δυτικής Ελλάδας. Τέτοιες κλιματικές διαφορές συναντώνται ακόμη και σε τόπους που βρίσκονται σε μικρή απόσταση μεταξύ τους, πράγμα που παρουσιάζεται σε λίγες μόνο χώρες σε όλο τον κόσμο.\n" + "Από κλιματολογικής πλευράς το έτος μπορεί να χωριστεί κυρίως σε δύο εποχές: Την ψυχρή και βροχερή χειμερινή περίοδο που διαρκεί από τα μέσα του Οκτωβρίου και μέχρι το τέλος Μαρτίου και τη θερμή και άνομβρη εποχή που διαρκεί από τον Απρίλιο έως τον Οκτώβριο.\n" + "Κατά την πρώτη περίοδο οι ψυχρότεροι μήνες είναι ο Ιανουάριος και ο Φεβρουάριος, όπου κατά μέσον όρο η μέση ελάχιστη θερμοκρασία κυμαίνεται από 5-10 °C στις παραθαλάσσιες περιοχές, από 0-5 °C στις ηπειρωτικές περιοχές και σε χαμηλότερες τιμές κάτω από το μηδέν στις βόρειες περιοχές.\n" + "Οι βροχές ακόμη και τη χειμερινή περίοδο δεν διαρκούν για πολλές ημέρες και ο ουρανός της Ελλάδας δεν μένει συννεφιασμένος για αρκετές συνεχόμενες ημέρες, όπως συμβαίνει σε άλλες περιοχές της γης. Οι χειμερινές κακοκαιρίες διακόπτονται συχνά κατά τον Ιανουάριο και το πρώτο δεκαπενθήμερο του Φεβρουαρίου από ηλιόλουστες ημέρες, τις γνωστές από την αρχαιότητα Αλκυονίδες ημέρες.\n" + "Η χειμερινή εποχή είναι γλυκύτερη στα νησιά του Αιγαίου και του Ιονίου από ό,τι στη Βόρεια και Ανατολική ηπειρωτική Ελλάδα. Κατά τη θερμή και άνομβρη εποχή ο καιρός είναι σταθερός, ο ουρανός σχεδόν αίθριος, ο ήλιος λαμπερός και δεν βρέχει εκτός από σπάνια διαστήματα με ραγδαίες βροχές ή καταιγίδες μικρής γενικά διάρκειας.\n" + "Η θερμότερη περίοδος είναι το τελευταίο δεκαήμερο του Ιουλίου και το πρώτο του Αυγούστου οπότε η μέση μεγίστη θερμοκρασία κυμαίνεται από 29 °C μέχρι 35 °C. Κατά τη θερμή εποχή οι υψηλές θερμοκρασίες μετριάζονται από τη δροσερή θαλάσσια αύρα στις παράκτιες περιοχές της χώρας και από τους βόρειους ανέμους (ετησίες) που φυσούν κυρίως στο Αιγαίο.\n" + "Η άνοιξη έχει μικρή διάρκεια, διότι ο μεν χειμώνας είναι όψιμος, το δε καλοκαίρι αρχίζει πρώιμα. Το φθινόπωρο είναι μακρύ και θερμό και πολλές φορές παρατείνεται στη νότια Ελλάδα μέχρι τα μισά του Δεκεμβρίου.\n" + "[Επεξεργασία]\n" + "Οικονομία\n" + "\n" + "Κύριο άρθρο: Οικονομία της Ελλάδας\n" + "Η Ελλάδα έχει μικτή καπιταλιστική οικονομία, με τον δημόσιο τομέα να συνεισφέρει περίπου στο μισό του Α.Ε.Π.. Ο Τουρισμός αποτελεί μία πολύ σημαντική βιομηχανία, που συνεισφέρει κι αυτή σε μεγάλο ποσοστό του Α.Ε.Π., και επίσης αποτελεί πηγή συναλλάγματος. Το 2004 η μεγαλύτερη βιομηχανία στην Ελλάδα με έσοδα γύρω στα 12 δισ. ευρώ ήταν η συνήθως σχετικά αφανής ναυτιλία.\n" + "Η οικονομία βελτιώνεται σταθερά τα τελευταία χρόνια, καθώς η κυβέρνηση εφάρμοσε αποτελεσματική οικονομική πολιτική, στην προσπάθεια της ένταξης της Ελλάδας στην ζώνη του ευρώ, την 1 Ιανουαρίου 2001. Παράγων που σίγουρα βοήθησε σε αυτήν την πορεία είναι ότι η Ελλάδα είναι αποδέκτης οικονομικής βοήθειας από την Ευρωπαϊκή Ένωση, ίσης περίπου με το 3,3% του Α.Ε.Π. Η συνέχιση τόσο γενναιόδωρων ενισχύσεων από την Ε.Ε. όμως είναι υπό αμφισβήτηση. Η διεύρυνση της Ευρωπαϊκής Ένωσης με την είσοδο χωρών πολύ φτωχότερων από την Ελλάδα σε συνδυασμό με την ανοδική πορεία της ελληνικής οικονομίας θα βγάλει πιθανότατα πολλές περιοχές από τον λεγόμενο Στόχο 1 του Κοινοτικού Πλαισίου Στήριξης στον οποίο κατευθύνονται και οι περισσότερες επιδοτήσεις και στον οποίο ανήκουν περιοχές με Α.Ε.Π. κατά κεφαλήν μικρότερο του 75% του ευρωπαϊκού μέσου όρου. Με τα στοιχεία του 2003 από τον Στόχο 1 έχουν βγει οι εξής περιοχές: Αττική, Νότιο Αιγαίο, Στερεά Ελλάδα, Κεντρική Μακεδονία, Βόρειο Αιγαίο και οριακά η Πελοπόννησος.\n" + "Μεγάλες προκλήσεις παραμένουν, η μείωση της ανεργίας και η περαιτέρω ανοικοδόμηση της οικονομίας μέσω και της ιδιωτικοποίησης διαφόρων μεγάλων κρατικών εταιρειών, η αναμόρφωση της κοινωνικής ασφάλισης, διόρθωση του φορολογικού συστήματος, και η ελαχιστοποίηση των γραφειοκρατικών αδυναμιών. Η ανάπτυξη υπολογίζεται σε 3,9% για το 2004.\n" + "Η εθνική κεντρική τράπεζα του κράτους της Ελλάδας είναι η Τράπεζα της Ελλάδος (ΤτΕ), η οποία όμως έχει παραχωρήσει τις περισσότερες αρμοδιότητές της στην Ευρωπαϊκή Κεντρική Τράπεζα (Ε.Κ.Τ.), μετά την είσοδό της στην ζώνη του ευρώ το 2001.\n" + "[Επεξεργασία]\n" + "Δημογραφία\n" + "\n" + "Κύριο άρθρο: Δημογραφία της Ελλάδας\n" + "Άρθρο βασικών αποτελεσμάτων απογραφής: Απογραφή 2001\n" + "Σύμφωνα με την τελευταία απογραφή (2001)[5] ο μόνιμος πληθυσμός της χώρας είναι 10.934.097 κ. Την ημέρα της απογραφής, στη χώρα βρέθηκαν και απογράφηκαν (πραγματικός πληθυσμός) 10.964.020 κ.\n" + "Η Διεθνής Έκθεση για τις Θρησκευτικές Ελευθερίες που συντάσσει κάθε έτος το Υπουργείο Εξωτερικών των Ηνωμένων Πολιτειών, αναφέρει το 2005: «Περίπου 97% των πολιτών αυτοπροσδιορίζονται, τουλάχιστον κατ’ όνομα, ως Ελληνoρθόδοξοι. Υπάρχουν περίπου 500.000-800.000 παλαιοημερολογίτες σε ολόκληρη τη χώρα – υπερ-συντηρητικοί Ορθόδοξοι, οι οποίοι χρησιμοποιούν το Ιουλιανό ημερολόγιο και είναι αφοσιωμένοι στις παραδοσιακές Ελληνορθόδοξες πρακτικές. Η κυβέρνηση δεν τηρεί στατιστικά στοιχεία για τις θρησκευτικές ομάδες. Κατά τη διάρκεια των απογραφών πληθυσμού, οι κάτοικοι δεν ερωτώνται για το θρησκευτικό τους πιστεύω. Οι αρχές υπολογίζουν ότι η Τουρκόφωνη Μουσουλμανική κοινότητα αριθμεί 98.000 άτομα, αλλά, άλλοι υπολογίζουν ότι ο αριθμός αυτός ανέρχεται σε 140.000 άτομα. Τα περισσότερα χριστιανικά μη Ορθόδοξα δόγματα συναπαρτίζονται κατά κύριο λόγο από γηγενείς Έλληνες. Οι Μάρτυρες του Ιεχωβά αναφέρουν ότι έχουν 30.000 περίπου ενεργά μέλη και 50.000 άτομα που έχουν προσχωρήσει στην πίστη. Οι Καθολικοί υπολογίζονται σε 50.000. Οι Προτεστάντες, συμπεριλαμβανόμενων των Ευαγγελιστών, είναι 30.000, και οι οπαδοί της Εκκλησίας του Ιησού Χριστού των Αγίων των Τελευταίων Ημερών (Μορμόνοι) 300. Οι Σαϊεντολόγοι ισχυρίζονται ότι έχουν 500 ενεργά εγγεγραμμένα μέλη. Η από αιώνων υπάρχουσα Εβραϊκή κοινότητα αριθμεί περίπου 5.000 πιστούς, από τους οποίους 2.000 υπολογίζεται ότι διαμένουν στη Θεσσαλονίκη. Περίπου 250 μέλη της κοινότητας των Μπαχάι είναι διασκορπισμένα στην χώρα, τα περισσότερα των οποίων δεν είναι πολίτες ελληνικής καταγωγής. Η αρχαία Ελληνική Θρησκεία του Δωδεκαθέου έχει περίπου 2.000 μέλη. Υπάρχουν ακόμα μικρές ομάδες Αγγλικανών, Βαπτιστών, καθώς και άλλοι Χριστιανοί που δεν ανήκουν σε κάποιο συγκεκριμένο δόγμα. Δεν υπάρχει επίσημη ή ανεπίσημη εκτίμηση ως προς τον αριθμό των αθέων. Η πλειοψηφία των κατοίκων μη ελληνικής υπηκοότητας δεν είναι Ορθόδοξοι. Η μεγαλύτερη από αυτές τις ομάδες είναι Αλβανοί[5], συμπεριλαμβανόμενων των νομίμων και παρανόμων μεταναστών. Αν και οι περισσότεροι Αλβανοί δεν ανήκουν σε κάποια θρησκεία, παραδοσιακά συνδέονται με τη Μουσουλμανική, την Ορθόδοξη, ή τη Ρωμαιοκαθολική πίστη. Εκτός της εντόπιας Μουσουλμανικής μειονότητας στη Θράκη, οι Μουσουλμάνοι μετανάστες που βρίσκονται στην υπόλοιπη χώρα υπολογίζεται ότι ανέρχονται σε 200.000-300.000.» [6]\n" + "Τις τελευταίες δεκαετίες η Ελλάδα έχει δεχτεί ένα μεγάλο κύμα μετανάστευσης. Ο συνολικός αριθμός των μεταναστών υπολογίζεται περίπου στο 10% του συνολικού πληθυσμού ή στις 950.000 ανθρώπους. Νόμιμοι κάτοικοι της χώρας είναι περίπου οι μισοί αν και οι αριθμοί έχουν μεγάλη διακύμανση λόγω της έλλειψης επίσημης μεταναστευτικής πολιτικής και της αστάθειας στις γειτονικές χώρες πηγές μεταναστών. Οι μεγαλύτερες πληθυσμιακές ομάδες σύμφωνα με την απογραφή του 2001 φαίνεται να είναι οι προερχόμενοι από Αλβανία, Ρουμανία, Βουλγαρία, Πακιστάν, Ουκρανία, Πολωνία, Αίγυπτο.\n" + "Πέρα από τους αλλοδαπούς μετανάστες έχουν έρθει μετά την πτώση του Τείχους και αρκετοί ομογενείς από περιοχές της πρώην Ε.Σ.Σ.Δ. και από τα Βαλκάνια. Οι μεγαλύτερες ομάδες παλιννοστούντων είναι από την Αλβανία, την Ρωσία και την Γεωργία.\n" + "[Επεξεργασία]\n" + "Ένοπλες δυνάμεις και Σώματα ασφαλείας\n" + "\n" + "Ελληνικές Ένοπλες Δυνάμεις:\n" + "Ελληνικός Στρατός\n" + "Ελληνικό Πολεμικό Ναυτικό\n" + "Ελληνική Πολεμική Αεροπορία\n" + "Σώματα ασφαλείας:\n" + "Ελληνική Αστυνομία\n" + "Πυροσβεστικό Σώμα\n" + "Λιμενικό Σώμα\n" + "[Επεξεργασία]\n" + "Υποχρεωτική στράτευση\n" + "Κύριο άρθρο: Η θητεία στην Ελλάδα\n" + "Μέχρι το 2004, η Ελλάδα είχε νομοθετήσει υποχρεωτική θητεία 12 μηνών, για όλους τους άνδρες άνω των 18 ετών. Ωστόσο, κινείται προς την ανάπτυξη ενός πλήρως επαγγελματικού στρατού, με στόχο την πλήρη κατάργηση της θητείας. Το Υπουργείο Εθνικής Άμυνας έχει αναγγείλει τη σταδιακή μείωση στους 6 μήνες το 2008 και πιθανολογείται ότι μπορεί και να καταργηθεί τελείως. Παρότι γίνονται δεκτές αιτήσεις γυναικών που θέλουν να υπηρετήσουν, δεν είναι υποχρεωτικό. Η κίνηση αυτή δημιουργεί αντιρρήσεις από τους κύκλους που αντιτίθενται στην υποχρεωτική στράτευση, γιατί ενώ το Άρθρο 2 του Ελληνικού Συντάγματος θέτει υπόχρεους όλους τους Έλληνες πολίτες να υπερασπιστούν την Ελλάδα, ο φόρτος έγκειται ολοκληρωτικά στον ανδρικό πληθυσμό.\n" + "Οι κληρωτοί δεν λαμβάνουν ιατρική ασφάλιση κατά τη διάρκεια της θητείας τους, ούτε ο χρόνος της θητείας συνυπολογίζεται στα χρόνια εργασίας τους που θεμελιώνουν το συνταξιοδοτικό δικαίωμα. Λαμβάνουν, όμως, πλήρη ιατρική και νοσοκομειακή περίθαλψη από τα κατά τόπους στρατιωτικά νοσοκομεία, εφ' όσον αυτά υπάρχουν στον τόπο που υπηρετούν, αλλιώς αναγκάζονται να μεταφερθούν στην Αθήνα. Ο μισθός του κληρωτού είναι συμβολικός (9 ευρώ το μήνα για τους οπλίτες, σμηνίτες, κληρωτούς, 11 ευρώ για τους στρατεύσιμους δεκανείς, υποσμηνίες, υποκελευστές και τους στρατεύσιμους λοχίες, σμηνίες, κελευστές και 600 ευρώ για τους δόκιμους και των τριών σωμάτων). Οι δόκιμοι υπηρετούν 5 μήνες παραπάνω από τους υπόλοιπους συναδέλφους τους. Ο μισθός δεν αρκεί για να καλύψει τα έξοδα των κληρωτών, ιδιαίτερα όταν ένας κληρωτός υπηρετεί μακριά από τον τόπο διαμονής του, με αποτέλεσμα πρακτικά οι κληρωτοί να ζούνε από την οικονομική στήριξη των γονέων τους κατά την διάρκεια της θητείας τους.\n" + "[Επεξεργασία]\n" + "Πολιτισμός\n" + "\n" + "Κατάλογος διάσημων Ελλήνων\n" + "Ελληνική μυθολογία\n" + "Αρχαία ελληνική λογοτεχνία\n" + "Ελληνική Αρχιτεκτονική\n" + "Ελληνική κουζίνα\n" + "Ελληνική Γλώσσα\n" + "Ελληνική Μουσική\n" + "Ελληνικά Μουσεία\n" + "Μέσα Ενημέρωσης\n" + "[Επεξεργασία]\n" + "Αργίες\n" + "Ημερομηνία Ονομασία Σχόλια\n" + "1 Ιανουαρίου Πρωτοχρονιά \n" + "6 Ιανουαρίου Θεοφάνεια \n" + "κινητή Καθαρά Δευτέρα έναρξη της Μεγάλης Τεσσαρακοστής\n" + "25η Μαρτίου Ευαγγελισμός της Θεοτόκου και Εθνική Εορτή Εθνική Εορτή για την Επανάσταση του 1821\n" + "κινητή Μεγάλη Παρασκευή \n" + "κινητή Πάσχα Ανάσταση του Χριστού\n" + "κινητή Δευτέρα Διακαινησίμου (Δευτέρα του Πάσχα) Δευτέρα μετά την Ανάσταση\n" + "1 Μαΐου Πρωτομαγιά \n" + "κινητή Αγίου Πνεύματος \n" + "15 Αυγούστου Κοίμηση της Θεοτόκου \n" + "28η Οκτωβρίου Επέτειος του Όχι Εθνική Εορτή (1940)\n" + "25 Δεκεμβρίου Χριστούγεννα \n" + "26 Δεκεμβρίου Σύναξις Θεοτόκου \n" + "[Επεξεργασία]\n" + "Σημειώσεις\n" + "\n" + "↑ www.destatis.de εκτίμηση πληθυσμού χώρας, 2006\n" + "↑ Σύνταγμα της Ελλάδας, άρθρο 30\n" + "↑ 3,0 3,1 Σύνταγμα της Ελλάδας, άρθρο 82\n" + "↑ 4,0 4,1 4,2 Πηγάζει στη Βουλγαρία\n" + "↑ 5,0 5,1 απογραφή 2001\n" + "↑ Πηγή: Διεθνής Έκθεση Θρησκευτικής Ελευθερίας του 2005 στην ελληνική και στην αγγλική, Υπουργείο Εξωτερικών των Η.Π.Α.\n" + "[Επεξεργασία]\n" + "Δείτε επίσης\n" + "\n" + "Σημαία της Ελλάδας\n" + "Κατάλογος γλωσσών της Ελλάδας\n" + "Τράπεζα της Ελλάδος\n" + "Ονομασίες της Ελλάδας σε διάφορες γλώσσες\n" + "Άτλας της Ελλάδας: συλλογή διαφόρων χαρτών της Ελλάδας στα Κοινά (Commons).\n" + "Κατάλογος νοσοκομείων της Ελλάδας\n" + "[Επεξεργασία]\n" + "Εξωτερικές συνδέσεις\n" + "\n" + "Πρωθυπουργός της Ελλάδας (Γραφείο Πρωθυπουργού)\n" + "Βουλή των Ελλήνων\n" + "Παράθυρο στην Ελλάδα (χρήσιμες πληροφορίες και σύνδεσμοι για την Ελλάδα)\n" + "Παράθυρο στην Ελλάδα (παλαιότερη «έκδοση»)\n" + "Ελληνικός Οργανισμός Τουρισμού\n" + "Υπουργείο Εξωτερικών\n"; var hebrew = "היסטוריה של סין\n" + "מתוך ויקיפדיה, האנציקלופדיה החופשית\n" + "קפיצה אל: ניווט, חפש\n" + "\n" + " ערך זה עוסק בההיסטוריה של הישות התרבותית והגאוגרפית במזרח אסיה. אם התכוונתם לההיסטוריה של מדינה המוכרת היום בשם \"סין\", ראו היסטוריה של הרפובליקה העממית של סין.\n" + "\n" + "בערך זה מופיע גופן מזרח אסייתי\n" + "\n" + "כדי שתוכלו לראות את הכתוב בערך זה בצורה תקינה, תצטרכו להתקין גופן מזרח אסייתי במחשבכם. אם אינכם יודעים כיצד לעשות זאת, לחצו כאן לקבלת עזרה\n" + "\n" + "סין הנה התרבות המפותחת והרציפה העתיקה ביותר בעולם, תיעודים כתובים של התרבות נמצאים כבר מלפני 3,500 שנים והסינים עצמם נוקבים במספר 5,000 כמספר שנות קיומה של תרבותם. שושלות השלטון בסין פיתחו לאורך השנים שיטות בירוקרטיה שלטונית שהעניקו לסינים יתרון משמעותי על העמים השבטיים שחיו מסביבם. פיתוח אידאולוגיה למדינה, המבוססת על משנתו הפילוסופית של קונפוציוס (המאה ה-1 לפנה\"ס), יחד עם פיתוח מערכת כתב זמינה לכל (המאה ה-2 לפנה\"ס) חיזקו עוד יותר את התרבות הסינית. מבחינה פוליטית, סין נעה בתנועה מתמדת בין איחוד ופירוד ולעתים גם נכבשה על ידי כוחות זרים אשר מרביתם התמזגו לתוך תרבותה והפכו לחלק בלתי נפרד ממנה. השפעות תרבותיות ופוליטיות אלו שהגיעו מכל קצוות אסיה כמו גם גלי הגירה אל ומחוץ למדינה יצרו יחד את דמותם של התרבות והעם הסיני כפי שהם מוכרים לנו היום.\n" + "היסטוריה של סין\n" + "\n" + " * התקופה הקדומה\n" + "\n" + " שלושת המלכים וחמשת הקיסרים\n" + " שושלת שיה\n" + " שושלת שאנג\n" + " שושלת ג'ואו\n" + " תקופת האביב והסתיו\n" + " תקופת המדינות הלוחמות\n" + "\n" + " * סין הקיסרית\n" + "\n" + " שושלת צ'ין\n" + " שושלת האן המערבית\n" + " שושלת שין\n" + " שושלת האן המזרחית\n" + " שלושת הממלכות\n" + " שושלת ג'ין\n" + " השושלת הצפונית והדרומית\n" + " שושלת סוי\n" + " שושלת טאנג\n" + " שושלת סונג\n" + " שושלת יו'אן\n" + " שושלת מינג\n" + " שושלת צ'ינג\n" + "\n" + " * התפוררות הקיסרות\n" + "\n" + " מלחמת האופיום הראשונה\n" + " מרד טאיפינג\n" + " מלחמת האופיום השנייה\n" + " מלחמת סין-צרפת\n" + " מלחמת סין-יפן הראשונה\n" + " רפורמת מאה הימים\n" + " מרד הבוקסרים\n" + "\n" + " * סין המודרנית\n" + "\n" + " מהפכת שינהאי\n" + " הקמתה של המפלגה הקומניסטית של סין\n" + " המצעד הארוך\n" + " תקרית שיאן\n" + " מלחמת סין-יפן השנייה\n" + " מלחמת האזרחים הסינית\n" + "\n" + " * העת החדשה\n" + "\n" + " הקמת הרפובליקה העממית של סין\n" + " מערכת מאה הפרחים\n" + " הזינוק הגדול קדימה\n" + " הפיצול הסיני-סובייטי\n" + " מלחמת הודו-סין\n" + " מהפכת התרבות בסין\n" + " תקרית טיאנאנמן\n" + "\n" + "ראו גם\n" + "\n" + " * הרפובליקה הסינית\n" + " * לוח זמנים של ההיסטוריה של סין\n" + "\n" + "פורטל סין\n" + "קטגוריה ראשית\n" + "\n" + "\n" + "תוכן עניינים\n" + "[הסתר]\n" + "\n" + " * 1 פרה-היסטוריה\n" + " o 1.1 שלושת המלכים וחמשת הקיסרים\n" + " * 2 היסטוריה קדומה\n" + " o 2.1 שושלת שְׂיָה\n" + " o 2.2 שושלת שָׁאנְג\n" + " o 2.3 שושלת ג'וֹאוּ\n" + " o 2.4 תקופת האביב והסתיו\n" + " o 2.5 תקופת המדינות הלוחמות\n" + " * 3 שושלת צ'ין: האימפריה הסינית הראשונה\n" + " * 4 שושלת האן: תקופה של שגשוג\n" + " * 5 ג'ין, שש עשרה הממלכות והשושלות הדרומית והצפונית: התקופה האפלה של סין\n" + " * 6 שושלת טאנג: חזרה לשיגשוג\n" + " * 7 שושלת סונג ושכנותיה הצפוניות, ליאו וג'ין\n" + " * 8 המונגולים\n" + " * 9 תחייתה מחדש של התרבות הסינית\n" + " * 10 תקופת מינג: מהתפתחות לבידוד\n" + " * 11 שושלת צ'ינג\n" + " * 12 הרפובליקה הסינית\n" + " * 13 הרפובליקה העממית של סין\n" + " * 14 ראו גם\n" + " * 15 לקריאה נוספת\n" + " * 16 קישורים חיצוניים\n" + " * 17 הערות שוליים\n" + "\n" + "[עריכה] פרה-היסטוריה\n" + "\n" + "העדויות הארכאולוגיות הקדומות ביותר לנוכחות אנושית בסין של ימינו הן של הומו ארקטוס. מחקרים חדשים מגלים כי עמודי האבן שנמצאו באתר שיאוצ'אנגליאנג מתאורכים מבחינה סטרטיגרפית מלפני 1.36 מיליוני שנים. באתר הארכאולוגי שִׂיהוֹאוּדוּ שבמחוז שאנסי נמצאות העדויות הראשונות בעולם לשימוש באש על ידי ההומו ארקטוס, ומתאורכות ללפני 1.27 מיליוני שנים. עם זאת תושביו הנוכחיים של האזור אינם צאצאי אותו הומו ארקטוס, אלא צאצאי הומו סאפיינס שהגיע לאזור מאזור אפריקה רק לפני 65,000 שנים.\n" + "\n" + "עדויות מוקדמות לחקלאות סינית טיפוסית – גידולי אורז בברכות – מתוארכות לשנת 6,000 לפנה\"ס. בדומה לתרבויות קדומות בכל העולם, הביאה החקלאות לגידול מהיר באוכלוסייה, כיוון שהתבססות על גידולים חקלאיים הבטיחה יכולת שימור המזון ואגירתו לזמן ממושך יותר, וזו הביאה בהדרגה לגידול האוכלוסייה, להתפתחותה התרבותית ולריבוד חברתי.\n" + "\n" + "בשלהי התקופה הניאוליטית החל עמק הנהר הצהוב בסין לפתח את מעמדו כמרכז תרבותי, כאשר ראשוני הכפרים באזור הופיעו שם. מרבית העדויות למרכז חשוב זה נמצאות באזור העיר שי-אן בסין.\n" + "\n" + "[עריכה] שלושת המלכים וחמשת הקיסרים\n" + "\n" + " ערך מורחב – שלושת המלכים וחמשת הקיסרים\n" + "\n" + "ספרי ההיסטוריה הקדומים, רשומות ההיסטוריון, שנכתבו על ידי ההיסטורוגרף הסיני סְה-מָה צְ'ייֵן במאה השנייה לפנה\"ס, וספר תולדות החיזרן, שנכתבו במאה הרביעית לפנה\"ס מתארכים את תחילת ההיסטוריה הסינית לתקופת שלושת המלכים וחמשת הקיסרים - 2800 לפנה\"ס. לתקופה זו מאפיינים מיתולוגיים מובהקים. למלכים ולקיסרים תכונות מיסטיות והם מתוארים כשליטים נבונים ובעלי מוסר למופת. אחד מהם, הקיסר הצהוב נחשב לאבי בני ההאן.\n" + "\n" + "סה-מה צ'יאן כותב כי תחילת ביסוס מערכת ממשלתית נעשה בימי שושלת שיה, וסגנון המערכת הונצח על ידי שושלות שאנג וג'ואו. בתקופת שלושת השושלות האלו, החלה סין לפצוע על שחר ההיסטוריה. מכאן ואילך, עד למאה העשרים, מתוארות תולדות סין לפי השושלות שמשלו בה.\n" + "\n" + "[עריכה] היסטוריה קדומה\n" + "\n" + "[עריכה] שושלת שְׂיָה\n" + "\n" + " ערך מורחב – שושלת שיה\n" + "\n" + "שושלת שְׂיָה (סינית: 夏, פיניין: Xià), היא השושלת הראשונה בתולדות סין. שושלת זו התקיימה לפני המצאת הכתב בסין, כך שהעדויות לקיומה מסתמכות על מסמכים מאוחרים יותר ועל ארכאולוגיה. סְה-מָה צְ'ייֵן וספר תולדות החיזרן מתארכים את ימי השושלת לכלפני 4,200 שנה, אולם אין בידינו לאמת את הדברים. 17 מלכים ו-14 דורות מנתה השושלת, שהתחילה בימיו של יוּ'‏ הגדול והסתיימה בימיו של גְ'יֵה איש שְׂיָה, כך על-פי סְה-מָה צְ'ייֵן ומקורות אחרים מתקופת שושלת צ'ין.\n" + "\n" + "שושלות שאנג וג'ואו התקיימו במקביל לשושלת שיה כבר מתחילתה, אך היו כפופות לה. אורך ימיה של השושלת לא ברור, אך 431 או 471 שנים הן שתי החלופות הסבירות ביותר.\n" + "\n" + "ארכאולוגים רבים מזהים את שושלת שְׂיָה עם אתר אָרלִיטוֹאוּ שבמרכז מחוז הנאן[1]. באתר זה נתגלה כור היתוך מברונזה משנת 2000 לפנה\"ס לערך. נטען גם כי סימונים על-גבי חרס וקונכיות מתקופה זו הן גילגול קדום של הכתב הסיני[2]. בהיעדר עדויות כתובות בכתב המוכר מעצמות הניחוש של שושלת שאנג ומכלי הברונזה של שושלת ג'ואו, נותר טיבה של שושלת שיה לוט בערפל.\n" + "\n" + "[עריכה] שושלת שָׁאנְג\n" + "\n" + " ערך מורחב – שושלת שאנג\n" + "\n" + "הרישומים הכתובים העתיקים ביותר בסין נחרטו לצורך הגדת עתידות על עצמות או קונכיות. כתבים אלה, המכונים עצמות ניחוש, מתוארכים למאה ה-13 לפנה\"ס לערך, תקופת שושלת שָׁאנְג (סינית: 商, פיניין: Shāng). ממצאים ארכאולוגיים, המעידים על קיומה של השושלת בשנים 1600-1046 לפנה\"ס בקירוב, מחולקים לשתי קבוצות. הקבוצה המוקדמת, עד ל-1300 בקירוב, מגיעה מאתרים שונים במחוז הנאן. הקבוצה המאוחרת, מתקופת יִין (殷), מורכבת מאסופה רחבה של עצמות ניחוש, גם הן ממחוז הנאן. אָנְיָאנְג שבמחוז הנאן הייתה הבירה התשיעית והאחרונה של שושלת שאנג. לשושלת היו 31 מלכים, והיא הייתה הארוכה שבשושלות סין.\n" + "\n" + "על פי רשומות ההיסטוריון העבירה שושלת שאנג את בירתה שש פעמים, כשהמעבר השישי והאחרון לעיר יִין ב-1350 לפנה\"ס סימן את תחילת תור הזהב של השושלת. ההיסטוריה התמטית של סין מתארת בדרך-כלל קיום של שושלת אחת אחרי השנייה, אך המצב לאשורו באותה עת היה מורכב יותר. חוקרים טוענים כי ייתכן ושושלות שיה ושאנג התקיימו במקביל, כשם ששושלת ג'ואו (שֶׁירשה את שושלת שאנג), התקיימה אף היא בזמן שושלת שאנג. עדויות כתובות מאתר אניאנג מאששים אמנם את קיומה של שושלת שאנג, אך חוקרים מערביים אינם נוטים לזהות יישובים בני אותה תקופה עם שושלת שאנג דווקא. כך למשל, ממצאים ארכאולוגיים מאותה עת באתר סָאנְשִׂינְגְדְווֵי מצביעים על חברה מתקדמת, השונה בתרבותה מזו שנתגלתה בְּאָנְיָאנְג. אין עדויות מכריעות במוגע לתחום שליטתה של שושלת שאנג. ההנחה המקובלת היא כי שושלת שאנג שבהיסטוריה הרשמית אכן שלטה בעיר אניאנג, תוך שהיא מקיימת קשרי מסחר עם יישובים שונים בסביבתה, שהיו שונים זה מזה מבחינה תרבותית.\n" + "\n" + "[עריכה] שושלת ג'וֹאוּ\n" + "\n" + " ערך מורחב – שושלת ג'ואו\n" + "\n" + "שושלת ג'וֹאוּ (סינית: 周, פיניין: Zhōu), הייתה השושלת ששלטה את הזמן הארוך ביותר בסין, מ-1122 לפנה\"ס ועד 256 לפנה\"ס - 866 שנה. השושלת התחילה להתגלות בנהר הצהוב והתפשטה אל תוך גבולותיה של השאנג. השושלת התחילה את שליטתה כפיאודליזם. הג'ואו חיו מערבית לשאנג, ושליטם היה מכונה בפיהם של שאנג כ\"מגן המערבי\". שליט ג'ואו המלך ווּ, בעזרת דודו הדוכס של ג'ואו, הצליחו להכניע את אחרון קיסרי שאנג בקרב שקבל את השם הקרב של מויה. היה זה מלכה של ג'ואו באותו הזמן, שטבע את מושג מנדט השמים, רעיון לפיו השמים הם המחליטים מי יהיה הקעסר הבא, ודרכם להביע את זה היא הצלחתו של הקיסר בניהול מלכותו, כך שמרד נתפס כלגיטימי, כל עוד זכה להצלחה. הקיסר העביר את בירתו אל עבר מערב האזור, סמוך למקום המכונה כיום שיאן, לגדות הנהר הצהוב, אולם שליטתם התפרסה אל כל עבר מושבות נהר היאנגטסה. זו הייתה ההגירה הראשונה בגודל כזה מצפון סין לדרומה.\n" + "\n" + "[עריכה] תקופת האביב והסתיו\n" + "\n" + " ערך מורחב – תקופת האביב והסתיו\n" + "\n" + "תקופת האביב והסתיו (בסינית: 春秋時代) הוא כינויה של תקופה בין השנים 722 לפנה\"ס ל 481 לפנה\"ס. שמה של התקופה לקוח משם הספר רשומות האביב והסתיו, תיעוד היסטורי של אותה תקופה אשר נכתב בידי קונפוציוס.\n" + "\n" + "במהלך התקופה נערכו מלחמות רבות בין המדינות שהרכיבו באותה תקופה את סין מה שהביא לביזור של הכח השלטוני בסין העתיקה. בעקבות המלחמות הודחו שליטים רבים מכסאם, ושכבת האצולה בסין התפוררה למעשה. עם התפשטותם של האצילים ברחבי הארץ נפוצה איתם גם ידיעת הקרוא וכתוב אשר הייתה נחלתם הכמעט בלעדית של האצילים עד לאותה תקופה. התפשטות הקריאה והכתיבה עודדה את חופש המחשבה וההתפתחות הטכנולוגית. לאחר תקופת האביב והסתיו החלה בסין תקופת מלחמת המדינות.\n" + "\n" + "[עריכה] תקופת המדינות הלוחמות\n" + "\n" + " ערך מורחב – תקופת המדינות הלוחמות\n" + "\n" + "תקופת המדינות הלוחמות (סינית: 戰國, פיניין: Zhàn Guó) החלה במאה החמישית לפנה\"ס והסתיימה בשנת 221 לפנה\"ס באיחודה של סין על ידי שושלת צ'ין. רשמית, בתקופת המדינות הלוחמות, כמו גם בתקופה שקדמה לה, תקופת האביב והסתיו, הייתה סין תחת שלטונה של שושלת ג'וֹאוּ המזרחית, אך שליטה זו הייתה רק להלכה, ולשושלת לא הייתה השפעה ממשית, ולמעשה חדלה להתקיים 35 שנה לפני סיומה הרשמי של התקופה. את שמה קיבלה התקופה מ\"רשומות המדינות הלוחמות\", תיעוד היסטורי של התקופה, שנכתב בתקופת שושלת האן.\n" + "\n" + "תקופת המדינות הלוחמות, שלא כמו תקופת האביב והסתיו, הייתה תקופה בה שרי צבא ואריסטוקרטים מקומיים סיפחו לאחוזותיהם כפרים, ערים ומדינות זעירות סמוכות והשליטו עליהם את שלטונם. במאה השלישית לפנה\"ס הביא מצב זה ליצירת שבע מדינות עיקריות בסין: מדינות צִ'י (齊), צ'וּ (楚), יֵן (燕), הַאן (韓), גָ'או (趙), ווֶי (魏) וצִ'ין (秦). סימן נוסף לשינוי במעמדם של הגנרלים היה שינוי תארם הרשמי מגונג (公 - המקבילה הסינית לדוכס), הכפופים כביכול למלך של ג'ואו, לוואנג (王) - מלכים, השווים במעמדם למלך של ג'ואו.\n" + "\n" + "תקופת המדינות הלוחמות היא גם תחילתו של השימוש בברזל במקום ארד בסין כמתכת עיקרית בכל תחומי החיים האזרחיים והצבאיים. במהלך תקופה זו החלו להבנות החומות, שיגנו על הממלכות מפני פלישה של שבטים ברבריים מהצפון חומות, שהיוו את היסוד לחומה הסינית המאוחרת יותר. מאפיין תרבותי נוסף של התקופה היה הפיכתן של פילוסופיות שונות כגון קונפוציזם, דאואיזם, לגאליזם, ומוהיזם למעמד של דתות במדינות השונות.\n" + "\n" + "בתום התקופה, לאחר שממלכת צ'ין הצליחה להביס ולכבוש את שאר הממלכות, הפך המלך צ'ין לקיסר הראשון של סין המאוחדת.\n" + "\n" + "[עריכה] שושלת צ'ין: האימפריה הסינית הראשונה\n" + "\n" + " ערך מורחב – שושלת צ'ין\n" + "\n" + "סין אוחדה לראשונה בשנת 212 לפנה\"ס בידי צִ'ין שְׁה-חְוָאנג, מייסד שושלת צ'ין. קדמה לאיחוד תקופת מלחמת המדינות ותקופת האביב והסתיו, שהתאפיינו שתיהן במספר ממלכות שהתקיימו במקביל ולחמו זו בזו. בשנת 212 לפנה\"ס עלה בידו של צ'ין להשתלט סופית על כל הממלכות בסין העתיקה ולשים קץ למלחמות הפנימיות.\n" + "\n" + "למרות שהאימפריה המאוחדת של הקיסר צ'ין התקיימה רק 12 שנים, הצליח הקיסר בזמן מועט זה למסד את רוב שטחה של המדינה כפי שאנו מכירים אותה כיום ולהשליט בה משטר ריכוזי המבוסס על לגאליזם אשר מושבו היה בשיאניאנג, שיאן של ימינו. שושלת צ'ין מפורסמת גם בשל תחילת בנייתה של החומה הסינית הגדולה (החומה הוגדלה בתקופת שושלת מינג). בניו של הקיסר לא היו מוצלחים כמוהו, ועם מותו של הקיסר תמה תקופת שלטונה של שושלתו.\n" + "\n" + "מקור המילה סין בשפה העברית וכן בשפה האנגלית (China), מגיע ככל הנראה מהמילה צ'ין (秦), שמה של השושלת הראשונה.\n" + "\n" + "[עריכה] שושלת האן: תקופה של שגשוג\n" + "\n" + " ערך מורחב – שושלת האן\n" + "\n" + "שושלת האן הופיעה בסין בשנת 202 לפנה\"ס. בתקופת שלטונה הפכה הקונפוציוניזם לדת המדינה ולפילוסופיה המנחה אותה ואשר המשיכה להנחות את המשטר הסיני עד לסוף התקופה הקיסרית בתחילת המאה ה-20. תחת שלטון ההאן עשתה התרבות הסינית התקדמות אדירה בתחומי ההיסטוריוגפיה, האומנות והמדע. הקיסר וו חיזק והרחיב את הממלכה בהודפו את ה\"שׂיוֹנג-נוּ\" (שבטים שלעתים מזוהים עם ההונים) אל תוך מונגוליה של ימינו, תוך שהוא מספח לממלכתו את השטחים בהם ישבו שבטים אלו. שטחים חדשים אלו אפשרו לסין לראשונה לפתוח קשר מסחר עם המערב: דרך המשי.\n" + "\n" + "אולם, השתלטותן של משפחות אצולה על אדמות המדינה, עירערה את בסיס המיסוי של הממלכה, גורמות בכך חוסר יציבות שלטוני. חוסר היציבות הזה נוצל על ידי וואנג מנג, שהקים את שושלת שין שהחזיקה מעמד זמן קצר מאוד. וואנג החל לבצע רפורמות ענפות בהחזקת האדמות ובכלכלה. תומכיה העיקריים של הרפורמה היו האיכרים ובני המעמדות הנמוכים, אך משפחות האצולה שהחזיקו באדמות, התנגדות להן בכל תוקף. עקב כך נוצא מצב של כאוס והתקוממויות רבות במדינה. צאצאה של שושלת האן, הקיסר גואנגוו, ייסד מחדש את שושלת האן בתמיכתם של משפחות האצילים והסוחרים בלוו-יאנג, מזרחית לשיאן, מכאן קיבל העידן החדש שהחל אז את שמו: שושלת האן המזרחית. אולם ייסודה מחדש של השושלת לא הביא את השקט הרצוי לממלכה. עימותים עם בעלי הקרקעות, יחד עם פלישות מבחוץ ומאבקים פנימיים במיעוטים החלישו שוב את השלטון. מרד הטורבן הצהוב שפרץ בשנת 184, סימן את תחילתו של עידן בו שליטים צבאיים מובילים מלחמות בתוך המדינה ומחלקים את המדינה למספר מדינות קטנות. תקופה זו ידועה כתקופת שלוש הממלכות.\n" + "\n" + "[עריכה] ג'ין, שש עשרה הממלכות והשושלות הדרומית והצפונית: התקופה האפלה של סין\n" + "\n" + " ערך מורחב – שושלת ג'ין\n" + "\n" + "שלוש הממלכות התאחדו בשנת 280 תחת שלטונה של שושלת ג'ין. אולם איחוד זה נמשך זמן קצר מאוד. בתחילת המאה ה-4 החלו המיעוטים בסין (כיום מכונים סינים לא בני האן ) להתמרד ולבתר את המדינה, גורמים בכך להגירה עצומה של סינים בני האן אל מדרום לנהר היאנגטסה. בשנת 303 החלו אנשי מיעוט הדאי במרד שבסופו הם כבשו את צ'נגדו שבסצ'ואן. השׂיוֹנְג-נוּ, שנהדפו מסין בתחילת שלטונה של שושלת האן, חזרו להלחם בסין, כבשו חלקים ממנה והוציאו להורג את שני קיסריה האחרונים של שושלת ג'ין. יותר משש-עשרה מדינות הוקמו על ידי המיעוטים האתניים בצפונה של סין. הצפון הכאוטי אוחד לזמן קצר על ידי פו ג'יאן, אך הוא הובס בנסיון פלישתו לדרום סין וממלכתו התפוררה. נסיון נוסף לאיחוד הצפון בוצע על ידי הקיסר טאיוון, שהקים את השושלות הצפוניות, סדרה של משטרים מקומיים ששלטו בסין שמצפון לנהר היאנג צה.\n" + "\n" + "עם הפליטים שנסו לדרומה של המדינה, היה גם הקיסר יואן, נצר לשושלת ג'ין, שחידש את שלטון השושלת בדרום המדינה . שושלת זו הייתה הראשונה מבין השושלות הדרומיות שכללו את שושלות סונג, צי, ליאנג וצ'ן. בירתן של השושלות הדרומיות הייתה ג'יאנקאנג, ליד ננג'ינג של ימינו. התקופה בה התקיימו במקביל שתי מדינות הנשלטות על ידי שושלות שונות בצפונה ובדרומה של הארץ נקראה תקופת השושלות הצפונית והדרומית. שושלת סוי קצרת המועד, הצליחה לאחד את המדינה ב589 לאחר כמעט 300 שנות פירוד.\n" + "\n" + "[עריכה] שושלת טאנג: חזרה לשיגשוג\n" + "\n" + " ערך מורחב – שושלת טאנג\n" + "\n" + "בשנת 618 נוסדה שושלת טאנג, פותחת עידן חדש של שיגשוג וחידושים בתחומי האמנות והטכנולוגיה. בתקופה זו פעלו משוררים נודעים כלי באי ודו פו. הבודהיזם, שהחל חודר לסין כבר במאה ה-1, הוכרז כדת הרשמית של המדינה ואומץ על ידי המשפחה הקיסרית. צ'אנג-אן (שיאן של ימינו), בירת השושלת הייתה באותה תקופה העיר הגדולה ביותר בעולם. תקופות טאנג והאן נחשבות לרוב כתקופות השגשוג הממושכות ביותר בהיסטוריה של סין. אולם, על אף השגשוג, כוחה של שושלת טאנג החל להחלש והמדינה החלה נקרעת בשנית בידי שליטים מקומיים. תקופה נוספת של כאוס הגיעה למדינה: תקופת חמש השושלות ועשר הממלכות.\n" + "\n" + "[עריכה] שושלת סונג ושכנותיה הצפוניות, ליאו וג'ין\n" + "\n" + " ערך מורחב – שושלת סונג\n" + "\n" + "בשנת 960 הצליחה שושלת סונג לאסוף מספיק כח כדי לאחד את סין תחת שלטונה. תחת שלטון סונג, שבירתו הייתה קאיפנג, החלה תקופת צמיחה חדשה בסין. אולם שושלת סונג לא הייתה הכח הפוליטי הגדול היחיד באזור. במנצ'וריה ובמזרח מונגוליה התהוותה ממלכתה של שושלת ליאו החיטאנית וב1115 עלתה לשלטון במנצ'וריה שושלת ג'ין הג'ורצ'נית (הג'ורצ'נים היו אבותיהם של המנצ'ורים) שתוך 10 שנים בלעה את שושלת ליאו לתוכה. שושלת ג'ין השתלטה גם על שטחים בצפון סין, בתוכם הבירה הסינית קאיפנג, מה שאילץ את שושלת סונג הסינית להעביר את בירתה לחאנגג'ואו. שושלת סונג גם אולצה על ידי שושלת ג'ין להכריז על הכרתה בשושלת ג'ין כשליטה העליונה שלה. בתקופה שלאחר מכן הוקמו שלוש ממלכות גדולות בשטחה של סין (ממלכת סונג, ממלכת ג'ין וממלכה שלישית של מיעוטים שנקראה ממלכת שיה המערבית). בתקופה זו נעשו פיתוחים משמעותיים בטכנולוגיה, ככל הנראה עקב הלחץ הצבאי שהופעל על ממלכת סונג מצד שכנותיה הצפוניות.\n" + "\n" + "[עריכה] המונגולים\n" + "\n" + "ממלכת ג'ין הייתה הראשונה מבין הממלכות בסין שהובסה על ידי המונגולים, שהמשיכו וכבשו גם את ממלכת סונג במלחמה ארוכה ועקובה מדם שהייתה המלחמה הראשונה בהיסטוריה בה נעשה שימוש מכריע בנשק חם. לאחר תום המלחמה החל עידן של שלום כמעט בכל אסיה (שהייתה נתונה לשלטון המונגולים), עידן שנקרא \"השלום המונגולי\" (Pax Mongolica). שלום זה איפשר לנוסעים מהמערב, דוגמת מרקו פולו, להגיע לסין ולחשוף לראשונה את אוצרתיה למערב. בסין, נחלקו המונגולים בין אלו שרצו להחיל בסין את מנהגי המונגולים ובין אלו שרצו לאמץ את המנהגים הסינים לעצמם. קובלאי חאן, שנמנה עם הקבוצה השנייה, הקים בסין את שושלת יואן (מילולית: \"השושלת הראשונה\") זו הייתה הממלכה הראשונה שהשתרעה על כל שטחה של סין ושבירתה הייתה בייג'ינג (בייג'ינג הייתה בירתה של שושלת גי'ן אך השושלת לא שלטה על סין כולה).\n" + "\n" + "[עריכה] תחייתה מחדש של התרבות הסינית\n" + "\n" + "בקרב העם בסין, הייתה התמרמרות רבה ביחס לשלטון ה\"זרים\" החדש, התמרמרות שלבסוף הובילה להתקוממויות איכרים במדינה שהתפתחו למאבק בשלטון שנדחף למעשה אל מחוץ לגבולותיה של סין. את השלטון המונגולי החליף שלטונה של שושלת מינג בשנת 1368. שושלת זו פתחה תקופה של פריחה והתחדשות תרבותית: האומנות, ובעיקר תעשיית הפורצלן, נסקה לגבהים שלא נודעו קודם לכן, סחורות סיניות נעו ברחבי האוקיינוס ההודי, מגיעות עד לחופיה המזרחיים של אפריקה במסעותיו של צ'נג חה. סין בנתה צי ספינות שהגדולות מבניהן שינעו 1,500 טונות של סחורות וחיילים מהצבא בן מיליון החיילים שהיה ברשותה באותה העת. יותר מ100,000 טונות ברזל יוצרו כל שנה וספרים רבים נדפסו. יש הטוענים כי שהאומה הסינית בתקופת מינג הייתה האומה המתקדמת ביותר בעולם.\n" + "\n" + "הקיסר חונג-וו, מייסד השושלת, הניח את היסודות לנטייתה של המדינה למעט במסחר ותעשייה ולהתמקד בעיקר בהגדלת הרווחים מהמגזר החקלאי, כנראה בשל מוצאו החקלאי של הקיסר. חברות פאודליות זעירות שהתפתחו במהלך שנות שלטונם של שושלת סונג ושל המונגולים פורקו ואדמותיהם הולאמו, חולקו והושכרו לאיכרים מחדש. כמו כן, הוטל חוק האוסר החזקת עבדים במדינה. החוקים נגד מסחר נשארו בממלכה עוד מתקופת שושלת סונג, אך כעת הם חלו גם על סוחרים זרים מה שהביא במהרה לגוויעת סחר החוץ בין סין לשאר העולם.\n" + "\n" + "ככל שחלף הזמן, שלטון הקיסר נעשה חזק יותר ויותר על אף שהחצר הקיסרית עשתה שימוש נרחב בפקידים ממשלתיים שהיו אחראיים לתפקודה השוטף של המדינה.\n" + "\n" + "במהלך שלטון המונגולים פחתה האוכלוסייה בכ-40% לכ-60 מיליון נפש. שתי מאות מאוחר יותר המספר הוכפל. הערים החלו להתפתח בקצב מואץ ובעקבות כך החלה להופיע גם תעשייה זעירה. כתוצאה מהתערבות שלטונית, נמנעה בסין התפתחותו של מרכז אורבני מצומצם ובמקום זאת צמחו מספר רב של ערים שהיוו מרכזים מקומיים לאזורים המקיפים אותן.\n" + "\n" + "[עריכה] תקופת מינג: מהתפתחות לבידוד\n" + "\n" + " ערך מורחב – שושלת מינג\n" + "\n" + "למרות הסלידה ממסחר עם מדינות אחרות, וההתרכזות הפנימית בענייני המדינה, סין תחת שלטונה של שושלת מינג לא הייתה מבודדת. הסחר עם מדינות אחרות, ובעיקר עם יפן, המשיך להתקיים והקיסר יונגלה השתדל ככל יכולתו למסד קשרים דיפלומטיים עם המדינות הסובבות את סין. צבאה של סין כבש את אנאם והצי הימי שלה הפליג במסעותיו עד לחופי אפריקה. הסינים גם הצליחו לייצר השפעה מסוימת בטורקסטן.\n" + "\n" + "אחת הדרכים המרשימות ביותר בהן התבטאה מדיניות החוץ הסינית של אותה תקופה הייתה מסעותיו הימיים של צ'אנג חֶה, סריס מוסלמי ונצר למשפחה מונגולית, אשר הוביל שבעה מסעות ימיים מפוארים בין 1405 ל1433 שעברו בכל האוקיינוס ההודי והאיים שבו והגיעו עד לכף התקווה הטובה. מסעו הראשון של הה, כלל 62 ספינות שנשאו 28,000 מלחים – ללא ספק המסע הימי הגדול ביותר בהיסטוריה האנושית.\n" + "\n" + "אולם, לקראת סופה של המאה ה-15, הוטל איסור על אזרחי המדינה לבנות ספינות בעלות כושר הפלגה באוקיינוס וכן נאסר על כלל האזרחים לעזוב את המדינה. כיום קיימת הסכמה על כך שצעד זה ננקט כדי להגן על הקיסרות מפני התקפות של שודדי ים. הגבלות אלו בוטלו לבסוף באמצע המאה ה-17.\n" + "\n" + "[עריכה] שושלת צ'ינג\n" + "\n" + " ערך מורחב – שושלת צ'ינג\n" + "\n" + "השושלת הקיסרית האחרונה בסין, נוסדה ב1644 כאשר המנצ'ורים כבשו את המדינה, הדיחו מהשלטון את שושלת מינג המקומית והקימו את שושלת צ'ינג שבירתה בייג'ינג. במשך חצי מאה נלחמו המנצ'ורים מלחמות עקובות מדם שבמהלכן השתלטו על האזורים שהיו בשליטת שושלת מינג ובכללם מחוז יונאן המרוחקת, טיבט ומונגוליה. את ההצלחה לה זכו המנצ'ורים בתחילת תקופת שלטונם יש לזקוף לזכות כוחם הצבאי האדיר והמיומן ששולב עם מיומנויות בירוקרטיות סיניות.\n" + "\n" + "חלק מההיסטוריונים רואים בתקופה של תחילת שלטון צ'ינג המשך רציף להתדרדרות התרבותית שחלה בסוף תקופת מינג. אך יש כאלה הרואים בתחילת שלטון צ'ינג תקופה של שיגשוג יותר מאשר נסיגה. בהוראת הקיסר קנגשי נכתב המילון המקיף והמפורט ביותר לשפה הסינית שנכתב עד אז ותחת שלטונו של הקיסר קיאנלונג חובר הקטלוג המלא של כל העבודות החשובות של התרבות הסינית. שושלת צ'ינג גם המשיכה בהרחבת אוצר הספרות העממית ובפיתוח החקלאות תוך יבוא גידולים חדשים מהעולם החדש דוגמת התירס. גם צמיחת האוכלוסייה המשיכה להאיץ בתקופת צ'ינג ואוכלוסיית המדינה, שבשנת 1700 מנתה 100 מיליון נפש, הגיעה לכדי 220 מליון בשנת 1800.\n" + "\n" + "\n" + "בקריקטורה צרפתית מפורסמת זו, נראית חלוקתה של סין בין בריטניה, גרמניה, רוסיה, צרפת ויפן\n" + "בקריקטורה צרפתית מפורסמת זו, נראית חלוקתה של סין בין בריטניה, גרמניה, רוסיה, צרפת ויפן\n" + "\n" + "במהלך המאה ה-19, נחלשה שליטתה של שושלת צ'ינג במדינה והשגשוג שהיה בה התפוגג. סין סבלה מרעב קשה, התפוצצות אוכלוסין וחדירה בלתי פוסקת של מדינות המערב בנסיון להשיג לעצמן השפעה במדינה. שאיפתה של בריטניה להמשיך בסחר הבלתי חוקי באופיום, נתקל בהתנגדות עזה של המשטר הקיסרי, מה שהביא לפריצתה של מלחמת האופיום הראשונה ב1840. סין, שהפסידה במלחמה, אולצה לבצע ויתורים כואבים ולפתוח את נמליה לסחר חפשי עם מדינות המערב. ויתוריה הטריטוריאלים של סין כללו את העברת הונג קונג לידיה של בריטניה ב1842 כחלק מחוזה נאנג'ינג. בנוסף מרד טאי פינג (1864-1851) ומרד ניאן (1868-1853), יחד עם תנועות לאומיות מוסלמיות ששאפו לעצמאות וחוזקו על ידי רוסיה ייבשו את קופת המדינה וכמעט שהביאו לנפילת השלטון בה.\n" + "\n" + "המרידות בשלטון דוכאו בעיקר על ידי כוחות המערב שבאותו הזמן עשו במדינה כבשלהם וניצלו את שווקיה ואת מערכתה הכלכלית.\n" + "\n" + "לאחר שוך המהומות בשנות השישים של המאה ה-19, החלה שושלת צ'ינג לטפל בבעיות המודרניזציה במדינה על ידי ביצוע רפורמות בכל תחומי שליטתה. אבל, הקיסרית האלמנה צישי, יחד עם גורמים שמרניים במדינה, ביצעה מעין הפיכה והדיחה את הקיסר הצעיר מהשלטון, מורידה בכך לטמיון את הרפורמות שאך החלו להתבצע. הרפורמות הצבאיות, שהושארו על כנן, היו חסרות ערך עקב השחיתות האיומה שהתפשטה בצמרת השלטון. חלק מספינות הקרב החדישות של הצבא כלל לא יכלו לבצע ירי, וזאת עקב מעילות גדולות בתקציבי בנייתן שלא השאירו די כסף לרכישת אבק שריפה. כתוצאה מכך כוחות \"הצבא הסיני החדש\" נחלו תבוסות משפילות הן במלחמת סין-צרפת (1885-1883) והן במלחמת סין-יפן הראשונה (1895-1894)\n" + "\n" + "עם תחילתה של המאה ה-20, הייתה החצר הקיסרית בסין הרוסה, שחיתות הייתה בכל והאוכלוסייה גדלה בקצב בלתי ניתן לעצירה. המדינה נשלטה על ידי הקיסרית צישי, דמות שמרנית ביותר שהתנגדה לכל סוג של רפורמה. מותו של הקיסר גוואנגשו יום אחד לפני מותה של הקיסרית (יש הטוענים שהוא הורעל על ידה) הרס את הסיכוי האחרון לביסוס הנהגה אפקטיבית במדינה.\n" + "\n" + "[עריכה] הרפובליקה הסינית\n" + "\n" + " ערך מורחב – היסטוריה של הרפובליקה הסינית\n" + "\n" + "ביאושם מאוזלת ידו של השלטון, החלו פקידי ממשל צעירים, קציני צבא וסטודנטים, שהושפעו מרעיונותיו המהפכניים של סון יאט-סן להתארגן לקראת הפיכה במדינה שתסלק את שושלת צ'ינג מהשלטון ותהפוך את המדינה לרפובליקה. התקוממות ווצ'אנג, התקוממות מהפכנית צבאית, החלה ב10 באוקטובר 1911. כחצי שנה מאוחר יותר, ב12 בפברואר 1912 הוקמה הממשלה הזמנית של הרפובליקה הסינית בנאנג'ינג כשבראשה עומד סון יאט-סן כנשיאה הזמני. אך סון נאלץ לוותר על תפקידו לטובת יואן שיקאי אשר פיקד באותו הזמן על \"הצבא החדש\" והיה ראש הממשלה תחת שלטון צ'ינג, כחלק מהסכם שנחתם להדחת הקיסר האחרון – הילד הנרי פו-יי. בשנים שלאחר הכתרתו כנשיא, ניסה יואן שיקאי לעקוף את סמכויותיהן של הוועדות הפרובינציאליות של הרפובליקה ואף הכריז על עצמו קיסר ב1915. שאיפותיו הקיסריות של יואן נתקלו בהתנגדות עזה של המהפכנים שראו כיצד מהפכתם הולכת לכינונה מחדש של קיסרות במדינה ולא של רפובליקה, והם החלו מתמרדים נגד יואן עד למותו ב1916 שהשאיר ריק שלטוני בסין. סין שלאחר מותו של יואן נחלקה בין הממשל הרפובליקני החדש, ובין מצביאים מקומיים ששלטו באזוריהם עוד מתקופת צ'ינג.\n" + "\n" + "לאירוע חסר החשיבות (בעיני המעצמות מחוץ לסין) שהתרחש ב1919 הייתה השלכה מכריעה על המשך ההיסטוריה הסינית במאה ה-20, אירוע זה הוא תנועת הארבעה במאי. התנועה, שהוציאה שם רע לפילוסופיות המערביות המקובלות והאימוץ של קוי מחשבה קיצוניים יותר שבאו לאחר מכן זרעו את הזרעים לקונפליקט בלתי ניתן לגישור בין הימין והשמאל בסין, קונפליקט שהמשיך עד לסופה של המאה.\n" + "\n" + "ב1920, הקים סון יאט-סן בסיס לתנועתו המהפכנית בדרום סין, אשר ממנו הוא יצא לאיחוד האומה השסועה. בעזרתם של הסובייטים, הוא הקים ברית עם המפלגה הקומוניסטית הסינית, ברית שלחמה בשאריות המשטר הקיסרי שהיו מפוזרות בצפון המדינה. לאחר מותו של סון ב1925 השתלט יורשו צ'יאנג קאי שק על המפלגה הלאומנית (הקוומינטנג) והצליח לאחד תחת שלטונו את מרבית דרום המדינה ומרכזה במערכה צבאית שנקראה המשלחת הצפונית. לאחר שהצליח להביס גם את תומכי הקיסר בצפון, פנה צ'יאנג למלחמה באנשי המפלגה הקומוניסטית, שעד לאותה תקופה נלחמו יחד איתו. הקומוניסטים פרשו מהקוומינטנג ב1927 וברחו להרים שבדרום סין. ב1934 יצאו הקומוניסטים מההרים שבשליטתם (שם הקימו את הרפובליקה הסינית-סובייטית) למצעד הארוך, מסע צבאי מפרך באזורים הטרשיים ביותר במדינה אל עבר צפון מערבה של המדינה לפרובינציית שאאנסי שם הקימו לעצמם בסיסי לוחמת גרילה.\n" + "\n" + "במהלך המצעד הארוך, הכירו הקומוניסטים במנהיגם החדש מאו צה דונג. המאבק בין הקוומינטנג והמפלגה הקומוניסטית הסינית נמשך לעתים בגלוי ולעתים בחשאי תוך כדי מלחמת סין-יפן השנייה (1945-1931) על אף שהכוחות יצרו לכאורה חזית מאוחדת כנגד פלישת היפנים ב1937 כחלק ממלחמת העולם השנייה. הלחימה בין שתי המפלגות המשיכה לאחר תבוסתם של היפנים ב-1945, וב-1949 שלטו הקומוניסטים ברוב שטחה של המדינה.\n" + "\n" + "[עריכה] הרפובליקה העממית של סין\n" + "\n" + " ערך מורחב – היסטוריה של הרפובליקה העממית של סין\n" + "\n" + "פרק זה לוקה בחסר. אתם מוזמנים לתרום לוויקיפדיה ולהשלים אותו. ראו פירוט בדף השיחה.\n" + "\n" + "צ'יאנג קאי שק נמלט עם שאריות ממשלתו וצבאו לטיוואן שם הוא הכריז על טייפה כבירה הזמנית של הרפובליקה עד להשלמת הכיבוש מחדש של סין היבשתית על ידי כוחותיו. הרפובליקה הסינית ממשיכה להתקיים עד ימינו (סוף 2004) בטיוואן אך היא טרם הכריזה עצמאות והיא אינה מוכרת רשמית כמדינה על ידי שאר העולם.\n" + "\n" + "עם ההכרזה על הקמתה של הרפובליקה העממית של סין ב1 באוקטובר 1949, חולקה סין שוב לרפובליקה העממית של סין בסין היבשתית ולרפובליקה הסינית שישבה בטיוואן ובמספר איים קטנים בסביבה, כאשר לכל רפובליקה יש ממשלה הרואה בעצמה את הממשלה הסינית האמיתית והמתייחסת אל הממשלה האחרת בבוז ובביטול. מצב זה נמשך עד לשנות התשעים של המאה ה-20, כאשר שינויים פוליטים ברפובליקה הסינית הביאו אותה להפסקת הטענה הפומבית להיותה ממשלת סין היחידה.\n" + "\n" + "[עריכה] ראו גם\n" + "\n" + " * לוח זמנים של ההיסטוריה של סין – טבלה המתארת את האירועים והאישים החשובים בתולדותיה של סין.\n" + "\n" + "[עריכה] לקריאה נוספת\n" + "\n" + " * עמנואל צ' י' שו, צמיחתה של סין המודרנית, הוצאת שוקן, 2005.\n" + "\n" + "[עריכה] קישורים חיצוניים\n" + "\n" + " * ירדן ניר-בוכבינדר, סין אימנו, קונפוציוס אבינו, באתר \"האייל הקורא\"\n" + "\n" + "\n" + "[עריכה] הערות שוליים\n" + "\n" + " 1. ^ סין של תקופת הברונזה בגלריה הלאומית לאמנות של ארצות-הברית\n" + " 2. ^ כתב על חרסים מאתר ארליטואו (כתוב בסינית מפושטת)\n"; var japanese = "中国の歴史\n" + "出典: フリー百科事典『ウィキペディア(Wikipedia)』\n" + "移動: ナビゲーション, 検索\n" + "中国歴史\n" + "中国の歴史\n" + "元謀・藍田・北京原人\n" + "神話伝説(三皇五帝)\n" + "黄河・長江文明\n" + "夏\n" + "殷\n" + "周 西周\n" + "東周 春秋\n" + "戦国\n" + "秦\n" + "漢 前漢\n" + "新\n" + "後漢\n" + "三国 魏 呉 蜀\n" + "晋 西晋\n" + "東晋 十六国\n" + "南北朝 宋 北魏\n" + "斉\n" + "梁 西魏 東魏\n" + "陳 北周 北斉\n" + "隋\n" + "唐\n" + "五代十国\n" + "宋 北宋 遼 西夏\n" + "南宋 金\n" + "元\n" + "明 北元\n" + "後金 南明 大順\n" + "清\n" + "中華民国\n" + "中華人民共和国 (参考:\n" + "台湾問題)\n" + "\n" + "中国の歴史(ちゅうごくのれきし)、或いは中国史(ちゅうごくし)\n" + "\n" + "中国の黄河文明は古代の四大文明の一つに数えられ、また黄河文明よりも更に遡る長江文明が存在した。\n" + "目次\n" + "[非表示]\n" + "\n" + " * 1 王朝、政権の変遷\n" + " * 2 概略\n" + " o 2.1 先史人類史\n" + " o 2.2 文明の萌芽\n" + " + 2.2.1 黄河文明\n" + " + 2.2.2 長江文明\n" + " + 2.2.3 その他\n" + " o 2.3 先秦時代\n" + " + 2.3.1 三代\n" + " + 2.3.2 春秋戦国\n" + " o 2.4 秦漢帝国\n" + " o 2.5 魏晋南北朝時代\n" + " o 2.6 隋唐帝国\n" + " o 2.7 五代十国・宋\n" + " o 2.8 モンゴル帝国\n" + " o 2.9 明清帝国\n" + " o 2.10 中国の半植民地化\n" + " o 2.11 中華民国\n" + " + 2.11.1 革命後の中国の政局\n" + " + 2.11.2 袁世凱の台頭と帝制運動(1913年~1916年)\n" + " + 2.11.3 袁世凱死後の政局(1916年~1920年)\n" + " + 2.11.4 国民革命(1920年~1928年)\n" + " + 2.11.5 国民政府(1928年~1931年)\n" + " + 2.11.6 抗日戦争(1931年~1937年)\n" + " + 2.11.7 日中戦争(1937年~1945年)\n" + " + 2.11.8 漢民族以外の民族の動向\n" + " # 2.11.8.1 モンゴルとチベットでの動き\n" + " # 2.11.8.2 東トルキスタン(新疆)での動き\n" + " o 2.12 中華人民共和国\n" + " + 2.12.1 社会主義国化と粛清(1949年~1957年)\n" + " + 2.12.2 中国共産党の対ソ自立化(1958年~1965年)\n" + " + 2.12.3 文化大革命前期(1966年~1969年)\n" + " + 2.12.4 文化大革命後期(1969~1976年)\n" + " + 2.12.5 改革開放以後の現在(1976年~)\n" + " # 2.12.5.1 一党独裁\n" + " # 2.12.5.2 少数民族問題\n" + " * 3 人口の変遷\n" + " * 4 地方行政制度\n" + " o 4.1 封建制度(前1600年頃~前221年)\n" + " o 4.2 郡県制度(前221年~249年)\n" + " o 4.3 軍府による広域行政(249年~583年)\n" + " o 4.4 州県制(583年~1276年)\n" + " * 5 祭祀制度\n" + " * 6 外交\n" + " o 6.1 漢帝国\n" + " o 6.2 魏晋南北朝時代\n" + " o 6.3 隋唐帝国\n" + " * 7 関連項目\n" + " * 8 脚注\n" + "\n" + "[編集] 王朝、政権の変遷\n" + "現在の中国、すなわち中華人民共和国の領域\n" + "現在の中国、すなわち中華人民共和国の領域\n" + "\n" + " * 長江文明\n" + " * 黄河文明\n" + " * 夏(紀元前2070年頃 - 紀元前1600年頃\n" + " * 殷(紀元前1600年頃 - 紀元前12世紀・紀元前11世紀ごろ)\n" + "\n" + " * 周(紀元前12世紀・紀元前11世紀ごろ - 紀元前256年)…殷を倒し、西周建国。克殷の年代については諸説あり、はっきりしない。\n" + " o 春秋時代(紀元前770年 - 紀元前403年)…紀元前453年晋が韓魏趙に分割された時点、または紀元前403年韓魏趙が諸侯に列した時点をもって春秋時代の終わり、戦国時代の始まりとする。\n" + " o 戦国時代(紀元前403年 - 紀元前221年)…晋が韓・趙・魏に分裂し、戦国時代突入。\n" + " * 秦(紀元前221年 - 紀元前207年)…秦王・政が6国を滅ぼし中華統一。\n" + " * 漢\n" + " o 前漢(紀元前206年 - 8年)…秦滅亡後、楚の項羽との楚漢戦争に勝ち、劉邦が建国。\n" + " o 新(8年 - 23年)…外戚の王莽が前漢皇帝から帝位を簒奪し建国。\n" + " o 後漢(25年 - 220年)…前漢の景帝の子孫の劉秀(光武帝)が王莽軍を破り、漢を再興。\n" + " * 三国時代(220年 - 280年)\n" + " o 魏、蜀(蜀漢・漢)、呉…曹操の子曹丕が献帝から禅譲を受け即位すると、蜀の劉備も漢皇帝を名乗り即位、さらに呉の孫権も大帝として即位し、三国時代に入る。\n" + " * 晋(265年 - 420年)\n" + " o 西晋(265年 - 316年)…晋王司馬炎が魏の元帝より禅譲を受け即位し建国。だが、異民族五胡の侵入により衰退。異民族の漢に滅ぼされた。\n" + " o 東晋(317年 - 420年)…皇族でただ一人生き残った琅邪王・司馬睿は江南に逃れ、建康で即位(元帝)。これを中原の晋と区別して東晋という。\n" + " o 五胡十六国時代(304年 - 439年)\n" + " * 南北朝時代(439年 - 589年)\n" + " o 北魏、東魏、西魏、北斉、北周\n" + " o 宋、斉、梁、陳\n" + " * 隋(581年 - 619年)\n" + " * 唐(618年 - 907年)\n" + " o 武周\n" + " * 五代十国時代\n" + " o 後梁、後唐、後晋、後漢、後周……五代(中原を中心とする国)\n" + " o 呉、南唐・閩・呉越・荊南・楚・南漢・前蜀・後蜀・北漢……十国(中華東西南北に拠る勢力)\n" + " * 宋\n" + " o 北宋(960年 - 1127年)\n" + " o 南宋(1127年 - 1279年)\n" + " o 遼、西夏、金\n" + " * 元(1271年 - 1368年)\n" + " * 明(1368年 - 1644年)\n" + " o 南明\n" + " * 清(1616年 - 1912年)(1616年 - 1636年は後金、それ以前はマンジュ国)\n" + " o 太平天国、満州国\n" + " * 中華民国(台湾)(1912年 - 現在)\n" + " * 中華人民共和国(1949年 - 現在)\n" + "\n" + "[編集] 概略\n" + "\n" + "[編集] 先史人類史\n" + "\n" + "中国に現れた最初期の人類としては、元謀原人や藍田原人、そして北京原人が知られている。\n" + "\n" + "[編集] 文明の萌芽\n" + "\n" + "中国大陸では、古くから文明が発達した。中国文明と呼ばれるものは、大きく分けて黄河文明と長江文明の2つがある。黄河文明は、畑作が中心、長江文明は稲作が中心であった。黄河文明が、歴史時代の殷(商)や周などにつながっていき、中国大陸の歴史の中軸となった。長江文明は次第に、中央集権国家を創出した黄河文明に同化吸収されていった。\n" + "\n" + "[編集] 黄河文明\n" + "龍山文化時代の高杯。1976年山東省出土\n" + "龍山文化時代の高杯。1976年山東省出土\n" + "\n" + "黄河文明は、その後の中国の歴史の主軸となる。\n" + "\n" + " * 裴李崗文化…紀元前7000?~紀元前5000?。一般的な「新石器時代」のはじまり。定住し、農業も行われていた。河南省(黄河中流)。土器は赤褐色\n" + " * 老官台文化…紀元前6000?~紀元前5000?。土器作りや粟作りが行われていた。陝西省(黄河上流)。土器は赤色。\n" + " * 北辛文化…紀元前6000?~紀元前5000?。土器は黄褐色。山東省(黄河下流)\n" + " * 磁山文化…紀元前6000?~紀元前5000?。土器は赤褐色。河北省(黄河下流)\n" + " * 仰韶文化…紀元前4800?~紀元前2500?。前期黄河文明における最大の文化。陝西省から河南省にかけて存在。このころは母系社会で、農村の階層化も始まった。文化後期になると、社会の階層化、分業化が進み、マルクス経済学でいうところの原始共産制は仰韶文化のころに終焉したと見られる。土器は赤色。\n" + " * 後岡文化…紀元前5000?~紀元前4000?。北辛文化が発展。河南省。\n" + " * 大汶口文化…紀元前4300?~紀元前2400?。土器は前期は赤色(彩陶)、後期は黒色(黒陶)。なお、この区分は黄河文明全体に見られる。山東省。\n" + " * 龍山文化…紀元前2500?~紀元前2000?。大汶口文化から発展。後期黄河文明最大の文化。土器は黒色。山東省。\n" + " * 二里頭文化…紀元前2000?~紀元前1600?。遺跡の中心部には二つの宮殿がある。河南省。\n" + "\n" + "[編集] 長江文明\n" + "母なる長江\n" + "母なる長江\n" + "\n" + "長江文明は黄河文明が萌芽する遥か前より栄えていた。夏王朝の始祖とされる禹が南方出身であるとされるため、この長江流域に夏王朝が存在したのではないかという説[1]がある。\n" + "\n" + " * 玉蟾岩遺跡…湖南省(長江中流)。紀元前14000年?~紀元前12000年?の稲モミが見つかっているが、栽培したものかは確定できない。\n" + " * 仙人洞・呂桶環遺跡…江西省(長江中流)。紀元前12000年ごろ?の栽培した稲が見つかっており、それまで他から伝播してきたと考えられていた中国の農耕が中国独自でかつ最も古いものの一つだと確かめられた。\n" + " * 彭頭山文化…湖南省(長江中流)。紀元前7000年?~紀元前5000年?。散播農法が行われており、中国における最古の水稲とされる。\n" + " * 大渓文化…四川省(長江上流)。紀元前4500年?~紀元前3300年?。彩文紅陶(紋様を付けた紅い土器)が特徴で、後期には黒陶・灰陶が登場。灌漑農法が確立され、住居地が水の補給のための水辺から大規模に農耕を行う事の出来る平野部へ移動した。\n" + " * 屈家嶺文化…湖北省。紀元前3000年?~紀元前2500年?大渓文化を引き継いで、ろくろを使用した黒陶が特徴。河南地方の黄河文明にも影響を与えたと考えられる。\n" + " * 石家河文化…屈家嶺文化から発展し、湖北省天門県石家河に大規模な都城を作った紀元前2500年頃を境として屈家嶺と区別する。この都城は南北1.3Km、東西1.1Kmという大きさで、上述の黄河流域の部族と抗争したのはこの頃と考えられる。\n" + " * 河姆渡文化 …紀元前5000年?~紀元前4000年?下流域では最古の稲作。狩猟や漁労も合わせて行われ、ブタの家畜化なども行われた。\n" + " * 良渚文化… 浙江省(銭塘江流域)。紀元前5260年?~紀元前4200年?(以前は文化形態から大汶口文化中期ごろにはじまったとされていたが、1977年出土木材の年輪分析で改められた)青銅器以前の文明。多数の玉器の他に、絹が出土している。分業や階層化も行われたと見られ、殉死者を伴う墓が発見されている。黄河文明の山東竜山文化とは相互に関係があったと見られ、同時期に衰退したことは何らかの共通の原因があると見られている。\n" + " * 三星堆遺跡… 紀元前2600年?~紀元前850年?。大量の青銅器が出土し、前述の他に目が飛び出た仮面・縦目の仮面・黄金の杖などがあり、また子安貝や象牙なども集められており、権力の階層があったことがうかがい知れる。青銅器については原始的な部分が無いままに高度な青銅器を作っているため他の地域、おそらくは黄河流域からの技術の流入と考えられる。長江文明と同じく文字は発見されていないが、「巴蜀文字」と呼ばれる文字らしきものがあり、一部にこれをインダス文字と結びつける説もある。\n" + "\n" + "[編集] その他\n" + "\n" + " * 新楽遺跡…遼寧省(遼河流域)。紀元前5200年?ごろの定住集落。母系社会が定着し、農業も行われていた。\n" + "\n" + "[編集] 先秦時代\n" + "\n" + "[編集] 三代\n" + "\n" + "史記では伝説と目される三皇五帝時代に続いて夏[2]王朝について記述されている。夏については実在が確かでなくまた定説もない。\n" + "\n" + "殷[3](商)が実在の確認されている最古の王朝である。殷では、王が占いによって政治を行っていた(神権政治)。殷は以前は山東で興ったとされたが、近年は河北付近に興ったとする見方が有力で、黄河文明で生まれた村のうち強大になり発展した都市国家の盟主であった[4]と考えられる。\n" + "\n" + "紀元前11世紀頃に殷を滅ぼした周は、各地の有力者や王族を諸侯として封建制をおこなった。しかし、周王朝は徐々に弱体化し、異民族に攻められ、紀元前770年には成周へ遷都した。その後、史記周本紀によれば犬戎の侵入により西周が滅び、洛陽に東周が再興されたされるが、同じく平勢隆郎の検討によれば幽王が殺害されたあと短期間携王が西、平王が東に並立し、紀元前759年平王が携王を滅ぼしたと考えられる。平王のもとで周は洛陽にあり、西周の故地には秦が入る。これ以降を春秋時代と呼ぶ。春秋時代には、周王朝の権威はまだ残っていたが、紀元前403年から始まるとされる戦国時代には、周王朝の権威は無視されるようになる。\n" + "\n" + "[編集] 春秋戦国\n" + "諸子百家の一、孔子\n" + "諸子百家の一、孔子\n" + "\n" + "春秋戦国時代は、諸侯が争う戦乱の時代であった。\n" + "\n" + "春秋時代は都市国家の盟主どうしの戦いだった。しかし春秋末期最強の都市国家晋が三分割されたころから様子が変わる。その当時の晋の有力な家臣六家が相争い、最初力が抜きん出ていた智氏が弱小な趙氏を攻めたものの、趙氏がよく農村を経済的ではなく封建的に支配し、それによって集めた食糧が多かったために城を守りきり、疲弊した智氏を魏氏、韓氏が攻め滅ぼしたために最終的に趙、魏、韓の三国が出来た。このこともあってそれまで人口多くてもせいぜい5万人程度だった都市国家が富国強兵に努め、商工業が発達し、貨幣も使用し始めやがて領土国家に変貌しその国都となった旧都市国家は30万人規模の都市に変貌する。また鉄器が普及したこともあいまって、農業生産も増大した。晋の分裂以後を一般に戦国時代という。\n" + "\n" + "また、このような戦乱の世をどのように過ごすべきかという思想がさまざまな人たちによって作られた。このような思想を説いた人たちを諸子百家(陰陽家、儒家、墨家、法家、名家、道家、兵家等が代表的)という。\n" + "\n" + "[編集] 秦漢帝国\n" + "始皇帝\n" + "\n" + "現在の陝西省あたりにあった秦は、戦国時代に着々と勢力を伸ばした。勢力を伸ばした背景には、厳格な法律で人々を統治しようとする法家の思想を採用して、富国強兵に努めたことにあった。秦王政は、他の6つの列強を次々と滅ぼし、紀元前221年には史上はじめての中国統一を成し遂げた。秦王政は、自らの偉業をたたえ、王を超える称号として皇帝を用い、自ら始皇帝と名乗った。\n" + "兵馬俑\n" + "\n" + "始皇帝は、法家の李斯を登用し、中央集権化を推し進めた。このとき、中央から派遣した役人が全国の各地方を支配する郡県制が施行された。また、文字・貨幣・度量衡の統一も行われた。さらに、当時モンゴル高原に勢力をもっていた遊牧民族の匈奴を防ぐために万里の長城を建設させた。さらに、軍隊を派遣して、匈奴の南下を抑えた。また、嶺南地方(現在の広東省)にも軍を派遣し、この地にいた百越諸族を制圧した。しかし、このような中央集権化や土木事業・軍事作戦は人々に多大な負担を与えた。そのため、紀元前210年に始皇帝が死ぬと、翌年には陳勝・呉広の乱という農民反乱がおきた。これに刺激され各地で反乱がおき、ついに秦は紀元前206年に滅びた。\n" + "漢の偉大な発明、紙\n" + "漢の偉大な発明、紙\n" + "\n" + "秦が滅びたあと、劉邦と項羽が覇権をめぐって争った(楚漢戦争)が、紀元前202年には、劉邦が項羽を破り、漢の皇帝となった。劉邦は、始皇帝が急速な中央集権化を推し進めて失敗したことから、一部の地域には親戚や臣下を王として治めさせ、ほかの地域を中央が直接管理できるようにした。これを郡国制という。しかし、紀元前154年には、各地の王が中央に対して呉楚七国の乱と呼ばれる反乱を起こした。この反乱は鎮圧され、結果として、中央集権化が進んだ。紀元前141年に即位した武帝は、国内の安定もあり、対外発展を推し進めた。武帝は匈奴を撃退し、シルクロードを通じた西方との貿易を直接行えるようにした。また、朝鮮半島北部、ベトナム北中部にも侵攻した。これらの地域はその後も強く中国文化の影響を受けることとなった。また、武帝は董仲舒の意見を聞いて、儒教を統治の基本とした。これ以降、中国の王朝は基本的に儒教を統治の基本としていく。一方で文帝の頃より貨幣経済が広汎に浸透しており、度重なる軍事行動と相まって、農民の生活を苦しめた。漢の宮廷では貨幣の浸透が農民に不利益であることがしばしば論じられており、農民の救済策が検討され、富商を中心に増税をおこなうなど大土地所有を抑制しようと努力した。また儒教の国教化に関連して儒教の教義論争がしばしば宮廷の重大問題とされるようになった。\n" + "\n" + "8年には、王莽が皇帝の位を奪って、一旦漢を滅ぼした。王莽は当初儒教主義的な徳治政治をおこなったが、相次ぐ貨幣の改鋳や頻繁な地名、官名の変更など理想主義的で恣意的な政策をおこなったため徐々に民心を失い、辺境異民族が頻繁に侵入し、赤眉の乱など漢の復興を求める反乱が起き、内乱状態に陥った。結局、漢の皇族の血を引く劉秀によって漢王朝が復興された。この劉秀が建てた漢を後漢という。王朝初期には雲南に進出し、また班超によって西域経営がおこなわれ、シルクロードをおさえた。初期の後漢王朝は豪族連合的な政権であったが、章帝の時代までは中央集権化につとめ安定した政治が行われた。しかし安帝時代以後外戚や宦官の権力の増大と官僚の党派対立に悩まされるようになった。\n" + "\n" + "[編集] 魏晋南北朝時代\n" + "三国決戦の地、赤壁\n" + "三国決戦の地、赤壁\n" + "\n" + "後漢末期の184年には、黄巾の乱と呼ばれる農民反乱がおきた。これ以降、隋が589年に中国を再統一するまで、一時期を除いて中国は分裂を続けた。この隋の再統一までの分裂の時代を魏晋南北朝時代という。また、この時期には日本や朝鮮など中国周辺の諸民族が独自の国家を形成し始めた時期でもある。\n" + "\n" + "さて、黄巾の乱が鎮圧されたあと、豪族が各地に独自政権を立てた。中でも有力であったのが、漢王朝の皇帝を擁していた曹操である。しかし、中国統一を目指していた曹操は、208年に赤壁の戦いで、江南の豪族孫権に敗れた。結局、曹操の死後、220年に曹操の子の曹丕が後漢の皇帝から皇帝の位を譲られ、魏を建国した。これに対して、221年には、現在の四川省に割拠していた劉備が皇帝となり、蜀を建国した。さらに、江南の孫権も229年に皇帝と称して、呉を建国した。この魏・呉・蜀の三国が並立した時代を三国時代という。\n" + "\n" + "三国の中で、もっとも有力であったのは魏であった。魏は後漢の半分以上の領土を継承したが、戦乱で荒廃した地域に積極的な屯田をおこない、支配地域の国力の回復につとめた。魏では官吏登用法として、九品官人法[5]がおこなわれた。\n" + "\n" + "三国は基本的に魏と呉・蜀同盟との争いを軸としてしばしば交戦したが、蜀がまず263年に魏に滅ぼされ、その魏も有力な臣下であった司馬炎に265年に皇帝の位を譲るという形で滅亡した。司馬炎は皇帝となって国号を晋と命名し、さらに280年に呉を滅ぼし、中国を統一した。しかし、300年から帝位をめぐって各地の皇族が戦争を起こした(八王の乱)。このとき、五胡と呼ばれる異民族を軍隊として用いたため、これらの五胡が非常に強い力を持つようになった。316年には、五胡の1つである匈奴が晋をいったん滅ぼした。これ以降、中国の北方は、五胡の建てた国々が支配し、南方は江南に避難した晋王朝(南に移ったあとの晋を東晋という)が支配した。この時期は、戦乱を憎み、宗教に頼る向きがあった。代表的な宗教が仏教と道教であり、この2つの宗教は時には激しく対立することがあった。\n" + "\n" + "さて、江南を中心とする中国の南方では、異民族を恐れて、中国の北方から人々が多く移住してきた。これらの人々によって、江南の開発が進んだ。それに伴い、貴族が大土地所有を行うということが一般的になり、貴族が国の政治を左右した。一部の貴族の権力は、しばしば皇帝権力よりも強かった。これらの貴族階層の者により散文、書画等の六朝文化と呼ばれる文化が発展した。東晋滅亡後、宋・斉・梁・陳という4つの王朝が江南地方を支配したが、貴族が強い力を握ることは変わらなかった。梁の武帝は仏教の保護に努めた。\n" + "\n" + "北方では、鮮卑族の王朝である北魏が台頭し、439年には、華北を統一した。471年に即位した孝文帝は漢化政策を推し進めた。また、土地を国家が民衆に割り振る均田制を始め、律令制の基礎付けをした。しかし、このような漢化政策に反対するものがいたこともあり、北魏は、西魏と東魏に分裂した。西魏は北周へと、東魏は北斉へと王朝が交代した。577年には北周が北斉を滅ぼしたが、581年に隋が北周にとって代わった。589年に隋は南方の陳を滅ぼし、中国を統一した。\n" + "\n" + "魏晋南北朝表も参照。\n" + "\n" + "[編集] 隋唐帝国\n" + "現在でも使用される世界最大の大運河\n" + "現在でも使用される世界最大の大運河\n" + "\n" + "中国を統一した隋の文帝は、均田制・租庸調制・府兵制などを進め、中央集権化を目指した。また同時に九品中正法を廃止し、試験によって実力を測る科挙を採用した。しかし、文帝の後を継いだ煬帝は、江南・華北を結ぶ大運河を建設したり、度重なる遠征を行ったために、民衆の負担が増大した。このため農民反乱が起き、618年に隋は滅亡した。\n" + "\n" + "隋に代わって、中国を支配したのが、唐である。唐は基本的に隋の支配システムを受け継いだ。626年に即位した太宗は、租庸調制を整備し、律令制を完成させた。唐の都の長安は、当時世界最大級の都市であり、各国の商人などが集まった。長安は、西方にはシルクロードによってイスラム帝国や東ローマ帝国などと結ばれ、ゾロアスター教・景教・マニ教をはじめとする各地の宗教が流入した。また、文化史上も唐時代の詩は最高のものとされる。\n" + "当時世界最大の都市だった長安のシンボルタワー・大雁塔\n" + "当時世界最大の都市だった長安のシンボルタワー・大雁塔\n" + "\n" + "太宗の死後着々と力を付けた太宗とその子の高宗の皇后武則天はついに690年皇帝に即位した。前にも後にも中国にはこれのほかに女帝はいない。\n" + "\n" + "712年に即位した玄宗は国内の安定を目指したが、すでに律令制は制度疲労を起こしていた。また、周辺諸民族の統治に失敗したため、辺境に強大な軍事力が置かれた。これを節度使という。節度使は、後に軍権以外にも、民政権・財政権をももつようになり、力を強めていく。763年には、節度使の安禄山たちが安史の乱と呼ばれる反乱を起こした。この反乱は郭子儀や僕固懐恩、ウイグル帝国の太子葉護らの活躍で何とか鎮圧されたが、反乱軍の投降者の勢力を無視できず、投降者を節度使に任じたことなどから各地で土地の私有(荘園)が進み、土地の国有を前提とする均田制が行えなくなっていった。結局、政府は土地の私有を認めざるを得なくなった。結果として、律令制度は崩壊した。875年から884年には黄巣の乱と呼ばれる農民反乱がおき、唐王朝の権威は失墜した。このような中、各地の節度使はますます権力を強めた。907年には、節度使の1人である朱全忠が唐を滅ぼした。\n" + "\n" + "[編集] 五代十国・宋\n" + "画像:Compass in a wooden frame.jpg\n" + "中国航海術の偉大な発明、羅針盤\n" + "\n" + "唐の滅亡後、各地で節度使があい争った。この時代を五代十国時代という。この戦乱を静めたのが、960年に皇帝となって宋を建国した趙匡胤である。ただし、完全に中国を宋が統一したのは趙匡胤の死後の976年である。\n" + "\n" + "趙匡胤は、節度使が強い権力をもっていたことで戦乱が起きていたことを考え、軍隊は文官が率いるという文治主義をとった。また、これらの文官は、科挙によって登用された。宋からは、科挙の最終試験は皇帝自らが行うものとされ、科挙で登用された官吏と皇帝の結びつきは深まった。また、多くの国家機関を皇帝直属のものとし、中央集権・皇帝権力強化を進めた。科挙を受験した人々は大体が、地主層であった。これらの地主層を士大夫と呼び、のちの清時代まで、この層が皇帝権力を支え、官吏を輩出し続けた。\n" + "杭州\n" + "杭州\n" + "\n" + "唐は、その強大な力によって、周辺諸民族を影響下においていたが、唐の衰退によってこれらの諸民族は自立し、独自文化を発達させた。また、宋は文治主義を採用していたたため、戦いに不慣れな文官が軍隊を統制したので、軍事力が弱く、周辺諸民族との戦いにも負け続けた。なかでも、契丹族の遼・タングート族の西夏・女真族の金は、中国本土にも侵入し、宋を圧迫した。これらの民族は、魏晋南北朝時代の五胡と違い、中国文化を唯一絶対なものとせず、独自文化を保持し続けた。このような王朝を征服王朝という。後代の元や清も征服王朝であり、以降、中国文化はこれらの周辺諸民族の影響を強く受けるようになった。\n" + "\n" + "1127年には、金の圧迫を受け、宋は、江南に移った。これ以前の宋を北宋、以降を南宋という。南宋時代には、江南の経済が急速に発展した。また、すでに唐代の終わりから、陸上の東西交易は衰退していたが、この時期には、ムスリム商人を中心とした海上の東西交易が発達した。当時の宋の特産品であった陶磁器から、この交易路は陶磁の道と呼ばれる。南宋の首都にして海上貿易の中心港だった杭州は経済都市として栄え、元時代に中国を訪れたマルコ・ポーロは杭州を「世界一繁栄し、世界一豊かな都市」と評している。\n" + "\n" + "文化的には、経済発展に伴って庶民文化が発達した。また、士大夫の中では新しい学問をもとめる動きが出て、儒教の一派として朱子学が生まれた。\n" + "\n" + "[編集] モンゴル帝国\n" + "\n" + "13世紀初頭にモンゴル高原で、チンギス・ハーンが、モンゴルの諸部族を統一し、ユーラシア大陸各地へと、征服運動を開始した。モンゴル人たちは、東ヨーロッパ、ロシア、小アジア、メソポタミア、ペルシャ、アフガニスタン、チベットに至る広大な領域を支配し、この帝国はモンゴル帝国と呼ばれる。中国もまた征服活動の例外ではなかった。当時、黄河が南流し、山東半島の南に流れていたため、漢民族は北方民族の攻勢を防げなかった。華北は満州系の女真族による金が、南部を南宋が支配していたが、金は1234年、南宋は1279年にモンゴルに滅ぼされた。\n" + "\n" + "モンゴル帝国は各地に王族や漢人有力者を分封した。モンゴル帝国の5代目の君主(ハーン)にクビライが即位すると、これに反発する者たちが、反乱を起こした。結局、モンゴル帝国西部に対する大ハーン直轄支配は消滅し、大ハーンの政権は中国に軸足を置くようになった。もっとも、西方が離反しても、帝国としての緩やかな連合は保たれ、ユーラシアには平和が訪れていた。1271年にクビライは元を国号として中国支配をすすめた。\n" + "宋代に発明された火薬は元寇の時使用され、日本の武士を驚かせた\n" + "宋代に発明された火薬は元寇の時使用され、日本の武士を驚かせた\n" + "\n" + "モンゴル帝国(元)は未だ征服していなかった南宋への牽制のためにも日本に対して通交を求めたが、日本側は断った。このため二度に渡り日本に侵攻したが、成功しなかった(元寇)。元は三度目の日本侵攻を計画したが、実現には至らなかった。\n" + "\n" + "中国南部を支配していた南宋を1279年に元が滅ぼしたのはすでに見たとおりである。\n" + "\n" + "元の中国支配は、伝統的な中国王朝とは大きく異なっていた。元は中国の伝統的な統治機構を採用せず、遊牧民の政治の仕組みを中国に移入したからである。元の支配階級の人々は、すでに西方の優れた文化に触れていたため、中国文化を無批判に取り入れることはなかった。それは政治においても同様だったのである。それに伴い、伝統的な統治機構を担ってきた、儒教的な教養を身に付けた士大夫層は冷遇され、政権から遠ざけられた。そのため、彼らは曲や小説などの娯楽性の強い文学作品の執筆に携わった。この時代の曲は元曲と呼ばれ、中国文学史上最高のものとされる。また、モンゴル帝国がユーラシア大陸を広く支配したために、この時期は東西交易が前代に増して盛んになった。\n" + "\n" + "元は、宮廷費用などを浪費しており、そのため塩の専売策や紙幣の濫発で収入を増やそうとした。しかし、これは経済を混乱させるだけであった。そして、庶民の生活は困窮した。こうした中、各地で反乱が発生した。中でも最大規模のものは1351年に勃発した紅巾党の乱であった。紅巾党の中から頭角をあらわした朱元璋は、1368年に南京で皇帝に即位して明を建国した。同年、朱元璋は元の都の大都を陥落させ、元の政府はモンゴル高原へと撤退した。撤退後の元のことを北元といい、明と北元はしばしば争った。明側は1388年に北元は滅んだと称しているが、実質的にはその後も両者の争いは続いた。\n" + "\n" + "[編集] 明清帝国\n" + "鄭和の南海大遠征の時の巨艦・「宝船」\n" + "鄭和の南海大遠征の時の巨艦・「宝船」\n" + "\n" + "洪武帝の死後、孫の建文帝が即位したが、洪武帝の四男である朱棣が反乱(靖難の変)を起こし、朱棣が永楽帝として皇帝になった。永楽帝は、モンゴルを攻撃するなど、積極的に対外進出を進めた。また、鄭和を南洋に派遣して、諸国に朝貢を求めた。この時の船が近年の研究によって長さ170m余、幅50m余という巨艦で、その約70年後の大航海時代の船の5倍から10倍近い船であったことが分かっている。\n" + "\n" + "また、永楽帝によって現在に至るまで世界最大の宮殿である紫禁城が北京に築かれた。\n" + "\n" + "永楽帝の死後、財政事情もあって、明は海禁政策をとり、貿易を著しく制限することとなる。このとき永楽帝を引き継いで、鄭和のようにずっと積極的に海外へ進出していれば、ヨーロッパのアジア・アフリカ支配も実現しなかっただろうと多くの歴史家は推測する。その後、モンゴルが再び勢力を強めはじめ、1449年には皇帝がモンゴルの捕虜になるという事件(土木の変)まで起きた。同じ頃、中国南部沿岸には、倭寇と呼ばれる海上の無法者たちが襲撃を重ねていた。これは、海禁政策で貿易が自由にできなくなっていたためである。倭寇とモンゴルを併称して北虜南倭というが、北虜南倭は明を強く苦しめた。\n" + "紫禁城の中心、太和殿\n" + "紫禁城の中心、太和殿\n" + "\n" + "また、皇帝による贅沢や多額の軍事費用の負担は民衆に重税となって圧し掛かってきた。これに対し、各地で反乱がおき、その中で頭角をあらわした李自成が1644年に明を滅ぼした。\n" + "\n" + "17世紀初頭には、現在の中国東北地方でヌルハチが女真族を統一した。その子のホンタイジは中国東北地方と内モンゴルを征服し、1636年にはモンゴル人から元の玉璽を譲られ、清を建国した。李自成が明を滅ぼすと清の軍隊は万里の長城を越えて、李自成の軍隊を打ち破り、中国全土を支配下に置いた。17世紀後半から18世紀にかけて、康熙帝・雍正帝・乾隆帝という3人の賢い皇帝の下で、清の支配領域は中国本土と中国東北地方・モンゴルのほかに、台湾・東トルキスタン・チベットにまで及んだ。\n" + "\n" + "この清の支配領域が大幅に広がった時期は、『四庫全書』の編纂など文化事業も盛んになった。しかし、これは学者をこのような事業に動員して、異民族支配に反抗する暇をなくそうとした面もあった。\n" + "\n" + "明代の後期には、メキシコや日本から大量の銀が中国に流入し、貨幣として基本的に銀が使われるようになった。そのため、政府も一条鞭法と呼ばれる税を銀で払わせる税法を始めた。また、清代に入ると、人頭税を廃止し土地課税のみとする地丁銀制が始まった。また明清両代ともに商品経済が盛んになり、農業生産も向上した。\n" + "\n" + "[編集] 中国の半植民地化\n" + "フランス人が描いた中国半植民地化の風刺画。イギリス、ドイツ、ロシア、フランス、日本が中国を分割している。\n" + "フランス人が描いた中国半植民地化の風刺画。イギリス、ドイツ、ロシア、フランス、日本が中国を分割している。\n" + "\n" + "18世紀が終わるまでには、清とヨーロッパとの貿易はイギリスがほぼ独占していた。しかし、当時イギリスの物産で中国に売れるものはほとんどなく、逆に中国の安いお茶はイギリスの労働者階級を中心に大きな需要があったこともあり、イギリスは貿易赤字に苦しんだ。そこで、イギリスは麻薬であるアヘンを中国に輸出し始めた。結果、イギリスは大幅な貿易黒字に転じた。しかし、中国にはアヘン中毒者が蔓延し、この事態を重く見た清朝政府は、1839年に林則徐に命じてアヘン貿易を取り締まらせた。しかし、これに反発したイギリス政府は清に対して翌1840年宣戦布告した。アヘン戦争と呼ばれるこの戦争では、工業化をとげ、近代兵器を持っていたイギリス軍が勝利した。これ以降、イギリスをはじめとするヨーロッパの列強は中国に対し、不平等条約(治外法権の承認、関税自主権の喪失、片務的最恵国待遇の承認、開港、租借といった)を締結させ、中国の半植民地化が進んだ。\n" + "\n" + "国内的には、太平天国の乱などの反乱もしばしば起きた。これに対し、同治帝(在位1861年 - 1875年)の治世の下で、ヨーロッパの技術の取り入れ(洋務運動)が行われた。\n" + "\n" + "1894年から翌1895年にかけて清と日本との間で行われた日清戦争にも清は敗退した。これは洋務運動の失敗を意味するものであった。この戦争の結果、日本と清との間で結んだ下関条約により、李氏朝鮮の独立が認められ、中国の王朝が長年続けてきた冊封体制が崩壊した。\n" + "\n" + "その後、清朝政府は改革を進めようとしたものの、沿岸地域を租借地とされるなどのイギリス・フランス・ロシア・ドイツ・アメリカ合衆国・日本による半植民地化の動きは止まらなかった。結局、1911年の武昌での軍隊蜂起をきっかけに辛亥革命が起こり、各地の省が清からの独立を宣言した。翌1912年1月1日、革命派の首領の孫文によって南京で中華民国の樹立が宣言された。北京にいた清の皇帝溥儀(宣統帝)は、清朝政府内部の実力者である袁世凱により2月12日に退位させられ、清は完全に滅亡した。\n" + "\n" + "[編集] 中華民国\n" + "\n" + "[編集] 革命後の中国の政局\n" + "\n" + "中華民国は成立したものの、清朝を打倒した時点で革命に参加した勢力どうしで利害をめぐって対立するようになり、政局は混乱した。各地の軍閥も民国政府の税金を横領したり勝手に新税を導入して独自の財源を持つようになり、自立化した。\n" + "\n" + "[編集] 袁世凱の台頭と帝制運動(1913年~1916年)\n" + "袁世凱\n" + "袁世凱\n" + "\n" + "臨時大総統であった袁世凱は大総統の権力強化を図って議会主義的な国民党の勢力削減を企てた。国民党の急進派はこれに反発、第二革命を起こしたが鎮圧された。1913年10月袁は正式な大総統となり、さらに11月には国民党を非合法化し、解散を命じた。1914年1月には国会を廃止、5月1日には立法府の権限を弱め大総統の権力を大幅に強化した中華民国約法を公布した。\n" + "\n" + "袁は列強から多額の借款を借り受けて積極的な軍備強化・経済政策に着手した。当初列強の袁政権に対する期待は高かった。しかしこのような外国依存の財政は、のちに列強による中国の半植民地化をますます進めることにもなった。第一次世界大戦が始まると、新規借款の望みがなくなったため、袁は財政的に行き詰まった。また日本が中国での権益拡大に積極的に動いた。\n" + "\n" + "1915年5月9日に、袁が大隈重信内閣の21ヶ条要求を受けたことは大きな外交的失敗と見られ、同日は国恥記念日とされ袁の外交姿勢は激しく非難された。袁は独裁を強化することでこの危機を乗り越えようとし、立憲君主制的な皇帝制度へ移行し、自身が皇帝となることを望んだ。日本も立憲君主制には当初賛成していたようだが、中国国内で帝制反対運動が激化すると反対に転じ外交圧力をかけた。1916年袁は失意のうちに没した。\n" + "\n" + "[編集] 袁世凱死後の政局(1916年~1920年)\n" + "\n" + "袁の死後、北京政府の実権を掌握したのは国務総理となった段祺瑞であった。段は当初国会[6]の国民党議員などと提携し、調整的な政策をとっていた。しかし、第一次世界戦に対独参戦しようとしたため徐々に国会と対立した。段は日本の援助の下に強硬な政策を断行した。1917年8月14日第一次世界大戦に対独参戦。軍備を拡張して国内の統一を進めた。また鉄道や通信などの業界を背景とする利権集団が段を支えた。1918年には国会議員改定選挙を強行した。国民党はこれに激しく対立し、南方の地方軍とともに孫文を首班とする広東軍政府をつくった。5月には日本と日中軍事協定[7]を結んだ。寺内正毅内閣失脚後に日本の外交方針が転回すると、段は急速に没落した。段の安徽派と対立関係にあった直隷派の馮国璋は徐世昌を大総統に推薦し、段もこれを受け入れた。親日的な安徽派は徐々に影響力を失っていった。1919年5月4日、山東半島での主権回復と反日を訴えるデモ行進が始まった。これを五・四運動という。なお山東半島は1922年に返還された。1920年7月の安直戦争で直隷派に敗れたことで段は失脚した。\n" + "\n" + "[編集] 国民革命(1920年~1928年)\n" + "革命家・孫文\n" + "革命家・孫文\n" + "\n" + "袁世凱により国民党が非合法化されたのち、孫文は1914年7月に中国革命党を東京で結成した。1919年には拠点を上海に移し、中国国民党と改称した。1921年には上海で中国共産党が成立した。これらの政党は1918年のロシア革命の影響を受けており、議会政党というよりも明確な計画性と組織性を備えた革命政党を目指した。1924年国民党は第一回全国大会をおこない、党の組織を改編するとともに共産党との合同(第一次国共合作)を打ち出した。孫文はこのころ全く機能していなかった国会に代わって国内の団体代表による国民会議を提唱し、これに呼応した馮国璋により北京に迎えられた。1925年には国民会議促成会が開かれたが、この会期中に孫文は没した。7月には広東軍政府で機構再編が進み、中華民国国民政府の成立が宣言された。一方で1924年6月には蒋介石を校長として黄埔軍官学校が設立された。1925年4月に国民革命軍が正式に発足され、国民党は蒋介石を指導者として軍事的な革命路線を推し進めることとなった。1926年に広州から北伐を開始した。1927年1月には武漢に政府を移し、武漢国民政府と呼ばれるようになった。この武漢国民政府では当初国民党左派と共産党が優位にあったが、蒋介石は同年4月12日上海クーデターを起こしてこれらを弾圧し、4月18日には反共を前面に打ち出した南京国民政府を成立させた。南京国民政府は主に上海系の資本家に支えられ、北京・武漢・南京に3つの政権が鼎立することになったが、9月ごろから武漢政府も反共に転じ、南京政府に吸収された。1928年6月南京政府の国民革命軍は北京の中華民国政府を打倒し、12月に張学良もこれを承認したことから、国民政府によって中国は再び統一された。\n" + "\n" + "[編集] 国民政府(1928年~1931年)\n" + "蒋介石\n" + "蒋介石\n" + "\n" + "国民政府においては基本的に国民党の一党独裁の立場が貫かれた。しかし一般党員の数は50万人以下であったとされており、4億をこえると考えられた中国国民のなかではかなり少数であった(国民の多くが「国民」として登録されておらず、しかも文盲のものも多かった)。そのため支配基盤は完全とは言えず、土地税を中心として地方政権の財源を確保する国地画分政策がおこなって、割拠的傾向がいまだに強い地方勢力に配慮したりした。1930年代前半には国民政府に叛旗を翻す形で地方政権が樹立される例が多くなり、軍事衝突なども起きた。1930年に閻錫山と汪兆銘が中心となった北平政府や1931年に孫科らがたてた広州政府などである。\n" + "\n" + "しかしこのような軍事的緊張は国民政府の中央軍を掌握していた蒋介石の立場を強めることにもなった。蒋介石は経済政策[8]でも手腕を発揮し影響力を増した。\n" + "\n" + "[編集] 抗日戦争(1931年~1937年)\n" + "満州国皇帝愛新覚羅溥儀\n" + "満州国皇帝愛新覚羅溥儀\n" + "\n" + "張作霖が関東軍に爆殺されたあとをついだ張学良は国民革命を支持しており、自身の支配していた中国東北地方を国民政府へ合流させた。このために反日運動が中国東北地方にも広がったが、日本は中国東北地方の権益を確保しようとしていたためにこれに大きく反発した。1931年9月、満州事変がおこり、関東軍によって日本政府の意向を無視して大規模な武力行動がおこなわれた。しかし列強はこれを傍観する姿勢をとったので、日本政府はこの行動を追認した。\n" + "\n" + "東北地方をほぼ制圧した日本軍は、1932年に上海事変を起こし、列強がそれに注目している間に傀儡政権として満州国を東北地方に樹立した。同年10月、リットン調査団が国際連盟によって派遣され、満州国を中国の主権の下に列強の共同管理による自治政府とするべきという妥協案を示したが、日本は採択に反対した。1933年5月日中間で停戦協定(塘沽協定)が結ばれた。1934年には満州国は帝制に移行し、満州帝国となった。\n" + "\n" + "1931年に瑞金に政権を樹立していた中国共産党は満州国建国時に日本に宣戦布告していたが、国民党との抗争に忙しく、中国国民で一致して日本の侵略に立ち向かうことはできなかった。1934年には瑞金は国民党により陥落し、打撃を受けた中国共産党は長征と称して西部に移動し、組織の再編をはかった。長征の結果中国共産党は延安に拠点を移した。\n" + "\n" + "[編集] 日中戦争(1937年~1945年)\n" + "\n" + "1937年には、盧溝橋事件を契機に、日本軍が中国本土に進出し、中華民国と全面戦争に入った(日中戦争)。これに対し、蒋介石は当初日本との戦いよりも中国共産党との戦いを優先していたが、西安事件により、二つの党が協力して日本と戦うことになった(第二次国共合作)。\n" + "カイロ会談に出席した蒋介石とアメリカのフランクリン・D・ルーズベルト大統領、イギリスのウィンストン・チャーチル首相\n" + "カイロ会談に出席した蒋介石とアメリカのフランクリン・D・ルーズベルト大統領、イギリスのウィンストン・チャーチル首相\n" + "\n" + "しかし日中戦争は当初日本軍優位に進み、日本軍は多くの都市を占領したが、各拠点支配はできても広大な中国において面での支配はできず、これを利用した国民党軍・共産党軍ともに各地でゲリラ戦を行い日本軍を苦しめ、戦線を膠着させた。日本は汪兆銘ら国民党左派を懐柔、南京国民政府を樹立させたが、国内外ともに支持は得られなかった。加えて1941年12月、日本はアメリカやイギリス(連合国)とも戦端を開いたが(太平洋戦争)、一方で中国で多くの戦力を釘付けにされるなど、苦しい状況に落ち込まされた。国民党政府は連合国側に所属し、アメリカやイギリスなどから豊富な援助を受けることとなった。\n" + "\n" + "結局、中国大陸戦線では終始日本側が優勢であったものの、1945年8月ポツダム宣言の受諾とともに日本が無条件降伏することで終結した。国民党政府は連合国の1国として大きな地位を占めていたこともあり、戦勝国として有利な立場を有することとなり、日本だけでなくヨーロッパ諸国も租界を返還するなど、中国の半植民地化は一応の終わりを見せた。\n" + "\n" + "しかしまもなく国民党と共産党との対立が激化して国共内戦が勃発し、結果として左派が力を持ったアメリカからの支援が減った国民党に対して、ソビエト連邦からの支援を受けていた中国共産党が勝利し、1949年10月1日に毛沢東が中華人民共和国の成立を宣言した。内戦に敗れた中国国民党率いる中華民国政府は台湾島に撤退し、現在に至るまで中国共産党率いる中華人民共和国と「中国を代表する正統な政府」の地位を争っている。\n" + "\n" + "[編集] 漢民族以外の民族の動向\n" + "\n" + "[編集] モンゴルとチベットでの動き\n" + "\n" + "辛亥革命により清国が消滅すると、その旧領をめぐって中国、モンゴル、チベットは、それぞれに自領域を主張した。\n" + "\n" + "中国は清領全域を主張した。これに対して、モンゴルとチベットは、自分たちは清朝の皇帝に服属していたのであって中国という国家に帰属するものではなく、服属先の清帝退位後は中国と対等の国家であると主張し独立を目指す動きが強まった。\n" + "ポタラ宮、当時のチベットの中心地\n" + "ポタラ宮、当時のチベットの中心地\n" + "\n" + "1913年、モンゴルではボグド・ハーンによって、チベットではダライ・ラマ13世よって中国からの独立が宣言され、両者はモンゴル・チベット相互承認条約を締結するなど国際的承認をもとめ、これを認めない中華民国とは戦火を交えた。 この状況は、モンゴル域への勢力浸透をはかるロシア、チベット域への進出をねらうイギリスの介入をゆるし、モンゴル・ロシア・中華民国はキャフタ協定に調印批准、チベット・イギリス・中華民国はシムラ協定(民国政府のみ調印、批准されなかった)が模索されたものの問題の解決には至らなかった。\n" + "\n" + "ダライ・ラマを補佐していたパンチェン・ラマは親中国的であったために、イギリスに接近するダライ・ラマに反発し、1925年に中国に亡命した。1933年、ダライ・ラマ13世が死去、中国の統治下にあったチベット東北部のアムド地方(青海省)で生まれたダライ・ラマ14世の即位式典に列席した国民政府の使節団は、式典が終了したのちも、蒙蔵委員会駐蔵弁事處を自称してラサにとどまった。1936年には長征中の中国共産党の労農紅軍が、カム地方東部(四川省西部、当時西康省)に滞留中、同地のチベット人に「チベット人人民共和国」(博巴人民共和国)[9]を組織させたが、紅軍の退出とともに、ほどなく消滅した。\n" + "\n" + "この問題は、モンゴルについては、1947年、外蒙古部分のみの独立を中華民国政府が承認することによって、チベットについては、1950年、十七ヶ条協定によってチベットの独立が否定され中華人民共和国の一地方となったことによって、一応の決着をみた。\n" + "\n" + "[編集] 東トルキスタン(新疆)での動き\n" + "\n" + "東トルキスタン(新疆)では、19世紀中に統治機構の中国化が達成されていた。すなわち、旗人の3将軍による軍政と、地元ムスリムによるベク官人制にかわり、省を頂点に府、州、県に行政区画された各地方に漢人科挙官僚が派遣されて統治する体制である。そのため、辛亥革命時、東トルキスタンでは、地元ムスリムがチベットやモンゴルと歩調をあわせて自身の独立国家を形成しようとする動きはみられず、新疆省の当局者たちは、すみやかに新共和国へ合流する姿勢を示した。この地では、楊増新が自立的な政権を維持し、またソ連と独自に難民や貿易の問題について交渉した。楊増新の暗殺後は金樹仁が実権が握ったが、彼は重税を課して腐敗した政治をおこなったため、1931年には大規模な内乱状態に陥った。その後金樹仁の部下であった盛世才が実権を握るようになり、彼はソ連にならった政策を打ち出して徐々に権力を強化した。一方で1933年には南部で東トルキスタン共和国の独立が宣言されたが、わずか6ヶ月で倒れた。\n" + "\n" + "[編集] 中華人民共和国\n" + "\n" + "[編集] 社会主義国化と粛清(1949年~1957年)\n" + "「建国宣言」を行なう毛沢東\n" + "「建国宣言」を行なう毛沢東\n" + "\n" + "1950年中ソ友好同盟相互援助条約が結ばれた。これは日本およびその同盟国との戦争を想定して締結されたものである。この条約でソ連が租借していた大連、旅順が返還され、ソ連の経済援助の下で復興を目指すこととなった。1953年より社会主義化が進み、人民政治協商会議に代わって全国人民代表大会が成立、農業生産合作社が組織された。\n" + "\n" + "1956年にソ連でフルシチョフによって「スターリン批判」がおこなわれると、東欧の社会主義国に動揺がはしった。中国共産党政府も共産圏にある国としてこの問題への対処を迫られ、この年初めて開催された党全国代表大会では、「毛沢東思想」という文言が党規約から消えた。そして全く一時的に(わずか2ヶ月)「百花斉放、百家争鳴」と称して民主党などの「ブルジョワ政党」の政治参加が試みられた。しかしブルジョワ政党が中国共産党政府による一党独裁に対して激しい批判を噴出させたため、逆に共産党による反右派闘争を惹起し、一党支配体制は強められた。一方で中ソ協定が結ばれ、軍事上の対ソ依存は強くなった。この時代の中華人民共和国をソ連のアメリカに対する緩衝国家あるいは衛星国家とみなすことも可能である。しかし徐々にデタント政策へと転回し始めていたソ連の対外政策は、中国共産党政府の中華民国に対する強硬政策と明らかに矛盾していた。\n" + "\n" + "[編集] 中国共産党の対ソ自立化(1958年~1965年)\n" + "\n" + "1958年に、毛沢東は大躍進政策を開始し、人民公社化を推進した。当初はかなりの効果をあげたかに見えた人民公社であったが、党幹部を意識した誇大報告の存在、極端な労働平均化などの問題が開始3ヶ月にしてすでに報告されていた。毛沢東はこのような報告を右派的な日和見主義であり、過渡的な問題に過ぎないと見ていたため、反対意見を封殺したが、あまりに急速な人民公社化は都市人口の異様な増大など深刻な問題を引き起こしていた。\n" + "\n" + "一方でこの年、中国共産党政府は台湾海峡で中華民国に対して大規模な軍事行動を起こし、アメリカ軍の介入を招いた。フルシチョフは中国共産党政府の強硬な姿勢を非難し、また自国がアメリカとの全面戦争に引きずり込まれないように努力した。ソ連はワルシャワ条約機構の東アジア版ともいうべき中ソの共同防衛体制を提案したが、中国共産党政府はソ連の対外政策への不信からこれを断った。その後1959年6月ソ連は中ソ協定を一方的に破棄した。1960年には経済技術援助条約も打ち切られ、この年の中国のGNPは1%も下落した。\n" + "\n" + "1959年と1960年に大規模な飢饉が中国を襲い、1500万人程度(2000万から5000万人以上とも)と言われる餓死者を出して大躍進政策も失敗に終わった。1960年代初頭には人民公社の縮小がおこなわれ、毛沢東自身が自己批判をおこなうなど、一見調整的な時期に入ったように思われた。劉少奇が第2次5ヶ年計画の失敗を人民公社による分権的傾向にあると指摘し、中央集権を目指した政治改革、個人経営を一部認めるなど官僚主義的な経済調整をおこなった。\n" + "\n" + "しかし党組織の中央集権化と個人経営に懐疑的であった毛沢東はこれを修正主義に陥るものであると見ていた。1963年に毛沢東は「社会主義教育運動」を提唱し、下部構造である「農村の基層組織の3分の1」は地主やブルジョワ分子によって簒奪されていると述べた。これは劉少奇ら「実権派」を暗に批判するものであった。またこのころ毛沢東は「文芸整風」運動と称して学術界、芸術界の刷新をはかっていたことも、のちの文化大革命の伏線となった。1964年中国は核実験に成功し、軍事的な自立化に大きな一歩を踏み出した。一方で1965年にアメリカによる北爆が始まりベトナム戦争が本格化すると、軍事的緊張も高まった。\n" + "\n" + "チベットでは独立運動が高まったが、政府はこれを運動家に対する拷問など暴力によって弾圧した。このため多数の難民がインドへ流入した。\n" + "\n" + "[編集] 文化大革命前期(1966年~1969年)\n" + "天安門広場は中華人民共和国時代にも多くの歴史の舞台となった\n" + "天安門広場は中華人民共和国時代にも多くの歴史の舞台となった\n" + "\n" + "1966年に毛沢東は文化大革命を提唱した。毛沢東の指示によって中央文化革命小組が設置され、北京の青少年によって革命に賛同する組織である紅衛兵が結成された。毛沢東は「造反有理」(反動派に対する謀反には道理がある)という言葉でこの運動を支持したので、紅衛兵は各地で組織されるようになった。\n" + "\n" + "毛沢東は文革の目的をブルジョワ的反動主義者と「実権派」であるとし、劉少奇とその支持者を攻撃対象とした。毛沢東は林彪の掌握する軍を背景として劉少奇を失脚させた。しかし文化大革命は政治だけにとどまることがなく、広く社会や文化一般にも批判の矛先が向けられ、反革命派とされた文化人をつるし上げたり、反動的とされた文物が破壊されたりした。\n" + "\n" + "1966年の末ごろから武力的な闘争が本格化し、地方では党組織と紅衛兵との間で武力を伴った激しい権力闘争がおこなわれた。毛沢東は秩序維持の目的から軍を介入させたが、軍は毛沢東の意向を汲んで紅衛兵などの中国共産党左派に加担した。中央では周恩来らと文革小組の間で権力闘争がおこなわれた。1967年の後半になると、毛沢東は内乱状態になった国内を鎮めるために軍を紅衛兵運動の基盤であった学校や工場に駐屯させた。\n" + "\n" + "この時期軍の影響力は極端に増大し、それに伴って林彪が急速に台頭した。1969年には中ソ国境の珍宝島で両国の軍事衝突があり(中ソ国境紛争)、軍事的緊張が高まったこともこれを推進した。同年採択された党規約で林彪は毛沢東の後継者であると定められた。\n" + "\n" + "[編集] 文化大革命後期(1969~1976年)\n" + "\n" + "文化大革命は後期になると国内の権力闘争や内乱状態を引き起こしたが、最終的に文化大革命は1976年の毛沢東死去で終結した。 文化大革命では各地で文化財破壊や大量の殺戮が行われ、その犠牲者の合計数は数百万人とも数千万人とも言われている。また学生たちが下放され農村で働くなど、生産現場や教育現場は混乱し、特に産業育成や高等教育などで長いブランクをもたらした。\n" + "\n" + "一方この時期、ソ連に敵対する中国共産党政府は、同じくソ連と敵対する日本やアメリカなどからの外交的承認を受け、この結果国連の常任理事国の議席も台湾島に遷都した中華民国政府(国民党政権)に変わって手にするなど、国際政治での存在感を高めつつあった。\n" + "\n" + "[編集] 改革開放以後の現在(1976年~)\n" + "返還された香港は中国経済の牽引都市になっている\n" + "返還された香港は中国経済の牽引都市になっている\n" + "\n" + "その後は一旦華国鋒が後を継いだが、1978年12月第11期三中全会で鄧小平が政権を握った。鄧小平は、政治体制は共産党一党独裁を堅持しつつ、資本主義経済導入などの改革開放政策を取り、近代化を進めた(社会主義市場経済、鄧小平理論)。この結果、香港ほか日米欧などの外資の流入が開始され、中国経済は離陸を始めた。\n" + "\n" + "[編集] 一党独裁\n" + "\n" + "冷戦崩壊後に、複数政党による選挙や言論の自由などの民主主義化を達成した中華民国と違い、いまだに中国共産党政府による一党独裁から脱却できない中華人民共和国には多数の問題が山積している。\n" + "\n" + "1989年には北京で、1980年代の改革開放政策を進めながら失脚していた胡耀邦の死を悼み、民主化を求める学生や市民の百万人規模のデモ(天安門事件)が起きたが、これは政府により武力鎮圧された。その一連の民主化運動の犠牲者数は中国共産党政府の報告と諸外国の調査との意見の違いがあるが、数百人から数万人に上るといわれている。しかし中国共産党政府はこの事件に関しては国内での正確な報道を許さず、事件後の国外からの非難についても虐殺の正当化に終始している。\n" + "\n" + "この事件以降も、中国共産党政府は情報や政策の透明化、民主化や法整備の充実などの国際市場が要求する近代化と、暴動や国家分裂につながる事態を避けるため、内外の報道機関やインターネットに統制を加え、反政府活動家に対する弾圧を加えるなどの前近代的な動きとの間で揺れている。この様な中、2003年には国内でSARSの大発生があったが、このときも政府は虚偽の発表を行なうなど問題の隠蔽を繰り返した。\n" + "\n" + "天安門事件で外資流入に急ブレーキがかかったが、1990年代には、江沢民政権のもとで、鄧小平路線に従い、経済の改革開放が進み、特に安い人件費を生かした工場誘致で「世界の工場」と呼ばれるほど経済は急成長した。なお、1997年にイギリスから香港が、1999年にポルトガルからマカオが、それぞれ中華人民共和国に返還され、植民地時代に整備された経済的、法的インフラを引き継ぎ、中華人民共和国の経済の大きな推進役となっている。また、敵対している中華民国との間にも経済的な交流が進み、両国の首都の間に直行便が就航するまでになっている。\n" + "\n" + "人口、面積ともに世界的な規模をもつことから、アメリカの証券会社であるゴールドマンサックスは、「中華人民共和国は2050年に世界最大の経済大国になる」と予想するなど、現在、中国経済の動向は良くも悪くも注目されているが、低賃金による大量生産を売り物にしてきた経済成長は賃金上昇・東南アジアやインドの追い上げなどで限界に達しており、産業の高度化や高付加価値化などの難題に迫られている。また、各種経済統計も中国共産党政府発表のそれは信憑性が乏しいと諸外国から指摘されている。各省など地方も独自の産業振興策に走り、中国共産党中央政府に対して経済統計の水増し発表や災害などの情報隠蔽を行うなど、統計や発表の信憑性不足に拍車をかけている。\n" + "\n" + "これらのことより、中国共産党の一党独裁による言論統制や貧富格差、地域格差など国内のひずみを放置し続ければ、いずれ内部崩壊を起こして再度混乱状態に陥り、ソ連同様に中華人民共和国という国家体制そのものが解体、消滅するという意見も多い。\n" + "\n" + "[編集] 少数民族問題\n" + "\n" + "なお、少数民族が住む新疆ウイグル自治区(東トルキスタン)では現在漢化政策の進展によって、漢民族が同地域へ大量に流入する、都市を中心として就職などに有利な中国語教育の充実によりウイグル語が廃れるなどの民族的なマイノリティ問題が発生している。またタクラマカン砂漠の石油資源利用や新疆南北の経済格差が広がっているなど、中国共産党政府の経済政策に対する批判も根強い。\n" + "\n" + "1997年には新疆ウイグル自治区で大規模な暴動が起きた。海外で東トルキスタン独立運動がおこなわれている一方国内でもウイグル人活動家の処刑などが行われているが、民族自治における権限拡大という現実主義的な主張もあらわれている。たとえば中国語教育を受けたウイグル人が中国共産党組織に参加する、新疆での中国共産党政府の経済政策に積極的に参加するといった事例も見られる。\n" + "\n" + "チベット自治区では歴史的なチベットの主権を主張するダライ・ラマの亡命政権が海外に存在し、中国共産党政府が不法な領土占拠をしていると訴えるとともに独立運動が継続されている。中国共産党政府はこれを武力で弾圧し続け、独立運動家への拷問などを行なったために、多数の難民が隣国のインドに流入した。\n" + "\n" + "[編集] 人口の変遷\n" + "\n" + "以下のデータは主に楊学通「計画生育是我国人口史発展的必然」(1980年)による。\n" + "時代 年代 戸数 人口 資料出所\n" + "(夏) 禹(前2205年とされる) 13,553,923 『帝王世紀』\n" + "秦 20,000,000? \n" + "前漢 平帝元始2年(2年) 12,233,062 59,594,978 『漢書』地理志\n" + "新 20,000,000? \n" + "後漢 順帝建康元年(144年) 9,946,919 49,730,550 『冊府元亀』\n" + "晋 武帝泰康元年(280年) 2,459,804 16,163,863 『晋書』食貨志\n" + "隋 煬帝大業2年(606年) 8,907,536 46,019,056 『隋書』地理志・食貨志\n" + "唐 玄宗天宝14年(755年) 8,914,709 52,919,309 『通志』\n" + "宋 神宗元豊3年(1080年) 14,852,684 33,303,889 『宋史』地理志\n" + "金 章宗明昌6年(1195年) 7,223,400 48,490,400 『金史』食貨志\n" + "元 世祖至元27年(1290年) 13,196,206 58,834,711 『元史』地理志\n" + "明 神宗万暦6年(1570年) 10,621,436 60,692,850 『続文献通考』\n" + "清 清初(1644年) 45,000,000 \n" + "聖祖康熙50年(1711年) 100,000,000以上 \n" + "高宗乾隆27年(1762年) 200,000,000以上 \n" + "高宗乾隆55年(1790年) 300,000,000以上 \n" + "仁宗嘉慶17年(1812年) 333,700,560 『東華録』\n" + "宣宗道光14年(1834年) 400,000,000以上 \n" + "中華民国 民国36年(1947年) 455,590,000 『統計提要』\n" + "中華人民共和国 1995年 1,211,210,000 『中国統計年鑑』\n" + "\n" + "[編集] 地方行政制度\n" + "\n" + "[編集] 封建制度(前1600年頃~前221年)\n" + "\n" + "殷・周の時代は封建制度[10]によって一定の直轄地以外は間接的に統治された。\n" + "\n" + "[編集] 郡県制度(前221年~249年)\n" + "\n" + "中国最初の統一王朝である秦は全国を郡とその下級単位である県に分ける郡県制度によって征服地を統治した。前漢初期においては、郡以上に広域な自治を認められた行政単位である国が一部の功臣や皇族のために設置された。しかし徐々に国の行政権限が回収されるとともに、推恩政策によって国の細分化が進められ、国は郡県と等しいものとなり、後漢時代には実質郡県制度そのままとなっていた。\n" + "\n" + "前漢時代に広域な監察制度としての刺史制度が始められると全国を13州[11]に分けた。これはいまだ行政的なものではない[12]と考えられている。後漢の後の魏王朝では官僚登用制度としての九品官人法が249年に司馬懿によって州単位でおこなわれるように適用されたので、行政単位として郡以上に広域な州が現実的な行政単位として確立したと考えられている。が、軍政面と官吏登用面のほかにどれほど地方行政に貢献したか[13]はあまり明確ではない。\n" + "\n" + "[編集] 軍府による広域行政(249年~583年)\n" + "\n" + "魏晋時代から都督府などの軍府の重要性が高まった。五胡十六国および南北朝時代になると、中国内部で複数の王朝が割拠し軍事的な緊張が高まったことから、とくに南朝において重要性が増した。これは本来特定の行政機関を持たなかったと思われる刺史に対して、軍事的に重要な地域の刺史に例外的に複数の州を統括できる行政権を与えたものであった。長官である府主(府の長官は一般的にさまざまな将軍号を帯び、呼称は一定ではないため便宜的に府主とする)は属僚の選定に対して大幅な裁量権が与えられており、そのため地方で自治的な支配を及ぼすことが出来た。また南朝では西晋末期から官吏登用において州は形骸化しており、吏部尚書によって官制における中央集権化が進行している。したがって中正官も単なる地方官吏に過ぎなくなり、広域行政単位としての州は官吏登用の面からは重要性が低下したが、地方行政単位としてはより実際性を帯びた。この時代州は一般に細分化傾向にあり、南北朝前期には中国全土で5,60州、南北朝末期に至ると中国全土で300州以上になり、ひとつの州がわずか2郡、ひとつの郡はわずか2,3県しか含まないという有様であった。\n" + "\n" + "[編集] 州県制(583年~1276年)\n" + "\n" + "南朝では都督制度が発達していたころ、北魏では州鎮制度が発達した。北魏では征服地にまず軍事的性格の強い鎮を置き、鎮は一般の平民と区別され軍籍に登録された鎮民を隷属させて支配した。鎮は徐々に州に改められたようであるが、北部辺境などでは鎮がずっと維持された。583年に隋の文帝が郡を廃止し、州県二級の行政制度を開始した。この際従来の軍府制度[14]にあった漢代地方制度的な旧州刺史系統の地方官は廃止され、軍府系統の地方官に統一されたと考えられている。595年には形骸化していた中正官も最終的に廃止されたという指摘もされている。またこれにより府主の属官任命権が著しく制限され、中央集権化がはかられた。唐では辺境を中心に広域な州鎮的軍府である総管府が置かれたが徐々に廃止され、刺史制度に基づいた地方軍的軍府、それに中央軍に対する吏部の人事権が強化・一元化され、軍事制度の中央集権化が完成された。特定の州に折衝府が置かれ、自営農民を中心として府兵が組織され常備地方軍[15]とされた。唐では州の上に10の道も設置されたが、これは監察区域で行政単位ではないと考えられている。\n" + "\n" + "[編集] 祭祀制度\n" + "\n" + "中国でおこなわれた国家祭祀については皇帝祭祀を参照。\n" + "\n" + "[編集] 外交\n" + "\n" + "中国大陸の諸王朝は前近代まで基本的に東アジアでの優越的な地位を主張し、外交的には大国として近隣諸国を従属的に扱う冊封体制が主流であった。\n" + "\n" + "[編集] 漢帝国\n" + "\n" + "漢代には南越、閩越、衛氏朝鮮などが漢の宗主権下にあったと考えられ、これらの国々は漢の冊封体制下にあったと考えられている。前漢武帝の時にこれらの諸国は征服され郡県に編入された。このことは漢の冊封が必ずしも永続的な冊封秩序を形成することを意図したものではなく、機会さえあれば実効支配を及ぼそうとしていたことを示す。また匈奴は基本的には冊封体制に組み込まれず、匈奴の単于と中国王朝の皇帝は原則的には対等であった。大秦(ローマ帝国のことを指すとされる)や大月氏などとの外交関係は冊封を前提とされていない。\n" + "\n" + "[編集] 魏晋南北朝時代\n" + "\n" + "魏晋南北朝時代には、中国王朝が分立する事態になったので、冊封体制は変質し実効支配を意図しない名目的な傾向が強くなったと考えられている。朝鮮半島では高句麗をはじめとして中小国家が分立する状態があらわれ、日本列島の古代国家[16] も半島の紛争に介入するようになったために、半島の紛争での外交的優位を得るため、これらの国々は積極的に中国王朝の冊封を求めた。しかし高句麗が北朝の実効支配には頑強に抵抗しているように、あくまで名目的関係にとどめようという努力がなされており、南越と閩越の紛争においておこなわれたような中国王朝の主導による紛争解決などは期待されていないという見方が主流である。\n" + "\n" + "[編集] 隋唐帝国\n" + "\n" + "再び中国大陸を統一した隋・唐の王朝の時代は東アジアの冊封体制がもっとも典型的となったという見方が主流である。隋は高句麗がみだりに突厥と通交し、辺境を侵したことからこれを討伐しようとしたが、遠征に失敗した。唐は、新羅と連合し、高句麗・百済を滅亡させ、朝鮮半島を州県支配しようとしたが、新羅に敗北し、願いは、叶わなかった。したがって隋・唐の冊封は実効支配とは無関係に形成されるようになった。唐の冊封体制の下では、律令的な政治体制・仏教的な文化が共有された。\n" + "\n" + "一方、突厥や西域諸国が服属すると、それらの地域に対する支配は直接支配としての州県、外交支配としての冊封とは異なった羈縻政策[17]がおこなわれた。\n" + "\n" + "[編集] 関連項目\n" + "\n" + " * 中華人民共和国\n" + " * 中華民国\n" + " * 中国帝王一覧\n" + " * 中国の首都\n" + " * 中国史時代区分表\n" + " o 夏商周年表\n" + " o 魏晋南北朝表\n" + " * 元号一覧\n" + " * 二十四史(清によって公認された正史)\n" + " * 中国史関係記事一覧\n" + " * マカオの歴史\n" + " * 香港の歴史\n" + " * 台湾の歴史\n" + " * 中国の通貨制度史\n" + " * 中国の仏教\n" + " * 中国法制史\n" + " * 中国化\n" + "\n" + "Wikibooks\n" + "ウィキブックスに中国史関連の教科書や解説書があります。\n" + "[編集] 脚注\n" + "\n" + " 1. ^ 浙江省紹興市郊外にある陵墓が禹のものであるとされ、戦国時代同地を支配していた越王勾践が禹の子孫を標榜していること、夏の桀王が『史記』鄭玄注などで淮河と長江の中間にある南巣で死んだとしていることなどによる。\n" + " 2. ^ 河南省にある偃師二里頭遺跡が夏のものではないかとされているが、文書などが発見されていないため確定はされていない。また偃師二里頭遺跡での発掘結果から殷との連続性が確認されたが、細かい分析においては殷との非連続性も確認されているため、偃師二里頭遺跡が夏王朝のものであっても、夏が黄河流域起源の王朝であったかどうかは論争中である。\n" + " 3. ^ 代表的な遺跡殷墟が有名であるため日本では一般に殷と呼ばれるが、商の地が殷王朝の故郷とされており、商が自称であるという説もあるため、中国では商と呼ぶほうが一般的である。\n" + " 4. ^ ただし殷を北西から侵入してきた遊牧民族による征服王朝だとする説もある。これは偃師二里頭遺跡では青銅器が現地生産されているのに対し、殷時代の青銅器は主に蜀方面で生産されていたことが確認されていることによる。\n" + " 5. ^ 当初は漢魏革命の際に漢の官僚を魏宮廷に回収する目的で制定されたものであったが、優れたものであったために一般的な官吏登用に使用されるようになった。これは中正官を通して地方の世論を反映した人事政策をおこなうもので、地方で名望のあったものをその程度に応じて品位に分け官僚として登用するものであった。官僚は自身の品位と官職の官品に従って一定の官職を歴任した。地方の世論に基づくとはいえ、一般的に家柄が重視される傾向にあり、「上品に寒門なく、下品に勢族なし」といわれた。南北朝時代になると官職内で名誉的な清流官職と濁流官職が貴族意識によって明確に分けられ、また家柄によって官職が固定される傾向が顕著となった。このような傾向は専制支配を貫徹しようとする皇帝の意向と対立するものであったため、官品の整理をおこなって清濁の区別をなくす努力が続けられた。しかし皇帝も貴族社会の解体そのものを望んでおらず、貴族社会の上位に皇帝権力を位置づけることでヒエラルキーを維持しようとしていたから、官職制度の根幹的な改変には至らず、官職の家柄による独占傾向を抑えることは出来なかった。\n" + " 6. ^ 1916年8月に復活された。\n" + " 7. ^ これはロシア革命に対するシベリア出兵において日中両軍が協力するという秘密条約である。\n" + " 8. ^ 1928年~30年に各国と交渉して関税自主権を回復し、関税を引き上げ、塩税と統一消費税をさだめて財源を確保した。アメリカとイギリスの銀行資本に「法幣」という紙幣を使用させ、秤量貨幣であった銀両を廃止した。さらにアメリカ政府に銀を売ってドルを外為資金として貯蓄した。これにより国際的な銀価格の中国の国内経済に対する影響が大幅に緩和された。このような経済政策を積極的に推進したのは国民政府財政部長の宋子文で、彼は孫文の妻宋慶齢の弟で、妹はのちに蒋介石と結婚した宋美齢であった。\n" + " 9. ^ 博巴あるいは波巴とはチベット人の自称。日本語に訳せばチベット人の人民政府という意味である。博巴と波巴はともに「ぽぱ」と読む。\n" + " 10. ^ 封建制度は殷代からおこなわれているが、殷代封建制についてはあまり明確なことはわからない。殷では封建がおこなわれている地域と方国と呼ばれる、外様あるいは異民族の国家の存在が知られ、殷を方国の連盟の盟主であり、封建された国々は殷の同族国家であるとする説もあるが詳しいことはわからない。周では一定の城市を基準とした邑に基づいた封建制が広汎におこなわれたと考えられているが、この邑制国家の実態も不明である。邑をポリス的な都市国家とみる見方から、邑と周辺農地である鄙が一緒になって(これを邑土という)、貴族による大土地所有であるとする見方もある。明らかであるのは邑を支配した貴族が長子相続を根幹とした血族共同体をもっていたということで、このような共同体に基づいた支配形態を宗法制度という。宗法制度については殷代にさかのぼる見方もあるが、広汎におこなわれたのは春秋あるいは戦国時代であったとする説もある。周の封建制を宗法制度の延長にあるものと捉え、封建儀礼を宗族への加盟儀礼の延長として捉える見方もある。\n" + " 11. ^ 中国古来より中国世界を9つの地方に分ける考え方が漠然と存在した。中国王朝の支配領域を「九州」といい、それがすなわち「天下」であった。ただし九州の概念は後漢時代にいたるまでははっきりしたものではなく一様でない。\n" + " 12. ^ 前漢成帝のときに州の監察権が御史中丞へ移行され、刺史が行政官となったという見方もあるが、後漢末期に刺史に軍事権が認められると、広域行政単位としての州はにわかに現実化したとみる見方もある。\n" + " 13. ^ このころの州を行政単位ではなく、軍管区のような概念上の管理単位であるとする見方も強い。\n" + " 14. ^ 北周の宇文護が創始した二十四軍制をもっていわゆる府兵制の成立と見做す見方があるがこれについては詳しいことはわからない。\n" + " 15. ^ 折衝府の置かれた州と非設置州では当然差異があったのであるが、唐代はほかに募兵に基づく行軍制度もおこなわれており、大規模な対外戦争の際にはおもに折衝府非設置州を中心として兵が集められた。唐後期にはこの募兵制が常態化することで節度使制度がおこなわれるようになった。\n" + " 16. ^ なお、史書からうかがえる外交記録と日本国内での銅鏡など出土品に記載された年号の問題などから、日本の古代王朝は特に南朝との外交関係を重視していたという見方が主流であるが、北朝との通交事実を明らかにしようという研究は続けられている。\n" + " 17. ^ これは都護府を通じて服属民族を部族別に自治権を与えて間接支配するもので、羈縻政策がおこなわれた地域では現地民の国家は否定された。このことは羈縻州の住民が自発的に中国王朝の文化を受け入れることを阻害したと考えられており、羈縻政策のおこなわれた地域では冊封のおこなわれた地域とは異なり、漢字や律令などの文化の共有はおこなわれず、唐の支配が後退すると、唐の文化もこの地域では衰退することになった。冊封された国々で唐の支配が後退したあとも漢字文化が存続したことと対照的である。\n"; var korean = "한국의 역사\n" + "위키백과 ― 우리 모두의 백과사전.\n" + " 이 문서는 남, 북으로 분단된 1945년 이전의 한국에 대한 역사를 주로 기술하고 있다.\n" + "\n" + "한국의 역사 (연표)\n" + "한국의 선사 시대 (유적)\n" + "환인 · 환웅 (신시)\n" + "  고조선 - 단군\n" + "진국\n" + "원\n" + "삼\n" + "국\n" + "|\n" + "삼\n" + "국\n" + "|\n" + "남\n" + "북\n" + "국\n" + "|\n" + "후\n" + "삼\n" + "국 삼한 옥\n" + "저 동\n" + "예 부\n" + "여\n" + "진\n" + "한 변\n" + "한 마\n" + "한\n" + "  가\n" + "야  \n" + " \n" + "백\n" + "제\n" + " \n" + "  고\n" + "구\n" + "려    \n" + "신\n" + "라    \n" + "   \n" + "후\n" + "백\n" + "제 태\n" + "봉 발\n" + "해\n" + " \n" + "고려\n" + " \n" + " \n" + "조선\n" + " \n" + "대한제국\n" + "대한민국임시정부\n" + "일제 강점기 (조선총독부)\n" + "군정기\n" + "대한민국 조선민주주의\n" + "인민공화국\n" + "한국의 인물\n" + "한국의 역사는 구석기 시대 이후의 주로 한반도와 만주, 넓게는 동아시아 지역을 배경으로 발전되어 온 한국인의 역사이다.\n" + "목차 [숨기기]\n" + "1 선사 시대\n" + "1.1 유적에 의한 구분\n" + "1.2 문헌에 의한 구분\n" + "2 상고 시대 (B.C. 2333년 ~ A.D. 1세기)\n" + "2.1 고조선 시대\n" + "2.2 고조선 멸망 이후 여러나라의 성장\n" + "3 고대 시대 (A.D. 1세기~A.D. 900)\n" + "3.1 삼국시대\n" + "3.1.1 삼국시대 경제\n" + "3.1.2 삼국시대 정치\n" + "3.2 남북국시대\n" + "4 중세시대 (A.D. 918년 ~ A.D. 1392년)\n" + "4.1 고려의 정치\n" + "4.2 고려의 경제\n" + "4.3 고려의 사회\n" + "4.4 고려의 문화\n" + "5 근세시대 (A.D. 1392년 ~ A.D. 1506년)\n" + "5.1 초기 조선의 정치\n" + "5.2 초기 조선의 경제\n" + "5.3 초기 조선의 사회\n" + "5.4 초기 조선의 문화\n" + "6 근대 태동기 (A.D. 1506년 ~ A.D. 1907년)\n" + "6.1 후기 조선의 정치\n" + "6.2 후기 조선의 경제\n" + "6.3 후기 조선의 사회\n" + "6.4 후기 조선의 문화\n" + "7 근현대시대 (A.D. 1907년 ~ )\n" + "7.1 개괄\n" + "7.2 근대시대\n" + "7.3 현대시대\n" + "8 주석\n" + "9 같이 보기\n" + "10 참고문헌 및 링크\n" + "10.1 역사 일반\n" + "10.2 재단, 기타, 정부 기관\n" + "[편집]\n" + "선사 시대\n" + "\n" + "[편집]\n" + "유적에 의한 구분\n" + "한국의 구석기 시대(20만 년 이전 ~ 약 1만 년 전)\n" + "한국의 신석기 시대(약 1만 년 전 ~ 약 4천 년 전)\n" + "참고>> 웅기 부포리와 평양 만달리 유적, 통영 상노대도의 조개더미 최하층, 거창 임불리, 홍천 화화계리 유적 등을 중석기 유적지로 보는 사학자도 있다.\n" + "[편집]\n" + "문헌에 의한 구분\n" + "환국시대 [1](비공식)\n" + "신시[2] 또는 배달국 시대 [3](비공식)\n" + "[편집]\n" + "상고 시대 (B.C. 2333년 ~ A.D. 1세기)\n" + "\n" + "농경의 발달로 잉여 생산물이 생기고 청동기가 사용되면서 사유 재산 제도와 계급이 발생하였고, 그 결과, 부와 권력을 가진 족장(군장)이 출현하였다고 추측된다. 이 시기의 대표적인 유적으로 고인돌, 비파형 동검, 미송리식 토기 등이 있다. 부족장은 세력을 키워 주변 지역을 아우르고, 마침내 국가를 이룩하였다. 이 시기에 성립된 한국 최초의 국가가 고조선이다. 기원전 4세기경 철기가 보급되었고, 이후, 고조선은 철기 문화를 수용하면서 중국과 대립할 정도로 크게 발전하였으며, 만주와 한반도 각지에는 부여, 고구려, 옥저, 동예, 삼한 등 여러 나라가 성립될 수 있는 터전이 마련되었다.\n" + "[편집]\n" + "고조선 시대\n" + "단군조선\n" + "위만조선\n" + "조선 시대 이전에는 은나라에서 건너온 기자가 세운 기자조선이 정식 역사로서 인정되었으나, 일제강점기를 전후로 점차 부인되어 현재에는 대한민국과 조선민주주의인민공화국의 역사학계 모두 이를 공식적으로 인정하지 않고 있으며, 사학자들도 대체적으로 이 설을 부정한다.\n" + "[편집]\n" + "고조선 멸망 이후 여러나라의 성장\n" + "철기문명을 받아들인 각 나라들은 철기를 이용하여 농업을 발전시키면서도 독특한 사회 풍습을 유지하였다. 많은 소국들이 경쟁하는 가운데 일부는 다른 나라를 병합되었고, 다시 연맹 왕국으로 발전하여 중앙 집권 국가를 형성할 수 있는 기반을 마련하게 되었다.\n" + "부여: 북부여, 동부여, 졸본부여\n" + "옥저\n" + "동예\n" + "삼한:\n" + "마한\n" + "변한\n" + "진한\n" + "[편집]\n" + "고대 시대 (A.D. 1세기~A.D. 900)\n" + "\n" + "[편집]\n" + "삼국시대\n" + "고구려\n" + "백제\n" + "신라\n" + "삼국시대 초반은 고구려와 백제가 주도했으나 진흥왕 이후 국력이 막강해진 신라가 삼국시대 후기를 주도 했다.\n" + "[편집]\n" + "삼국시대 경제\n" + "삼국의 경제는 기본적으로 물물교환 경제를 못 벗어난 체제였다고 한다.[출처 필요]\n" + "삼국사기에는 신라가 수도에 시전을 세웠다는 기록이 있다.\n" + "[편집]\n" + "삼국시대 정치\n" + "삼국의 정치는 기본적으로 중앙집권체제를 토대로 한 전제왕권 또는 귀족정치였다.\n" + "[편집]\n" + "남북국시대\n" + "신라\n" + "발해\n" + "[편집]\n" + "중세시대 (A.D. 918년 ~ A.D. 1392년)\n" + "\n" + "한국사에서는 고려시대를 중세시대로 보고 있다.\n" + "[편집]\n" + "고려의 정치\n" + "고려는 새로운 통일 왕조로서 커다란 역사적 의의를 지닌다. 고려의 성립은 고대 사회에서 중세 사회로 이행하는 우리 역사의 내재적 발전을 의미한다. 신라말의 득난(6두품 세력) 출신 지식인과 호족 출신을 중심으로 성립한 고려는 골품 위주의 신라 사회보다 개방적이었고, 통치 체제도 과거제를 실시하는 등 효율성과 합리성이 강화되는 방향으로 정비되었다. 특히, 사상적으로 유교 정치 이념을 수용하여 고대적 성격을 벗어날 수 있었다.\n" + "고려 시대는 외적의 침입이 유달리 많았던 시기였다. 그러나 고려는 줄기찬 항쟁으로 이를 극복할 수 있었다. 12세기 후반에 무신들이 일으킨 무신정변은 종전의 문신 귀족 중심의 사회를 변화 시키는 계기가 되어 신분이 낮은 사람도 정치적으로 진출할 수 있었다.\n" + "이후, 무신 집권기와 원나라 간섭기를 지나 고려 후기에 이르러서는 새롭게 성장한 신진 사대부를 중심으로 성리학이 수용되어 합리적이고 민본적인 정치 이념이 성립되었고, 이에 따른 사회 개혁이 진전되었다.\n" + "[편집]\n" + "고려의 경제\n" + "고려는 후삼국 시기의 혼란을 극복하고 전시과 제도를 만드는 등 토지 제도를 정비하여 통치 체제의 토대를 확립하였다. 또, 수취 체제를 정비하면서 토지와 인구를 파악하기 위하여 양전 사업을 실시하고 호적을 작성하였다. 아울러 국가가 주도하여 산업을 재편하면서 경작지를 확대시키고, 상업과 수공업의 체제를 확립하여 안정된 경제 기반을 확보하였다.\n" + "농업에서는 기술의 발달로 농업 생산력이 증대되었고, 상업은 시전을 중심으로 도시 상업이 발달하면서 점차 지방에서도 상업 활동이 증가하였다. 수공업도 관청 수공업 중심에서 점차 사원이나 농민을 중심으로한 민간 수공업을 중심으로 발전해 갔다.\n" + "[편집]\n" + "고려의 사회\n" + "고려의 사회 신분은 귀족, 중류층, 양민, 천민으로 구성되었다. 고려 지배층의 핵심은 귀족이었다. 신분은 세습되는 것이 원칙이었고, 각 신분에는 그에 따른 역이 부과되었다. 그러나 그렇지 않은 경우도 있었는데, 향리로부터 문반직에 오르는 경우와 군인이 군공을 쌓아 무반으로 출세하는 경우를 들 수 있다.\n" + "백성의 대부분을 이루는 양민은 군현에 거주하는 농민으로, 조세, 공납, 역을 부담하였다. 향, 부곡, 소 같은 특수 행정 구역에 거주하는 백성은 조세 부담에 있어서 군현민보다 차별받았으나, 고려 후기 이후 특수 행정 구역은 일반 군현으로 바뀌어 갔다. 흉년이나 재해 등으로 어려움을 겪는 백성들의 생활을 안정시키기 위하여 국가는 의창과 상평창을 설치하고, 여러 가지 사회 복지 시책을 실시 하였다.\n" + "[편집]\n" + "고려의 문화\n" + "고려 시대에 해당하는 중세 문화는 고대 문화의 기반 위에서 조상들의 노력과 슬기가 보태져 새로운 양상을 보였다.\n" + "유교가 정치 이념으로 채택, 적용됨으로써 유교에 대한 인식이 확대 되었으며, 후기에는 성리학도 전래 되었다. 불교는 그 저변이 확대되어 생활 전반에 영향을 끼쳤다. 이런 가운데 불교 사상이 심화되고, 교종과 선종의 통합운동이 꾸준히 추진되었다.\n" + "중세의 예술은 귀족 중심의 우아하고 세련된 특징을 드러내고 있다. 건축과 조각에서는 고대의 성격을 벗어나 중세적 양식을 창출하였으며, 청자와 인쇄술은 세계적인 수준을 자랑하고 있다. 그림과 문학에서도 중세의 품격 높은 멋을 찾아 볼 수 있다.\n" + "[편집]\n" + "근세시대 (A.D. 1392년 ~ A.D. 1506년)\n" + "\n" + "한국사에서는 초기 조선 시대를 근세시대로 보고 있다.\n" + "[편집]\n" + "초기 조선의 정치\n" + "조선은 왕과 양반 관료들에 의하여 통치되었다. 왕은 최고 명령권자로서 통치 체제의 중심이었다. 조선 초기에는 고려 말에 성리학을 정치 이념으로 하면서 지방에서 성장한 신진 사대부들이 지배층이 되어 정국을 이끌어 나갔다. 그러나 15세기 말부터 새롭게 성장한 사림이 16세기 후반 이후 정국을 주도해 나가면서 학파를 중심으로 사림이 분열하여 붕당을 이루었다. 이후 여러 붕당 사이에 서로 비판하며 견제하는 붕당 정치를 전개하였다.\n" + "정치 구조는 권력의 집중을 방지하면서 행정의 효율성을 높이는 방향으로 정비되었다. 관리 등용에 혈연이나 지연보다 능력을 중시하였고, 언로를 개방하여 독점적인 권력 행사를 견제하였다. 아울러 육조를 중심으로 행정을 분담하여 효율성을 높이면서 정책의 협의나 집행 과정에서 유기적인 연결이 가능하도록 하였다. 조선은 고려에 비하여 한 단계 발전된 모습을 보여 주면서 중세 사회에서 벗어나 근세 사회로 나아갔다.\n" + "[편집]\n" + "초기 조선의 경제\n" + "조선은 고려 말기의 파탄된 국가 재정과 민생 문제를 해결하고 재정 확충과 민생 안정을 위한 방안으로 농본주의 경제 정책을 내세웠다. 특히 애민사상을 주장하는 왕도 정치 사상에서 민생 안정은 가장 먼저 해결해야 할 과제였다.\n" + "조선 건국을 주도하였던 신진 사대부들은 중농 정책을 표방하면서 농경지를 확대하고 농업 생산력을 증가시키며, 농민의 조세 부담을 줄여 농민들의 생활을 안정시키려 하였다. 그리하여 건국 초부터 토지 개간을 장려하고 양전 사업을 실시한 결과 고려 말 50여만 결이었던 경지 면적이 15세기 중엽에는 160여만 결로 증가하였다. 또한 농업 생산력을 향상시키기 위하여 새로운 농업 기술과 농기구를 개발하여 민간에 널리 보급하였다.\n" + "반면 상공업자가 허가 없이 마음대로 영업 활동을 벌이는 것을 규제하였는데, 이는 당시 검약한 생활을 강조하는 유교적인 경제관을 가진 사대부들이 물화의 수량과 종류를 정부가 통제하지 않고 자유 활동에 맡겨 두면 사치와 낭비가 조장되며 농업이 피폐하여 빈부의 격차가 커지게 된다고 생각하였기 때문이다. 더욱이 당시 사회에서는 직업적인 차별이 있어 상공업자들이 제대로 대우받지 못하였다.\n" + "[편집]\n" + "초기 조선의 사회\n" + "조선은 사회 신분을 양인과 천민으로 구분하는 양천 제도를 법제화하였다. 양인은 과거에 응시하고 벼슬길에 오를 수 있는 자유민으로서 조세, 국역 등의 의무를 지녔다. 천민은 비(非)자유민으로서 개인이나 국가에 소속되어 천역을 담당하였다.\n" + "양천 제도는 갑오개혁 이전까지 조선 사회를 지탱해 온 기본적인 신분 제도였다. 그러나 실제로는 양천 제도의 원칙에만 입각하여 운영되지는 않았다. 세월이 흐를수록 관직을 가진 사람을 의미하던 양반은 하나의 신분으로 굳어져 갔고, 양반 관료들을 보좌하던 중인도 신분층으로 정착되어 갔다. 그리하여 지배층인 양반과 피지배층인 상민 간의 차별을 두는 반상 제도가 일반화되고 양반, 중인, 상민, 천민의 신분 제도가 점차 정착되었다.\n" + "조선 시대는 엄격한 신분제 사회였으나 신분 이동이 가능하였다. 법적으로 양인 이상이면 누구나 과거에 응시하여 관직에 오를 수 있었고, 양반도 죄를 지으면 노비가 되거나 경제적으로 몰락하여 중인이나 상민이 되기도 하였다.\n" + "[편집]\n" + "초기 조선의 문화\n" + "조선 초기에는 괄목할 만한 민족적이면서 실용적인 성격의 학문이 발달하여 다른 시기보다 민족 문화의 발전이 크게 이루어졌다. 당시의 집권층은 민생 안정과 부국강병을 위하여 과학 기술과 실용적 학문을 중시하여, 한글이 창제되고 역사책을 비롯한 각 분야의 서적들이 출반되는 등 민족 문화 발전의 기반이 형성되었다.\n" + "성리학이 정착, 발달하여 전 사회에 큰 영향을 끼쳤고, 여러 갈래의 학파가 나타났다. 15세기 문화를 주도한 관학파 계열의 관료들과 학자들은 성리학을 지도 이념으로 내세웠으나 성리학 이외의 학문과 사상이라도 좋은 점이 있으면 받아들이는 융통성을 보였다. 불교는 정부에 의하여 정비되면서 위축되었으나 민간에서는 여전히 신앙의 대상으로 자리 잡고 있었다.\n" + "천문학, 의학 등 과학 기술에 있어서도 큰 발전을 이룩하여 생활에 응용되었고, 농업 기술은 크게 향상되어 농업 생산력을 증대시켰다.\n" + "예술 분야에서도 민족적 특색이 돋보이는 발전을 나타내었고, 사대부들의 검소하고 소박한 생활이 반영된 그림과 필체 및 자기 공예가 두드러졌다.\n" + "[편집]\n" + "근대 태동기 (A.D. 1506년 ~ A.D. 1907년)\n" + "\n" + "한국사에서는 후기 조선 시대를 근대 태동기로 보고 있다.\n" + "[편집]\n" + "후기 조선의 정치\n" + "숙종 때에 이르러 붕당 정치가 변질되고 그 폐단이 심화되면서 특정 붕당이 정권을 독점하는 일당 전제화의 추세가 대두되었다. 붕당 정치가 변질되자 정치 집단 간의 세력 균형이 무너지고 왕권 자체도 불안하게 되었다. 이에 영조와 정조는 특정 붕당의 권력 장악을 견제하기 위하여 탕평 정치를 추진하였다. 탕평 정치는 특정 권력 집단을 억제하고 왕권을 강화하려는 방향으로 진행되어 어느 정도 성과를 거두었지만, 붕당 정치의 폐단을 일소하지는 못하였다.\n" + "탕평 정치로 강화된 왕권을 순조 이후의 왕들이 제대로 행사하지 못하면서 왕실의 외척을 중심으로 한 소수 가문에 권력이 집중되고 정치 기강이 문란해지는 세도 정치가 전개되었다. 이로써 부정부패가 만연해지고 정부의 백성들에 대한 수탈이 심해졌다.\n" + "[편집]\n" + "후기 조선의 경제\n" + "임진왜란과 병자호란을 거치면서 농촌 사회는 심각하게 파괴되었다. 수많은 농민들이 전란 중에 죽거나 피난을 가고 경작지는 황폐화되었다. 이에 정부는 수취 체제를 개편하여 농촌 사회를 안정시키고 재정 기반을 확대하려 하였다. 그것은 전세 제도, 공납 제도, 군역 제도의 개편으로 나타났다.\n" + "서민들은 생산력을 높이기 위하여 농기구와 시비법을 개량하는 등 새로운 영농 방법을 추구하였고, 상품 작물을 재배하여 소득을 늘리려 하였다. 상인들도 상업 활동에 적극적으로 참여하여 대자본을 가진 상인들도 출현하였다. 수공업 생산도 활발해져 민간에서 생산 활동을 주도하여 갔다. 이러한 과정에서 자본 축적이 이루어지고, 지방의 상공업 활동이 활기를 띠었으며, 상업 도시가 출현하기에 이르렀다.\n" + "[편집]\n" + "후기 조선의 사회\n" + "조선 후기 사회는 사회 경제적 변화로 인하여 신분 변동이 활발해져 양반 중심의 신분 체제가 크게 흔들렸다. 붕당 정치가 날이 갈수록 변질되어 가면서 양반 상호 간에 일어난 정치적 갈등은 양반층의 분화을 불러왔다. 이러한 현상은 일당 전제화가 전개되면서 더욱 두드러지고 권력을 장악한 소수의 양반을 제외한 다수의 양반들이 몰락하는 계기가 되었다. 이렇게 양반 계층의 도태 현상이 날로 심화되어 가면서도 양반의 수는 늘어나고 상민과 노비의 숫자는 줄어드는 경향을 보였다. 이는 부를 축적한 농민들이나 해방된 노비들이 자신들의 지위를 높이기 위하여 또는 역의 부담을 모면하기 위하여 양반 신분을 사는 경우가 많았기 때문이다.\n" + "이러한 급격한 사회 변화에 대한 집권층의 자세는 극히 보수적이고 임기응변적이었다. 이에 계층 간의 갈등은 더욱 심화되어 갔으며, 19세기에 들어와 평등 사상과 내세 신앙을 주장한 로마 가톨릭이 유포되면서 백성들의 의식이 점차 높아져서[출처 필요] 크고 작은 봉기가 전국적으로 일어나게 되었다. 정부는 로마 가톨릭이 점차 교세가 확장되자 양반 중심의 신분 질서 부정과 왕권에 대한 도전으로 받아들여[출처 필요] 사교로 규정하고 탄압을 가하기에 이르렀다.\n" + "[편집]\n" + "후기 조선의 문화\n" + "임진왜란과 병자호란 이후 사회 각 분야의 변화와 함께 문화에서는 새로운 기운이 나타났다. 양반층 뿐만 아니라 중인층과 서민층도 문화의 한 주역으로 등장하면서 문화의 질적 변화와 함께 문화의 폭이 확대되었다.\n" + "학문에서는 성리학의 교조화와 형식화를 비판하며 실천성을 강조한 양명학을 받아들였으며 민생 안정과 부국강병을 목표로 하여 비판적이면서 실증적인 논리로 사회 개혁론을 제시한 실학이 대두되어 개혁 추진을 주장하기도 하였다.\n" + "천문학의 의학 등 각 분야의 기술적 성과들이 농업과 상업 등 산업 발전을 촉진하였다. 서양 문물의 유입도 이러한 발전을 가속화하는 데 이바지하였다.\n" + "예술 분야에서는 판소리, 탈품, 서민 음악 등 서민 문화가 크게 유행하였고, 백자 등 공예도 생활 공예가 중심이 되었다. 자연 경치와 삶을 소재로 하는 문예 풍토가 진작되어 문학과 서화에 큰 영향을 끼쳤다.\n" + "[편집]\n" + "근현대시대 (A.D. 1907년 ~ )\n" + "\n" + "[편집]\n" + "개괄\n" + "조선 사회는 안에서 성장하고 있던 근대적인 요소를 충분히 발전시키지 못한 채 19C 후반 제국주의 열강에 문호를 개방하였다. 이후 정부와 각계(各界), 각당(各堂), 각단체(各單體), 각층(各層), 각파(各派)에서는 근대화하려는 노력을 하였으나, 성공하지 못하였다.\n" + "개항 이후 조선은 서구 문물을 수용하고 새로운 경제 정책을 펼치면서 자주적인 근대화를 모색하였다. 그러나 일본과 청을 비롯한 외세의 경제 침략이 본격화 되면서, 이러한 노력은 큰 성과를 거두지 못했다.\n" + "개항 이후, 사회 개혁이 진행되면서 신분 제도가 폐지되고 평등 의식도 점차 성장하였다. 또, 외국과의 교류를 통해 외래 문물과 제도 등이 수용됨에 따라 전통적인 생활 모습에도 많은 변화가 생겨났다.\n" + "개항 이후 서양 과학 기술에 대한 관심이 높아지자, 전기, 철도, 같은 근대 기술과 서양 의술 등 각종 근대 문물이 들어왔다. 근대 시설은 일상생활을 편리하게 해 주었으나, 열강의 침략 목적에 이용되기도 하였다.\n" + "일제는 강압적인 식민 통치를 통하여 우리 민족을 지배하였다. 이에 맞서 우리 민족은 국내외에서 무장 독립 투쟁, 민족 실력 양성 운동, 독립 외교 활동 등을 벌여 일제에 줄기차게 저항하였다. 이러한 우리 민족의 투쟁과 연합군의 승리로 1945년 8월에 광복을 맞이하였다.\n" + "일제 강점기에는 일제의 경제적 침략으로 경제 발전이 왜곡되어, 우리 민족은 고통을 겪게 되었다. 광복 이후 일제의 식민 지배를 벗어나면서부터는 새로운 경제 발전의 계기를 마련할 수 있었다. 그러나 분단과 전쟁으로 인한 경제적 어려움도 대단히 컸다.\n" + "일제 강점기에는 국권을 되찾으려는 독립 운동이 줄기차게 일어났고, 다른 한편에서는 근대화를 위한 각계(各界), 각당(各堂), 각단체(各單體), 각층(各層), 각파(各派)에서는 근대화하려는 노력이 펼쳐졌다. 이러한 가운데 근대 자본주의 문명이 본격적으로 유입되어 전통 사회는 점차 근대 사회로 변모해 갔는데, 식민지 현실 아래에서 근대화는 왜곡될 수밖에 없었다.\n" + "일제는 국권을 탈취한 후에 동화와 차별의 이중 정책을 바탕으로 황국 신민화를 강력하게 추진하였다. 특히, 우리 민족의 독립 의지를 꺾으려고 우리의 역사와 문화를 왜곡하였다. 이에 맞서 우리의 전통과 문화를 지키려는 움직임이 일어났다.\n" + "그런데, 미∙소의 한반도 분할 정책과 좌∙우익 세력의 갈등으로 남북이 분단되어 통일 국가를 세우지 못하였다. 특히, 6∙25 전쟁을 겪으면서 분단은 더욱 고착화되고 남북 사이의 상호 불신이 깊어 갔다.\n" + "대한민국 정부 수립 이후, 민주주의가 정착되는 과정에서 많은 시련을 겪었다. 그러나 4∙19혁명과 5∙18민주화 운동, 6월 민주 항쟁 등으로 민주주의가 점차 발전하였다. 이와 함께, 냉전 체제가 해체되면서 민족 통일을 위한 노력도 계속 되고 있다.\n" + "1960년대 이후 한국 경제는 비약적인 성장을 일구어 냈다. 한국은 이제 가난한 농업 국가가 아닌, 세계적인 경제 대국으로 변모하고 있다.\n" + "광복 후에 한국은 많은 어려움 속에서도 경제 발전을 이룩하였는데, 이는 커다란 사회 변화를 가져왔다. 농업 사회에서 산업 사회로, 다시 정보화 사회로 발전하면서 사람들의 생활양식과 가치관도 많이 변하였다.1980년대에 진행된 민주화 운동으로 권위주의적 정치 문화가 점차 극복되고, 사회의 민주화도 꾸준히 이루어 졌다.\n" + "광복 이후에는 학문 활동이 활발해지고 교육의 기회가 크게 확대되었다. 그러나 미국을 비롯한 서구 문화가 급속하게 유입되면서 가치관의 혼란과 전통문화의 위축 현상을 가져오기도 하였다.\n" + "민주화와 더불어 문화의 다양화가 촉진되고, 반도체 등 몇몇 과학 기술 분야는 세계적인 수준까지 도달하였다. 한편, 현대 사회의 윤리와 생명 과학 기술의 발달 사이에서 빚어지는 갈등을 해소하려는 노력도 펼쳐지고 있다.\n" + "[편집]\n" + "근대시대\n" + "대한 제국\n" + "일제강점기 : 일본의 제국주의 세력이 한반도를 강제적으로 식민지로 삼은 시기로서, 무단 통치 시기, 문화 통치 시기, 전시 체계 시기로 나뉜다.\n" + "무단 통치 시기 : 조선을 영구히 통치하기 위해 조선 총독부를 설치하고, 군대를 파견하여 의병 활동을 억누르고 국내의 저항 세력을 무단으로 통치한 시기이다. 언론, 집회, 출판, 결사의 자유같은 기본권을 박탈하고, 독립운동을 무자비하게 탄압하였다. 또, 헌병 경찰과 헌병 보조원을 전국에 배치하고 즉결 처분권을 부여하여 한국인을 태형에 처하기도 했다. 토지조사령을 공포하여 식민지 수탈을 시작하였고, 회사령을 공포하여 국내의 자본 세력을 억압하고 일본 자본 세력의 편의를 봐주었다. 이 시기의 한국인 노동자는 극악한 환경과 저임금, 민족적 차별까지 받으며 혹사 하였다.\n" + "문화 통치 시기 : 3·1 운동이 발발하자 일제는 무단통치로는 조선을 효과적으로 지배할 수 없다는 판단하에, 친일파를 육성하는 문화정책을 펼친다. 이 문화정치는 가혹한 식민 통치를 은폐하려는 술책에 불과 했다. 헌병 경찰제를 보통 경찰제로 전환하였지만, 경찰력은 오히려 증강되었다. 이 들은 교육의 기회를 늘리고 자본 운용의 기회와 참정권의 기회등을 제공하겠다고 선전 하였으나 소수의 친일 분자를 육성하고, 민족 운동가들을 회유하여 민족을 기만하고 분열을 획책하였다.\n" + "전시 체계 시기 : 1930년대 일제는 대륙침략을 본격적으로 시작하면서 한반도를 대륙 침략의 병참기지로 삼았다. 또한, 1941년 일제가 미국의 진주만을 불법적으로 기습하자 태평양 전쟁이 발발하였다. 조선에서는 일제의 강제 징용으로 한국인 노동력이 착취 되었고, 학도 지원병 제도, 징병 제도 등을 실시하여 수많은 젊은이를 전쟁에 동원하였다. 또, 젊은 여성을 정신대라는 이름으로 강제 동원하여 군수 공장 등에서 혹사시켰으며, 그 중 일부는 전선으로 끌고 가 일본군 위안부로 삼는 만행을 저질렀다.\n" + "[편집]\n" + "현대시대\n" + "군정기 : 미국과 소련의 군대가 진주하여 한반도에 정부가 세워지기 이전까지의 시기\n" + "대한민국\n" + "제1공화국\n" + "한국전쟁\n" + "제2공화국\n" + "제3공화국\n" + "제4공화국 - 유신헌법시기. 종신 대통령제 채택\n" + "제5공화국\n" + "1. 정치 : 전두환 정부(군사 쿠데타에 의한 정부 - 12.12 사태) 시기. 대통령 간접선거제도 채택. 이 시기에는 민주화에 대한 무자비한 탄압이 자행되었으나, 광범위한 대중들의 1987년 6월 혁명으로 6월29선언(대통령 직접선거제도 공약)을 이끌어 내기도 하였다.\n" + "2. 경제 : 1960~70년대에 닦아온 중공업, 경공업 기반을 첨단공업 수준으로 이끌어 올린 시기이다. 이 시기의 한국 경제는 세계에서 유래 없을 정도로 빠르게 성장했으며, 국내 물가가 가장 안정된 시기였다.\n" + "3. 문화 : 1986년 서울 아시안 게임을 개최하였고, 1988년 서울 올림픽 게임을 유치하는 데 성공했다.\n" + "제6공화국\n" + "노태우 정권\n" + "문민정부\n" + "국민의 정부\n" + "참여정부\n" + "조선민주주의인민공화국\n" + "조선민주주의인민공화국의 역사\n" + "[편집]\n" + "주석\n" + "\n" + "↑ 삼국유사 - 동경제국대학 1904년 판본, 환단고기 - 1979년 복원본\n" + "↑ 동사 - 허목 숙종조, 규원사화 - 북애자 숙종원년\n" + "↑ 환단고기 - 1979년 복원본\n" + "[편집]\n" + "같이 보기\n" + "\n" + "중국의 역사\n" + "일본의 역사\n" + "민족사관\n" + "식민사관\n" + "[편집]\n" + "참고문헌 및 링크\n" + "\n" + "[편집]\n" + "역사 일반\n" + "국사 편찬 위원회 : 한국사에 관한 정보를 수집, 정리, 편찬하는 국가 연구 기관, 소장 자료, 논문, 저서 검색, 한국사 관련 연구 기관. 소장 자료, 논문, 저서 검색, 한국사 관련 안내\n" + "국사 전자 교과서 : 현직 교사들이 연구.감수하고, 국사편찬위원회가 지원하였다. 2007년 개정된 국사교과서의 내용이 아직 반영되지 않았다.\n" + "한국 역사 정보 시스템 : 한국사 연표, 한국사 기초 사전 및 신문 자료, 문헌 자료, 문집 등을 제공\n" + "한국학 중앙 연구원 : 한국 문화 및 한국학 여러 분햐에 관한 연구와 교육을 수행하는 연구 기관. 디지털 한국학 개발, 정보 광장, 전자 도서관, 전통 문화 등 수록\n" + "역사 문제 연구소 : 순수 민간 연구 단체(역사적 중립성이 의심됨), 근현대사 자료실, 간행물 자료, 한국사 학습 자료 등 수록\n" + "[편집]\n" + "재단, 기타, 정부 기관\n" + "고구려 연구재단 : 고구려사를 비롯한 중국의 역사 왜곡에 학술적으로 대응하기 위하여 2004年 설립된 법인. 고구려, 발해를 비롯한 동아시아 역사 관련 자료의 조사, 수집, 정리, 정보화 자료 제공. 동북아역사재단으로 편입되어 더이상 유용하지 않다.\n" + "국가 기록 영상관 : 대한 뉴스, 문화 기록 영화, 대통령 기록 영상 등 멀티미디어 역사 자료 제공\n" + "국가 문화 유산 종합 정보 서비스 : 국보, 보물, 사적, 명승, 천연 기념물 지정 종목별, 시대별, 지역별, 유형별, 유물 정보, 검색 서비스 제공\n" + "국가 지식 정보 통합 검색 시스템 : 정보 통신부 제공, 과학 기술, 정보 통신, 교육, 학술, 문화, 역사 등의 포괄적이고 연동적인 학술 데이터 검색\n" + "국가기록유산 : 국가적 기록유산의 원본과 원문 열람 서비스 제공\n"; var persian = "تاریخ ایران پیش از اسلام\n" + "از ویکی‌پدیا، دانشنامهٔ آزاد.\n" + "تمدنهای باستانی آسیای غربی\n" + "بین‌النهرین، سومر، اکد، آشور، بابل\n" + "هیتی‌ها، لیدیه\n" + "ایلام، اورارتو، ماننا، ماد، هخامنشی\n" + "امپراتوری‌ها / شهرها\n" + "سومر: اوروک – اور – اریدو\n" + "کیش – لاگاش – نیپور – اکد\n" + "بابل – ایسین – کلدانی\n" + "آشور: آسور، نینوا، نوزی، نمرود\n" + "ایلامیان – اموری‌ها – شوش\n" + "هوری‌ها – میتانی\n" + "کاسی‌ها – اورارتو\n" + "گاهشماری\n" + "شاهان سومر\n" + "شاهان ایلام\n" + "شاهان آشور\n" + "شاهان بابل\n" + "شاهان ماد\n" + "شاهان هخامنشی\n" + "زبان\n" + "خط میخی\n" + "سومری – اکدی\n" + "ایلامی – هوری\n" + "اساطیر بین‌النهرین\n" + "انوما الیش\n" + "گیل گمش – مردوخ\n" + "نیبیرو\n" + "اگر بخواهیم تاریخ ایران پیش از اسلام را بررسی ‌‌کنیم باید از مردمانی که در دوران نوسنگی در فلات ایران زندگی می‌‌کردند نام ببریم. پیش از مهاجرت آریائیان به فلات ایران، اقوامی با تمدن‌های متفاوت در ایران می‌زیستند که آثار زیادی از آنها در نقاط مختلف فلات ایران مانند تمدن جیرفت (در کرمانِ کنونی) و شهر سوخته در سیستان، و تمدن ساکنان تمدن تپه سیلک (در کاشان)، تمدن اورارتو و ماننا (در آذربایجان)، تپه گیان نهاوند و تمدن کاسی‌ها (در لرستان امروز) بجای مانده است. اما تمدن این اقوام کم کم با ورود آریائیان، در فرهنگ و تمدن آنها حل شد.\n" + "برای بررسی تاریخ ایران پیش از اسلام باید از دیگر تمدنهای باستانی آسیای غربی نیز نام ببریم. شناخت اوضاع و رابطه این مناطق ایران در رابطه با تمدن‌های دیگر نظیر سومر - اکد، کلده - بابل - آشور، و غیره نیز مهم است.\n" + "فهرست مندرجات [مخفی شود]\n" + "۱ ایلامیان\n" + "۲ مهاجرت آریائیان به ایران\n" + "۳ مادها\n" + "۴ هخامنشیان\n" + "۵ سلوکیان\n" + "۶ اشکانیان\n" + "۷ ساسانیان\n" + "۸ منابع\n" + "۹ جستارهای وابسته\n" + "۱۰ پیوند به بیرون\n" + "[ویرایش]\n" + "ایلامیان\n" + "\n" + "ایلامیان یا عیلامی‌ها اقوامی بودند که از هزاره سوم پ. م. تا هزاره نخست پ. م. ، بر بخش بزرگی از مناطق جنوب و غرب ایران فرمانروایی داشتند. بر حسب تقسیمات جغرافیای سیاسی امروز، ایلام باستان سرزمین‌های خوزستان، فارس، ایلام و بخش‌هایی از استان‌های بوشهر، کرمان، لرستان و کردستان را شامل می‌شد.\n" + "آثار كشف ‌شده تمدن ایلامیان، در شوش نمایانگر تمدن شهری قابل توجهی است. تمدن ایلامیان از راه شهر سوخته در سیستان، با تمدن پیرامون رود سند هند و از راه شوش با تمدن سومر مربوط می‌شده است. ایلامیان نخستین مخترعان خط در ایران هستند.\n" + "به قدرت رسیدن حكومت ایلامیان و قدرت یافتن سلسله عیلامی پادشاهی اوان در شمال دشت خوزستان مهم ‌ترین رویداد سیاسی ایران در هزاره سوم پ. م. است. پادشاهی اَوان یکی از دودمان‌های ایلامی باستان در جنوب غربی ایران بود. پادشاهی آوان پس از شکوه و قدرت کوتیک ـ این شوشینک همچون امپراتوری اکد، ناگهان فرو پاشید؛ این فروپاشی و هرج و مرج در منطقه در پی تاخت و تاز گوتیان زاگرس نشین رخ داد. تا پیش از ورود مادها و پارسها حدود یك هزار سال تاریخ سرزمین ایران منحصر به تاریخ عیلام است.\n" + "سرزمین اصلی عیلام در شمال دشت خوزستان بوده. فرهنگ و تمدن عیلامی از شرق رودخانه دجله تا شهر سوخته زابل و از ارتفاعات زاگرس مركزی تا بوشهر اثر گذار بوده است. عیلامیان نه سامی نژادند و نه آریایی آنان ساكنان اوليه دشت خوزستان هستند.\n" + "[ویرایش]\n" + "مهاجرت آریائیان به ایران\n" + "\n" + "آریائیان، مردمانی از نژاد هند و اروپایی بودند که در شمال فلات ایران می‌‌زیستند. دلیل اصلی مهاجرت آنها مشخص نیست اما به نظر می‌‌رسد دشوار شدن شرایط آب و هوایی و کمبود چراگاه ها، از دلایل آن باشد. مهاجرت آریائیان به فلات ایران یک مهاجرت تدریجی بوده است که در پایان دوران نوسنگی (7000 سال پیش از میلاد) آغاز شد و تا 4000 پیش از میلاد ادامه داشته است.\n" + "نخستین آریایی‌هایی که به ایران آمدند شامل کاسی‌ها (کانتوها ـ کاشی‌ها)، لولوبیان و گوتیان بودند. کا‌سی‌ها تمدنی را پایه گذاری کردند که امروزه ما آن را بنام تمدن تپه سیلک می‌‌شناسیم. لولوبیان و گوتیان نیز در زاگرس مرکزی اقامت گزیدند که بعدها با آمدن مادها بخشی از آنها شدند. در حدود 5000 سال پیش از میلاد، مهاجرت بزرگ آریائیان به ایران آغاز شد و سه گروه بزرگ آریایی به ایران آمدند و هر یک در قسمتی از ایران سکنی گزیدند: مادها در شمال غربی ایران، پارس‌ها در قسمت جنوبی و پارت‌ها در حدود خراسان امروزی.\n" + "شاخه‌های قومِ ایرانی در نیمه‌های هزاره‌ی اول قبل از مسیح عبارت بوده‌اند از: باختریان در باختریه (تاجیکستان و شمالشرق افغانستانِ کنونی)، سکاهای هوم‌کار در سگائیه (شرقِ ازبکستانِ کنونی)، سُغدیان در سغدیه (جنوب ازبکستان کنونی)، خوارزمیان در خوارزمیه (شمال ازبکستان و شمالشرق ترکمنستانِ کنونی)، مرغزیان در مرغوه یا مرو (جنوبغرب ازبکستان و شرق ترکمستان کنونی)، داهه در مرکز ترکمستان کنونی، هَرَیویان در هَرَیوَه یا هرات (غرب افغانستان کنونی)، دِرَنگِیان در درنگیانه یا سیستان (غرب افغانستان کنونی و شرق ایران کنونی)، مکائیان در مکائیه یا مَک‌کُران (بلوچستانِ ایران و پاکستان کنونی)، هیرکانیان در هیرکانیا یا گرگان (جنوبغربِ ترکمنستان کنونی و شمال ایرانِ کنونی)، پَرتُوَه‌ئیان در پارتیه (شمالشرق ایران کنونی)، تپوریان در تپوریه یا تپورستان (گیلان و مازندران کنونی)، آریازَنتا در اسپدانه در مرکزِ ایرانِ کنونی، سکاهای تیزخود در الانیه یا اران (آذربایجان مستقل کنونی)، آترپاتیگان در آذربایجان ایرانِ کنونی، مادایَه در ماد (غرب ایرانِ کنونی)، کُردوخ در کردستانِ (چهارپاره‌شده‌ی) کنونی، پارسَی در پارس و کرمانِ کنونی، انشان در لرستان و شمال خوزستان کنونی. قبایلی که در تاریخ با نامهای مانناها، لولوبیان‌ها، گوتیان‌ها، و کاسی‌ها شناسانده شده‌اند و در مناطق غربی ایران ساکن بوده‌اند تیره‌هائی از شاخه‌های قوم ایرانی بوده‌اند که زمانی برای خودشان اتحادیه‌های قبایلی و امیرنشین داشته‌اند، و سپس در پادشاهی ماد ادغام شده‌اند.\n" + "مادها در ایران نزدیک 150 سال (708- 550 ق.م) هخامنشی‌ها کمی بیش از دویست سال (550-330 ق.م) اسکندر و سلوکی‌ها در حدود صد سال (330 -250 ق.م) اشکانیان قریب پانصد سال (250 ق.م – 226 م) و ساسانیان قریب چهار صد و سی سال (226-651 م) فرمانروایی داشتند.\n" + "[ویرایش]\n" + "مادها\n" + "\n" + "\n" + "\n" + "ماد در 675 پیش از میلاد\n" + "\n" + "\n" + "ماد در 600 پیش از میلاد\n" + "مادها قومی ایرانی بودند از تبار آریایی که در بخش غربی فلات ایران ساکن شدند. سرزمین مادها دربرگیرنده بخش غربی فلات ایران بود. سرزمین آذربایجان در شمال غربی فلات ایران را با نام ماد کوچک و بقیهٔ ناحیه زاگرس را با نام ماد بزرگ می‌شناختند. پایتخت ماد هگمتانه است آنها توانستند در اوایل قرن هفتم قبل از میلاد اولین دولت ایرانی را تأسیس کنند\n" + "پس از حملات شدید و خونین آشوریان به مناطق مادنشین، گروهی از بزرگان ماد گرد رهبری به نام دیاکو جمع شدند.\n" + "از پادشاهان بزرگ این دودمان هووخشتره بود که با دولت بابل متحد شد و سرانجام امپراتوری آشور را منقرض کرد و پایه‌های نخستین شاهنشاهی آریایی‌تباران در ایران را بنیاد نهاد.\n" + "دولت ماد در ۵۵۰ پیش از میلاد به دست کوروش منقرض شد و سلطنت ایران به پارسی‌ها منتقل گشت. در زمان داریوش بزرگ، امپراتوری هخامنشی به منتهای بزرگی خود رسید: از هند تا دریای آدریاتیک و از دریای عمان تا کوه‌های قفقاز.\n" + "[ویرایش]\n" + "هخامنشیان\n" + "\n" + "\n" + "\n" + "شاهنشاهی بزرگ هخامنشی در 330 ق.م.\n" + "هخامنشیان نخست پادشاهان بومی پارس و سپس انشان بودند ولی با شکستی که کوروش بزرگ بزرگ بر ایشتوویگو واپسین پادشاه ماد وارد ساخت و سپس فتح لیدیه و بابل پادشاهی هخامنشیان تبدیل به شاهنشاهی بزرگی شد. از این رو کوروش بزرگ را بنیادگذار شاهنشاهی هخامنشی می‌دانند.\n" + "در ۵۲۹ پ.م کوروش بزرگ پایه گذار دولت هخامنشی در جنگ‌های شمال شرقی ایران با سکاها، کشته شد. لشکرکشی کمبوجیه جانشین او به مصر آخرین رمق کشاورزان و مردم مغلوب را کشید و زمینه را برای شورشی همگانی فراهم کرد. داریوش بزرگ در کتیبهً بیستون می‌‌گوید: \" بعد از رفتن او (کمبوجیه) به مصر مردم از او برگشتند...\"\n" + "شورش‌ها بزرگ شد و حتی پارس زادگاه شاهان هخامنشی را نیز در برگرفت. داریوش در کتیبه بیستون شمه‌ای از این قیام‌ها را در بند دوم چنین نقل می‌کند: \" زمانی که من در بابل بودم این ایالات از من برگشتند: پارس، خوزستان، ماد، آشور، مصر، پارت خراسان (مرو، گوش) افغانستان (مکائیه).\" داریوش از 9 مهر ماه 522 تا 19 اسفند 520 ق.م به سرکوبی این جنبش‌ها مشغول بود.\n" + "جنگ‌های ایران و یونان در زمان داریوش آغاز شد. دولت هخامنشی سر انجام در 330 ق. م به دست اسکندر مقدونی منقرض گشت و ایران به دست سپاهیان او افتاد.\n" + "اسکندر سلسله هخامنشیان را نابود کرد، دارا را کشت ولی در حرکت خود به شرق همه جا به مقاومت‌های سخت برخورد، از جمله سغد و باکتریا یکی از سرداران جنگی او بنام سپتامان 327- 329 ق. م در راس جنبش همگانی مردم بیش از دو سال علیه مهاجم خارجی مبارزه دلاورانه کرد. در این ناحیه مکرر مردم علیه ساتراپهای اسکندر قیام کردند. گرچه سرانجام نیروهای مجهز و ورزیده اسکندر این جنبش‌ها را سرکوب کردند ولی از این تاریخ اسکندر ناچار روش خشونت آمیز خود را به نرمش و خوشخویی بدل کرد.\n" + "\n" + "ایران\n" + "تاریخ ایران\n" + "ایران پیش از آریایی‌ها \n" + "تاریخ ایران پیش از اسلام \n" + " | دودمان‌ها و حکومت‌ها\n" + "ایلامیان\n" + "ماد\n" + "هخامنشیان\n" + "سلوکیان\n" + "اشکانیان\n" + "ساسانیان\n" + "تاریخ ایران پس از اسلام \n" + " | دودمان‌ها و حکومت‌ها\n" + "خلفای راشدین\n" + "امویان\n" + "عباسیان\n" + "ایران در دوران حکومت‌های محلی \n" + " | دودمان‌ها و حکومت‌ها\n" + "طاهریان\n" + "صفاریان\n" + "سامانیان\n" + "آل زیار\n" + "آل بویه\n" + "غزنویان\n" + "سلجوقیان\n" + "خوارزمشاهیان\n" + "ایران در دوره مغول \n" + " | دودمان‌ها و حکومت‌ها\n" + "ایلخانیان\n" + "ایران در دوران ملوک‌الطوایفی \n" + " | دودمان‌ها و حکومت‌ها\n" + "سربداران\n" + "تیموریان\n" + "مرعشیان\n" + "کیائیان\n" + "قراقویونلو\n" + "آق‌قویونلو\n" + "ایران در دوران حکومت‌های ملی \n" + " | دودمان‌ها و حکومت‌ها\n" + "صفوی\n" + "افشاریان\n" + "زند\n" + "قاجار\n" + "پهلوی\n" + "جمهوری اسلامی\n" + "موضوعی\n" + "تاریخ معاصر ایران\n" + "تاریخ مذاهب ایران\n" + "مهرپرستی\n" + "زرتشتی\n" + "تسنن\n" + "تصوف\n" + "تشیع\n" + "تاریخ اسلام\n" + "تاریخ زبان و ادبیات ایران\n" + "جغرافیای ایران\n" + "استان‌های تاریخی ایران\n" + "اقتصاد ایران\n" + "گاهشمار تاریخ ایران\n" + "پروژه ایران\n" + "[ویرایش]\n" + "سلوکیان\n" + "\n" + "\n" + "ایران در زمان سلوکیان (330 - 150 ق.م.)\n" + "پس از مرگ اسکندر (323 ق. م) فتوحاتش بین سردارانش تقسیم شد و بیشتر متصرفات آسیائی او که ایران هسته آن بود به سلوکوس اول رسید. به این ترتیب ایران تحت حکومت سلوکیان (330 - 150 ق.م.) در آمد. پس از مدتی پارت‌ها نفوذ خود را گسترش دادند و سرانجام توانستند سلوکیان را نابود و امپراتوری اشکانی را ایجاد کنند.\n" + "[ویرایش]\n" + "اشکانیان\n" + "\n" + "\n" + "\n" + "امپراتوری اشکانی 250 ق.م. 224 م.\n" + "اشکانیان (250 ق. م 224 م) که از تیره ایرانی پرنی و شاخه‌ای از طوایف وابسته به اتحادیه داهه از عشایر سکاهای حدود باختر بودند، از ایالت پارت که مشتمل بر خراسان فعلی بود برخاستند. نام سرزمین پارت در کتیبه‌های داریوش پرثوه آمده است که به زبان پارتی پهلوه می‌شود. چون پارتیان از اهل ایالت پهله بودند، از این جهت در نسبت به آن سرزمین ایشان را پهلوی نیز می‌‌توان خواند. ایالت پارتیها از مغرب به دامغان و سواحل جنوب شرقی دریای خزر و از شمال به ترکستان و از مشرق به رود تجن و از جنوب به کویر نمک و سیستان محدود می‌‌شد. قبایل پارتی در آغاز با قوم داهه که در مشرق دریای خزر می‌‌زیستند در یک جا سکونت داشتند و سپس از آنان جدا شده در ناحیه خراسان مسکن گزیدند.\n" + "این امپراتوری در دوره اقتدارش از رود فرات تا هندوکش و از کوه‌های قفقاز تا خلیج فارس توسعه یافت. در عهد اشکانی جنگ‌های ایران و روم آغاز شد. سلسله اشکانی در اثر اختلافات داخلی و جنگ‌های خارجی به تدریج ضعیف شد تا سر انجام به دست اردشیر اول ساسانی منقرض گردید.\n" + "[ویرایش]\n" + "ساسانیان\n" + "\n" + "\n" + "\n" + "شاهنشاهی ساسانی در سالهای ۲۲۴ تا ۶۵۱ م.\n" + "ساسانیان خاندان شاهنشاهی ایرانی در سالهای ۲۲۴ تا ۶۵۱ میلادی بودند. شاهنشاهان ساسانی که اصلیتشان از استان پارس بود بر بخش بزرگی از غرب قارهٔ آسیا چیرگی یافتند. پایتخت ساسانیان شهر تیسفون در نزدیکی بغداد در عراق امروزی بود.\n" + "سلسله اشکانی به دست اردشیر اول ساسانی منقرض گردید. وی سلسله ساسانیان را بنا نهاد که تا 652 میلادی در ایران ادامه یافت. دولت ساسانی حکومتی ملی و متکی به دین و تمدن ایرانی بود و قدرت بسیار زیادی کسب کرد. در این دوره نیز جنگ‌های ایران و روم ادامه یافت.\n" + "\n" + "در همين دوران مانی[1] (216 - 276 میلادی) به تبلیغ مذهب خود پرداخت. مانی پس از مسافرت به هند و آشنائی با مذهب بودائی سیستم جهان مذهبی مانوی خود را که التقاطی از مذهب زردشتی، بودائی و مسیحی و اسطوره بود با دقت تنظیم کرد و در کتاب \"شاهپورگان\" اصول آن‌ها را بیان و هنگام تاجگذاری شاپوراول به شاه هدیه کرد. مانی اصول اخلاقی خود را بر پایه فلسفی مثنویت: روشنائی و تاریکی که ازلی و ابدی هستند استوار نمود. در واقع این اصول) خودداری از قتل نفس حتی در مورد حیوانات، نخوردن می، دوری از زن و جمع نکردن مال (واکنش در مقابل زندگی پر تجمل و پر از لذت طبقات حاکم و عکس العمل منفی در برابر بحران اجتماعی پایان حکومت اشکانی و آغاز حکومت ساسانی است. شاپور و هرمزد، نشر چنین مذهبی را تجویز کردند، زیرا با وجود مخالفت آن با شهوت پرستی و غارتگری و سود جوئی طبقات حاکم، از جانبی مردم را به راه \"معنویت\" و \"آشتی‌خواهی\" سوق می‌‌داد و از جانب دیگر از قدرت مذهب زردشت می‌‌کاست.\n" + "جنبش معنوی مانی به سرعت در جهان آن روز گسترش یافت و تبدیل به نیروئی شد که با وجود جنبه منفی آن با هدف‌های شاهان و نجبا و پیشرفت جامعه آن روزی وفق نمی‌داد. پیشوایان زردتشتی و عیسوی که با هم دائما در نبرد بودند، متحد شدند و در دوران شاهی بهرام اول که شاهی تن آسا و شهوت پرست بود در جریان محاکمه او را محکوم و مقتول نمودند ( 276 میلادی). از آن پس مانی کشی آغاز شد و مغان مردم بسیاری را به نام زندک(زندیق) کشتند. مانویان درد و جانب شرق و غرب، در آسیای میانه تا سرحد چین و در غرب تا روم پراکنده شدند.\n" + "\n" + "امپراتوری پهناور ساسانی که از رود سند تا دریای سرخ وسعت داشت، در اثر مشکلات خارجی و داخلی ضعیف شد. آخرین پادشاه این سلسله یزدگرد سوم بود. در دوره او مسلمانان عرب به ایران حمله کردند و ایرانیان را در جنگ‌های قادسیه، مدائن، جلولاء و نهاوند شکست دادند و بدین ترتیب دولت ساسانی از میان رفت.\n" + "در پایان سده پنجم و آغاز قرن ششم میلادی جنبش بزرگی جامعه ایران را تکان داد که به صورت قیامی واقعی سی سال ( 24-494 م.) دوام آورد و تأثیر شگرفی در تکامل جامعه آن روزایران بخشید.\n" + "در چنین اوضاعی مزدک[2] پسر بامدادان به تبلیغ مذهب خود که گویند موسسش زردشت خورک بابوندس بوده، پرداخت. عقاید مزدک بر دو گانگی مانوی استوار است:\n" + "روشنائی دانا و تاریکی نادان، به عبارت دیگر نیکی با عقل و بدی جاهل، این دو نیرو با هم در نبردند و چون روشنائی داناست سرانجام پیروز خواهد شد.\n" + "اساس تعلیمات اجتماعی مزدک دو چیز است: یکی برابری و دیگری دادگری.\n" + "مردم بسیاری به سرعت پیرو مذهب مزدک شدند. جنبش مزدکی با قتل او و پیروانش به طرز وحشیانه‌ای سرکوب شد، اما افکار او اثر خود را حتی در قیام‌ها و جنبش‌های مردم ایران در دوران اسلام، باقی گذاشت.\n" + "[ویرایش]\n" + "منابع\n" + "\n" + "تاریخ ایران - دکتر خنجی\n" + "تاریخ اجتماعی ایران. مرتضی راوندی. ( جلد ۱ ) 1354\n" + "تاریخ ماد. ایگور میخائیلوویچ دیاکونوف. ترجمه کریم کشاورز، تهران: نشر امیرکبیر.\n" + "تاريخ ايران باستان. دياكونوف، ميخائيل ميخائيلوويچ. روحی ارباب. انتشارات علمی و فرهنگی، چاپ دوم 1380\n" + "سهم ایرانیان در پیدایش و آفرینش خط در جهان ،دکتر رکن الدین همایونفرخ، انتشارات اساطیر.\n" + "کمرون، جرج. ایران در سپیده دم تاریخ. ترجمه حسن انوشه. تهران، مرکز نشر دانشگاهی، 1379\n" + "تاریخ ایران از زمان باستان تا امروز، ا. آ. گرانتوسكی - م. آ. داندامایو، مترجم، كیخسرو كشاورزی، ناشر: مرواريد 1385\n" + "تاریخ ایران از عهد باستان تا قرن 18، پیگولووسکایا، ترجمه کریم کشاورز، تهران، 1353.\n" + "[ویرایش]\n" + "جستارهای وابسته\n" + "\n" + "ماد\n" + "کاسی\n" + "ایلامیان\n" + "تپه هگمتانه\n" + "تاریخ ایران\n" + "ایران پیش از آریایی‌ها\n" + "تمدنهای باستانی آسیای غربی\n" + "[ویرایش]\n" + "پیوند به بیرون\n" + "\n" + "ایران قبل از آریاها\n" + "ايران پيش از آريایی‌ها\n" + "تمدنهای قبل از آریایی ایران\n" + "ایران ازدیدگاه باستانشناسی\n" + "سنگ‌نبشته‌ی داریوش بزرگ در بیستون\n" + "شیوه آسیائی تولید در ایران\n" + "نیای اساطیری ایرانیان\n" + "قیام‌های ایرانیان در طول تاریخ\n" + "خلاصهٔ تاریخ ایران\n" + "شهر، شهرسازی و شهرنشينی در ايران پيش از اسلام\n" + "\n" + "[3]\n" + "[4]\n" + "[5]\n" + "[6]\n" + "[7]\n" + "\n" + "\n" + "\n" + " این نوشتار خُرد است. با گسترش آن به ویکی‌پدیا کمک کنید.\n" + "\n" + "این مقاله نیازمند ویکی‌سازی است. لطفاً با توجه به راهنمای ویرایش و شیوه‌نامه آن را تغییر دهید. در پایان، پس از ویکی‌سازی این الگوی پیامی را بردارید.\n"; var source = ("/*\n" + " This is a version (aka dlmalloc) of malloc/free/realloc written by\n" + " Doug Lea and released to the public domain. Use, modify, and\n" + " redistribute this code without permission or acknowledgement in any\n" + " way you wish. Send questions, comments, complaints, performance\n" + " data, etc to dl@cs.oswego.edu\n" + "\n" + "* VERSION 2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee)\n" + "\n" + " Note: There may be an updated version of this malloc obtainable at\n" + " ftp://gee.cs.oswego.edu/pub/misc/malloc.c\n" + " Check before installing!\n" + "\n" + "* Quickstart\n" + "\n" + " This library is all in one file to simplify the most common usage:\n" + " ftp it, compile it (-O), and link it into another program. All\n" + " of the compile-time options default to reasonable values for use on\n" + " most unix platforms. Compile -DWIN32 for reasonable defaults on windows.\n" + " You might later want to step through various compile-time and dynamic\n" + " tuning options.\n" + "\n" + " For convenience, an include file for code using this malloc is at:\n" + " ftp://gee.cs.oswego.edu/pub/misc/malloc-2.7.1.h\n" + " You don't really need this .h file unless you call functions not\n" + " defined in your system include files. The .h file contains only the\n" + " excerpts from this file needed for using this malloc on ANSI C/C++\n" + " systems, so long as you haven't changed compile-time options about\n" + " naming and tuning parameters. If you do, then you can create your\n" + " own malloc.h that does include all settings by cutting at the point\n" + " indicated below.\n" + "\n" + "* Why use this malloc?\n" + "\n" + " This is not the fastest, most space-conserving, most portable, or\n" + " most tunable malloc ever written. However it is among the fastest\n" + " while also being among the most space-conserving, portable and tunable.\n" + " Consistent balance across these factors results in a good general-purpose\n" + " allocator for malloc-intensive programs.\n" + "\n" + " The main properties of the algorithms are:\n" + " * For large (>= 512 bytes) requests, it is a pure best-fit allocator,\n" + " with ties normally decided via FIFO (i.e. least recently used).\n" + " * For small (<= 64 bytes by default) requests, it is a caching\n" + " allocator, that maintains pools of quickly recycled chunks.\n" + " * In between, and for combinations of large and small requests, it does\n" + " the best it can trying to meet both goals at once.\n" + " * For very large requests (>= 128KB by default), it relies on system\n" + " memory mapping facilities, if supported.\n" + "\n" + " For a longer but slightly out of date high-level description, see\n" + " http://gee.cs.oswego.edu/dl/html/malloc.html\n" + "\n" + " You may already by default be using a C library containing a malloc\n" + " that is based on some version of this malloc (for example in\n" + " linux). You might still want to use the one in this file in order to\n" + " customize settings or to avoid overheads associated with library\n" + " versions.\n" + "\n" + "* Contents, described in more detail in \"description of public routines\" below.\n" + "\n" + " Standard (ANSI/SVID/...) functions:\n" + " malloc(size_t n);\n" + " calloc(size_t n_elements, size_t element_size);\n" + " free(Void_t* p);\n" + " realloc(Void_t* p, size_t n);\n" + " memalign(size_t alignment, size_t n);\n" + " valloc(size_t n);\n" + " mallinfo()\n" + " mallopt(int parameter_number, int parameter_value)\n" + "\n" + " Additional functions:\n" + " independent_calloc(size_t n_elements, size_t size, Void_t* chunks[]);\n" + " independent_comalloc(size_t n_elements, size_t sizes[], Void_t* chunks[]);\n" + " pvalloc(size_t n);\n" + " cfree(Void_t* p);\n" + " malloc_trim(size_t pad);\n" + " malloc_usable_size(Void_t* p);\n" + " malloc_stats();\n" + "\n" + "* Vital statistics:\n" + "\n" + " Supported pointer representation: 4 or 8 bytes\n" + " Supported size_t representation: 4 or 8 bytes\n" + " Note that size_t is allowed to be 4 bytes even if pointers are 8.\n" + " You can adjust this by defining INTERNAL_SIZE_T\n" + "\n" + " Alignment: 2 * sizeof(size_t) (default)\n" + " (i.e., 8 byte alignment with 4byte size_t). This suffices for\n" + " nearly all current machines and C compilers. However, you can\n" + " define MALLOC_ALIGNMENT to be wider than this if necessary.\n" + "\n" + " Minimum overhead per allocated chunk: 4 or 8 bytes\n" + " Each malloced chunk has a hidden word of overhead holding size\n" + " and status information.\n" + "\n" + " Minimum allocated size: 4-byte ptrs: 16 bytes (including 4 overhead)\n" + " 8-byte ptrs: 24/32 bytes (including, 4/8 overhead)\n" + "\n" + " When a chunk is freed, 12 (for 4byte ptrs) or 20 (for 8 byte\n" + " ptrs but 4 byte size) or 24 (for 8/8) additional bytes are\n" + " needed; 4 (8) for a trailing size field and 8 (16) bytes for\n" + " free list pointers. Thus, the minimum allocatable size is\n" + " 16/24/32 bytes.\n" + "\n" + " Even a request for zero bytes (i.e., malloc(0)) returns a\n" + " pointer to something of the minimum allocatable size.\n" + "\n" + " The maximum overhead wastage (i.e., number of extra bytes\n" + " allocated than were requested in malloc) is less than or equal\n" + " to the minimum size, except for requests >= mmap_threshold that\n" + " are serviced via mmap(), where the worst case wastage is 2 *\n" + " sizeof(size_t) bytes plus the remainder from a system page (the\n" + " minimal mmap unit); typically 4096 or 8192 bytes.\n" + "\n" + " Maximum allocated size: 4-byte size_t: 2^32 minus about two pages\n" + " 8-byte size_t: 2^64 minus about two pages\n" + "\n" + " It is assumed that (possibly signed) size_t values suffice to\n" + " represent chunk sizes. `Possibly signed' is due to the fact\n" + " that `size_t' may be defined on a system as either a signed or\n" + " an unsigned type. The ISO C standard says that it must be\n" + " unsigned, but a few systems are known not to adhere to this.\n" + " Additionally, even when size_t is unsigned, sbrk (which is by\n" + " default used to obtain memory from system) accepts signed\n" + " arguments, and may not be able to handle size_t-wide arguments\n" + " with negative sign bit. Generally, values that would\n" + " appear as negative after accounting for overhead and alignment\n" + " are supported only via mmap(), which does not have this\n" + " limitation.\n" + "\n" + " Requests for sizes outside the allowed range will perform an optional\n" + " failure action and then return null. (Requests may also\n" + " also fail because a system is out of memory.)\n" + "\n" + " Thread-safety: NOT thread-safe unless USE_MALLOC_LOCK defined\n" + "\n" + " When USE_MALLOC_LOCK is defined, wrappers are created to\n" + " surround every public call with either a pthread mutex or\n" + " a win32 spinlock (depending on WIN32). This is not\n" + " especially fast, and can be a major bottleneck.\n" + " It is designed only to provide minimal protection\n" + " in concurrent environments, and to provide a basis for\n" + " extensions. If you are using malloc in a concurrent program,\n" + " you would be far better off obtaining ptmalloc, which is\n" + " derived from a version of this malloc, and is well-tuned for\n" + " concurrent programs. (See http://www.malloc.de) Note that\n" + " even when USE_MALLOC_LOCK is defined, you can can guarantee\n" + " full thread-safety only if no threads acquire memory through\n" + " direct calls to MORECORE or other system-level allocators.\n" + "\n" + " Compliance: I believe it is compliant with the 1997 Single Unix Specification\n" + " (See http://www.opennc.org). Also SVID/XPG, ANSI C, and probably\n" + " others as well.\n" + "\n" + "* Synopsis of compile-time options:\n" + "\n" + " People have reported using previous versions of this malloc on all\n" + " versions of Unix, sometimes by tweaking some of the defines\n" + " below. It has been tested most extensively on Solaris and\n" + " Linux. It is also reported to work on WIN32 platforms.\n" + " People also report using it in stand-alone embedded systems.\n" + "\n" + " The implementation is in straight, hand-tuned ANSI C. It is not\n" + " at all modular. (Sorry!) It uses a lot of macros. To be at all\n" + " usable, this code should be compiled using an optimizing compiler\n" + " (for example gcc -O3) that can simplify expressions and control\n" + " paths. (FAQ: some macros import variables as arguments rather than\n" + " declare locals because people reported that some debuggers\n" + " otherwise get confused.)\n" + "\n" + " OPTION DEFAULT VALUE\n" + "\n" + " Compilation Environment options:\n" + "\n" + " __STD_C derived from C compiler defines\n" + " WIN32 NOT defined\n" + " HAVE_MEMCPY defined\n" + " USE_MEMCPY 1 if HAVE_MEMCPY is defined\n" + " HAVE_MMAP defined as 1\n" + " MMAP_CLEARS 1\n" + " HAVE_MREMAP 0 unless linux defined\n" + " malloc_getpagesize derived from system #includes, or 4096 if not\n" + " HAVE_USR_INCLUDE_MALLOC_H NOT defined\n" + " LACKS_UNISTD_H NOT defined unless WIN32\n" + " LACKS_SYS_PARAM_H NOT defined unless WIN32\n" + " LACKS_SYS_MMAN_H NOT defined unless WIN32\n" + " LACKS_FCNTL_H NOT defined\n" + "\n" + " Changing default word sizes:\n" + "\n" + " INTERNAL_SIZE_T size_t\n" + " MALLOC_ALIGNMENT 2 * sizeof(INTERNAL_SIZE_T)\n" + " PTR_UINT unsigned long\n" + " CHUNK_SIZE_T unsigned long\n" + "\n" + " Configuration and functionality options:\n" + "\n" + " USE_DL_PREFIX NOT defined\n" + " USE_PUBLIC_MALLOC_WRAPPERS NOT defined\n" + " USE_MALLOC_LOCK NOT defined\n" + " DEBUG NOT defined\n" + " REALLOC_ZERO_BYTES_FREES NOT defined\n" + " MALLOC_FAILURE_ACTION errno = ENOMEM, if __STD_C defined, else no-op\n" + " TRIM_FASTBINS 0\n" + " FIRST_SORTED_BIN_SIZE 512\n" + "\n" + " Options for customizing MORECORE:\n" + "\n" + " MORECORE sbrk\n" + " MORECORE_CONTIGUOUS 1\n" + " MORECORE_CANNOT_TRIM NOT defined\n" + " MMAP_AS_MORECORE_SIZE (1024 * 1024)\n" + "\n" + " Tuning options that are also dynamically changeable via mallopt:\n" + "\n" + " DEFAULT_MXFAST 64\n" + " DEFAULT_TRIM_THRESHOLD 256 * 1024\n" + " DEFAULT_TOP_PAD 0\n" + " DEFAULT_MMAP_THRESHOLD 256 * 1024\n" + " DEFAULT_MMAP_MAX 65536\n" + "\n" + " There are several other #defined constants and macros that you\n" + " probably don't want to touch unless you are extending or adapting malloc.\n" + "*/\n" + "\n" + "#define MORECORE_CONTIGUOUS 0\n" + "#define MORECORE_CANNOT_TRIM 1\n" + "#define MALLOC_FAILURE_ACTION abort()\n" + "\n" + "\n" + "namespace khtml {\n" + "\n" + "#ifndef NDEBUG\n" + "\n" + "// In debugging builds, use the system malloc for its debugging features.\n" + "\n" + "void *main_thread_malloc(size_t n)\n" + "{\n" + " assert(pthread_main_np());\n" + " return malloc(n);\n" + "}\n" + "\n" + "void *main_thread_calloc(size_t n_elements, size_t element_size)\n" + "{\n" + " assert(pthread_main_np());\n" + " return calloc(n_elements, element_size);\n" + "}\n" + "\n" + "void main_thread_free(void* p)\n" + "{\n" + " // it's ok to main_thread_free on a non-main thread - the actual\n" + " // free will be scheduled on the main thread in that case.\n" + " free(p);\n" + "}\n" + "\n" + "void *main_thread_realloc(void* p, size_t n)\n" + "{\n" + " assert(pthread_main_np());\n" + " return realloc(p, n);\n" + "}\n" + "\n" + "#else\n" + "\n" + "/*\n" + " WIN32 sets up defaults for MS environment and compilers.\n" + " Otherwise defaults are for unix.\n" + "*/\n" + "\n" + "/* #define WIN32 */\n" + "\n" + "#ifdef WIN32\n" + "\n" + "#define WIN32_LEAN_AND_MEAN\n" + "#include <windows.h>\n" + "\n" + "/* Win32 doesn't supply or need the following headers */\n" + "#define LACKS_UNISTD_H\n" + "#define LACKS_SYS_PARAM_H\n" + "#define LACKS_SYS_MMAN_H\n" + "\n" + "/* Use the supplied emulation of sbrk */\n" + "#define MORECORE sbrk\n" + "#define MORECORE_CONTIGUOUS 1\n" + "#define MORECORE_FAILURE ((void*)(-1))\n" + "\n" + "/* Use the supplied emulation of mmap and munmap */\n" + "#define HAVE_MMAP 1\n" + "#define MUNMAP_FAILURE (-1)\n" + "#define MMAP_CLEARS 1\n" + "\n" + "/* These values don't really matter in windows mmap emulation */\n" + "#define MAP_PRIVATE 1\n" + "#define MAP_ANONYMOUS 2\n" + "#define PROT_READ 1\n" + "#define PROT_WRITE 2\n" + "\n" + "/* Emulation functions defined at the end of this file */\n" + "\n" + "/* If USE_MALLOC_LOCK, use supplied critical-section-based lock functions */\n" + "#ifdef USE_MALLOC_LOCK\n") + ("static int slwait(int *sl);\n" + "static int slrelease(int *sl);\n" + "#endif\n" + "\n" + "static long getpagesize(void);\n" + "static long getregionsize(void);\n" + "static void *sbrk(long size);\n" + "static void *mmap(void *ptr, long size, long prot, long type, long handle, long arg);\n" + "static long munmap(void *ptr, long size);\n" + "\n" + "static void vminfo (unsigned long*free, unsigned long*reserved, unsigned long*committed);\n" + "static int cpuinfo (int whole, unsigned long*kernel, unsigned long*user);\n" + "\n" + "#endif\n" + "\n" + "/*\n" + " __STD_C should be nonzero if using ANSI-standard C compiler, a C++\n" + " compiler, or a C compiler sufficiently close to ANSI to get away\n" + " with it.\n" + "*/\n" + "\n" + "#ifndef __STD_C\n" + "#if defined(__STDC__) || defined(_cplusplus)\n" + "#define __STD_C 1\n" + "#else\n" + "#define __STD_C 0\n" + "#endif\n" + "#endif /*__STD_C*/\n" + "\n" + "\n" + "/*\n" + " Void_t* is the pointer type that malloc should say it returns\n" + "*/\n" + "\n" + "#ifndef Void_t\n" + "#if (__STD_C || defined(WIN32))\n" + "#define Void_t void\n" + "#else\n" + "#define Void_t char\n" + "#endif\n" + "#endif /*Void_t*/\n" + "\n" + "#if __STD_C\n" + "#include <stddef.h> /* for size_t */\n" + "#else\n" + "#include <sys/types.h>\n" + "#endif\n" + "\n" + "/* define LACKS_UNISTD_H if your system does not have a <unistd.h>. */\n" + "\n" + "/* #define LACKS_UNISTD_H */\n" + "\n" + "#ifndef LACKS_UNISTD_H\n" + "#include <unistd.h>\n" + "#endif\n" + "\n" + "/* define LACKS_SYS_PARAM_H if your system does not have a <sys/param.h>. */\n" + "\n" + "/* #define LACKS_SYS_PARAM_H */\n" + "\n" + "\n" + "#include <stdio.h> /* needed for malloc_stats */\n" + "#include <errno.h> /* needed for optional MALLOC_FAILURE_ACTION */\n" + "\n" + "\n" + "/*\n" + " Debugging:\n" + "\n" + " Because freed chunks may be overwritten with bookkeeping fields, this\n" + " malloc will often die when freed memory is overwritten by user\n" + " programs. This can be very effective (albeit in an annoying way)\n" + " in helping track down dangling pointers.\n" + "\n" + " If you compile with -DDEBUG, a number of assertion checks are\n" + " enabled that will catch more memory errors. You probably won't be\n" + " able to make much sense of the actual assertion errors, but they\n" + " should help you locate incorrectly overwritten memory. The\n" + " checking is fairly extensive, and will slow down execution\n" + " noticeably. Calling malloc_stats or mallinfo with DEBUG set will\n" + " attempt to check every non-mmapped allocated and free chunk in the\n" + " course of computing the summmaries. (By nature, mmapped regions\n" + " cannot be checked very much automatically.)\n" + "\n" + " Setting DEBUG may also be helpful if you are trying to modify\n" + " this code. The assertions in the check routines spell out in more\n" + " detail the assumptions and invariants underlying the algorithms.\n" + "\n" + " Setting DEBUG does NOT provide an automated mechanism for checking\n" + " that all accesses to malloced memory stay within their\n" + " bounds. However, there are several add-ons and adaptations of this\n" + " or other mallocs available that do this.\n" + "*/\n" + "\n" + "/*\n" + " The unsigned integer type used for comparing any two chunk sizes.\n" + " This should be at least as wide as size_t, but should not be signed.\n" + "*/\n" + "\n" + "#ifndef CHUNK_SIZE_T\n" + "#define CHUNK_SIZE_T unsigned long\n" + "#endif\n" + "\n" + "/*\n" + " The unsigned integer type used to hold addresses when they are are\n" + " manipulated as integers. Except that it is not defined on all\n" + " systems, intptr_t would suffice.\n" + "*/\n" + "#ifndef PTR_UINT\n" + "#define PTR_UINT unsigned long\n" + "#endif\n" + "\n" + "\n" + "/*\n" + " INTERNAL_SIZE_T is the word-size used for internal bookkeeping\n" + " of chunk sizes.\n" + "\n" + " The default version is the same as size_t.\n" + "\n" + " While not strictly necessary, it is best to define this as an\n" + " unsigned type, even if size_t is a signed type. This may avoid some\n" + " artificial size limitations on some systems.\n" + "\n" + " On a 64-bit machine, you may be able to reduce malloc overhead by\n" + " defining INTERNAL_SIZE_T to be a 32 bit `unsigned int' at the\n" + " expense of not being able to handle more than 2^32 of malloced\n" + " space. If this limitation is acceptable, you are encouraged to set\n" + " this unless you are on a platform requiring 16byte alignments. In\n" + " this case the alignment requirements turn out to negate any\n" + " potential advantages of decreasing size_t word size.\n" + "\n" + " Implementors: Beware of the possible combinations of:\n" + " - INTERNAL_SIZE_T might be signed or unsigned, might be 32 or 64 bits,\n" + " and might be the same width as int or as long\n" + " - size_t might have different width and signedness as INTERNAL_SIZE_T\n" + " - int and long might be 32 or 64 bits, and might be the same width\n" + " To deal with this, most comparisons and difference computations\n" + " among INTERNAL_SIZE_Ts should cast them to CHUNK_SIZE_T, being\n" + " aware of the fact that casting an unsigned int to a wider long does\n" + " not sign-extend. (This also makes checking for negative numbers\n" + " awkward.) Some of these casts result in harmless compiler warnings\n" + " on some systems.\n" + "*/\n" + "\n" + "#ifndef INTERNAL_SIZE_T\n" + "#define INTERNAL_SIZE_T size_t\n" + "#endif\n" + "\n" + "/* The corresponding word size */\n" + "#define SIZE_SZ (sizeof(INTERNAL_SIZE_T))\n" + "\n" + "\n") + ("\n" + "/*\n" + " MALLOC_ALIGNMENT is the minimum alignment for malloc'ed chunks.\n" + " It must be a power of two at least 2 * SIZE_SZ, even on machines\n" + " for which smaller alignments would suffice. It may be defined as\n" + " larger than this though. Note however that code and data structures\n" + " are optimized for the case of 8-byte alignment.\n" + "*/\n" + "\n" + "\n" + "#ifndef MALLOC_ALIGNMENT\n" + "#define MALLOC_ALIGNMENT (2 * SIZE_SZ)\n" + "#endif\n" + "\n" + "/* The corresponding bit mask value */\n" + "#define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)\n" + "\n" + "\n" + "\n" + "/*\n" + " REALLOC_ZERO_BYTES_FREES should be set if a call to\n" + " realloc with zero bytes should be the same as a call to free.\n" + " Some people think it should. Otherwise, since this malloc\n" + " returns a unique pointer for malloc(0), so does realloc(p, 0).\n" + "*/\n" + "\n" + "/* #define REALLOC_ZERO_BYTES_FREES */\n" + "\n" + "/*\n" + " TRIM_FASTBINS controls whether free() of a very small chunk can\n" + " immediately lead to trimming. Setting to true (1) can reduce memory\n" + " footprint, but will almost always slow down programs that use a lot\n" + " of small chunks.\n" + "\n" + " Define this only if you are willing to give up some speed to more\n" + " aggressively reduce system-level memory footprint when releasing\n" + " memory in programs that use many small chunks. You can get\n" + " essentially the same effect by setting MXFAST to 0, but this can\n" + " lead to even greater slowdowns in programs using many small chunks.\n" + " TRIM_FASTBINS is an in-between compile-time option, that disables\n" + " only those chunks bordering topmost memory from being placed in\n" + " fastbins.\n" + "*/\n" + "\n" + "#ifndef TRIM_FASTBINS\n" + "#define TRIM_FASTBINS 0\n" + "#endif\n" + "\n" + "\n" + "/*\n" + " USE_DL_PREFIX will prefix all public routines with the string 'dl'.\n" + " This is necessary when you only want to use this malloc in one part\n" + " of a program, using your regular system malloc elsewhere.\n" + "*/\n" + "\n" + "#define USE_DL_PREFIX\n" + "\n" + "\n" + "/*\n" + " USE_MALLOC_LOCK causes wrapper functions to surround each\n" + " callable routine with pthread mutex lock/unlock.\n" + "\n" + " USE_MALLOC_LOCK forces USE_PUBLIC_MALLOC_WRAPPERS to be defined\n" + "*/\n" + "\n" + "\n" + "/* #define USE_MALLOC_LOCK */\n" + "\n" + "\n" + "/*\n" + " If USE_PUBLIC_MALLOC_WRAPPERS is defined, every public routine is\n" + " actually a wrapper function that first calls MALLOC_PREACTION, then\n" + " calls the internal routine, and follows it with\n" + " MALLOC_POSTACTION. This is needed for locking, but you can also use\n" + " this, without USE_MALLOC_LOCK, for purposes of interception,\n" + " instrumentation, etc. It is a sad fact that using wrappers often\n" + " noticeably degrades performance of malloc-intensive programs.\n" + "*/\n" + "\n" + "#ifdef USE_MALLOC_LOCK\n" + "#define USE_PUBLIC_MALLOC_WRAPPERS\n" + "#else\n" + "/* #define USE_PUBLIC_MALLOC_WRAPPERS */\n" + "#endif\n" + "\n" + "\n" + "/*\n" + " Two-phase name translation.\n" + " All of the actual routines are given mangled names.\n" + " When wrappers are used, they become the public callable versions.\n" + " When DL_PREFIX is used, the callable names are prefixed.\n" + "*/\n" + "\n" + "#ifndef USE_PUBLIC_MALLOC_WRAPPERS\n" + "#define cALLOc public_cALLOc\n" + "#define fREe public_fREe\n" + "#define cFREe public_cFREe\n" + "#define mALLOc public_mALLOc\n" + "#define mEMALIGn public_mEMALIGn\n" + "#define rEALLOc public_rEALLOc\n" + "#define vALLOc public_vALLOc\n" + "#define pVALLOc public_pVALLOc\n" + "#define mALLINFo public_mALLINFo\n" + "#define mALLOPt public_mALLOPt\n" + "#define mTRIm public_mTRIm\n" + "#define mSTATs public_mSTATs\n" + "#define mUSABLe public_mUSABLe\n" + "#define iCALLOc public_iCALLOc\n" + "#define iCOMALLOc public_iCOMALLOc\n" + "#endif\n" + "\n" + "#ifdef USE_DL_PREFIX\n" + "#define public_cALLOc main_thread_calloc\n" + "#define public_fREe main_thread_free\n" + "#define public_cFREe main_thread_cfree\n" + "#define public_mALLOc main_thread_malloc\n" + "#define public_mEMALIGn main_thread_memalign\n" + "#define public_rEALLOc main_thread_realloc\n" + "#define public_vALLOc main_thread_valloc\n" + "#define public_pVALLOc main_thread_pvalloc\n" + "#define public_mALLINFo main_thread_mallinfo\n" + "#define public_mALLOPt main_thread_mallopt\n" + "#define public_mTRIm main_thread_malloc_trim\n" + "#define public_mSTATs main_thread_malloc_stats\n" + "#define public_mUSABLe main_thread_malloc_usable_size\n" + "#define public_iCALLOc main_thread_independent_calloc\n" + "#define public_iCOMALLOc main_thread_independent_comalloc\n" + "#else /* USE_DL_PREFIX */\n" + "#define public_cALLOc calloc\n" + "#define public_fREe free\n" + "#define public_cFREe cfree\n" + "#define public_mALLOc malloc\n" + "#define public_mEMALIGn memalign\n" + "#define public_rEALLOc realloc\n" + "#define public_vALLOc valloc\n" + "#define public_pVALLOc pvalloc\n" + "#define public_mALLINFo mallinfo\n" + "#define public_mALLOPt mallopt\n" + "#define public_mTRIm malloc_trim\n" + "#define public_mSTATs malloc_stats\n" + "#define public_mUSABLe malloc_usable_size\n" + "#define public_iCALLOc independent_calloc\n" + "#define public_iCOMALLOc independent_comalloc\n" + "#endif /* USE_DL_PREFIX */\n" + "\n" + "\n" + "/*\n" + " HAVE_MEMCPY should be defined if you are not otherwise using\n" + " ANSI STD C, but still have memcpy and memset in your C library\n" + " and want to use them in calloc and realloc. Otherwise simple\n" + " macro versions are defined below.\n" + "\n") + (" USE_MEMCPY should be defined as 1 if you actually want to\n" + " have memset and memcpy called. People report that the macro\n" + " versions are faster than libc versions on some systems.\n" + "\n" + " Even if USE_MEMCPY is set to 1, loops to copy/clear small chunks\n" + " (of <= 36 bytes) are manually unrolled in realloc and calloc.\n" + "*/\n" + "\n" + "#define HAVE_MEMCPY\n" + "\n" + "#ifndef USE_MEMCPY\n" + "#ifdef HAVE_MEMCPY\n" + "#define USE_MEMCPY 1\n" + "#else\n" + "#define USE_MEMCPY 0\n" + "#endif\n" + "#endif\n" + "\n" + "\n" + "#if (__STD_C || defined(HAVE_MEMCPY))\n" + "\n" + "#ifdef WIN32\n" + "/* On Win32 memset and memcpy are already declared in windows.h */\n" + "#else\n" + "#if __STD_C\n" + "extern \"C\" {\n" + "void* memset(void*, int, size_t);\n" + "void* memcpy(void*, const void*, size_t);\n" + "}\n" + "#else\n" + "extern \"C\" {\n" + "Void_t* memset();\n" + "Void_t* memcpy();\n" + "}\n" + "#endif\n" + "#endif\n" + "#endif\n" + "\n" + "/*\n" + " MALLOC_FAILURE_ACTION is the action to take before \"return 0\" when\n" + " malloc fails to be able to return memory, either because memory is\n" + " exhausted or because of illegal arguments.\n" + "\n" + " By default, sets errno if running on STD_C platform, else does nothing.\n" + "*/\n" + "\n" + "#ifndef MALLOC_FAILURE_ACTION\n" + "#if __STD_C\n" + "#define MALLOC_FAILURE_ACTION \\n" + " errno = ENOMEM;\n" + "\n" + "#else\n" + "#define MALLOC_FAILURE_ACTION\n" + "#endif\n" + "#endif\n" + "\n" + "/*\n" + " MORECORE-related declarations. By default, rely on sbrk\n" + "*/\n" + "\n" + "\n" + "#ifdef LACKS_UNISTD_H\n" + "#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)\n" + "#if __STD_C\n" + "extern Void_t* sbrk(ptrdiff_t);\n" + "#else\n" + "extern Void_t* sbrk();\n" + "#endif\n" + "#endif\n" + "#endif\n" + "\n" + "/*\n" + " MORECORE is the name of the routine to call to obtain more memory\n" + " from the system. See below for general guidance on writing\n" + " alternative MORECORE functions, as well as a version for WIN32 and a\n" + " sample version for pre-OSX macos.\n" + "*/\n" + "\n" + "#ifndef MORECORE\n" + "#define MORECORE sbrk\n" + "#endif\n" + "\n" + "/*\n" + " MORECORE_FAILURE is the value returned upon failure of MORECORE\n" + " as well as mmap. Since it cannot be an otherwise valid memory address,\n" + " and must reflect values of standard sys calls, you probably ought not\n" + " try to redefine it.\n" + "*/\n" + "\n" + "#ifndef MORECORE_FAILURE\n" + "#define MORECORE_FAILURE (-1)\n" + "#endif\n" + "\n" + "/*\n" + " If MORECORE_CONTIGUOUS is true, take advantage of fact that\n" + " consecutive calls to MORECORE with positive arguments always return\n" + " contiguous increasing addresses. This is true of unix sbrk. Even\n" + " if not defined, when regions happen to be contiguous, malloc will\n" + " permit allocations spanning regions obtained from different\n" + " calls. But defining this when applicable enables some stronger\n" + " consistency checks and space efficiencies.\n" + "*/\n" + "\n" + "#ifndef MORECORE_CONTIGUOUS\n" + "#define MORECORE_CONTIGUOUS 1\n" + "#endif\n" + "\n" + "/*\n" + " Define MORECORE_CANNOT_TRIM if your version of MORECORE\n" + " cannot release space back to the system when given negative\n" + " arguments. This is generally necessary only if you are using\n" + " a hand-crafted MORECORE function that cannot handle negative arguments.\n" + "*/\n" + "\n" + "/* #define MORECORE_CANNOT_TRIM */\n" + "\n" + "\n" + "/*\n" + " Define HAVE_MMAP as true to optionally make malloc() use mmap() to\n" + " allocate very large blocks. These will be returned to the\n" + " operating system immediately after a free(). Also, if mmap\n" + " is available, it is used as a backup strategy in cases where\n" + " MORECORE fails to provide space from system.\n" + "\n" + " This malloc is best tuned to work with mmap for large requests.\n" + " If you do not have mmap, operations involving very large chunks (1MB\n" + " or so) may be slower than you'd like.\n" + "*/\n" + "\n" + "#ifndef HAVE_MMAP\n" + "#define HAVE_MMAP 1\n" + "#endif\n" + "\n" + "#if HAVE_MMAP\n" + "/*\n" + " Standard unix mmap using /dev/zero clears memory so calloc doesn't\n" + " need to.\n" + "*/\n" + "\n" + "#ifndef MMAP_CLEARS\n" + "#define MMAP_CLEARS 1\n" + "#endif\n" + "\n" + "#else /* no mmap */\n" + "#ifndef MMAP_CLEARS\n" + "#define MMAP_CLEARS 0\n" + "#endif\n" + "#endif\n" + "\n" + "\n" + "/*\n") + (" MMAP_AS_MORECORE_SIZE is the minimum mmap size argument to use if\n" + " sbrk fails, and mmap is used as a backup (which is done only if\n" + " HAVE_MMAP). The value must be a multiple of page size. This\n" + " backup strategy generally applies only when systems have \"holes\" in\n" + " address space, so sbrk cannot perform contiguous expansion, but\n" + " there is still space available on system. On systems for which\n" + " this is known to be useful (i.e. most linux kernels), this occurs\n" + " only when programs allocate huge amounts of memory. Between this,\n" + " and the fact that mmap regions tend to be limited, the size should\n" + " be large, to avoid too many mmap calls and thus avoid running out\n" + " of kernel resources.\n" + "*/\n" + "\n" + "#ifndef MMAP_AS_MORECORE_SIZE\n" + "#define MMAP_AS_MORECORE_SIZE (1024 * 1024)\n" + "#endif\n" + "\n" + "/*\n" + " Define HAVE_MREMAP to make realloc() use mremap() to re-allocate\n" + " large blocks. This is currently only possible on Linux with\n" + " kernel versions newer than 1.3.77.\n" + "*/\n" + "\n" + "#ifndef HAVE_MREMAP\n" + "#ifdef linux\n" + "#define HAVE_MREMAP 1\n" + "#else\n" + "#define HAVE_MREMAP 0\n" + "#endif\n" + "\n" + "#endif /* HAVE_MMAP */\n" + "\n" + "\n" + "/*\n" + " The system page size. To the extent possible, this malloc manages\n" + " memory from the system in page-size units. Note that this value is\n" + " cached during initialization into a field of malloc_state. So even\n" + " if malloc_getpagesize is a function, it is only called once.\n" + "\n" + " The following mechanics for getpagesize were adapted from bsd/gnu\n" + " getpagesize.h. If none of the system-probes here apply, a value of\n" + " 4096 is used, which should be OK: If they don't apply, then using\n" + " the actual value probably doesn't impact performance.\n" + "*/\n" + "\n" + "\n" + "#ifndef malloc_getpagesize\n" + "\n" + "#ifndef LACKS_UNISTD_H\n" + "# include <unistd.h>\n" + "#endif\n" + "\n" + "# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */\n" + "# ifndef _SC_PAGE_SIZE\n" + "# define _SC_PAGE_SIZE _SC_PAGESIZE\n" + "# endif\n" + "# endif\n" + "\n" + "# ifdef _SC_PAGE_SIZE\n" + "# define malloc_getpagesize sysconf(_SC_PAGE_SIZE)\n" + "# else\n" + "# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE)\n" + " extern size_t getpagesize();\n" + "# define malloc_getpagesize getpagesize()\n" + "# else\n" + "# ifdef WIN32 /* use supplied emulation of getpagesize */\n" + "# define malloc_getpagesize getpagesize()\n" + "# else\n" + "# ifndef LACKS_SYS_PARAM_H\n" + "# include <sys/param.h>\n" + "# endif\n" + "# ifdef EXEC_PAGESIZE\n" + "# define malloc_getpagesize EXEC_PAGESIZE\n" + "# else\n" + "# ifdef NBPG\n" + "# ifndef CLSIZE\n" + "# define malloc_getpagesize NBPG\n" + "# else\n" + "# define malloc_getpagesize (NBPG * CLSIZE)\n" + "# endif\n" + "# else\n" + "# ifdef NBPC\n" + "# define malloc_getpagesize NBPC\n" + "# else\n" + "# ifdef PAGESIZE\n" + "# define malloc_getpagesize PAGESIZE\n" + "# else /* just guess */\n" + "# define malloc_getpagesize (4096)\n" + "# endif\n" + "# endif\n" + "# endif\n" + "# endif\n" + "# endif\n" + "# endif\n" + "# endif\n" + "#endif\n" + "\n" + "/*\n" + " This version of malloc supports the standard SVID/XPG mallinfo\n" + " routine that returns a struct containing usage properties and\n" + " statistics. It should work on any SVID/XPG compliant system that has\n" + " a /usr/include/malloc.h defining struct mallinfo. (If you'd like to\n" + " install such a thing yourself, cut out the preliminary declarations\n" + " as described above and below and save them in a malloc.h file. But\n" + " there's no compelling reason to bother to do this.)\n" + "\n" + " The main declaration needed is the mallinfo struct that is returned\n" + " (by-copy) by mallinfo(). The SVID/XPG malloinfo struct contains a\n" + " bunch of fields that are not even meaningful in this version of\n" + " malloc. These fields are are instead filled by mallinfo() with\n" + " other numbers that might be of interest.\n" + "\n" + " HAVE_USR_INCLUDE_MALLOC_H should be set if you have a\n" + " /usr/include/malloc.h file that includes a declaration of struct\n" + " mallinfo. If so, it is included; else an SVID2/XPG2 compliant\n" + " version is declared below. These must be precisely the same for\n" + " mallinfo() to work. The original SVID version of this struct,\n" + " defined on most systems with mallinfo, declares all fields as\n" + " ints. But some others define as unsigned long. If your system\n" + " defines the fields using a type of different width than listed here,\n" + " you must #include your system version and #define\n" + " HAVE_USR_INCLUDE_MALLOC_H.\n" + "*/\n" + "\n" + "/* #define HAVE_USR_INCLUDE_MALLOC_H */\n" + "\n" + "#ifdef HAVE_USR_INCLUDE_MALLOC_H\n" + "#include \"/usr/include/malloc.h\"\n" + "#else\n" + "\n" + "/* SVID2/XPG mallinfo structure */\n" + "\n" + "struct mallinfo {\n" + " int arena; /* non-mmapped space allocated from system */\n" + " int ordblks; /* number of free chunks */\n" + " int smblks; /* number of fastbin blocks */\n" + " int hblks; /* number of mmapped regions */\n" + " int hblkhd; /* space in mmapped regions */\n" + " int usmblks; /* maximum total allocated space */\n" + " int fsmblks; /* space available in freed fastbin blocks */\n" + " int uordblks; /* total allocated space */\n" + " int fordblks; /* total free space */\n" + " int keepcost; /* top-most, releasable (via malloc_trim) space */\n" + "};\n" + "\n" + "/*\n" + " SVID/XPG defines four standard parameter numbers for mallopt,\n" + " normally defined in malloc.h. Only one of these (M_MXFAST) is used\n" + " in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,\n" + " so setting them has no effect. But this malloc also supports other\n" + " options in mallopt described below.\n" + "*/\n") + ("#endif\n" + "\n" + "\n" + "/* ---------- description of public routines ------------ */\n" + "\n" + "/*\n" + " malloc(size_t n)\n" + " Returns a pointer to a newly allocated chunk of at least n bytes, or null\n" + " if no space is available. Additionally, on failure, errno is\n" + " set to ENOMEM on ANSI C systems.\n" + "\n" + " If n is zero, malloc returns a minumum-sized chunk. (The minimum\n" + " size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit\n" + " systems.) On most systems, size_t is an unsigned type, so calls\n" + " with negative arguments are interpreted as requests for huge amounts\n" + " of space, which will often fail. The maximum supported value of n\n" + " differs across systems, but is in all cases less than the maximum\n" + " representable value of a size_t.\n" + "*/\n" + "#if __STD_C\n" + "Void_t* public_mALLOc(size_t);\n" + "#else\n" + "Void_t* public_mALLOc();\n" + "#endif\n" + "\n" + "/*\n" + " free(Void_t* p)\n" + " Releases the chunk of memory pointed to by p, that had been previously\n" + " allocated using malloc or a related routine such as realloc.\n" + " It has no effect if p is null. It can have arbitrary (i.e., bad!)\n" + " effects if p has already been freed.\n" + "\n" + " Unless disabled (using mallopt), freeing very large spaces will\n" + " when possible, automatically trigger operations that give\n" + " back unused memory to the system, thus reducing program footprint.\n" + "*/\n" + "#if __STD_C\n" + "void public_fREe(Void_t*);\n" + "#else\n" + "void public_fREe();\n" + "#endif\n" + "\n" + "/*\n" + " calloc(size_t n_elements, size_t element_size);\n" + " Returns a pointer to n_elements * element_size bytes, with all locations\n" + " set to zero.\n" + "*/\n" + "#if __STD_C\n" + "Void_t* public_cALLOc(size_t, size_t);\n" + "#else\n" + "Void_t* public_cALLOc();\n" + "#endif\n" + "\n" + "/*\n" + " realloc(Void_t* p, size_t n)\n" + " Returns a pointer to a chunk of size n that contains the same data\n" + " as does chunk p up to the minimum of (n, p's size) bytes, or null\n" + " if no space is available.\n" + "\n" + " The returned pointer may or may not be the same as p. The algorithm\n" + " prefers extending p when possible, otherwise it employs the\n" + " equivalent of a malloc-copy-free sequence.\n" + "\n" + " If p is null, realloc is equivalent to malloc.\n" + "\n" + " If space is not available, realloc returns null, errno is set (if on\n" + " ANSI) and p is NOT freed.\n" + "\n" + " if n is for fewer bytes than already held by p, the newly unused\n" + " space is lopped off and freed if possible. Unless the #define\n" + " REALLOC_ZERO_BYTES_FREES is set, realloc with a size argument of\n" + " zero (re)allocates a minimum-sized chunk.\n" + "\n" + " Large chunks that were internally obtained via mmap will always\n" + " be reallocated using malloc-copy-free sequences unless\n" + " the system supports MREMAP (currently only linux).\n" + "\n" + " The old unix realloc convention of allowing the last-free'd chunk\n" + " to be used as an argument to realloc is not supported.\n" + "*/\n" + "#if __STD_C\n" + "Void_t* public_rEALLOc(Void_t*, size_t);\n" + "#else\n" + "Void_t* public_rEALLOc();\n" + "#endif\n" + "\n" + "/*\n" + " memalign(size_t alignment, size_t n);\n" + " Returns a pointer to a newly allocated chunk of n bytes, aligned\n" + " in accord with the alignment argument.\n" + "\n" + " The alignment argument should be a power of two. If the argument is\n" + " not a power of two, the nearest greater power is used.\n" + " 8-byte alignment is guaranteed by normal malloc calls, so don't\n" + " bother calling memalign with an argument of 8 or less.\n" + "\n" + " Overreliance on memalign is a sure way to fragment space.\n" + "*/\n" + "#if __STD_C\n" + "Void_t* public_mEMALIGn(size_t, size_t);\n" + "#else\n" + "Void_t* public_mEMALIGn();\n" + "#endif\n" + "\n" + "/*\n" + " valloc(size_t n);\n" + " Equivalent to memalign(pagesize, n), where pagesize is the page\n" + " size of the system. If the pagesize is unknown, 4096 is used.\n" + "*/\n" + "#if __STD_C\n" + "Void_t* public_vALLOc(size_t);\n" + "#else\n" + "Void_t* public_vALLOc();\n" + "#endif\n" + "\n" + "\n" + "\n" + "/*\n" + " mallopt(int parameter_number, int parameter_value)\n" + " Sets tunable parameters The format is to provide a\n" + " (parameter-number, parameter-value) pair. mallopt then sets the\n" + " corresponding parameter to the argument value if it can (i.e., so\n" + " long as the value is meaningful), and returns 1 if successful else\n" + " 0. SVID/XPG/ANSI defines four standard param numbers for mallopt,\n" + " normally defined in malloc.h. Only one of these (M_MXFAST) is used\n" + " in this malloc. The others (M_NLBLKS, M_GRAIN, M_KEEP) don't apply,\n" + " so setting them has no effect. But this malloc also supports four\n" + " other options in mallopt. See below for details. Briefly, supported\n" + " parameters are as follows (listed defaults are for \"typical\"\n" + " configurations).\n" + "\n" + " Symbol param # default allowed param values\n" + " M_MXFAST 1 64 0-80 (0 disables fastbins)\n" + " M_TRIM_THRESHOLD -1 256*1024 any (-1U disables trimming)\n" + " M_TOP_PAD -2 0 any\n" + " M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support)\n" + " M_MMAP_MAX -4 65536 any (0 disables use of mmap)\n" + "*/\n" + "#if __STD_C\n" + "int public_mALLOPt(int, int);\n" + "#else\n" + "int public_mALLOPt();\n" + "#endif\n" + "\n" + "\n" + "/*\n" + " mallinfo()\n" + " Returns (by copy) a struct containing various summary statistics:\n" + "\n") + (" arena: current total non-mmapped bytes allocated from system\n" + " ordblks: the number of free chunks\n" + " smblks: the number of fastbin blocks (i.e., small chunks that\n" + " have been freed but not use resused or consolidated)\n" + " hblks: current number of mmapped regions\n" + " hblkhd: total bytes held in mmapped regions\n" + " usmblks: the maximum total allocated space. This will be greater\n" + " than current total if trimming has occurred.\n" + " fsmblks: total bytes held in fastbin blocks\n" + " uordblks: current total allocated space (normal or mmapped)\n" + " fordblks: total free space\n" + " keepcost: the maximum number of bytes that could ideally be released\n" + " back to system via malloc_trim. (\"ideally\" means that\n" + " it ignores page restrictions etc.)\n" + "\n" + " Because these fields are ints, but internal bookkeeping may\n" + " be kept as longs, the reported values may wrap around zero and\n" + " thus be inaccurate.\n" + "*/\n" + "#if __STD_C\n" + "struct mallinfo public_mALLINFo(void);\n" + "#else\n" + "struct mallinfo public_mALLINFo();\n" + "#endif\n" + "\n" + "/*\n" + " independent_calloc(size_t n_elements, size_t element_size, Void_t* chunks[]);\n" + "\n" + " independent_calloc is similar to calloc, but instead of returning a\n" + " single cleared space, it returns an array of pointers to n_elements\n" + " independent elements that can hold contents of size elem_size, each\n" + " of which starts out cleared, and can be independently freed,\n" + " realloc'ed etc. The elements are guaranteed to be adjacently\n" + " allocated (this is not guaranteed to occur with multiple callocs or\n" + " mallocs), which may also improve cache locality in some\n" + " applications.\n" + "\n" + " The \"chunks\" argument is optional (i.e., may be null, which is\n" + " probably the most typical usage). If it is null, the returned array\n" + " is itself dynamically allocated and should also be freed when it is\n" + " no longer needed. Otherwise, the chunks array must be of at least\n" + " n_elements in length. It is filled in with the pointers to the\n" + " chunks.\n" + "\n" + " In either case, independent_calloc returns this pointer array, or\n" + " null if the allocation failed. If n_elements is zero and \"chunks\"\n" + " is null, it returns a chunk representing an array with zero elements\n" + " (which should be freed if not wanted).\n" + "\n" + " Each element must be individually freed when it is no longer\n" + " needed. If you'd like to instead be able to free all at once, you\n" + " should instead use regular calloc and assign pointers into this\n" + " space to represent elements. (In this case though, you cannot\n" + " independently free elements.)\n" + "\n" + " independent_calloc simplifies and speeds up implementations of many\n" + " kinds of pools. It may also be useful when constructing large data\n" + " structures that initially have a fixed number of fixed-sized nodes,\n" + " but the number is not known at compile time, and some of the nodes\n" + " may later need to be freed. For example:\n" + "\n" + " struct Node { int item; struct Node* next; };\n" + "\n" + " struct Node* build_list() {\n" + " struct Node** pool;\n" + " int n = read_number_of_nodes_needed();\n" + " if (n <= 0) return 0;\n" + " pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0);\n" + " if (pool == 0) die();\n" + " // organize into a linked list...\n" + " struct Node* first = pool[0];\n" + " for (i = 0; i < n-1; ++i)\n" + " pool[i]->next = pool[i+1];\n" + " free(pool); // Can now free the array (or not, if it is needed later)\n" + " return first;\n" + " }\n" + "*/\n" + "#if __STD_C\n" + "Void_t** public_iCALLOc(size_t, size_t, Void_t**);\n" + "#else\n" + "Void_t** public_iCALLOc();\n" + "#endif\n" + "\n" + "/*\n" + " independent_comalloc(size_t n_elements, size_t sizes[], Void_t* chunks[]);\n" + "\n" + " independent_comalloc allocates, all at once, a set of n_elements\n" + " chunks with sizes indicated in the \"sizes\" array. It returns\n" + " an array of pointers to these elements, each of which can be\n" + " independently freed, realloc'ed etc. The elements are guaranteed to\n" + " be adjacently allocated (this is not guaranteed to occur with\n" + " multiple callocs or mallocs), which may also improve cache locality\n" + " in some applications.\n" + "\n" + " The \"chunks\" argument is optional (i.e., may be null). If it is null\n" + " the returned array is itself dynamically allocated and should also\n" + " be freed when it is no longer needed. Otherwise, the chunks array\n" + " must be of at least n_elements in length. It is filled in with the\n" + " pointers to the chunks.\n" + "\n" + " In either case, independent_comalloc returns this pointer array, or\n" + " null if the allocation failed. If n_elements is zero and chunks is\n" + " null, it returns a chunk representing an array with zero elements\n" + " (which should be freed if not wanted).\n" + "\n" + " Each element must be individually freed when it is no longer\n" + " needed. If you'd like to instead be able to free all at once, you\n" + " should instead use a single regular malloc, and assign pointers at\n" + " particular offsets in the aggregate space. (In this case though, you\n" + " cannot independently free elements.)\n" + "\n" + " independent_comallac differs from independent_calloc in that each\n" + " element may have a different size, and also that it does not\n" + " automatically clear elements.\n" + "\n" + " independent_comalloc can be used to speed up allocation in cases\n" + " where several structs or objects must always be allocated at the\n" + " same time. For example:\n" + "\n" + " struct Head { ... }\n" + " struct Foot { ... }\n" + "\n" + " void send_message(char* msg) {\n" + " int msglen = strlen(msg);\n" + " size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };\n" + " void* chunks[3];\n" + " if (independent_comalloc(3, sizes, chunks) == 0)\n" + " die();\n" + " struct Head* head = (struct Head*)(chunks[0]);\n" + " char* body = (char*)(chunks[1]);\n" + " struct Foot* foot = (struct Foot*)(chunks[2]);\n" + " // ...\n" + " }\n" + "\n" + " In general though, independent_comalloc is worth using only for\n" + " larger values of n_elements. For small values, you probably won't\n" + " detect enough difference from series of malloc calls to bother.\n" + "\n" + " Overuse of independent_comalloc can increase overall memory usage,\n" + " since it cannot reuse existing noncontiguous small chunks that\n" + " might be available for some of the elements.\n" + "*/\n" + "#if __STD_C\n" + "Void_t** public_iCOMALLOc(size_t, size_t*, Void_t**);\n" + "#else\n" + "Void_t** public_iCOMALLOc();\n" + "#endif\n" + "\n" + "\n" + "/*\n") + (" pvalloc(size_t n);\n" + " Equivalent to valloc(minimum-page-that-holds(n)), that is,\n" + " round up n to nearest pagesize.\n" + " */\n" + "#if __STD_C\n" + "Void_t* public_pVALLOc(size_t);\n" + "#else\n" + "Void_t* public_pVALLOc();\n" + "#endif\n" + "\n" + "/*\n" + " cfree(Void_t* p);\n" + " Equivalent to free(p).\n" + "\n" + " cfree is needed/defined on some systems that pair it with calloc,\n" + " for odd historical reasons (such as: cfree is used in example\n" + " code in the first edition of K&R).\n" + "*/\n" + "#if __STD_C\n" + "void public_cFREe(Void_t*);\n" + "#else\n" + "void public_cFREe();\n" + "#endif\n" + "\n" + "/*\n" + " malloc_trim(size_t pad);\n" + "\n" + " If possible, gives memory back to the system (via negative\n" + " arguments to sbrk) if there is unused memory at the `high' end of\n" + " the malloc pool. You can call this after freeing large blocks of\n" + " memory to potentially reduce the system-level memory requirements\n" + " of a program. However, it cannot guarantee to reduce memory. Under\n" + " some allocation patterns, some large free blocks of memory will be\n" + " locked between two used chunks, so they cannot be given back to\n" + " the system.\n" + "\n" + " The `pad' argument to malloc_trim represents the amount of free\n" + " trailing space to leave untrimmed. If this argument is zero,\n" + " only the minimum amount of memory to maintain internal data\n" + " structures will be left (one page or less). Non-zero arguments\n" + " can be supplied to maintain enough trailing space to service\n" + " future expected allocations without having to re-obtain memory\n" + " from the system.\n" + "\n" + " Malloc_trim returns 1 if it actually released any memory, else 0.\n" + " On systems that do not support \"negative sbrks\", it will always\n" + " rreturn 0.\n" + "*/\n" + "#if __STD_C\n" + "int public_mTRIm(size_t);\n" + "#else\n" + "int public_mTRIm();\n" + "#endif\n" + "\n" + "/*\n" + " malloc_usable_size(Void_t* p);\n" + "\n" + " Returns the number of bytes you can actually use in\n" + " an allocated chunk, which may be more than you requested (although\n" + " often not) due to alignment and minimum size constraints.\n" + " You can use this many bytes without worrying about\n" + " overwriting other allocated objects. This is not a particularly great\n" + " programming practice. malloc_usable_size can be more useful in\n" + " debugging and assertions, for example:\n" + "\n" + " p = malloc(n);\n" + " assert(malloc_usable_size(p) >= 256);\n" + "\n" + "*/\n" + "#if __STD_C\n" + "size_t public_mUSABLe(Void_t*);\n" + "#else\n" + "size_t public_mUSABLe();\n" + "#endif\n" + "\n" + "/*\n" + " malloc_stats();\n" + " Prints on stderr the amount of space obtained from the system (both\n" + " via sbrk and mmap), the maximum amount (which may be more than\n" + " current if malloc_trim and/or munmap got called), and the current\n" + " number of bytes allocated via malloc (or realloc, etc) but not yet\n" + " freed. Note that this is the number of bytes allocated, not the\n" + " number requested. It will be larger than the number requested\n" + " because of alignment and bookkeeping overhead. Because it includes\n" + " alignment wastage as being in use, this figure may be greater than\n" + " zero even when no user-level chunks are allocated.\n" + "\n" + " The reported current and maximum system memory can be inaccurate if\n" + " a program makes other calls to system memory allocation functions\n" + " (normally sbrk) outside of malloc.\n" + "\n" + " malloc_stats prints only the most commonly interesting statistics.\n" + " More information can be obtained by calling mallinfo.\n" + "\n" + "*/\n" + "#if __STD_C\n" + "void public_mSTATs();\n" + "#else\n" + "void public_mSTATs();\n" + "#endif\n" + "\n" + "/* mallopt tuning options */\n" + "\n" + "/*\n" + " M_MXFAST is the maximum request size used for \"fastbins\", special bins\n" + " that hold returned chunks without consolidating their spaces. This\n" + " enables future requests for chunks of the same size to be handled\n" + " very quickly, but can increase fragmentation, and thus increase the\n" + " overall memory footprint of a program.\n" + "\n" + " This malloc manages fastbins very conservatively yet still\n" + " efficiently, so fragmentation is rarely a problem for values less\n" + " than or equal to the default. The maximum supported value of MXFAST\n" + " is 80. You wouldn't want it any higher than this anyway. Fastbins\n" + " are designed especially for use with many small structs, objects or\n" + " strings -- the default handles structs/objects/arrays with sizes up\n" + " to 16 4byte fields, or small strings representing words, tokens,\n" + " etc. Using fastbins for larger objects normally worsens\n" + " fragmentation without improving speed.\n" + "\n" + " M_MXFAST is set in REQUEST size units. It is internally used in\n" + " chunksize units, which adds padding and alignment. You can reduce\n" + " M_MXFAST to 0 to disable all use of fastbins. This causes the malloc\n" + " algorithm to be a closer approximation of fifo-best-fit in all cases,\n" + " not just for larger requests, but will generally cause it to be\n" + " slower.\n" + "*/\n" + "\n" + "\n" + "/* M_MXFAST is a standard SVID/XPG tuning option, usually listed in malloc.h */\n" + "#ifndef M_MXFAST\n" + "#define M_MXFAST 1\n" + "#endif\n" + "\n" + "#ifndef DEFAULT_MXFAST\n" + "#define DEFAULT_MXFAST 64\n" + "#endif\n" + "\n" + "\n" + "/*\n" + " M_TRIM_THRESHOLD is the maximum amount of unused top-most memory\n" + " to keep before releasing via malloc_trim in free().\n" + "\n" + " Automatic trimming is mainly useful in long-lived programs.\n" + " Because trimming via sbrk can be slow on some systems, and can\n" + " sometimes be wasteful (in cases where programs immediately\n" + " afterward allocate more large chunks) the value should be high\n" + " enough so that your overall system performance would improve by\n" + " releasing this much memory.\n" + "\n") + (" The trim threshold and the mmap control parameters (see below)\n" + " can be traded off with one another. Trimming and mmapping are\n" + " two different ways of releasing unused memory back to the\n" + " system. Between these two, it is often possible to keep\n" + " system-level demands of a long-lived program down to a bare\n" + " minimum. For example, in one test suite of sessions measuring\n" + " the XF86 X server on Linux, using a trim threshold of 128K and a\n" + " mmap threshold of 192K led to near-minimal long term resource\n" + " consumption.\n" + "\n" + " If you are using this malloc in a long-lived program, it should\n" + " pay to experiment with these values. As a rough guide, you\n" + " might set to a value close to the average size of a process\n" + " (program) running on your system. Releasing this much memory\n" + " would allow such a process to run in memory. Generally, it's\n" + " worth it to tune for trimming rather tham memory mapping when a\n" + " program undergoes phases where several large chunks are\n" + " allocated and released in ways that can reuse each other's\n" + " storage, perhaps mixed with phases where there are no such\n" + " chunks at all. And in well-behaved long-lived programs,\n" + " controlling release of large blocks via trimming versus mapping\n" + " is usually faster.\n" + "\n" + " However, in most programs, these parameters serve mainly as\n" + " protection against the system-level effects of carrying around\n" + " massive amounts of unneeded memory. Since frequent calls to\n" + " sbrk, mmap, and munmap otherwise degrade performance, the default\n" + " parameters are set to relatively high values that serve only as\n" + " safeguards.\n" + "\n" + " The trim value must be greater than page size to have any useful\n" + " effect. To disable trimming completely, you can set to\n" + " (unsigned long)(-1)\n" + "\n" + " Trim settings interact with fastbin (MXFAST) settings: Unless\n" + " TRIM_FASTBINS is defined, automatic trimming never takes place upon\n" + " freeing a chunk with size less than or equal to MXFAST. Trimming is\n" + " instead delayed until subsequent freeing of larger chunks. However,\n" + " you can still force an attempted trim by calling malloc_trim.\n" + "\n" + " Also, trimming is not generally possible in cases where\n" + " the main arena is obtained via mmap.\n" + "\n" + " Note that the trick some people use of mallocing a huge space and\n" + " then freeing it at program startup, in an attempt to reserve system\n" + " memory, doesn't have the intended effect under automatic trimming,\n" + " since that memory will immediately be returned to the system.\n" + "*/\n" + "\n" + "#define M_TRIM_THRESHOLD -1\n" + "\n" + "#ifndef DEFAULT_TRIM_THRESHOLD\n" + "#define DEFAULT_TRIM_THRESHOLD (256 * 1024)\n" + "#endif\n" + "\n" + "/*\n" + " M_TOP_PAD is the amount of extra `padding' space to allocate or\n" + " retain whenever sbrk is called. It is used in two ways internally:\n" + "\n" + " * When sbrk is called to extend the top of the arena to satisfy\n" + " a new malloc request, this much padding is added to the sbrk\n" + " request.\n" + "\n" + " * When malloc_trim is called automatically from free(),\n" + " it is used as the `pad' argument.\n" + "\n" + " In both cases, the actual amount of padding is rounded\n" + " so that the end of the arena is always a system page boundary.\n" + "\n" + " The main reason for using padding is to avoid calling sbrk so\n" + " often. Having even a small pad greatly reduces the likelihood\n" + " that nearly every malloc request during program start-up (or\n" + " after trimming) will invoke sbrk, which needlessly wastes\n" + " time.\n" + "\n" + " Automatic rounding-up to page-size units is normally sufficient\n" + " to avoid measurable overhead, so the default is 0. However, in\n" + " systems where sbrk is relatively slow, it can pay to increase\n" + " this value, at the expense of carrying around more memory than\n" + " the program needs.\n" + "*/\n" + "\n" + "#define M_TOP_PAD -2\n" + "\n" + "#ifndef DEFAULT_TOP_PAD\n" + "#define DEFAULT_TOP_PAD (0)\n" + "#endif\n" + "\n" + "/*\n" + " M_MMAP_THRESHOLD is the request size threshold for using mmap()\n" + " to service a request. Requests of at least this size that cannot\n" + " be allocated using already-existing space will be serviced via mmap.\n" + " (If enough normal freed space already exists it is used instead.)\n" + "\n" + " Using mmap segregates relatively large chunks of memory so that\n" + " they can be individually obtained and released from the host\n" + " system. A request serviced through mmap is never reused by any\n" + " other request (at least not directly; the system may just so\n" + " happen to remap successive requests to the same locations).\n" + "\n" + " Segregating space in this way has the benefits that:\n" + "\n" + " 1. Mmapped space can ALWAYS be individually released back\n" + " to the system, which helps keep the system level memory\n" + " demands of a long-lived program low.\n" + " 2. Mapped memory can never become `locked' between\n" + " other chunks, as can happen with normally allocated chunks, which\n" + " means that even trimming via malloc_trim would not release them.\n" + " 3. On some systems with \"holes\" in address spaces, mmap can obtain\n" + " memory that sbrk cannot.\n" + "\n" + " However, it has the disadvantages that:\n" + "\n" + " 1. The space cannot be reclaimed, consolidated, and then\n" + " used to service later requests, as happens with normal chunks.\n" + " 2. It can lead to more wastage because of mmap page alignment\n" + " requirements\n" + " 3. It causes malloc performance to be more dependent on host\n" + " system memory management support routines which may vary in\n" + " implementation quality and may impose arbitrary\n" + " limitations. Generally, servicing a request via normal\n" + " malloc steps is faster than going through a system's mmap.\n" + "\n" + " The advantages of mmap nearly always outweigh disadvantages for\n" + " \"large\" chunks, but the value of \"large\" varies across systems. The\n" + " default is an empirically derived value that works well in most\n" + " systems.\n" + "*/\n" + "\n" + "#define M_MMAP_THRESHOLD -3\n" + "\n" + "#ifndef DEFAULT_MMAP_THRESHOLD\n" + "#define DEFAULT_MMAP_THRESHOLD (256 * 1024)\n" + "#endif\n" + "\n" + "/*\n" + " M_MMAP_MAX is the maximum number of requests to simultaneously\n" + " service using mmap. This parameter exists because\n" + ". Some systems have a limited number of internal tables for\n" + " use by mmap, and using more than a few of them may degrade\n" + " performance.\n" + "\n" + " The default is set to a value that serves only as a safeguard.\n" + " Setting to 0 disables use of mmap for servicing large requests. If\n" + " HAVE_MMAP is not set, the default value is 0, and attempts to set it\n" + " to non-zero values in mallopt will fail.\n" + "*/\n" + "\n" + "#define M_MMAP_MAX -4\n" + "\n") + ("#ifndef DEFAULT_MMAP_MAX\n" + "#if HAVE_MMAP\n" + "#define DEFAULT_MMAP_MAX (65536)\n" + "#else\n" + "#define DEFAULT_MMAP_MAX (0)\n" + "#endif\n" + "#endif\n" + "\n" + "/*\n" + " ========================================================================\n" + " To make a fully customizable malloc.h header file, cut everything\n" + " above this line, put into file malloc.h, edit to suit, and #include it\n" + " on the next line, as well as in programs that use this malloc.\n" + " ========================================================================\n" + "*/\n" + "\n" + "/* #include \"malloc.h\" */\n" + "\n" + "/* --------------------- public wrappers ---------------------- */\n" + "\n" + "#ifdef USE_PUBLIC_MALLOC_WRAPPERS\n" + "\n" + "/* Declare all routines as internal */\n" + "#if __STD_C\n" + "static Void_t* mALLOc(size_t);\n" + "static void fREe(Void_t*);\n" + "static Void_t* rEALLOc(Void_t*, size_t);\n" + "static Void_t* mEMALIGn(size_t, size_t);\n" + "static Void_t* vALLOc(size_t);\n" + "static Void_t* pVALLOc(size_t);\n" + "static Void_t* cALLOc(size_t, size_t);\n" + "static Void_t** iCALLOc(size_t, size_t, Void_t**);\n" + "static Void_t** iCOMALLOc(size_t, size_t*, Void_t**);\n" + "static void cFREe(Void_t*);\n" + "static int mTRIm(size_t);\n" + "static size_t mUSABLe(Void_t*);\n" + "static void mSTATs();\n" + "static int mALLOPt(int, int);\n" + "static struct mallinfo mALLINFo(void);\n" + "#else\n" + "static Void_t* mALLOc();\n" + "static void fREe();\n" + "static Void_t* rEALLOc();\n" + "static Void_t* mEMALIGn();\n" + "static Void_t* vALLOc();\n" + "static Void_t* pVALLOc();\n" + "static Void_t* cALLOc();\n" + "static Void_t** iCALLOc();\n" + "static Void_t** iCOMALLOc();\n" + "static void cFREe();\n" + "static int mTRIm();\n" + "static size_t mUSABLe();\n" + "static void mSTATs();\n" + "static int mALLOPt();\n" + "static struct mallinfo mALLINFo();\n" + "#endif\n" + "\n" + "/*\n" + " MALLOC_PREACTION and MALLOC_POSTACTION should be\n" + " defined to return 0 on success, and nonzero on failure.\n" + " The return value of MALLOC_POSTACTION is currently ignored\n" + " in wrapper functions since there is no reasonable default\n" + " action to take on failure.\n" + "*/\n" + "\n" + "\n" + "#ifdef USE_MALLOC_LOCK\n" + "\n" + "#ifdef WIN32\n" + "\n" + "static int mALLOC_MUTEx;\n" + "#define MALLOC_PREACTION slwait(&mALLOC_MUTEx)\n" + "#define MALLOC_POSTACTION slrelease(&mALLOC_MUTEx)\n" + "\n" + "#else\n" + "\n" + "#include <pthread.h>\n" + "\n" + "static pthread_mutex_t mALLOC_MUTEx = PTHREAD_MUTEX_INITIALIZER;\n" + "\n" + "#define MALLOC_PREACTION pthread_mutex_lock(&mALLOC_MUTEx)\n" + "#define MALLOC_POSTACTION pthread_mutex_unlock(&mALLOC_MUTEx)\n" + "\n" + "#endif /* USE_MALLOC_LOCK */\n" + "\n" + "#else\n" + "\n" + "/* Substitute anything you like for these */\n" + "\n" + "#define MALLOC_PREACTION (0)\n" + "#define MALLOC_POSTACTION (0)\n" + "\n" + "#endif\n" + "\n" + "Void_t* public_mALLOc(size_t bytes) {\n" + " Void_t* m;\n" + " if (MALLOC_PREACTION != 0) {\n" + " return 0;\n" + " }\n" + " m = mALLOc(bytes);\n" + " if (MALLOC_POSTACTION != 0) {\n" + " }\n" + " return m;\n" + "}\n" + "\n" + "\n" + "static pthread_once_t free_mutex_once = PTHREAD_ONCE_INIT;\n" + "static pthread_mutex_t free_mutex;\n" + "static int scheduled_free_size;\n" + "static int scheduled_free_capacity;\n" + "static int scheduled_free_list;\n" + "bool free_is_scheduled;\n" + "\n" + "static void initialize_scheduled_free_list()\n" + "{\n" + " pthread_mutex_init(&free_mutex, NULL);\n" + "}\n" + "\n" + "static void drain_scheduled_free_list()\n" + "{\n" + " pthread_mutex_lock(&free_mutex);\n" + " if (free_is_scheduled) {\n" + " for(int i = 0; i < scheduled_free_size; i++) {\n" + " main_thread_free(scheduled_free_list[i]);\n" + " }\n" + " free(scheduled_free_list);\n" + " scheduled_free_list = NULL;\n" + " scheduled_free_size = 0;\n" + " scheduled_free_capacity = 0;\n" + " free_is_scheduled = false;\n" + " }\n" + " pthread_mutex_unlock(&free_mutex);\n" + "}\n" + "\n" + "static void schedule_free_on_main_thread(Void_t* m)\n" + "{\n" + " pthread_once(&free_mutex_once, initialize_scheduled_free_list);\n" + "\n" + " pthread_mutex_lock(&free_mutex);\n" + " if (scheduled_free_size == scheduled_free_capacity) {\n" + " scheduled_free_capacity = scheduled_free_capacity == 0 ? 16 : scheduled_free_capacity * 1.2;\n" + " scheduled_free_list = (Void_t**)realloc(scheduled_free_list, sizeof(Void_t*) * scheduled_free_capacity);\n" + " }\n" + " scheduled_free_list[scheduled_free_size++] = m;\n" + " if (!free_is_scheduled) {\n" + " QTimer::immediateSingleShotOnMainThread(0, drain_scheduled_free_list);\n" + " free_is_scheduled = true;\n" + " }\n" + " pthread_mutex_unlock(&free_mutex);\n" + "}\n") + ("\n" + "void public_fREe(Void_t* m) {\n" + " if (!pthread_main_np()) {\n" + " schedule_free_on_main_thread(m);\n" + " return;\n" + " }\n" + "\n" + " if (MALLOC_PREACTION != 0) {\n" + " return;\n" + " }\n" + " fREe(m);\n" + " if (MALLOC_POSTACTION != 0) {\n" + " }\n" + "}\n" + "\n" + "Void_t* public_rEALLOc(Void_t* m, size_t bytes) {\n" + " if (MALLOC_PREACTION != 0) {\n" + " return 0;\n" + " }\n" + " m = rEALLOc(m, bytes);\n" + " if (MALLOC_POSTACTION != 0) {\n" + " }\n" + " return m;\n" + "}\n" + "\n" + "Void_t* public_mEMALIGn(size_t alignment, size_t bytes) {\n" + " Void_t* m;\n" + " if (MALLOC_PREACTION != 0) {\n" + " return 0;\n" + " }\n" + " m = mEMALIGn(alignment, bytes);\n" + " if (MALLOC_POSTACTION != 0) {\n" + " }\n" + " return m;\n" + "}\n" + "\n" + "Void_t* public_vALLOc(size_t bytes) {\n" + " Void_t* m;\n" + " if (MALLOC_PREACTION != 0) {\n" + " return 0;\n" + " }\n" + " m = vALLOc(bytes);\n" + " if (MALLOC_POSTACTION != 0) {\n" + " }\n" + " return m;\n" + "}\n" + "\n" + "Void_t* public_pVALLOc(size_t bytes) {\n" + " Void_t* m;\n" + " if (MALLOC_PREACTION != 0) {\n" + " return 0;\n" + " }\n" + " m = pVALLOc(bytes);\n" + " if (MALLOC_POSTACTION != 0) {\n" + " }\n" + " return m;\n" + "}\n" + "\n" + "Void_t* public_cALLOc(size_t n, size_t elem_size) {\n" + " Void_t* m;\n" + " if (MALLOC_PREACTION != 0) {\n" + " return 0;\n" + " }\n" + " m = cALLOc(n, elem_size);\n" + " if (MALLOC_POSTACTION != 0) {\n" + " }\n" + " return m;\n" + "}\n" + "\n" + "\n" + "Void_t** public_iCALLOc(size_t n, size_t elem_size, Void_t** chunks) {\n" + " Void_t** m;\n" + " if (MALLOC_PREACTION != 0) {\n" + " return 0;\n" + " }\n" + " m = iCALLOc(n, elem_size, chunks);\n" + " if (MALLOC_POSTACTION != 0) {\n" + " }\n" + " return m;\n" + "}\n" + "\n" + "Void_t** public_iCOMALLOc(size_t n, size_t sizes[], Void_t** chunks) {\n" + " Void_t** m;\n" + " if (MALLOC_PREACTION != 0) {\n" + " return 0;\n" + " }\n" + " m = iCOMALLOc(n, sizes, chunks);\n" + " if (MALLOC_POSTACTION != 0) {\n" + " }\n" + " return m;\n" + "}\n" + "\n" + "void public_cFREe(Void_t* m) {\n" + " if (MALLOC_PREACTION != 0) {\n" + " return;\n" + " }\n" + " cFREe(m);\n" + " if (MALLOC_POSTACTION != 0) {\n" + " }\n" + "}\n" + "\n" + "int public_mTRIm(size_t s) {\n" + " int result;\n" + " if (MALLOC_PREACTION != 0) {\n" + " return 0;\n" + " }\n" + " result = mTRIm(s);\n" + " if (MALLOC_POSTACTION != 0) {\n" + " }\n" + " return result;\n" + "}\n" + "\n" + "size_t public_mUSABLe(Void_t* m) {\n" + " size_t result;\n" + " if (MALLOC_PREACTION != 0) {\n" + " return 0;\n" + " }\n" + " result = mUSABLe(m);\n" + " if (MALLOC_POSTACTION != 0) {\n" + " }\n" + " return result;\n" + "}\n" + "\n" + "void public_mSTATs() {\n" + " if (MALLOC_PREACTION != 0) {\n" + " return;\n" + " }\n" + " mSTATs();\n" + " if (MALLOC_POSTACTION != 0) {\n" + " }\n" + "}\n" + "\n" + "struct mallinfo public_mALLINFo() {\n" + " struct mallinfo m;\n" + " if (MALLOC_PREACTION != 0) {\n" + " struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };\n" + " return nm;\n" + " }\n" + " m = mALLINFo();\n" + " if (MALLOC_POSTACTION != 0) {\n" + " }\n" + " return m;\n" + "}\n" + "\n" + "int public_mALLOPt(int p, int v) {\n" + " int result;\n" + " if (MALLOC_PREACTION != 0) {\n" + " return 0;\n" + " }\n" + " result = mALLOPt(p, v);\n" + " if (MALLOC_POSTACTION != 0) {\n" + " }\n" + " return result;\n" + "}\n" + "\n") + ("#endif\n" + "\n" + "\n" + "\n" + "/* ------------- Optional versions of memcopy ---------------- */\n" + "\n" + "\n" + "#if USE_MEMCPY\n" + "\n" + "/*\n" + " Note: memcpy is ONLY invoked with non-overlapping regions,\n" + " so the (usually slower) memmove is not needed.\n" + "*/\n" + "\n" + "#define MALLOC_COPY(dest, src, nbytes) memcpy(dest, src, nbytes)\n" + "#define MALLOC_ZERO(dest, nbytes) memset(dest, 0, nbytes)\n" + "\n" + "#else /* !USE_MEMCPY */\n" + "\n" + "/* Use Duff's device for good zeroing/copying performance. */\n" + "\n" + "#define MALLOC_ZERO(charp, nbytes) \\n" + "do { \\n" + " INTERNAL_SIZE_T* mzp = (INTERNAL_SIZE_T*)(charp); \\n" + " CHUNK_SIZE_T mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T); \\n" + " long mcn; \\n" + " if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \\n" + " switch (mctmp) { \\n" + " case 0: for(;;) { *mzp++ = 0; \\n" + " case 7: *mzp++ = 0; \\n" + " case 6: *mzp++ = 0; \\n" + " case 5: *mzp++ = 0; \\n" + " case 4: *mzp++ = 0; \\n" + " case 3: *mzp++ = 0; \\n" + " case 2: *mzp++ = 0; \\n" + " case 1: *mzp++ = 0; if(mcn <= 0) break; mcn--; } \\n" + " } \\n" + "} while(0)\n" + "\n" + "#define MALLOC_COPY(dest,src,nbytes) \\n" + "do { \\n" + " INTERNAL_SIZE_T* mcsrc = (INTERNAL_SIZE_T*) src; \\n" + " INTERNAL_SIZE_T* mcdst = (INTERNAL_SIZE_T*) dest; \\n" + " CHUNK_SIZE_T mctmp = (nbytes)/sizeof(INTERNAL_SIZE_T); \\n" + " long mcn; \\n" + " if (mctmp < 8) mcn = 0; else { mcn = (mctmp-1)/8; mctmp %= 8; } \\n" + " switch (mctmp) { \\n" + " case 0: for(;;) { *mcdst++ = *mcsrc++; \\n" + " case 7: *mcdst++ = *mcsrc++; \\n" + " case 6: *mcdst++ = *mcsrc++; \\n" + " case 5: *mcdst++ = *mcsrc++; \\n" + " case 4: *mcdst++ = *mcsrc++; \\n" + " case 3: *mcdst++ = *mcsrc++; \\n" + " case 2: *mcdst++ = *mcsrc++; \\n" + " case 1: *mcdst++ = *mcsrc++; if(mcn <= 0) break; mcn--; } \\n" + " } \\n" + "} while(0)\n" + "\n" + "#endif\n" + "\n" + "/* ------------------ MMAP support ------------------ */\n" + "\n" + "\n" + "#if HAVE_MMAP\n" + "\n" + "#ifndef LACKS_FCNTL_H\n" + "#include <fcntl.h>\n" + "#endif\n" + "\n" + "#ifndef LACKS_SYS_MMAN_H\n" + "#include <sys/mman.h>\n" + "#endif\n" + "\n" + "#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)\n" + "#define MAP_ANONYMOUS MAP_ANON\n" + "#endif\n" + "\n" + "/*\n" + " Nearly all versions of mmap support MAP_ANONYMOUS,\n" + " so the following is unlikely to be needed, but is\n" + " supplied just in case.\n" + "*/\n" + "\n" + "#ifndef MAP_ANONYMOUS\n" + "\n" + "static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */\n" + "\n" + "#define MMAP(addr, size, prot, flags) ((dev_zero_fd < 0) ? \\n" + " (dev_zero_fd = open(\"/dev/zero\", O_RDWR), \\n" + " mmap((addr), (size), (prot), (flags), dev_zero_fd, 0)) : \\n" + " mmap((addr), (size), (prot), (flags), dev_zero_fd, 0))\n" + "\n" + "#else\n" + "\n" + "#define MMAP(addr, size, prot, flags) \\n" + " (mmap((addr), (size), (prot), (flags)|MAP_ANONYMOUS, -1, 0))\n" + "\n" + "#endif\n" + "\n" + "\n" + "#endif /* HAVE_MMAP */\n" + "\n" + "\n" + "/*\n" + " ----------------------- Chunk representations -----------------------\n" + "*/\n" + "\n" + "\n" + "/*\n" + " This struct declaration is misleading (but accurate and necessary).\n" + " It declares a \"view\" into memory allowing access to necessary\n" + " fields at known offsets from a given base. See explanation below.\n" + "*/\n" + "\n" + "struct malloc_chunk {\n" + "\n" + " INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */\n" + " INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */\n" + "\n" + " struct malloc_chunk* fd; /* double links -- used only if free. */\n" + " struct malloc_chunk* bk;\n" + "};\n" + "\n" + "\n" + "typedef struct malloc_chunk* mchunkptr;\n" + "\n" + "/*\n" + " malloc_chunk details:\n" + "\n" + " (The following includes lightly edited explanations by Colin Plumb.)\n" + "\n" + " Chunks of memory are maintained using a `boundary tag' method as\n" + " described in e.g., Knuth or Standish. (See the paper by Paul\n" + " Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a\n" + " survey of such techniques.) Sizes of free chunks are stored both\n" + " in the front of each chunk and at the end. This makes\n" + " consolidating fragmented chunks into bigger chunks very fast. The\n" + " size fields also hold bits representing whether chunks are free or\n" + " in use.\n" + "\n" + " An allocated chunk looks like this:\n" + "\n" + "\n" + " chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n" + " | Size of previous chunk, if allocated | |\n" + " +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n" + " | Size of chunk, in bytes |P|\n" + " mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n" + " | User data starts here... .\n" + " . .\n" + " . (malloc_usable_space() bytes) .\n" + " . |\n" + "nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n" + " | Size of chunk |\n" + " +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n" + "\n") + ("\n" + " Where \"chunk\" is the front of the chunk for the purpose of most of\n" + " the malloc code, but \"mem\" is the pointer that is returned to the\n" + " user. \"Nextchunk\" is the beginning of the next contiguous chunk.\n" + "\n" + " Chunks always begin on even word boundries, so the mem portion\n" + " (which is returned to the user) is also on an even word boundary, and\n" + " thus at least double-word aligned.\n" + "\n" + " Free chunks are stored in circular doubly-linked lists, and look like this:\n" + "\n" + " chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n" + " | Size of previous chunk |\n" + " +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n" + " `head:' | Size of chunk, in bytes |P|\n" + " mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n" + " | Forward pointer to next chunk in list |\n" + " +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n" + " | Back pointer to previous chunk in list |\n" + " +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n" + " | Unused space (may be 0 bytes long) .\n" + " . .\n" + " . |\n" + "nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n" + " `foot:' | Size of chunk, in bytes |\n" + " +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n" + "\n" + " The P (PREV_INUSE) bit, stored in the unused low-order bit of the\n" + " chunk size (which is always a multiple of two words), is an in-use\n" + " bit for the *previous* chunk. If that bit is *clear*, then the\n" + " word before the current chunk size contains the previous chunk\n" + " size, and can be used to find the front of the previous chunk.\n" + " The very first chunk allocated always has this bit set,\n" + " preventing access to non-existent (or non-owned) memory. If\n" + " prev_inuse is set for any given chunk, then you CANNOT determine\n" + " the size of the previous chunk, and might even get a memory\n" + " addressing fault when trying to do so.\n" + "\n" + " Note that the `foot' of the current chunk is actually represented\n" + " as the prev_size of the NEXT chunk. This makes it easier to\n" + " deal with alignments etc but can be very confusing when trying\n" + " to extend or adapt this code.\n" + "\n" + " The two exceptions to all this are\n" + "\n" + " 1. The special chunk `top' doesn't bother using the\n" + " trailing size field since there is no next contiguous chunk\n" + " that would have to index off it. After initialization, `top'\n" + " is forced to always exist. If it would become less than\n" + " MINSIZE bytes long, it is replenished.\n" + "\n" + " 2. Chunks allocated via mmap, which have the second-lowest-order\n" + " bit (IS_MMAPPED) set in their size fields. Because they are\n" + " allocated one-by-one, each must contain its own trailing size field.\n" + "\n" + "*/\n" + "\n" + "/*\n" + " ---------- Size and alignment checks and conversions ----------\n" + "*/\n" + "\n" + "/* conversion from malloc headers to user pointers, and back */\n" + "\n" + "#define chunk2mem(p) ((Void_t*)((char*)(p) + 2*SIZE_SZ))\n" + "#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - 2*SIZE_SZ))\n" + "\n" + "/* The smallest possible chunk */\n" + "#define MIN_CHUNK_SIZE (sizeof(struct malloc_chunk))\n" + "\n" + "/* The smallest size we can malloc is an aligned minimal chunk */\n" + "\n" + "#define MINSIZE \\n" + " (CHUNK_SIZE_T)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))\n" + "\n" + "/* Check if m has acceptable alignment */\n" + "\n" + "#define aligned_OK(m) (((PTR_UINT)((m)) & (MALLOC_ALIGN_MASK)) == 0)\n" + "\n" + "\n" + "/*\n" + " Check if a request is so large that it would wrap around zero when\n" + " padded and aligned. To simplify some other code, the bound is made\n" + " low enough so that adding MINSIZE will also not wrap around sero.\n" + "*/\n" + "\n" + "#define REQUEST_OUT_OF_RANGE(req) \\n" + " ((CHUNK_SIZE_T)(req) >= \\n" + " (CHUNK_SIZE_T)(INTERNAL_SIZE_T)(-2 * MINSIZE))\n" + "\n" + "/* pad request bytes into a usable size -- internal version */\n" + "\n" + "#define request2size(req) \\n" + " (((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \\n" + " MINSIZE : \\n" + " ((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)\n" + "\n" + "/* Same, except also perform argument check */\n" + "\n" + "#define checked_request2size(req, sz) \\n" + " if (REQUEST_OUT_OF_RANGE(req)) { \\n" + " MALLOC_FAILURE_ACTION; \\n" + " return 0; \\n" + " } \\n" + " (sz) = request2size(req);\n" + "\n" + "/*\n" + " --------------- Physical chunk operations ---------------\n" + "*/\n" + "\n" + "\n" + "/* size field is or'ed with PREV_INUSE when previous adjacent chunk in use */\n" + "#define PREV_INUSE 0x1\n" + "\n" + "/* extract inuse bit of previous chunk */\n" + "#define prev_inuse(p) ((p)->size & PREV_INUSE)\n" + "\n" + "\n" + "/* size field is or'ed with IS_MMAPPED if the chunk was obtained with mmap() */\n" + "#define IS_MMAPPED 0x2\n" + "\n" + "/* check for mmap()'ed chunk */\n" + "#define chunk_is_mmapped(p) ((p)->size & IS_MMAPPED)\n" + "\n" + "/*\n" + " Bits to mask off when extracting size\n" + "\n" + " Note: IS_MMAPPED is intentionally not masked off from size field in\n" + " macros for which mmapped chunks should never be seen. This should\n" + " cause helpful core dumps to occur if it is tried by accident by\n" + " people extending or adapting this malloc.\n" + "*/\n" + "#define SIZE_BITS (PREV_INUSE|IS_MMAPPED)\n" + "\n" + "/* Get size, ignoring use bits */\n" + "#define chunksize(p) ((p)->size & ~(SIZE_BITS))\n" + "\n" + "\n" + "/* Ptr to next physical malloc_chunk. */\n" + "#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->size & ~PREV_INUSE) ))\n" + "\n" + "/* Ptr to previous physical malloc_chunk */\n" + "#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_size) ))\n" + "\n" + "/* Treat space at ptr + offset as a chunk */\n" + "#define chunk_at_offset(p, s) ((mchunkptr)(((char*)(p)) + (s)))\n" + "\n" + "/* extract p's inuse bit */\n" + "#define inuse(p)\\n" + "((((mchunkptr)(((char*)(p))+((p)->size & ~PREV_INUSE)))->size) & PREV_INUSE)\n" + "\n" + "/* set/clear chunk as being inuse without otherwise disturbing */\n" + "#define set_inuse(p)\\n" + "((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size |= PREV_INUSE\n" + "\n") + ("#define clear_inuse(p)\\n" + "((mchunkptr)(((char*)(p)) + ((p)->size & ~PREV_INUSE)))->size &= ~(PREV_INUSE)\n" + "\n" + "\n" + "/* check/set/clear inuse bits in known places */\n" + "#define inuse_bit_at_offset(p, s)\\n" + " (((mchunkptr)(((char*)(p)) + (s)))->size & PREV_INUSE)\n" + "\n" + "#define set_inuse_bit_at_offset(p, s)\\n" + " (((mchunkptr)(((char*)(p)) + (s)))->size |= PREV_INUSE)\n" + "\n" + "#define clear_inuse_bit_at_offset(p, s)\\n" + " (((mchunkptr)(((char*)(p)) + (s)))->size &= ~(PREV_INUSE))\n" + "\n" + "\n" + "/* Set size at head, without disturbing its use bit */\n" + "#define set_head_size(p, s) ((p)->size = (((p)->size & PREV_INUSE) | (s)))\n" + "\n" + "/* Set size/use field */\n" + "#define set_head(p, s) ((p)->size = (s))\n" + "\n" + "/* Set size at footer (only when chunk is not in use) */\n" + "#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_size = (s))\n" + "\n" + "\n" + "/*\n" + " -------------------- Internal data structures --------------------\n" + "\n" + " All internal state is held in an instance of malloc_state defined\n" + " below. There are no other static variables, except in two optional\n" + " cases:\n" + " * If USE_MALLOC_LOCK is defined, the mALLOC_MUTEx declared above.\n" + " * If HAVE_MMAP is true, but mmap doesn't support\n" + " MAP_ANONYMOUS, a dummy file descriptor for mmap.\n" + "\n" + " Beware of lots of tricks that minimize the total bookkeeping space\n" + " requirements. The result is a little over 1K bytes (for 4byte\n" + " pointers and size_t.)\n" + "*/\n" + "\n" + "/*\n" + " Bins\n" + "\n" + " An array of bin headers for free chunks. Each bin is doubly\n" + " linked. The bins are approximately proportionally (log) spaced.\n" + " There are a lot of these bins (128). This may look excessive, but\n" + " works very well in practice. Most bins hold sizes that are\n" + " unusual as malloc request sizes, but are more usual for fragments\n" + " and consolidated sets of chunks, which is what these bins hold, so\n" + " they can be found quickly. All procedures maintain the invariant\n" + " that no consolidated chunk physically borders another one, so each\n" + " chunk in a list is known to be preceeded and followed by either\n" + " inuse chunks or the ends of memory.\n" + "\n" + " Chunks in bins are kept in size order, with ties going to the\n" + " approximately least recently used chunk. Ordering isn't needed\n" + " for the small bins, which all contain the same-sized chunks, but\n" + " facilitates best-fit allocation for larger chunks. These lists\n" + " are just sequential. Keeping them in order almost never requires\n" + " enough traversal to warrant using fancier ordered data\n" + " structures.\n" + "\n" + " Chunks of the same size are linked with the most\n" + " recently freed at the front, and allocations are taken from the\n" + " back. This results in LRU (FIFO) allocation order, which tends\n" + " to give each chunk an equal opportunity to be consolidated with\n" + " adjacent freed chunks, resulting in larger free chunks and less\n" + " fragmentation.\n" + "\n" + " To simplify use in double-linked lists, each bin header acts\n" + " as a malloc_chunk. This avoids special-casing for headers.\n" + " But to conserve space and improve locality, we allocate\n" + " only the fd/bk pointers of bins, and then use repositioning tricks\n" + " to treat these as the fields of a malloc_chunk*.\n" + "*/\n" + "\n" + "typedef struct malloc_chunk* mbinptr;\n" + "\n" + "/* addressing -- note that bin_at(0) does not exist */\n" + "#define bin_at(m, i) ((mbinptr)((char*)&((m)->bins[(i)<<1]) - (SIZE_SZ<<1)))\n" + "\n" + "/* analog of ++bin */\n" + "#define next_bin(b) ((mbinptr)((char*)(b) + (sizeof(mchunkptr)<<1)))\n" + "\n" + "/* Reminders about list directionality within bins */\n" + "#define first(b) ((b)->fd)\n" + "#define last(b) ((b)->bk)\n" + "\n" + "/* Take a chunk off a bin list */\n" + "#define unlink(P, BK, FD) { \\n" + " FD = P->fd; \\n" + " BK = P->bk; \\n" + " FD->bk = BK; \\n" + " BK->fd = FD; \\n" + "}\n" + "\n" + "/*\n" + " Indexing\n" + "\n" + " Bins for sizes < 512 bytes contain chunks of all the same size, spaced\n" + " 8 bytes apart. Larger bins are approximately logarithmically spaced:\n" + "\n" + " 64 bins of size 8\n" + " 32 bins of size 64\n" + " 16 bins of size 512\n" + " 8 bins of size 4096\n" + " 4 bins of size 32768\n" + " 2 bins of size 262144\n" + " 1 bin of size what's left\n" + "\n" + " The bins top out around 1MB because we expect to service large\n" + " requests via mmap.\n" + "*/\n" + "\n" + "#define NBINS 96\n" + "#define NSMALLBINS 32\n" + "#define SMALLBIN_WIDTH 8\n" + "#define MIN_LARGE_SIZE 256\n" + "\n" + "#define in_smallbin_range(sz) \\n" + " ((CHUNK_SIZE_T)(sz) < (CHUNK_SIZE_T)MIN_LARGE_SIZE)\n" + "\n" + "#define smallbin_index(sz) (((unsigned)(sz)) >> 3)\n" + "\n" + "/*\n" + " Compute index for size. We expect this to be inlined when\n" + " compiled with optimization, else not, which works out well.\n" + "*/\n" + "static int largebin_index(unsigned int sz) {\n" + " unsigned int x = sz >> SMALLBIN_WIDTH;\n" + " unsigned int m; /* bit position of highest set bit of m */\n" + "\n" + " if (x >= 0x10000) return NBINS-1;\n" + "\n" + " /* On intel, use BSRL instruction to find highest bit */\n" + "#if defined(__GNUC__) && defined(i386)\n" + "\n" + " __asm__(\"bsrl %1,%0\\n\\t\"\n" + " : \"=r\" (m)\n" + " : \"g\" (x));\n" + "\n" + "#else\n" + " {\n" + " /*\n" + " Based on branch-free nlz algorithm in chapter 5 of Henry\n" + " S. Warren Jr's book \"Hacker's Delight\".\n" + " */\n" + "\n" + " unsigned int n = ((x - 0x100) >> 16) & 8;\n" + " x <<= n;\n" + " m = ((x - 0x1000) >> 16) & 4;\n" + " n += m;\n" + " x <<= m;\n" + " m = ((x - 0x4000) >> 16) & 2;\n" + " n += m;\n" + " x = (x << m) >> 14;\n" + " m = 13 - n + (x & ~(x>>1));\n" + " }\n" + "#endif\n" + "\n") + ( " /* Use next 2 bits to create finer-granularity bins */\n" + " return NSMALLBINS + (m << 2) + ((sz >> (m + 6)) & 3);\n" + "}\n" + "\n" + "#define bin_index(sz) \\n" + " ((in_smallbin_range(sz)) ? smallbin_index(sz) : largebin_index(sz))\n" + "\n" + "/*\n" + " FIRST_SORTED_BIN_SIZE is the chunk size corresponding to the\n" + " first bin that is maintained in sorted order. This must\n" + " be the smallest size corresponding to a given bin.\n" + "\n" + " Normally, this should be MIN_LARGE_SIZE. But you can weaken\n" + " best fit guarantees to sometimes speed up malloc by increasing value.\n" + " Doing this means that malloc may choose a chunk that is\n" + " non-best-fitting by up to the width of the bin.\n" + "\n" + " Some useful cutoff values:\n" + " 512 - all bins sorted\n" + " 2560 - leaves bins <= 64 bytes wide unsorted\n" + " 12288 - leaves bins <= 512 bytes wide unsorted\n" + " 65536 - leaves bins <= 4096 bytes wide unsorted\n" + " 262144 - leaves bins <= 32768 bytes wide unsorted\n" + " -1 - no bins sorted (not recommended!)\n" + "*/\n" + "\n" + "#define FIRST_SORTED_BIN_SIZE MIN_LARGE_SIZE\n" + "/* #define FIRST_SORTED_BIN_SIZE 65536 */\n" + "\n" + "/*\n" + " Unsorted chunks\n" + "\n" + " All remainders from chunk splits, as well as all returned chunks,\n" + " are first placed in the \"unsorted\" bin. They are then placed\n" + " in regular bins after malloc gives them ONE chance to be used before\n" + " binning. So, basically, the unsorted_chunks list acts as a queue,\n" + " with chunks being placed on it in free (and malloc_consolidate),\n" + " and taken off (to be either used or placed in bins) in malloc.\n" + "*/\n" + "\n" + "/* The otherwise unindexable 1-bin is used to hold unsorted chunks. */\n" + "#define unsorted_chunks(M) (bin_at(M, 1))\n" + "\n" + "/*\n" + " Top\n" + "\n" + " The top-most available chunk (i.e., the one bordering the end of\n" + " available memory) is treated specially. It is never included in\n" + " any bin, is used only if no other chunk is available, and is\n" + " released back to the system if it is very large (see\n" + " M_TRIM_THRESHOLD). Because top initially\n" + " points to its own bin with initial zero size, thus forcing\n" + " extension on the first malloc request, we avoid having any special\n" + " code in malloc to check whether it even exists yet. But we still\n" + " need to do so when getting memory from system, so we make\n" + " initial_top treat the bin as a legal but unusable chunk during the\n" + " interval between initialization and the first call to\n" + " sYSMALLOc. (This is somewhat delicate, since it relies on\n" + " the 2 preceding words to be zero during this interval as well.)\n" + "*/\n" + "\n" + "/* Conveniently, the unsorted bin can be used as dummy top on first call */\n" + "#define initial_top(M) (unsorted_chunks(M))\n" + "\n" + "/*\n" + " Binmap\n" + "\n" + " To help compensate for the large number of bins, a one-level index\n" + " structure is used for bin-by-bin searching. `binmap' is a\n" + " bitvector recording whether bins are definitely empty so they can\n" + " be skipped over during during traversals. The bits are NOT always\n" + " cleared as soon as bins are empty, but instead only\n" + " when they are noticed to be empty during traversal in malloc.\n" + "*/\n" + "\n" + "/* Conservatively use 32 bits per map word, even if on 64bit system */\n" + "#define BINMAPSHIFT 5\n" + "#define BITSPERMAP (1U << BINMAPSHIFT)\n" + "#define BINMAPSIZE (NBINS / BITSPERMAP)\n" + "\n" + "#define idx2block(i) ((i) >> BINMAPSHIFT)\n" + "#define idx2bit(i) ((1U << ((i) & ((1U << BINMAPSHIFT)-1))))\n" + "\n" + "#define mark_bin(m,i) ((m)->binmap[idx2block(i)] |= idx2bit(i))\n" + "#define unmark_bin(m,i) ((m)->binmap[idx2block(i)] &= ~(idx2bit(i)))\n" + "#define get_binmap(m,i) ((m)->binmap[idx2block(i)] & idx2bit(i))\n" + "\n" + "/*\n" + " Fastbins\n" + "\n" + " An array of lists holding recently freed small chunks. Fastbins\n" + " are not doubly linked. It is faster to single-link them, and\n" + " since chunks are never removed from the middles of these lists,\n" + " double linking is not necessary. Also, unlike regular bins, they\n" + " are not even processed in FIFO order (they use faster LIFO) since\n" + " ordering doesn't much matter in the transient contexts in which\n" + " fastbins are normally used.\n" + "\n" + " Chunks in fastbins keep their inuse bit set, so they cannot\n" + " be consolidated with other free chunks. malloc_consolidate\n" + " releases all chunks in fastbins and consolidates them with\n" + " other free chunks.\n" + "*/\n" + "\n" + "typedef struct malloc_chunk* mfastbinptr;\n" + "\n" + "/* offset 2 to use otherwise unindexable first 2 bins */\n" + "#define fastbin_index(sz) ((((unsigned int)(sz)) >> 3) - 2)\n" + "\n" + "/* The maximum fastbin request size we support */\n" + "#define MAX_FAST_SIZE 80\n" + "\n" + "#define NFASTBINS (fastbin_index(request2size(MAX_FAST_SIZE))+1)\n" + "\n" + "/*\n" + " FASTBIN_CONSOLIDATION_THRESHOLD is the size of a chunk in free()\n" + " that triggers automatic consolidation of possibly-surrounding\n" + " fastbin chunks. This is a heuristic, so the exact value should not\n" + " matter too much. It is defined at half the default trim threshold as a\n" + " compromise heuristic to only attempt consolidation if it is likely\n" + " to lead to trimming. However, it is not dynamically tunable, since\n" + " consolidation reduces fragmentation surrounding loarge chunks even\n" + " if trimming is not used.\n" + "*/\n" + "\n" + "#define FASTBIN_CONSOLIDATION_THRESHOLD \\n" + " ((unsigned long)(DEFAULT_TRIM_THRESHOLD) >> 1)\n" + "\n" + "/*\n" + " Since the lowest 2 bits in max_fast don't matter in size comparisons,\n" + " they are used as flags.\n" + "*/\n" + "\n" + "/*\n" + " ANYCHUNKS_BIT held in max_fast indicates that there may be any\n" + " freed chunks at all. It is set true when entering a chunk into any\n" + " bin.\n" + "*/\n" + "\n" + "#define ANYCHUNKS_BIT (1U)\n" + "\n" + "#define have_anychunks(M) (((M)->max_fast & ANYCHUNKS_BIT))\n" + "#define set_anychunks(M) ((M)->max_fast |= ANYCHUNKS_BIT)\n" + "#define clear_anychunks(M) ((M)->max_fast &= ~ANYCHUNKS_BIT)\n" + "\n" + "/*\n" + " FASTCHUNKS_BIT held in max_fast indicates that there are probably\n" + " some fastbin chunks. It is set true on entering a chunk into any\n" + " fastbin, and cleared only in malloc_consolidate.\n" + "*/\n" + "\n") + ( "#define FASTCHUNKS_BIT (2U)\n" + "\n" + "#define have_fastchunks(M) (((M)->max_fast & FASTCHUNKS_BIT))\n" + "#define set_fastchunks(M) ((M)->max_fast |= (FASTCHUNKS_BIT|ANYCHUNKS_BIT))\n" + "#define clear_fastchunks(M) ((M)->max_fast &= ~(FASTCHUNKS_BIT))\n" + "\n" + "/*\n" + " Set value of max_fast.\n" + " Use impossibly small value if 0.\n" + "*/\n" + "\n" + "#define set_max_fast(M, s) \\n" + " (M)->max_fast = (((s) == 0)? SMALLBIN_WIDTH: request2size(s)) | \\n" + " ((M)->max_fast & (FASTCHUNKS_BIT|ANYCHUNKS_BIT))\n" + "\n" + "#define get_max_fast(M) \\n" + " ((M)->max_fast & ~(FASTCHUNKS_BIT | ANYCHUNKS_BIT))\n" + "\n" + "\n" + "/*\n" + " morecore_properties is a status word holding dynamically discovered\n" + " or controlled properties of the morecore function\n" + "*/\n" + "\n" + "#define MORECORE_CONTIGUOUS_BIT (1U)\n" + "\n" + "#define contiguous(M) \\n" + " (((M)->morecore_properties & MORECORE_CONTIGUOUS_BIT))\n" + "#define noncontiguous(M) \\n" + " (((M)->morecore_properties & MORECORE_CONTIGUOUS_BIT) == 0)\n" + "#define set_contiguous(M) \\n" + " ((M)->morecore_properties |= MORECORE_CONTIGUOUS_BIT)\n" + "#define set_noncontiguous(M) \\n" + " ((M)->morecore_properties &= ~MORECORE_CONTIGUOUS_BIT)\n" + "\n" + "\n" + "/*\n" + " ----------- Internal state representation and initialization -----------\n" + "*/\n" + "\n" + "struct malloc_state {\n" + "\n" + " /* The maximum chunk size to be eligible for fastbin */\n" + " INTERNAL_SIZE_T max_fast; /* low 2 bits used as flags */\n" + "\n" + " /* Fastbins */\n" + " mfastbinptr fastbins[NFASTBINS];\n" + "\n" + " /* Base of the topmost chunk -- not otherwise kept in a bin */\n" + " mchunkptr top;\n" + "\n" + " /* The remainder from the most recent split of a small request */\n" + " mchunkptr last_remainder;\n" + "\n" + " /* Normal bins packed as described above */\n" + " mchunkptr bins[NBINS * 2];\n" + "\n" + " /* Bitmap of bins. Trailing zero map handles cases of largest binned size */\n" + " unsigned int binmap[BINMAPSIZE+1];\n" + "\n" + " /* Tunable parameters */\n" + " CHUNK_SIZE_T trim_threshold;\n" + " INTERNAL_SIZE_T top_pad;\n" + " INTERNAL_SIZE_T mmap_threshold;\n" + "\n" + " /* Memory map support */\n" + " int n_mmaps;\n" + " int n_mmaps_max;\n" + " int max_n_mmaps;\n" + "\n" + " /* Cache malloc_getpagesize */\n" + " unsigned int pagesize;\n" + "\n" + " /* Track properties of MORECORE */\n" + " unsigned int morecore_properties;\n" + "\n" + " /* Statistics */\n" + " INTERNAL_SIZE_T mmapped_mem;\n" + " INTERNAL_SIZE_T sbrked_mem;\n" + " INTERNAL_SIZE_T max_sbrked_mem;\n" + " INTERNAL_SIZE_T max_mmapped_mem;\n" + " INTERNAL_SIZE_T max_total_mem;\n" + "};\n" + "\n" + "typedef struct malloc_state *mstate;\n" + "\n" + "/*\n" + " There is exactly one instance of this struct in this malloc.\n" + " If you are adapting this malloc in a way that does NOT use a static\n" + " malloc_state, you MUST explicitly zero-fill it before using. This\n" + " malloc relies on the property that malloc_state is initialized to\n" + " all zeroes (as is true of C statics).\n" + "*/\n" + "\n" + "static struct malloc_state av_; /* never directly referenced */\n" + "\n" + "/*\n" + " All uses of av_ are via get_malloc_state().\n" + " At most one \"call\" to get_malloc_state is made per invocation of\n" + " the public versions of malloc and free, but other routines\n" + " that in turn invoke malloc and/or free may call more then once.\n" + " Also, it is called in check* routines if DEBUG is set.\n" + "*/\n" + "\n" + "#define get_malloc_state() (&(av_))\n" + "\n" + "/*\n" + " Initialize a malloc_state struct.\n" + "\n" + " This is called only from within malloc_consolidate, which needs\n" + " be called in the same contexts anyway. It is never called directly\n" + " outside of malloc_consolidate because some optimizing compilers try\n" + " to inline it at all call points, which turns out not to be an\n" + " optimization at all. (Inlining it in malloc_consolidate is fine though.)\n" + "*/\n" + "\n" + "#if __STD_C\n" + "static void malloc_init_state(mstate av)\n" + "#else\n" + "static void malloc_init_state(av) mstate av;\n" + "#endif\n" + "{\n" + " int i;\n" + " mbinptr bin;\n" + "\n" + " /* Establish circular links for normal bins */\n" + " for (i = 1; i < NBINS; ++i) {\n" + " bin = bin_at(av,i);\n" + " bin->fd = bin->bk = bin;\n" + " }\n" + "\n" + " av->top_pad = DEFAULT_TOP_PAD;\n" + " av->n_mmaps_max = DEFAULT_MMAP_MAX;\n" + " av->mmap_threshold = DEFAULT_MMAP_THRESHOLD;\n" + " av->trim_threshold = DEFAULT_TRIM_THRESHOLD;\n" + "\n" + "#if MORECORE_CONTIGUOUS\n" + " set_contiguous(av);\n" + "#else\n" + " set_noncontiguous(av);\n" + "#endif\n" + "\n" + "\n" + " set_max_fast(av, DEFAULT_MXFAST);\n" + "\n" + " av->top = initial_top(av);\n" + " av->pagesize = malloc_getpagesize;\n" + "}\n" + "\n" + "/*\n" + " Other internal utilities operating on mstates\n" + "*/\n" + "\n") + ( "#if __STD_C\n" + "static Void_t* sYSMALLOc(INTERNAL_SIZE_T, mstate);\n" + "#ifndef MORECORE_CANNOT_TRIM\n" + "static int sYSTRIm(size_t, mstate);\n" + "#endif\n" + "static void malloc_consolidate(mstate);\n" + "static Void_t** iALLOc(size_t, size_t*, int, Void_t**);\n" + "#else\n" + "static Void_t* sYSMALLOc();\n" + "static int sYSTRIm();\n" + "static void malloc_consolidate();\n" + "static Void_t** iALLOc();\n" + "#endif\n" + "\n" + "/*\n" + " Debugging support\n" + "\n" + " These routines make a number of assertions about the states\n" + " of data structures that should be true at all times. If any\n" + " are not true, it's very likely that a user program has somehow\n" + " trashed memory. (It's also possible that there is a coding error\n" + " in malloc. In which case, please report it!)\n" + "*/\n" + "\n" + "#if ! DEBUG\n" + "\n" + "#define check_chunk(P)\n" + "#define check_free_chunk(P)\n" + "#define check_inuse_chunk(P)\n" + "#define check_remalloced_chunk(P,N)\n" + "#define check_malloced_chunk(P,N)\n" + "#define check_malloc_state()\n" + "\n" + "#else\n" + "#define check_chunk(P) do_check_chunk(P)\n" + "#define check_free_chunk(P) do_check_free_chunk(P)\n" + "#define check_inuse_chunk(P) do_check_inuse_chunk(P)\n" + "#define check_remalloced_chunk(P,N) do_check_remalloced_chunk(P,N)\n" + "#define check_malloced_chunk(P,N) do_check_malloced_chunk(P,N)\n" + "#define check_malloc_state() do_check_malloc_state()\n" + "\n" + "/*\n" + " Properties of all chunks\n" + "*/\n" + "\n" + "#if __STD_C\n" + "static void do_check_chunk(mchunkptr p)\n" + "#else\n" + "static void do_check_chunk(p) mchunkptr p;\n" + "#endif\n" + "{\n" + " mstate av = get_malloc_state();\n" + " CHUNK_SIZE_T sz = chunksize(p);\n" + " /* min and max possible addresses assuming contiguous allocation */\n" + " char* max_address = (char*)(av->top) + chunksize(av->top);\n" + " char* min_address = max_address - av->sbrked_mem;\n" + "\n" + " if (!chunk_is_mmapped(p)) {\n" + "\n" + " /* Has legal address ... */\n" + " if (p != av->top) {\n" + " if (contiguous(av)) {\n" + " assert(((char*)p) >= min_address);\n" + " assert(((char*)p + sz) <= ((char*)(av->top)));\n" + " }\n" + " }\n" + " else {\n" + " /* top size is always at least MINSIZE */\n" + " assert((CHUNK_SIZE_T)(sz) >= MINSIZE);\n" + " /* top predecessor always marked inuse */\n" + " assert(prev_inuse(p));\n" + " }\n" + "\n" + " }\n" + " else {\n" + "#if HAVE_MMAP\n" + " /* address is outside main heap */\n" + " if (contiguous(av) && av->top != initial_top(av)) {\n" + " assert(((char*)p) < min_address || ((char*)p) > max_address);\n" + " }\n" + " /* chunk is page-aligned */\n" + " assert(((p->prev_size + sz) & (av->pagesize-1)) == 0);\n" + " /* mem is aligned */\n" + " assert(aligned_OK(chunk2mem(p)));\n" + "#else\n" + " /* force an appropriate assert violation if debug set */\n" + " assert(!chunk_is_mmapped(p));\n" + "#endif\n" + " }\n" + "}\n" + "\n" + "/*\n" + " Properties of free chunks\n" + "*/\n" + "\n" + "#if __STD_C\n" + "static void do_check_free_chunk(mchunkptr p)\n" + "#else\n" + "static void do_check_free_chunk(p) mchunkptr p;\n" + "#endif\n" + "{\n" + " mstate av = get_malloc_state();\n" + "\n" + " INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;\n" + " mchunkptr next = chunk_at_offset(p, sz);\n" + "\n" + " do_check_chunk(p);\n" + "\n" + " /* Chunk must claim to be free ... */\n" + " assert(!inuse(p));\n" + " assert (!chunk_is_mmapped(p));\n" + "\n" + " /* Unless a special marker, must have OK fields */\n" + " if ((CHUNK_SIZE_T)(sz) >= MINSIZE)\n" + " {\n" + " assert((sz & MALLOC_ALIGN_MASK) == 0);\n" + " assert(aligned_OK(chunk2mem(p)));\n" + " /* ... matching footer field */\n" + " assert(next->prev_size == sz);\n" + " /* ... and is fully consolidated */\n" + " assert(prev_inuse(p));\n" + " assert (next == av->top || inuse(next));\n" + "\n" + " /* ... and has minimally sane links */\n" + " assert(p->fd->bk == p);\n" + " assert(p->bk->fd == p);\n" + " }\n" + " else /* markers are always of size SIZE_SZ */\n" + " assert(sz == SIZE_SZ);\n" + "}\n" + "\n" + "/*\n" + " Properties of inuse chunks\n" + "*/\n" + "\n" + "#if __STD_C\n" + "static void do_check_inuse_chunk(mchunkptr p)\n" + "#else\n" + "static void do_check_inuse_chunk(p) mchunkptr p;\n" + "#endif\n" + "{\n" + " mstate av = get_malloc_state();\n" + " mchunkptr next;\n" + " do_check_chunk(p);\n" + "\n" + " if (chunk_is_mmapped(p))\n" + " return; /* mmapped chunks have no next/prev */\n" + "\n" + " /* Check whether it claims to be in use ... */\n" + " assert(inuse(p));\n" + "\n") + ( " next = next_chunk(p);\n" + "\n" + " /* ... and is surrounded by OK chunks.\n" + " Since more things can be checked with free chunks than inuse ones,\n" + " if an inuse chunk borders them and debug is on, it's worth doing them.\n" + " */\n" + " if (!prev_inuse(p)) {\n" + " /* Note that we cannot even look at prev unless it is not inuse */\n" + " mchunkptr prv = prev_chunk(p);\n" + " assert(next_chunk(prv) == p);\n" + " do_check_free_chunk(prv);\n" + " }\n" + "\n" + " if (next == av->top) {\n" + " assert(prev_inuse(next));\n" + " assert(chunksize(next) >= MINSIZE);\n" + " }\n" + " else if (!inuse(next))\n" + " do_check_free_chunk(next);\n" + "}\n" + "\n" + "/*\n" + " Properties of chunks recycled from fastbins\n" + "*/\n" + "\n" + "#if __STD_C\n" + "static void do_check_remalloced_chunk(mchunkptr p, INTERNAL_SIZE_T s)\n" + "#else\n" + "static void do_check_remalloced_chunk(p, s) mchunkptr p; INTERNAL_SIZE_T s;\n" + "#endif\n" + "{\n" + " INTERNAL_SIZE_T sz = p->size & ~PREV_INUSE;\n" + "\n" + " do_check_inuse_chunk(p);\n" + "\n" + " /* Legal size ... */\n" + " assert((sz & MALLOC_ALIGN_MASK) == 0);\n" + " assert((CHUNK_SIZE_T)(sz) >= MINSIZE);\n" + " /* ... and alignment */\n" + " assert(aligned_OK(chunk2mem(p)));\n" + " /* chunk is less than MINSIZE more than request */\n" + " assert((long)(sz) - (long)(s) >= 0);\n" + " assert((long)(sz) - (long)(s + MINSIZE) < 0);\n" + "}\n" + "\n" + "/*\n" + " Properties of nonrecycled chunks at the point they are malloced\n" + "*/\n" + "\n" + "#if __STD_C\n" + "static void do_check_malloced_chunk(mchunkptr p, INTERNAL_SIZE_T s)\n" + "#else\n" + "static void do_check_malloced_chunk(p, s) mchunkptr p; INTERNAL_SIZE_T s;\n" + "#endif\n" + "{\n" + " /* same as recycled case ... */\n" + " do_check_remalloced_chunk(p, s);\n" + "\n" + " /*\n" + " ... plus, must obey implementation invariant that prev_inuse is\n" + " always true of any allocated chunk; i.e., that each allocated\n" + " chunk borders either a previously allocated and still in-use\n" + " chunk, or the base of its memory arena. This is ensured\n" + " by making all allocations from the the `lowest' part of any found\n" + " chunk. This does not necessarily hold however for chunks\n" + " recycled via fastbins.\n" + " */\n" + "\n" + " assert(prev_inuse(p));\n" + "}\n" + "\n" + "\n" + "/*\n" + " Properties of malloc_state.\n" + "\n" + " This may be useful for debugging malloc, as well as detecting user\n" + " programmer errors that somehow write into malloc_state.\n" + "\n" + " If you are extending or experimenting with this malloc, you can\n" + " probably figure out how to hack this routine to print out or\n" + " display chunk addresses, sizes, bins, and other instrumentation.\n" + "*/\n" + "\n" + "static void do_check_malloc_state()\n" + "{\n" + " mstate av = get_malloc_state();\n" + " unsigned int i;\n" + " mchunkptr p;\n" + " mchunkptr q;\n" + " mbinptr b;\n" + " unsigned int binbit;\n" + " int empty;\n" + " unsigned int idx;\n" + " INTERNAL_SIZE_T size;\n" + " CHUNK_SIZE_T total = 0;\n" + " int max_fast_bin;\n" + "\n" + " /* internal size_t must be no wider than pointer type */\n" + " assert(sizeof(INTERNAL_SIZE_T) <= sizeof(char*));\n" + "\n" + " /* alignment is a power of 2 */\n" + " assert((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-1)) == 0);\n" + "\n" + " /* cannot run remaining checks until fully initialized */\n" + " if (av->top == 0 || av->top == initial_top(av))\n" + " return;\n" + "\n" + " /* pagesize is a power of 2 */\n" + " assert((av->pagesize & (av->pagesize-1)) == 0);\n" + "\n" + " /* properties of fastbins */\n" + "\n" + " /* max_fast is in allowed range */\n" + " assert(get_max_fast(av) <= request2size(MAX_FAST_SIZE));\n" + "\n" + " max_fast_bin = fastbin_index(av->max_fast);\n" + "\n" + " for (i = 0; i < NFASTBINS; ++i) {\n" + " p = av->fastbins[i];\n" + "\n" + " /* all bins past max_fast are empty */\n" + " if (i > max_fast_bin)\n" + " assert(p == 0);\n" + "\n" + " while (p != 0) {\n" + " /* each chunk claims to be inuse */\n" + " do_check_inuse_chunk(p);\n" + " total += chunksize(p);\n" + " /* chunk belongs in this bin */\n" + " assert(fastbin_index(chunksize(p)) == i);\n" + " p = p->fd;\n" + " }\n" + " }\n" + "\n" + " if (total != 0)\n" + " assert(have_fastchunks(av));\n" + " else if (!have_fastchunks(av))\n" + " assert(total == 0);\n" + "\n" + " /* check normal bins */\n" + " for (i = 1; i < NBINS; ++i) {\n" + " b = bin_at(av,i);\n" + "\n" + " /* binmap is accurate (except for bin 1 == unsorted_chunks) */\n" + " if (i >= 2) {\n" + " binbit = get_binmap(av,i);\n" + " empty = last(b) == b;\n" + " if (!binbit)\n" + " assert(empty);\n" + " else if (!empty)\n" + " assert(binbit);\n" + " }\n" + "\n") + ( " for (p = last(b); p != b; p = p->bk) {\n" + " /* each chunk claims to be free */\n" + " do_check_free_chunk(p);\n" + " size = chunksize(p);\n" + " total += size;\n" + " if (i >= 2) {\n" + " /* chunk belongs in bin */\n" + " idx = bin_index(size);\n" + " assert(idx == i);\n" + " /* lists are sorted */\n" + " if ((CHUNK_SIZE_T) size >= (CHUNK_SIZE_T)(FIRST_SORTED_BIN_SIZE)) {\n" + " assert(p->bk == b ||\n" + " (CHUNK_SIZE_T)chunksize(p->bk) >=\n" + " (CHUNK_SIZE_T)chunksize(p));\n" + " }\n" + " }\n" + " /* chunk is followed by a legal chain of inuse chunks */\n" + " for (q = next_chunk(p);\n" + " (q != av->top && inuse(q) &&\n" + " (CHUNK_SIZE_T)(chunksize(q)) >= MINSIZE);\n" + " q = next_chunk(q))\n" + " do_check_inuse_chunk(q);\n" + " }\n" + " }\n" + "\n" + " /* top chunk is OK */\n" + " check_chunk(av->top);\n" + "\n" + " /* sanity checks for statistics */\n" + "\n" + " assert(total <= (CHUNK_SIZE_T)(av->max_total_mem));\n" + " assert(av->n_mmaps >= 0);\n" + " assert(av->n_mmaps <= av->max_n_mmaps);\n" + "\n" + " assert((CHUNK_SIZE_T)(av->sbrked_mem) <=\n" + " (CHUNK_SIZE_T)(av->max_sbrked_mem));\n" + "\n" + " assert((CHUNK_SIZE_T)(av->mmapped_mem) <=\n" + " (CHUNK_SIZE_T)(av->max_mmapped_mem));\n" + "\n" + " assert((CHUNK_SIZE_T)(av->max_total_mem) >=\n" + " (CHUNK_SIZE_T)(av->mmapped_mem) + (CHUNK_SIZE_T)(av->sbrked_mem));\n" + "}\n" + "#endif\n" + "\n" + "\n" + "/* ----------- Routines dealing with system allocation -------------- */\n" + "\n" + "/*\n" + " sysmalloc handles malloc cases requiring more memory from the system.\n" + " On entry, it is assumed that av->top does not have enough\n" + " space to service request for nb bytes, thus requiring that av->top\n" + " be extended or replaced.\n" + "*/\n" + "\n" + "#if __STD_C\n" + "static Void_t* sYSMALLOc(INTERNAL_SIZE_T nb, mstate av)\n" + "#else\n" + "static Void_t* sYSMALLOc(nb, av) INTERNAL_SIZE_T nb; mstate av;\n" + "#endif\n" + "{\n" + " mchunkptr old_top; /* incoming value of av->top */\n" + " INTERNAL_SIZE_T old_size; /* its size */\n" + " char* old_end; /* its end address */\n" + "\n" + " long size; /* arg to first MORECORE or mmap call */\n" + " char* brk; /* return value from MORECORE */\n" + "\n" + " long correction; /* arg to 2nd MORECORE call */\n" + " char* snd_brk; /* 2nd return val */\n" + "\n" + " INTERNAL_SIZE_T front_misalign; /* unusable bytes at front of new space */\n" + " INTERNAL_SIZE_T end_misalign; /* partial page left at end of new space */\n" + " char* aligned_brk; /* aligned offset into brk */\n" + "\n" + " mchunkptr p; /* the allocated/returned chunk */\n" + " mchunkptr remainder; /* remainder from allocation */\n" + " CHUNK_SIZE_T remainder_size; /* its size */\n" + "\n" + " CHUNK_SIZE_T sum; /* for updating stats */\n" + "\n" + " size_t pagemask = av->pagesize - 1;\n" + "\n" + " /*\n" + " If there is space available in fastbins, consolidate and retry\n" + " malloc from scratch rather than getting memory from system. This\n" + " can occur only if nb is in smallbin range so we didn't consolidate\n" + " upon entry to malloc. It is much easier to handle this case here\n" + " than in malloc proper.\n" + " */\n" + "\n" + " if (have_fastchunks(av)) {\n" + " assert(in_smallbin_range(nb));\n" + " malloc_consolidate(av);\n" + " return mALLOc(nb - MALLOC_ALIGN_MASK);\n" + " }\n" + "\n" + "\n" + "#if HAVE_MMAP\n" + "\n" + " /*\n" + " If have mmap, and the request size meets the mmap threshold, and\n" + " the system supports mmap, and there are few enough currently\n" + " allocated mmapped regions, try to directly map this request\n" + " rather than expanding top.\n" + " */\n" + "\n" + " if ((CHUNK_SIZE_T)(nb) >= (CHUNK_SIZE_T)(av->mmap_threshold) &&\n" + " (av->n_mmaps < av->n_mmaps_max)) {\n" + "\n" + " char* mm; /* return value from mmap call*/\n" + "\n" + " /*\n" + " Round up size to nearest page. For mmapped chunks, the overhead\n" + " is one SIZE_SZ unit larger than for normal chunks, because there\n" + " is no following chunk whose prev_size field could be used.\n" + " */\n" + " size = (nb + SIZE_SZ + MALLOC_ALIGN_MASK + pagemask) & ~pagemask;\n" + "\n" + " /* Don't try if size wraps around 0 */\n" + " if ((CHUNK_SIZE_T)(size) > (CHUNK_SIZE_T)(nb)) {\n" + "\n" + " mm = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE));\n" + "\n" + " if (mm != (char*)(MORECORE_FAILURE)) {\n" + "\n" + " /*\n" + " The offset to the start of the mmapped region is stored\n" + " in the prev_size field of the chunk. This allows us to adjust\n" + " returned start address to meet alignment requirements here\n" + " and in memalign(), and still be able to compute proper\n" + " address argument for later munmap in free() and realloc().\n" + " */\n" + "\n" + " front_misalign = (INTERNAL_SIZE_T)chunk2mem(mm) & MALLOC_ALIGN_MASK;\n" + " if (front_misalign > 0) {\n" + " correction = MALLOC_ALIGNMENT - front_misalign;\n" + " p = (mchunkptr)(mm + correction);\n" + " p->prev_size = correction;\n" + " set_head(p, (size - correction) |IS_MMAPPED);\n" + " }\n" + " else {\n" + " p = (mchunkptr)mm;\n" + " p->prev_size = 0;\n" + " set_head(p, size|IS_MMAPPED);\n" + " }\n" + "\n" + " /* update statistics */\n" + "\n" + " if (++av->n_mmaps > av->max_n_mmaps)\n" + " av->max_n_mmaps = av->n_mmaps;\n" + "\n") + ( " sum = av->mmapped_mem += size;\n" + " if (sum > (CHUNK_SIZE_T)(av->max_mmapped_mem))\n" + " av->max_mmapped_mem = sum;\n" + " sum += av->sbrked_mem;\n" + " if (sum > (CHUNK_SIZE_T)(av->max_total_mem))\n" + " av->max_total_mem = sum;\n" + "\n" + " check_chunk(p);\n" + "\n" + " return chunk2mem(p);\n" + " }\n" + " }\n" + " }\n" + "#endif\n" + "\n" + " /* Record incoming configuration of top */\n" + "\n" + " old_top = av->top;\n" + " old_size = chunksize(old_top);\n" + " old_end = (char*)(chunk_at_offset(old_top, old_size));\n" + "\n" + " brk = snd_brk = (char*)(MORECORE_FAILURE);\n" + "\n" + " /*\n" + " If not the first time through, we require old_size to be\n" + " at least MINSIZE and to have prev_inuse set.\n" + " */\n" + "\n" + " assert((old_top == initial_top(av) && old_size == 0) ||\n" + " ((CHUNK_SIZE_T) (old_size) >= MINSIZE &&\n" + " prev_inuse(old_top)));\n" + "\n" + " /* Precondition: not enough current space to satisfy nb request */\n" + " assert((CHUNK_SIZE_T)(old_size) < (CHUNK_SIZE_T)(nb + MINSIZE));\n" + "\n" + " /* Precondition: all fastbins are consolidated */\n" + " assert(!have_fastchunks(av));\n" + "\n" + "\n" + " /* Request enough space for nb + pad + overhead */\n" + "\n" + " size = nb + av->top_pad + MINSIZE;\n" + "\n" + " /*\n" + " If contiguous, we can subtract out existing space that we hope to\n" + " combine with new space. We add it back later only if\n" + " we don't actually get contiguous space.\n" + " */\n" + "\n" + " if (contiguous(av))\n" + " size -= old_size;\n" + "\n" + " /*\n" + " Round to a multiple of page size.\n" + " If MORECORE is not contiguous, this ensures that we only call it\n" + " with whole-page arguments. And if MORECORE is contiguous and\n" + " this is not first time through, this preserves page-alignment of\n" + " previous calls. Otherwise, we correct to page-align below.\n" + " */\n" + "\n" + " size = (size + pagemask) & ~pagemask;\n" + "\n" + " /*\n" + " Don't try to call MORECORE if argument is so big as to appear\n" + " negative. Note that since mmap takes size_t arg, it may succeed\n" + " below even if we cannot call MORECORE.\n" + " */\n" + "\n" + " if (size > 0)\n" + " brk = (char*)(MORECORE(size));\n" + "\n" + " /*\n" + " If have mmap, try using it as a backup when MORECORE fails or\n" + " cannot be used. This is worth doing on systems that have \"holes\" in\n" + " address space, so sbrk cannot extend to give contiguous space, but\n" + " space is available elsewhere. Note that we ignore mmap max count\n" + " and threshold limits, since the space will not be used as a\n" + " segregated mmap region.\n" + " */\n" + "\n" + "#if HAVE_MMAP\n" + " if (brk == (char*)(MORECORE_FAILURE)) {\n" + "\n" + " /* Cannot merge with old top, so add its size back in */\n" + " if (contiguous(av))\n" + " size = (size + old_size + pagemask) & ~pagemask;\n" + "\n" + " /* If we are relying on mmap as backup, then use larger units */\n" + " if ((CHUNK_SIZE_T)(size) < (CHUNK_SIZE_T)(MMAP_AS_MORECORE_SIZE))\n" + " size = MMAP_AS_MORECORE_SIZE;\n" + "\n" + " /* Don't try if size wraps around 0 */\n" + " if ((CHUNK_SIZE_T)(size) > (CHUNK_SIZE_T)(nb)) {\n" + "\n" + " brk = (char*)(MMAP(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE));\n" + "\n" + " if (brk != (char*)(MORECORE_FAILURE)) {\n" + "\n" + " /* We do not need, and cannot use, another sbrk call to find end */\n" + " snd_brk = brk + size;\n" + "\n" + " /*\n" + " Record that we no longer have a contiguous sbrk region.\n" + " After the first time mmap is used as backup, we do not\n" + " ever rely on contiguous space since this could incorrectly\n" + " bridge regions.\n" + " */\n" + " set_noncontiguous(av);\n" + " }\n" + " }\n" + " }\n" + "#endif\n" + "\n" + " if (brk != (char*)(MORECORE_FAILURE)) {\n" + " av->sbrked_mem += size;\n" + "\n" + " /*\n" + " If MORECORE extends previous space, we can likewise extend top size.\n" + " */\n" + "\n" + " if (brk == old_end && snd_brk == (char*)(MORECORE_FAILURE)) {\n" + " set_head(old_top, (size + old_size) | PREV_INUSE);\n" + " }\n" + "\n" + " /*\n" + " Otherwise, make adjustments:\n" + "\n" + " * If the first time through or noncontiguous, we need to call sbrk\n" + " just to find out where the end of memory lies.\n" + "\n" + " * We need to ensure that all returned chunks from malloc will meet\n" + " MALLOC_ALIGNMENT\n" + "\n" + " * If there was an intervening foreign sbrk, we need to adjust sbrk\n" + " request size to account for fact that we will not be able to\n" + " combine new space with existing space in old_top.\n" + "\n" + " * Almost all systems internally allocate whole pages at a time, in\n" + " which case we might as well use the whole last page of request.\n" + " So we allocate enough more memory to hit a page boundary now,\n" + " which in turn causes future contiguous calls to page-align.\n" + " */\n" + "\n" + " else {\n" + " front_misalign = 0;\n" + " end_misalign = 0;\n" + " correction = 0;\n" + " aligned_brk = brk;\n" + "\n") + ( " /*\n" + " If MORECORE returns an address lower than we have seen before,\n" + " we know it isn't really contiguous. This and some subsequent\n" + " checks help cope with non-conforming MORECORE functions and\n" + " the presence of \"foreign\" calls to MORECORE from outside of\n" + " malloc or by other threads. We cannot guarantee to detect\n" + " these in all cases, but cope with the ones we do detect.\n" + " */\n" + " if (contiguous(av) && old_size != 0 && brk < old_end) {\n" + " set_noncontiguous(av);\n" + " }\n" + "\n" + " /* handle contiguous cases */\n" + " if (contiguous(av)) {\n" + "\n" + " /*\n" + " We can tolerate forward non-contiguities here (usually due\n" + " to foreign calls) but treat them as part of our space for\n" + " stats reporting.\n" + " */\n" + " if (old_size != 0)\n" + " av->sbrked_mem += brk - old_end;\n" + "\n" + " /* Guarantee alignment of first new chunk made from this space */\n" + "\n" + " front_misalign = (INTERNAL_SIZE_T)chunk2mem(brk) & MALLOC_ALIGN_MASK;\n" + " if (front_misalign > 0) {\n" + "\n" + " /*\n" + " Skip over some bytes to arrive at an aligned position.\n" + " We don't need to specially mark these wasted front bytes.\n" + " They will never be accessed anyway because\n" + " prev_inuse of av->top (and any chunk created from its start)\n" + " is always true after initialization.\n" + " */\n" + "\n" + " correction = MALLOC_ALIGNMENT - front_misalign;\n" + " aligned_brk += correction;\n" + " }\n" + "\n" + " /*\n" + " If this isn't adjacent to existing space, then we will not\n" + " be able to merge with old_top space, so must add to 2nd request.\n" + " */\n" + "\n" + " correction += old_size;\n" + "\n" + " /* Extend the end address to hit a page boundary */\n" + " end_misalign = (INTERNAL_SIZE_T)(brk + size + correction);\n" + " correction += ((end_misalign + pagemask) & ~pagemask) - end_misalign;\n" + "\n" + " assert(correction >= 0);\n" + " snd_brk = (char*)(MORECORE(correction));\n" + "\n" + " if (snd_brk == (char*)(MORECORE_FAILURE)) {\n" + " /*\n" + " If can't allocate correction, try to at least find out current\n" + " brk. It might be enough to proceed without failing.\n" + " */\n" + " correction = 0;\n" + " snd_brk = (char*)(MORECORE(0));\n" + " }\n" + " else if (snd_brk < brk) {\n" + " /*\n" + " If the second call gives noncontiguous space even though\n" + " it says it won't, the only course of action is to ignore\n" + " results of second call, and conservatively estimate where\n" + " the first call left us. Also set noncontiguous, so this\n" + " won't happen again, leaving at most one hole.\n" + "\n" + " Note that this check is intrinsically incomplete. Because\n" + " MORECORE is allowed to give more space than we ask for,\n" + " there is no reliable way to detect a noncontiguity\n" + " producing a forward gap for the second call.\n" + " */\n" + " snd_brk = brk + size;\n" + " correction = 0;\n" + " set_noncontiguous(av);\n" + " }\n" + "\n" + " }\n" + "\n" + " /* handle non-contiguous cases */\n" + " else {\n" + " /* MORECORE/mmap must correctly align */\n" + " assert(aligned_OK(chunk2mem(brk)));\n" + "\n" + " /* Find out current end of memory */\n" + " if (snd_brk == (char*)(MORECORE_FAILURE)) {\n" + " snd_brk = (char*)(MORECORE(0));\n" + " av->sbrked_mem += snd_brk - brk - size;\n" + " }\n" + " }\n" + "\n" + " /* Adjust top based on results of second sbrk */\n" + " if (snd_brk != (char*)(MORECORE_FAILURE)) {\n" + " av->top = (mchunkptr)aligned_brk;\n" + " set_head(av->top, (snd_brk - aligned_brk + correction) | PREV_INUSE);\n" + " av->sbrked_mem += correction;\n" + "\n" + " /*\n" + " If not the first time through, we either have a\n" + " gap due to foreign sbrk or a non-contiguous region. Insert a\n" + " double fencepost at old_top to prevent consolidation with space\n" + " we don't own. These fenceposts are artificial chunks that are\n" + " marked as inuse and are in any case too small to use. We need\n" + " two to make sizes and alignments work out.\n" + " */\n" + "\n" + " if (old_size != 0) {\n" + " /*\n" + " Shrink old_top to insert fenceposts, keeping size a\n" + " multiple of MALLOC_ALIGNMENT. We know there is at least\n" + " enough space in old_top to do this.\n" + " */\n" + " old_size = (old_size - 3*SIZE_SZ) & ~MALLOC_ALIGN_MASK;\n" + " set_head(old_top, old_size | PREV_INUSE);\n" + "\n" + " /*\n" + " Note that the following assignments completely overwrite\n" + " old_top when old_size was previously MINSIZE. This is\n" + " intentional. We need the fencepost, even if old_top otherwise gets\n" + " lost.\n" + " */\n" + " chunk_at_offset(old_top, old_size )->size =\n" + " SIZE_SZ|PREV_INUSE;\n" + "\n" + " chunk_at_offset(old_top, old_size + SIZE_SZ)->size =\n" + " SIZE_SZ|PREV_INUSE;\n" + "\n" + " /*\n" + " If possible, release the rest, suppressing trimming.\n" + " */\n" + " if (old_size >= MINSIZE) {\n" + " INTERNAL_SIZE_T tt = av->trim_threshold;\n" + " av->trim_threshold = (INTERNAL_SIZE_T)(-1);\n" + " fREe(chunk2mem(old_top));\n" + " av->trim_threshold = tt;\n" + " }\n" + " }\n" + " }\n" + " }\n" + "\n" + " /* Update statistics */\n" + " sum = av->sbrked_mem;\n" + " if (sum > (CHUNK_SIZE_T)(av->max_sbrked_mem))\n" + " av->max_sbrked_mem = sum;\n" + "\n") + ( " sum += av->mmapped_mem;\n" + " if (sum > (CHUNK_SIZE_T)(av->max_total_mem))\n" + " av->max_total_mem = sum;\n" + "\n" + " check_malloc_state();\n" + "\n" + " /* finally, do the allocation */\n" + "\n" + " p = av->top;\n" + " size = chunksize(p);\n" + "\n" + " /* check that one of the above allocation paths succeeded */\n" + " if ((CHUNK_SIZE_T)(size) >= (CHUNK_SIZE_T)(nb + MINSIZE)) {\n" + " remainder_size = size - nb;\n" + " remainder = chunk_at_offset(p, nb);\n" + " av->top = remainder;\n" + " set_head(p, nb | PREV_INUSE);\n" + " set_head(remainder, remainder_size | PREV_INUSE);\n" + " check_malloced_chunk(p, nb);\n" + " return chunk2mem(p);\n" + " }\n" + "\n" + " }\n" + "\n" + " /* catch all failure paths */\n" + " MALLOC_FAILURE_ACTION;\n" + " return 0;\n" + "}\n" + "\n" + "\n" + "\n" + "\n" + "/*\n" + " sYSTRIm is an inverse of sorts to sYSMALLOc. It gives memory back\n" + " to the system (via negative arguments to sbrk) if there is unused\n" + " memory at the `high' end of the malloc pool. It is called\n" + " automatically by free() when top space exceeds the trim\n" + " threshold. It is also called by the public malloc_trim routine. It\n" + " returns 1 if it actually released any memory, else 0.\n" + "*/\n" + "\n" + "#ifndef MORECORE_CANNOT_TRIM\n" + "\n" + "#if __STD_C\n" + "static int sYSTRIm(size_t pad, mstate av)\n" + "#else\n" + "static int sYSTRIm(pad, av) size_t pad; mstate av;\n" + "#endif\n" + "{\n" + " long top_size; /* Amount of top-most memory */\n" + " long extra; /* Amount to release */\n" + " long released; /* Amount actually released */\n" + " char* current_brk; /* address returned by pre-check sbrk call */\n" + " char* new_brk; /* address returned by post-check sbrk call */\n" + " size_t pagesz;\n" + "\n" + " pagesz = av->pagesize;\n" + " top_size = chunksize(av->top);\n" + "\n" + " /* Release in pagesize units, keeping at least one page */\n" + " extra = ((top_size - pad - MINSIZE + (pagesz-1)) / pagesz - 1) * pagesz;\n" + "\n" + " if (extra > 0) {\n" + "\n" + " /*\n" + " Only proceed if end of memory is where we last set it.\n" + " This avoids problems if there were foreign sbrk calls.\n" + " */\n" + " current_brk = (char*)(MORECORE(0));\n" + " if (current_brk == (char*)(av->top) + top_size) {\n" + "\n" + " /*\n" + " Attempt to release memory. We ignore MORECORE return value,\n" + " and instead call again to find out where new end of memory is.\n" + " This avoids problems if first call releases less than we asked,\n" + " of if failure somehow altered brk value. (We could still\n" + " encounter problems if it altered brk in some very bad way,\n" + " but the only thing we can do is adjust anyway, which will cause\n" + " some downstream failure.)\n" + " */\n" + "\n" + " MORECORE(-extra);\n" + " new_brk = (char*)(MORECORE(0));\n" + "\n" + " if (new_brk != (char*)MORECORE_FAILURE) {\n" + " released = (long)(current_brk - new_brk);\n" + "\n" + " if (released != 0) {\n" + " /* Success. Adjust top. */\n" + " av->sbrked_mem -= released;\n" + " set_head(av->top, (top_size - released) | PREV_INUSE);\n" + " check_malloc_state();\n" + " return 1;\n" + " }\n" + " }\n" + " }\n" + " }\n" + " return 0;\n" + "}\n" + "\n" + "#endif\n" + "\n" + "/*\n" + " ------------------------------ malloc ------------------------------\n" + "*/\n" + "\n" + "\n" + "#if __STD_C\n" + "Void_t* mALLOc(size_t bytes)\n" + "#else\n" + " Void_t* mALLOc(bytes) size_t bytes;\n" + "#endif\n" + "{\n" + " mstate av = get_malloc_state();\n" + "\n" + " INTERNAL_SIZE_T nb; /* normalized request size */\n" + " unsigned int idx; /* associated bin index */\n" + " mbinptr bin; /* associated bin */\n" + " mfastbinptr* fb; /* associated fastbin */\n" + "\n" + " mchunkptr victim; /* inspected/selected chunk */\n" + " INTERNAL_SIZE_T size; /* its size */\n" + " int victim_index; /* its bin index */\n" + "\n" + " mchunkptr remainder; /* remainder from a split */\n" + " CHUNK_SIZE_T remainder_size; /* its size */\n" + "\n" + " unsigned int block; /* bit map traverser */\n" + " unsigned int bit; /* bit map traverser */\n" + " unsigned int map; /* current word of binmap */\n" + "\n" + " mchunkptr fwd; /* misc temp for linking */\n" + " mchunkptr bck; /* misc temp for linking */\n" + "\n" + " /*\n" + " Convert request size to internal form by adding SIZE_SZ bytes\n" + " overhead plus possibly more to obtain necessary alignment and/or\n" + " to obtain a size of at least MINSIZE, the smallest allocatable\n" + " size. Also, checked_request2size traps (returning 0) request sizes\n" + " that are so large that they wrap around zero when padded and\n" + " aligned.\n" + " */\n" + "\n" + " checked_request2size(bytes, nb);\n" + "\n" + " /*\n" + " Bypass search if no frees yet\n" + " */\n" + " if (!have_anychunks(av)) {\n" + " if (av->max_fast == 0) /* initialization check */\n" + " malloc_consolidate(av);\n" + " goto use_top;\n" + " }\n" + "\n") + ( " /*\n" + " If the size qualifies as a fastbin, first check corresponding bin.\n" + " */\n" + "\n" + " if ((CHUNK_SIZE_T)(nb) <= (CHUNK_SIZE_T)(av->max_fast)) {\n" + " fb = &(av->fastbins[(fastbin_index(nb))]);\n" + " if ( (victim = *fb) != 0) {\n" + " *fb = victim->fd;\n" + " check_remalloced_chunk(victim, nb);\n" + " return chunk2mem(victim);\n" + " }\n" + " }\n" + "\n" + " /*\n" + " If a small request, check regular bin. Since these \"smallbins\"\n" + " hold one size each, no searching within bins is necessary.\n" + " (For a large request, we need to wait until unsorted chunks are\n" + " processed to find best fit. But for small ones, fits are exact\n" + " anyway, so we can check now, which is faster.)\n" + " */\n" + "\n" + " if (in_smallbin_range(nb)) {\n" + " idx = smallbin_index(nb);\n" + " bin = bin_at(av,idx);\n" + "\n" + " if ( (victim = last(bin)) != bin) {\n" + " bck = victim->bk;\n" + " set_inuse_bit_at_offset(victim, nb);\n" + " bin->bk = bck;\n" + " bck->fd = bin;\n" + "\n" + " check_malloced_chunk(victim, nb);\n" + " return chunk2mem(victim);\n" + " }\n" + " }\n" + "\n" + " /*\n" + " If this is a large request, consolidate fastbins before continuing.\n" + " While it might look excessive to kill all fastbins before\n" + " even seeing if there is space available, this avoids\n" + " fragmentation problems normally associated with fastbins.\n" + " Also, in practice, programs tend to have runs of either small or\n" + " large requests, but less often mixtures, so consolidation is not\n" + " invoked all that often in most programs. And the programs that\n" + " it is called frequently in otherwise tend to fragment.\n" + " */\n" + "\n" + " else {\n" + " idx = largebin_index(nb);\n" + " if (have_fastchunks(av))\n" + " malloc_consolidate(av);\n" + " }\n" + "\n" + " /*\n" + " Process recently freed or remaindered chunks, taking one only if\n" + " it is exact fit, or, if this a small request, the chunk is remainder from\n" + " the most recent non-exact fit. Place other traversed chunks in\n" + " bins. Note that this step is the only place in any routine where\n" + " chunks are placed in bins.\n" + " */\n" + "\n" + " while ( (victim = unsorted_chunks(av)->bk) != unsorted_chunks(av)) {\n" + " bck = victim->bk;\n" + " size = chunksize(victim);\n" + "\n" + " /*\n" + " If a small request, try to use last remainder if it is the\n" + " only chunk in unsorted bin. This helps promote locality for\n" + " runs of consecutive small requests. This is the only\n" + " exception to best-fit, and applies only when there is\n" + " no exact fit for a small chunk.\n" + " */\n" + "\n" + " if (in_smallbin_range(nb) &&\n" + " bck == unsorted_chunks(av) &&\n" + " victim == av->last_remainder &&\n" + " (CHUNK_SIZE_T)(size) > (CHUNK_SIZE_T)(nb + MINSIZE)) {\n" + "\n" + " /* split and reattach remainder */\n" + " remainder_size = size - nb;\n" + " remainder = chunk_at_offset(victim, nb);\n" + " unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;\n" + " av->last_remainder = remainder;\n" + " remainder->bk = remainder->fd = unsorted_chunks(av);\n" + "\n" + " set_head(victim, nb | PREV_INUSE);\n" + " set_head(remainder, remainder_size | PREV_INUSE);\n" + " set_foot(remainder, remainder_size);\n" + "\n" + " check_malloced_chunk(victim, nb);\n" + " return chunk2mem(victim);\n" + " }\n" + "\n" + " /* remove from unsorted list */\n" + " unsorted_chunks(av)->bk = bck;\n" + " bck->fd = unsorted_chunks(av);\n" + "\n" + " /* Take now instead of binning if exact fit */\n" + "\n" + " if (size == nb) {\n" + " set_inuse_bit_at_offset(victim, size);\n" + " check_malloced_chunk(victim, nb);\n" + " return chunk2mem(victim);\n" + " }\n" + "\n" + " /* place chunk in bin */\n" + "\n" + " if (in_smallbin_range(size)) {\n" + " victim_index = smallbin_index(size);\n" + " bck = bin_at(av, victim_index);\n" + " fwd = bck->fd;\n" + " }\n" + " else {\n" + " victim_index = largebin_index(size);\n" + " bck = bin_at(av, victim_index);\n" + " fwd = bck->fd;\n" + "\n" + " if (fwd != bck) {\n" + " /* if smaller than smallest, place first */\n" + " if ((CHUNK_SIZE_T)(size) < (CHUNK_SIZE_T)(bck->bk->size)) {\n" + " fwd = bck;\n" + " bck = bck->bk;\n" + " }\n" + " else if ((CHUNK_SIZE_T)(size) >=\n" + " (CHUNK_SIZE_T)(FIRST_SORTED_BIN_SIZE)) {\n" + "\n" + " /* maintain large bins in sorted order */\n" + " size |= PREV_INUSE; /* Or with inuse bit to speed comparisons */\n" + " while ((CHUNK_SIZE_T)(size) < (CHUNK_SIZE_T)(fwd->size))\n" + " fwd = fwd->fd;\n" + " bck = fwd->bk;\n" + " }\n" + " }\n" + " }\n" + "\n" + " mark_bin(av, victim_index);\n" + " victim->bk = bck;\n" + " victim->fd = fwd;\n" + " fwd->bk = victim;\n" + " bck->fd = victim;\n" + " }\n" + "\n" + " /*\n" + " If a large request, scan through the chunks of current bin to\n" + " find one that fits. (This will be the smallest that fits unless\n" + " FIRST_SORTED_BIN_SIZE has been changed from default.) This is\n" + " the only step where an unbounded number of chunks might be\n" + " scanned without doing anything useful with them. However the\n" + " lists tend to be short.\n" + " */\n" + "\n") + ( " if (!in_smallbin_range(nb)) {\n" + " bin = bin_at(av, idx);\n" + "\n" + " for (victim = last(bin); victim != bin; victim = victim->bk) {\n" + " size = chunksize(victim);\n" + "\n" + " if ((CHUNK_SIZE_T)(size) >= (CHUNK_SIZE_T)(nb)) {\n" + " remainder_size = size - nb;\n" + " unlink(victim, bck, fwd);\n" + "\n" + " /* Exhaust */\n" + " if (remainder_size < MINSIZE) {\n" + " set_inuse_bit_at_offset(victim, size);\n" + " check_malloced_chunk(victim, nb);\n" + " return chunk2mem(victim);\n" + " }\n" + " /* Split */\n" + " else {\n" + " remainder = chunk_at_offset(victim, nb);\n" + " unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;\n" + " remainder->bk = remainder->fd = unsorted_chunks(av);\n" + " set_head(victim, nb | PREV_INUSE);\n" + " set_head(remainder, remainder_size | PREV_INUSE);\n" + " set_foot(remainder, remainder_size);\n" + " check_malloced_chunk(victim, nb);\n" + " return chunk2mem(victim);\n" + " }\n" + " }\n" + " }\n" + " }\n" + "\n" + " /*\n" + " Search for a chunk by scanning bins, starting with next largest\n" + " bin. This search is strictly by best-fit; i.e., the smallest\n" + " (with ties going to approximately the least recently used) chunk\n" + " that fits is selected.\n" + "\n" + " The bitmap avoids needing to check that most blocks are nonempty.\n" + " */\n" + "\n" + " ++idx;\n" + " bin = bin_at(av,idx);\n" + " block = idx2block(idx);\n" + " map = av->binmap[block];\n" + " bit = idx2bit(idx);\n" + "\n" + " for (;;) {\n" + "\n" + " /* Skip rest of block if there are no more set bits in this block. */\n" + " if (bit > map || bit == 0) {\n" + " do {\n" + " if (++block >= BINMAPSIZE) /* out of bins */\n" + " goto use_top;\n" + " } while ( (map = av->binmap[block]) == 0);\n" + "\n" + " bin = bin_at(av, (block << BINMAPSHIFT));\n" + " bit = 1;\n" + " }\n" + "\n" + " /* Advance to bin with set bit. There must be one. */\n" + " while ((bit & map) == 0) {\n" + " bin = next_bin(bin);\n" + " bit <<= 1;\n" + " assert(bit != 0);\n" + " }\n" + "\n" + " /* Inspect the bin. It is likely to be non-empty */\n" + " victim = last(bin);\n" + "\n" + " /* If a false alarm (empty bin), clear the bit. */\n" + " if (victim == bin) {\n" + " av->binmap[block] = map &= ~bit; /* Write through */\n" + " bin = next_bin(bin);\n" + " bit <<= 1;\n" + " }\n" + "\n" + " else {\n" + " size = chunksize(victim);\n" + "\n" + " /* We know the first chunk in this bin is big enough to use. */\n" + " assert((CHUNK_SIZE_T)(size) >= (CHUNK_SIZE_T)(nb));\n" + "\n" + " remainder_size = size - nb;\n" + "\n" + " /* unlink */\n" + " bck = victim->bk;\n" + " bin->bk = bck;\n" + " bck->fd = bin;\n" + "\n" + " /* Exhaust */\n" + " if (remainder_size < MINSIZE) {\n" + " set_inuse_bit_at_offset(victim, size);\n" + " check_malloced_chunk(victim, nb);\n" + " return chunk2mem(victim);\n" + " }\n" + "\n" + " /* Split */\n" + " else {\n" + " remainder = chunk_at_offset(victim, nb);\n" + "\n" + " unsorted_chunks(av)->bk = unsorted_chunks(av)->fd = remainder;\n" + " remainder->bk = remainder->fd = unsorted_chunks(av);\n" + " /* advertise as last remainder */\n" + " if (in_smallbin_range(nb))\n" + " av->last_remainder = remainder;\n" + "\n" + " set_head(victim, nb | PREV_INUSE);\n" + " set_head(remainder, remainder_size | PREV_INUSE);\n" + " set_foot(remainder, remainder_size);\n" + " check_malloced_chunk(victim, nb);\n" + " return chunk2mem(victim);\n" + " }\n" + " }\n" + " }\n" + "\n" + " use_top:\n" + " /*\n" + " If large enough, split off the chunk bordering the end of memory\n" + " (held in av->top). Note that this is in accord with the best-fit\n" + " search rule. In effect, av->top is treated as larger (and thus\n" + " less well fitting) than any other available chunk since it can\n" + " be extended to be as large as necessary (up to system\n" + " limitations).\n" + "\n" + " We require that av->top always exists (i.e., has size >=\n" + " MINSIZE) after initialization, so if it would otherwise be\n" + " exhuasted by current request, it is replenished. (The main\n" + " reason for ensuring it exists is that we may need MINSIZE space\n" + " to put in fenceposts in sysmalloc.)\n" + " */\n" + "\n" + " victim = av->top;\n" + " size = chunksize(victim);\n" + "\n" + " if ((CHUNK_SIZE_T)(size) >= (CHUNK_SIZE_T)(nb + MINSIZE)) {\n" + " remainder_size = size - nb;\n" + " remainder = chunk_at_offset(victim, nb);\n" + " av->top = remainder;\n" + " set_head(victim, nb | PREV_INUSE);\n" + " set_head(remainder, remainder_size | PREV_INUSE);\n" + "\n" + " check_malloced_chunk(victim, nb);\n" + " return chunk2mem(victim);\n" + " }\n" + "\n" + " /*\n" + " If no space in top, relay to handle system-dependent cases\n" + " */\n" + " return sYSMALLOc(nb, av);\n" + "}\n" + "\n") + ( "/*\n" + " ------------------------------ free ------------------------------\n" + "*/\n" + "\n" + "#if __STD_C\n" + "void fREe(Void_t* mem)\n" + "#else\n" + "void fREe(mem) Void_t* mem;\n" + "#endif\n" + "{\n" + " mstate av = get_malloc_state();\n" + "\n" + " mchunkptr p; /* chunk corresponding to mem */\n" + " INTERNAL_SIZE_T size; /* its size */\n" + " mfastbinptr* fb; /* associated fastbin */\n" + " mchunkptr nextchunk; /* next contiguous chunk */\n" + " INTERNAL_SIZE_T nextsize; /* its size */\n" + " int nextinuse; /* true if nextchunk is used */\n" + " INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */\n" + " mchunkptr bck; /* misc temp for linking */\n" + " mchunkptr fwd; /* misc temp for linking */\n" + "\n" + " /* free(0) has no effect */\n" + " if (mem != 0) {\n" + " p = mem2chunk(mem);\n" + " size = chunksize(p);\n" + "\n" + " check_inuse_chunk(p);\n" + "\n" + " /*\n" + " If eligible, place chunk on a fastbin so it can be found\n" + " and used quickly in malloc.\n" + " */\n" + "\n" + " if ((CHUNK_SIZE_T)(size) <= (CHUNK_SIZE_T)(av->max_fast)\n" + "\n" + "#if TRIM_FASTBINS\n" + " /*\n" + " If TRIM_FASTBINS set, don't place chunks\n" + " bordering top into fastbins\n" + " */\n" + " && (chunk_at_offset(p, size) != av->top)\n" + "#endif\n" + " ) {\n" + "\n" + " set_fastchunks(av);\n" + " fb = &(av->fastbins[fastbin_index(size)]);\n" + " p->fd = *fb;\n" + " *fb = p;\n" + " }\n" + "\n" + " /*\n" + " Consolidate other non-mmapped chunks as they arrive.\n" + " */\n" + "\n" + " else if (!chunk_is_mmapped(p)) {\n" + " set_anychunks(av);\n" + "\n" + " nextchunk = chunk_at_offset(p, size);\n" + " nextsize = chunksize(nextchunk);\n" + "\n" + " /* consolidate backward */\n" + " if (!prev_inuse(p)) {\n" + " prevsize = p->prev_size;\n" + " size += prevsize;\n" + " p = chunk_at_offset(p, -((long) prevsize));\n" + " unlink(p, bck, fwd);\n" + " }\n" + "\n" + " if (nextchunk != av->top) {\n" + " /* get and clear inuse bit */\n" + " nextinuse = inuse_bit_at_offset(nextchunk, nextsize);\n" + " set_head(nextchunk, nextsize);\n" + "\n" + " /* consolidate forward */\n" + " if (!nextinuse) {\n" + " unlink(nextchunk, bck, fwd);\n" + " size += nextsize;\n" + " }\n" + "\n" + " /*\n" + " Place the chunk in unsorted chunk list. Chunks are\n" + " not placed into regular bins until after they have\n" + " been given one chance to be used in malloc.\n" + " */\n" + "\n" + " bck = unsorted_chunks(av);\n" + " fwd = bck->fd;\n" + " p->bk = bck;\n" + " p->fd = fwd;\n" + " bck->fd = p;\n" + " fwd->bk = p;\n" + "\n" + " set_head(p, size | PREV_INUSE);\n" + " set_foot(p, size);\n" + "\n" + " check_free_chunk(p);\n" + " }\n" + "\n" + " /*\n" + " If the chunk borders the current high end of memory,\n" + " consolidate into top\n" + " */\n" + "\n" + " else {\n" + " size += nextsize;\n" + " set_head(p, size | PREV_INUSE);\n" + " av->top = p;\n" + " check_chunk(p);\n" + " }\n" + "\n" + " /*\n" + " If freeing a large space, consolidate possibly-surrounding\n" + " chunks. Then, if the total unused topmost memory exceeds trim\n" + " threshold, ask malloc_trim to reduce top.\n" + "\n" + " Unless max_fast is 0, we don't know if there are fastbins\n" + " bordering top, so we cannot tell for sure whether threshold\n" + " has been reached unless fastbins are consolidated. But we\n" + " don't want to consolidate on each free. As a compromise,\n" + " consolidation is performed if FASTBIN_CONSOLIDATION_THRESHOLD\n" + " is reached.\n" + " */\n" + "\n" + " if ((CHUNK_SIZE_T)(size) >= FASTBIN_CONSOLIDATION_THRESHOLD) {\n" + " if (have_fastchunks(av))\n" + " malloc_consolidate(av);\n" + "\n" + "#ifndef MORECORE_CANNOT_TRIM\n" + " if ((CHUNK_SIZE_T)(chunksize(av->top)) >=\n" + " (CHUNK_SIZE_T)(av->trim_threshold))\n" + " sYSTRIm(av->top_pad, av);\n" + "#endif\n" + " }\n" + "\n" + " }\n" + " /*\n" + " If the chunk was allocated via mmap, release via munmap()\n" + " Note that if HAVE_MMAP is false but chunk_is_mmapped is\n" + " true, then user must have overwritten memory. There's nothing\n" + " we can do to catch this error unless DEBUG is set, in which case\n" + " check_inuse_chunk (above) will have triggered error.\n" + " */\n" + "\n" + " else {\n" + "#if HAVE_MMAP\n" + " int ret;\n" + " INTERNAL_SIZE_T offset = p->prev_size;\n" + " av->n_mmaps--;\n" + " av->mmapped_mem -= (size + offset);\n" + " ret = munmap((char*)p - offset, size + offset);\n" + " /* munmap returns non-zero on failure */\n" + " assert(ret == 0);\n" + "#endif\n" + " }\n" + " }\n" + "}\n" + "\n") + ( "/*\n" + " ------------------------- malloc_consolidate -------------------------\n" + "\n" + " malloc_consolidate is a specialized version of free() that tears\n" + " down chunks held in fastbins. Free itself cannot be used for this\n" + " purpose since, among other things, it might place chunks back onto\n" + " fastbins. So, instead, we need to use a minor variant of the same\n" + " code.\n" + "\n" + " Also, because this routine needs to be called the first time through\n" + " malloc anyway, it turns out to be the perfect place to trigger\n" + " initialization code.\n" + "*/\n" + "\n" + "#if __STD_C\n" + "static void malloc_consolidate(mstate av)\n" + "#else\n" + "static void malloc_consolidate(av) mstate av;\n" + "#endif\n" + "{\n" + " mfastbinptr* fb; /* current fastbin being consolidated */\n" + " mfastbinptr* maxfb; /* last fastbin (for loop control) */\n" + " mchunkptr p; /* current chunk being consolidated */\n" + " mchunkptr nextp; /* next chunk to consolidate */\n" + " mchunkptr unsorted_bin; /* bin header */\n" + " mchunkptr first_unsorted; /* chunk to link to */\n" + "\n" + " /* These have same use as in free() */\n" + " mchunkptr nextchunk;\n" + " INTERNAL_SIZE_T size;\n" + " INTERNAL_SIZE_T nextsize;\n" + " INTERNAL_SIZE_T prevsize;\n" + " int nextinuse;\n" + " mchunkptr bck;\n" + " mchunkptr fwd;\n" + "\n" + " /*\n" + " If max_fast is 0, we know that av hasn't\n" + " yet been initialized, in which case do so below\n" + " */\n" + "\n" + " if (av->max_fast != 0) {\n" + " clear_fastchunks(av);\n" + "\n" + " unsorted_bin = unsorted_chunks(av);\n" + "\n" + " /*\n" + " Remove each chunk from fast bin and consolidate it, placing it\n" + " then in unsorted bin. Among other reasons for doing this,\n" + " placing in unsorted bin avoids needing to calculate actual bins\n" + " until malloc is sure that chunks aren't immediately going to be\n" + " reused anyway.\n" + " */\n" + "\n" + " maxfb = &(av->fastbins[fastbin_index(av->max_fast)]);\n" + " fb = &(av->fastbins[0]);\n" + " do {\n" + " if ( (p = *fb) != 0) {\n" + " *fb = 0;\n" + "\n" + " do {\n" + " check_inuse_chunk(p);\n" + " nextp = p->fd;\n" + "\n" + " /* Slightly streamlined version of consolidation code in free() */\n" + " size = p->size & ~PREV_INUSE;\n" + " nextchunk = chunk_at_offset(p, size);\n" + " nextsize = chunksize(nextchunk);\n" + "\n" + " if (!prev_inuse(p)) {\n" + " prevsize = p->prev_size;\n" + " size += prevsize;\n" + " p = chunk_at_offset(p, -((long) prevsize));\n" + " unlink(p, bck, fwd);\n" + " }\n" + "\n" + " if (nextchunk != av->top) {\n" + " nextinuse = inuse_bit_at_offset(nextchunk, nextsize);\n" + " set_head(nextchunk, nextsize);\n" + "\n" + " if (!nextinuse) {\n" + " size += nextsize;\n" + " unlink(nextchunk, bck, fwd);\n" + " }\n" + "\n" + " first_unsorted = unsorted_bin->fd;\n" + " unsorted_bin->fd = p;\n" + " first_unsorted->bk = p;\n" + "\n" + " set_head(p, size | PREV_INUSE);\n" + " p->bk = unsorted_bin;\n" + " p->fd = first_unsorted;\n" + " set_foot(p, size);\n" + " }\n" + "\n" + " else {\n" + " size += nextsize;\n" + " set_head(p, size | PREV_INUSE);\n" + " av->top = p;\n" + " }\n" + "\n" + " } while ( (p = nextp) != 0);\n" + "\n" + " }\n" + " } while (fb++ != maxfb);\n" + " }\n" + " else {\n" + " malloc_init_state(av);\n" + " check_malloc_state();\n" + " }\n" + "}\n" + "\n" + "/*\n" + " ------------------------------ realloc ------------------------------\n" + "*/\n" + "\n" + "\n" + "#if __STD_C\n" + "Void_t* rEALLOc(Void_t* oldmem, size_t bytes)\n" + "#else\n" + "Void_t* rEALLOc(oldmem, bytes) Void_t* oldmem; size_t bytes;\n" + "#endif\n" + "{\n" + " mstate av = get_malloc_state();\n" + "\n" + " INTERNAL_SIZE_T nb; /* padded request size */\n" + "\n" + " mchunkptr oldp; /* chunk corresponding to oldmem */\n" + " INTERNAL_SIZE_T oldsize; /* its size */\n" + "\n" + " mchunkptr newp; /* chunk to return */\n" + " INTERNAL_SIZE_T newsize; /* its size */\n" + " Void_t* newmem; /* corresponding user mem */\n" + "\n" + " mchunkptr next; /* next contiguous chunk after oldp */\n" + "\n" + " mchunkptr remainder; /* extra space at end of newp */\n" + " CHUNK_SIZE_T remainder_size; /* its size */\n" + "\n" + " mchunkptr bck; /* misc temp for linking */\n" + " mchunkptr fwd; /* misc temp for linking */\n" + "\n" + " CHUNK_SIZE_T copysize; /* bytes to copy */\n" + " unsigned int ncopies; /* INTERNAL_SIZE_T words to copy */\n" + " INTERNAL_SIZE_T* s; /* copy source */\n" + " INTERNAL_SIZE_T* d; /* copy destination */\n" + "\n" + "\n" + "#ifdef REALLOC_ZERO_BYTES_FREES\n" + " if (bytes == 0) {\n" + " fREe(oldmem);\n" + " return 0;\n" + " }\n" + "#endif\n" + "\n") + ( " /* realloc of null is supposed to be same as malloc */\n" + " if (oldmem == 0) return mALLOc(bytes);\n" + "\n" + " checked_request2size(bytes, nb);\n" + "\n" + " oldp = mem2chunk(oldmem);\n" + " oldsize = chunksize(oldp);\n" + "\n" + " check_inuse_chunk(oldp);\n" + "\n" + " if (!chunk_is_mmapped(oldp)) {\n" + "\n" + " if ((CHUNK_SIZE_T)(oldsize) >= (CHUNK_SIZE_T)(nb)) {\n" + " /* already big enough; split below */\n" + " newp = oldp;\n" + " newsize = oldsize;\n" + " }\n" + "\n" + " else {\n" + " next = chunk_at_offset(oldp, oldsize);\n" + "\n" + " /* Try to expand forward into top */\n" + " if (next == av->top &&\n" + " (CHUNK_SIZE_T)(newsize = oldsize + chunksize(next)) >=\n" + " (CHUNK_SIZE_T)(nb + MINSIZE)) {\n" + " set_head_size(oldp, nb);\n" + " av->top = chunk_at_offset(oldp, nb);\n" + " set_head(av->top, (newsize - nb) | PREV_INUSE);\n" + " return chunk2mem(oldp);\n" + " }\n" + "\n" + " /* Try to expand forward into next chunk; split off remainder below */\n" + " else if (next != av->top &&\n" + " !inuse(next) &&\n" + " (CHUNK_SIZE_T)(newsize = oldsize + chunksize(next)) >=\n" + " (CHUNK_SIZE_T)(nb)) {\n" + " newp = oldp;\n" + " unlink(next, bck, fwd);\n" + " }\n" + "\n" + " /* allocate, copy, free */\n" + " else {\n" + " newmem = mALLOc(nb - MALLOC_ALIGN_MASK);\n" + " if (newmem == 0)\n" + " return 0; /* propagate failure */\n" + "\n" + " newp = mem2chunk(newmem);\n" + " newsize = chunksize(newp);\n" + "\n" + " /*\n" + " Avoid copy if newp is next chunk after oldp.\n" + " */\n" + " if (newp == next) {\n" + " newsize += oldsize;\n" + " newp = oldp;\n" + " }\n" + " else {\n" + " /*\n" + " Unroll copy of <= 36 bytes (72 if 8byte sizes)\n" + " We know that contents have an odd number of\n" + " INTERNAL_SIZE_T-sized words; minimally 3.\n" + " */\n" + "\n" + " copysize = oldsize - SIZE_SZ;\n" + " s = (INTERNAL_SIZE_T*)(oldmem);\n" + " d = (INTERNAL_SIZE_T*)(newmem);\n" + " ncopies = copysize / sizeof(INTERNAL_SIZE_T);\n" + " assert(ncopies >= 3);\n" + "\n" + " if (ncopies > 9)\n" + " MALLOC_COPY(d, s, copysize);\n" + "\n" + " else {\n" + " *(d+0) = *(s+0);\n" + " *(d+1) = *(s+1);\n" + " *(d+2) = *(s+2);\n" + " if (ncopies > 4) {\n" + " *(d+3) = *(s+3);\n" + " *(d+4) = *(s+4);\n" + " if (ncopies > 6) {\n" + " *(d+5) = *(s+5);\n" + " *(d+6) = *(s+6);\n" + " if (ncopies > 8) {\n" + " *(d+7) = *(s+7);\n" + " *(d+8) = *(s+8);\n" + " }\n" + " }\n" + " }\n" + " }\n" + "\n" + " fREe(oldmem);\n" + " check_inuse_chunk(newp);\n" + " return chunk2mem(newp);\n" + " }\n" + " }\n" + " }\n" + "\n" + " /* If possible, free extra space in old or extended chunk */\n" + "\n" + " assert((CHUNK_SIZE_T)(newsize) >= (CHUNK_SIZE_T)(nb));\n" + "\n" + " remainder_size = newsize - nb;\n" + "\n" + " if (remainder_size < MINSIZE) { /* not enough extra to split off */\n" + " set_head_size(newp, newsize);\n" + " set_inuse_bit_at_offset(newp, newsize);\n" + " }\n" + " else { /* split remainder */\n" + " remainder = chunk_at_offset(newp, nb);\n" + " set_head_size(newp, nb);\n" + " set_head(remainder, remainder_size | PREV_INUSE);\n" + " /* Mark remainder as inuse so free() won't complain */\n" + " set_inuse_bit_at_offset(remainder, remainder_size);\n" + " fREe(chunk2mem(remainder));\n" + " }\n" + "\n" + " check_inuse_chunk(newp);\n" + " return chunk2mem(newp);\n" + " }\n" + "\n" + " /*\n" + " Handle mmap cases\n" + " */\n" + "\n" + " else {\n" + "#if HAVE_MMAP\n" + "\n" + "#if HAVE_MREMAP\n" + " INTERNAL_SIZE_T offset = oldp->prev_size;\n" + " size_t pagemask = av->pagesize - 1;\n" + " char *cp;\n" + " CHUNK_SIZE_T sum;\n" + "\n" + " /* Note the extra SIZE_SZ overhead */\n" + " newsize = (nb + offset + SIZE_SZ + pagemask) & ~pagemask;\n" + "\n" + " /* don't need to remap if still within same page */\n" + " if (oldsize == newsize - offset)\n" + " return oldmem;\n" + "\n" + " cp = (char*)mremap((char*)oldp - offset, oldsize + offset, newsize, 1);\n" + "\n" + " if (cp != (char*)MORECORE_FAILURE) {\n" + "\n" + " newp = (mchunkptr)(cp + offset);\n" + " set_head(newp, (newsize - offset)|IS_MMAPPED);\n" + "\n" + " assert(aligned_OK(chunk2mem(newp)));\n" + " assert((newp->prev_size == offset));\n" + "\n") + ( " /* update statistics */\n" + " sum = av->mmapped_mem += newsize - oldsize;\n" + " if (sum > (CHUNK_SIZE_T)(av->max_mmapped_mem))\n" + " av->max_mmapped_mem = sum;\n" + " sum += av->sbrked_mem;\n" + " if (sum > (CHUNK_SIZE_T)(av->max_total_mem))\n" + " av->max_total_mem = sum;\n" + "\n" + " return chunk2mem(newp);\n" + " }\n" + "#endif\n" + "\n" + " /* Note the extra SIZE_SZ overhead. */\n" + " if ((CHUNK_SIZE_T)(oldsize) >= (CHUNK_SIZE_T)(nb + SIZE_SZ))\n" + " newmem = oldmem; /* do nothing */\n" + " else {\n" + " /* Must alloc, copy, free. */\n" + " newmem = mALLOc(nb - MALLOC_ALIGN_MASK);\n" + " if (newmem != 0) {\n" + " MALLOC_COPY(newmem, oldmem, oldsize - 2*SIZE_SZ);\n" + " fREe(oldmem);\n" + " }\n" + " }\n" + " return newmem;\n" + "\n" + "#else\n" + " /* If !HAVE_MMAP, but chunk_is_mmapped, user must have overwritten mem */\n" + " check_malloc_state();\n" + " MALLOC_FAILURE_ACTION;\n" + " return 0;\n" + "#endif\n" + " }\n" + "}\n" + "\n" + "/*\n" + " ------------------------------ memalign ------------------------------\n" + "*/\n" + "\n" + "#if __STD_C\n" + "Void_t* mEMALIGn(size_t alignment, size_t bytes)\n" + "#else\n" + "Void_t* mEMALIGn(alignment, bytes) size_t alignment; size_t bytes;\n" + "#endif\n" + "{\n" + " INTERNAL_SIZE_T nb; /* padded request size */\n" + " char* m; /* memory returned by malloc call */\n" + " mchunkptr p; /* corresponding chunk */\n" + " char* brk; /* alignment point within p */\n" + " mchunkptr newp; /* chunk to return */\n" + " INTERNAL_SIZE_T newsize; /* its size */\n" + " INTERNAL_SIZE_T leadsize; /* leading space before alignment point */\n" + " mchunkptr remainder; /* spare room at end to split off */\n" + " CHUNK_SIZE_T remainder_size; /* its size */\n" + " INTERNAL_SIZE_T size;\n" + "\n" + " /* If need less alignment than we give anyway, just relay to malloc */\n" + "\n" + " if (alignment <= MALLOC_ALIGNMENT) return mALLOc(bytes);\n" + "\n" + " /* Otherwise, ensure that it is at least a minimum chunk size */\n" + "\n" + " if (alignment < MINSIZE) alignment = MINSIZE;\n" + "\n" + " /* Make sure alignment is power of 2 (in case MINSIZE is not). */\n" + " if ((alignment & (alignment - 1)) != 0) {\n" + " size_t a = MALLOC_ALIGNMENT * 2;\n" + " while ((CHUNK_SIZE_T)a < (CHUNK_SIZE_T)alignment) a <<= 1;\n" + " alignment = a;\n" + " }\n" + "\n" + " checked_request2size(bytes, nb);\n" + "\n" + " /*\n" + " Strategy: find a spot within that chunk that meets the alignment\n" + " request, and then possibly free the leading and trailing space.\n" + " */\n" + "\n" + "\n" + " /* Call malloc with worst case padding to hit alignment. */\n" + "\n" + " m = (char*)(mALLOc(nb + alignment + MINSIZE));\n" + "\n" + " if (m == 0) return 0; /* propagate failure */\n" + "\n" + " p = mem2chunk(m);\n" + "\n" + " if ((((PTR_UINT)(m)) % alignment) != 0) { /* misaligned */\n" + "\n" + " /*\n" + " Find an aligned spot inside chunk. Since we need to give back\n" + " leading space in a chunk of at least MINSIZE, if the first\n" + " calculation places us at a spot with less than MINSIZE leader,\n" + " we can move to the next aligned spot -- we've allocated enough\n" + " total room so that this is always possible.\n" + " */\n" + "\n" + " brk = (char*)mem2chunk((PTR_UINT)(((PTR_UINT)(m + alignment - 1)) &\n" + " -((signed long) alignment)));\n" + " if ((CHUNK_SIZE_T)(brk - (char*)(p)) < MINSIZE)\n" + " brk += alignment;\n" + "\n" + " newp = (mchunkptr)brk;\n" + " leadsize = brk - (char*)(p);\n" + " newsize = chunksize(p) - leadsize;\n" + "\n" + " /* For mmapped chunks, just adjust offset */\n" + " if (chunk_is_mmapped(p)) {\n" + " newp->prev_size = p->prev_size + leadsize;\n" + " set_head(newp, newsize|IS_MMAPPED);\n" + " return chunk2mem(newp);\n" + " }\n" + "\n" + " /* Otherwise, give back leader, use the rest */\n" + " set_head(newp, newsize | PREV_INUSE);\n" + " set_inuse_bit_at_offset(newp, newsize);\n" + " set_head_size(p, leadsize);\n" + " fREe(chunk2mem(p));\n" + " p = newp;\n" + "\n" + " assert (newsize >= nb &&\n" + " (((PTR_UINT)(chunk2mem(p))) % alignment) == 0);\n" + " }\n" + "\n" + " /* Also give back spare room at the end */\n" + " if (!chunk_is_mmapped(p)) {\n" + " size = chunksize(p);\n" + " if ((CHUNK_SIZE_T)(size) > (CHUNK_SIZE_T)(nb + MINSIZE)) {\n" + " remainder_size = size - nb;\n" + " remainder = chunk_at_offset(p, nb);\n" + " set_head(remainder, remainder_size | PREV_INUSE);\n" + " set_head_size(p, nb);\n" + " fREe(chunk2mem(remainder));\n" + " }\n" + " }\n" + "\n" + " check_inuse_chunk(p);\n" + " return chunk2mem(p);\n" + "}\n" + "\n" + "/*\n" + " ------------------------------ calloc ------------------------------\n" + "*/\n" + "\n" + "#if __STD_C\n" + "Void_t* cALLOc(size_t n_elements, size_t elem_size)\n" + "#else\n" + "Void_t* cALLOc(n_elements, elem_size) size_t n_elements; size_t elem_size;\n" + "#endif\n" + "{\n" + " mchunkptr p;\n" + " CHUNK_SIZE_T clearsize;\n" + " CHUNK_SIZE_T nclears;\n" + " INTERNAL_SIZE_T* d;\n" + "\n") + ( " Void_t* mem = mALLOc(n_elements * elem_size);\n" + "\n" + " if (mem != 0) {\n" + " p = mem2chunk(mem);\n" + "\n" + " if (!chunk_is_mmapped(p))\n" + " {\n" + " /*\n" + " Unroll clear of <= 36 bytes (72 if 8byte sizes)\n" + " We know that contents have an odd number of\n" + " INTERNAL_SIZE_T-sized words; minimally 3.\n" + " */\n" + "\n" + " d = (INTERNAL_SIZE_T*)mem;\n" + " clearsize = chunksize(p) - SIZE_SZ;\n" + " nclears = clearsize / sizeof(INTERNAL_SIZE_T);\n" + " assert(nclears >= 3);\n" + "\n" + " if (nclears > 9)\n" + " MALLOC_ZERO(d, clearsize);\n" + "\n" + " else {\n" + " *(d+0) = 0;\n" + " *(d+1) = 0;\n" + " *(d+2) = 0;\n" + " if (nclears > 4) {\n" + " *(d+3) = 0;\n" + " *(d+4) = 0;\n" + " if (nclears > 6) {\n" + " *(d+5) = 0;\n" + " *(d+6) = 0;\n" + " if (nclears > 8) {\n" + " *(d+7) = 0;\n" + " *(d+8) = 0;\n" + " }\n" + " }\n" + " }\n" + " }\n" + " }\n" + "#if ! MMAP_CLEARS\n" + " else\n" + " {\n" + " d = (INTERNAL_SIZE_T*)mem;\n" + " /*\n" + " Note the additional SIZE_SZ\n" + " */\n" + " clearsize = chunksize(p) - 2*SIZE_SZ;\n" + " MALLOC_ZERO(d, clearsize);\n" + " }\n" + "#endif\n" + " }\n" + " return mem;\n" + "}\n" + "\n" + "/*\n" + " ------------------------------ cfree ------------------------------\n" + "*/\n" + "\n" + "#if __STD_C\n" + "void cFREe(Void_t *mem)\n" + "#else\n" + "void cFREe(mem) Void_t *mem;\n" + "#endif\n" + "{\n" + " fREe(mem);\n" + "}\n" + "\n" + "/*\n" + " ------------------------- independent_calloc -------------------------\n" + "*/\n" + "\n" + "#if __STD_C\n" + "Void_t** iCALLOc(size_t n_elements, size_t elem_size, Void_t* chunks[])\n" + "#else\n" + "Void_t** iCALLOc(n_elements, elem_size, chunks) size_t n_elements; size_t elem_size; Void_t* chunks[];\n" + "#endif\n" + "{\n" + " size_t sz = elem_size; /* serves as 1-element array */\n" + " /* opts arg of 3 means all elements are same size, and should be cleared */\n" + " return iALLOc(n_elements, &sz, 3, chunks);\n" + "}\n" + "\n" + "/*\n" + " ------------------------- independent_comalloc -------------------------\n" + "*/\n" + "\n" + "#if __STD_C\n" + "Void_t** iCOMALLOc(size_t n_elements, size_t sizes[], Void_t* chunks[])\n" + "#else\n" + "Void_t** iCOMALLOc(n_elements, sizes, chunks) size_t n_elements; size_t sizes[]; Void_t* chunks[];\n" + "#endif\n" + "{\n" + " return iALLOc(n_elements, sizes, 0, chunks);\n" + "}\n" + "\n" + "\n" + "/*\n" + " ------------------------------ ialloc ------------------------------\n" + " ialloc provides common support for independent_X routines, handling all of\n" + " the combinations that can result.\n" + "\n" + " The opts arg has:\n" + " bit 0 set if all elements are same size (using sizes[0])\n" + " bit 1 set if elements should be zeroed\n" + "*/\n" + "\n" + "\n" + "#if __STD_C\n" + "static Void_t** iALLOc(size_t n_elements,\n" + " size_t* sizes,\n" + " int opts,\n" + " Void_t* chunks[])\n" + "#else\n" + "static Void_t** iALLOc(n_elements, sizes, opts, chunks) size_t n_elements; size_t* sizes; int opts; Void_t* chunks[];\n" + "#endif\n" + "{\n" + " mstate av = get_malloc_state();\n" + " INTERNAL_SIZE_T element_size; /* chunksize of each element, if all same */\n" + " INTERNAL_SIZE_T contents_size; /* total size of elements */\n" + " INTERNAL_SIZE_T array_size; /* request size of pointer array */\n" + " Void_t* mem; /* malloced aggregate space */\n" + " mchunkptr p; /* corresponding chunk */\n" + " INTERNAL_SIZE_T remainder_size; /* remaining bytes while splitting */\n" + " Void_t** marray; /* either \"chunks\" or malloced ptr array */\n" + " mchunkptr array_chunk; /* chunk for malloced ptr array */\n" + " int mmx; /* to disable mmap */\n" + " INTERNAL_SIZE_T size;\n" + " size_t i;\n" + "\n" + " /* Ensure initialization */\n" + " if (av->max_fast == 0) malloc_consolidate(av);\n" + "\n" + " /* compute array length, if needed */\n" + " if (chunks != 0) {\n" + " if (n_elements == 0)\n" + " return chunks; /* nothing to do */\n" + " marray = chunks;\n" + " array_size = 0;\n" + " }\n" + " else {\n" + " /* if empty req, must still return chunk representing empty array */\n" + " if (n_elements == 0)\n" + " return (Void_t**) mALLOc(0);\n" + " marray = 0;\n" + " array_size = request2size(n_elements * (sizeof(Void_t*)));\n" + " }\n" + "\n" + " /* compute total element size */\n" + " if (opts & 0x1) { /* all-same-size */\n" + " element_size = request2size(*sizes);\n" + " contents_size = n_elements * element_size;\n" + " }\n" + " else { /* add up all the sizes */\n" + " element_size = 0;\n" + " contents_size = 0;\n" + " for (i = 0; i != n_elements; ++i)\n" + " contents_size += request2size(sizes[i]);\n" + " }\n" + "\n") + ( " /* subtract out alignment bytes from total to minimize overallocation */\n" + " size = contents_size + array_size - MALLOC_ALIGN_MASK;\n" + "\n" + " /*\n" + " Allocate the aggregate chunk.\n" + " But first disable mmap so malloc won't use it, since\n" + " we would not be able to later free/realloc space internal\n" + " to a segregated mmap region.\n" + " */\n" + " mmx = av->n_mmaps_max; /* disable mmap */\n" + " av->n_mmaps_max = 0;\n" + " mem = mALLOc(size);\n" + " av->n_mmaps_max = mmx; /* reset mmap */\n" + " if (mem == 0)\n" + " return 0;\n" + "\n" + " p = mem2chunk(mem);\n" + " assert(!chunk_is_mmapped(p));\n" + " remainder_size = chunksize(p);\n" + "\n" + " if (opts & 0x2) { /* optionally clear the elements */\n" + " MALLOC_ZERO(mem, remainder_size - SIZE_SZ - array_size);\n" + " }\n" + "\n" + " /* If not provided, allocate the pointer array as final part of chunk */\n" + " if (marray == 0) {\n" + " array_chunk = chunk_at_offset(p, contents_size);\n" + " marray = (Void_t**) (chunk2mem(array_chunk));\n" + " set_head(array_chunk, (remainder_size - contents_size) | PREV_INUSE);\n" + " remainder_size = contents_size;\n" + " }\n" + "\n" + " /* split out elements */\n" + " for (i = 0; ; ++i) {\n" + " marray[i] = chunk2mem(p);\n" + " if (i != n_elements-1) {\n" + " if (element_size != 0)\n" + " size = element_size;\n" + " else\n" + " size = request2size(sizes[i]);\n" + " remainder_size -= size;\n" + " set_head(p, size | PREV_INUSE);\n" + " p = chunk_at_offset(p, size);\n" + " }\n" + " else { /* the final element absorbs any overallocation slop */\n" + " set_head(p, remainder_size | PREV_INUSE);\n" + " break;\n" + " }\n" + " }\n" + "\n" + "#if DEBUG\n" + " if (marray != chunks) {\n" + " /* final element must have exactly exhausted chunk */\n" + " if (element_size != 0)\n" + " assert(remainder_size == element_size);\n" + " else\n" + " assert(remainder_size == request2size(sizes[i]));\n" + " check_inuse_chunk(mem2chunk(marray));\n" + " }\n" + "\n" + " for (i = 0; i != n_elements; ++i)\n" + " check_inuse_chunk(mem2chunk(marray[i]));\n" + "#endif\n" + "\n" + " return marray;\n" + "}\n" + "\n" + "\n" + "/*\n" + " ------------------------------ valloc ------------------------------\n" + "*/\n" + "\n" + "#if __STD_C\n" + "Void_t* vALLOc(size_t bytes)\n" + "#else\n" + "Void_t* vALLOc(bytes) size_t bytes;\n" + "#endif\n" + "{\n" + " /* Ensure initialization */\n" + " mstate av = get_malloc_state();\n" + " if (av->max_fast == 0) malloc_consolidate(av);\n" + " return mEMALIGn(av->pagesize, bytes);\n" + "}\n" + "\n" + "/*\n" + " ------------------------------ pvalloc ------------------------------\n" + "*/\n" + "\n" + "\n" + "#if __STD_C\n" + "Void_t* pVALLOc(size_t bytes)\n" + "#else\n" + "Void_t* pVALLOc(bytes) size_t bytes;\n" + "#endif\n" + "{\n" + " mstate av = get_malloc_state();\n" + " size_t pagesz;\n" + "\n" + " /* Ensure initialization */\n" + " if (av->max_fast == 0) malloc_consolidate(av);\n" + " pagesz = av->pagesize;\n" + " return mEMALIGn(pagesz, (bytes + pagesz - 1) & ~(pagesz - 1));\n" + "}\n" + "\n" + "\n" + "/*\n" + " ------------------------------ malloc_trim ------------------------------\n" + "*/\n" + "\n" + "#if __STD_C\n" + "int mTRIm(size_t pad)\n" + "#else\n" + "int mTRIm(pad) size_t pad;\n" + "#endif\n" + "{\n" + " mstate av = get_malloc_state();\n" + " /* Ensure initialization/consolidation */\n" + " malloc_consolidate(av);\n" + "\n" + "#ifndef MORECORE_CANNOT_TRIM\n" + " return sYSTRIm(pad, av);\n" + "#else\n" + " return 0;\n" + "#endif\n" + "}\n" + "\n" + "\n" + "/*\n" + " ------------------------- malloc_usable_size -------------------------\n" + "*/\n" + "\n" + "#if __STD_C\n" + "size_t mUSABLe(Void_t* mem)\n" + "#else\n" + "size_t mUSABLe(mem) Void_t* mem;\n" + "#endif\n" + "{\n" + " mchunkptr p;\n" + " if (mem != 0) {\n" + " p = mem2chunk(mem);\n" + " if (chunk_is_mmapped(p))\n" + " return chunksize(p) - 2*SIZE_SZ;\n" + " else if (inuse(p))\n" + " return chunksize(p) - SIZE_SZ;\n" + " }\n" + " return 0;\n" + "}\n" + "\n" + "/*\n" + " ------------------------------ mallinfo ------------------------------\n" + "*/\n" + "\n") + ( "struct mallinfo mALLINFo()\n" + "{\n" + " mstate av = get_malloc_state();\n" + " struct mallinfo mi;\n" + " unsigned int i;\n" + " mbinptr b;\n" + " mchunkptr p;\n" + " INTERNAL_SIZE_T avail;\n" + " INTERNAL_SIZE_T fastavail;\n" + " int nblocks;\n" + " int nfastblocks;\n" + "\n" + " /* Ensure initialization */\n" + " if (av->top == 0) malloc_consolidate(av);\n" + "\n" + " check_malloc_state();\n" + "\n" + " /* Account for top */\n" + " avail = chunksize(av->top);\n" + " nblocks = 1; /* top always exists */\n" + "\n" + " /* traverse fastbins */\n" + " nfastblocks = 0;\n" + " fastavail = 0;\n" + "\n" + " for (i = 0; i < NFASTBINS; ++i) {\n" + " for (p = av->fastbins[i]; p != 0; p = p->fd) {\n" + " ++nfastblocks;\n" + " fastavail += chunksize(p);\n" + " }\n" + " }\n" + "\n" + " avail += fastavail;\n" + "\n" + " /* traverse regular bins */\n" + " for (i = 1; i < NBINS; ++i) {\n" + " b = bin_at(av, i);\n" + " for (p = last(b); p != b; p = p->bk) {\n" + " ++nblocks;\n" + " avail += chunksize(p);\n" + " }\n" + " }\n" + "\n" + " mi.smblks = nfastblocks;\n" + " mi.ordblks = nblocks;\n" + " mi.fordblks = avail;\n" + " mi.uordblks = av->sbrked_mem - avail;\n" + " mi.arena = av->sbrked_mem;\n" + " mi.hblks = av->n_mmaps;\n" + " mi.hblkhd = av->mmapped_mem;\n" + " mi.fsmblks = fastavail;\n" + " mi.keepcost = chunksize(av->top);\n" + " mi.usmblks = av->max_total_mem;\n" + " return mi;\n" + "}\n" + "\n" + "/*\n" + " ------------------------------ malloc_stats ------------------------------\n" + "*/\n" + "\n" + "void mSTATs()\n" + "{\n" + " struct mallinfo mi = mALLINFo();\n" + "\n" + "#ifdef WIN32\n" + " {\n" + " CHUNK_SIZE_T free, reserved, committed;\n" + " vminfo (&free, &reserved, &committed);\n" + " fprintf(stderr, \"free bytes = %10lu\\n\",\n" + " free);\n" + " fprintf(stderr, \"reserved bytes = %10lu\\n\",\n" + " reserved);\n" + " fprintf(stderr, \"committed bytes = %10lu\\n\",\n" + " committed);\n" + " }\n" + "#endif\n" + "\n" + "\n" + " fprintf(stderr, \"max system bytes = %10lu\\n\",\n" + " (CHUNK_SIZE_T)(mi.usmblks));\n" + " fprintf(stderr, \"system bytes = %10lu\\n\",\n" + " (CHUNK_SIZE_T)(mi.arena + mi.hblkhd));\n" + " fprintf(stderr, \"in use bytes = %10lu\\n\",\n" + " (CHUNK_SIZE_T)(mi.uordblks + mi.hblkhd));\n" + "\n" + "#ifdef WIN32\n" + " {\n" + " CHUNK_SIZE_T kernel, user;\n" + " if (cpuinfo (TRUE, &kernel, &user)) {\n" + " fprintf(stderr, \"kernel ms = %10lu\\n\",\n" + " kernel);\n" + " fprintf(stderr, \"user ms = %10lu\\n\",\n" + " user);\n" + " }\n" + " }\n" + "#endif\n" + "}\n" + "\n" + "\n" + "/*\n" + " ------------------------------ mallopt ------------------------------\n" + "*/\n" + "\n" + "#if __STD_C\n" + "int mALLOPt(int param_number, int value)\n" + "#else\n" + "int mALLOPt(param_number, value) int param_number; int value;\n" + "#endif\n" + "{\n" + " mstate av = get_malloc_state();\n" + " /* Ensure initialization/consolidation */\n" + " malloc_consolidate(av);\n" + "\n" + " switch(param_number) {\n" + " case M_MXFAST:\n" + " if (value >= 0 && value <= MAX_FAST_SIZE) {\n" + " set_max_fast(av, value);\n" + " return 1;\n" + " }\n" + " else\n" + " return 0;\n" + "\n" + " case M_TRIM_THRESHOLD:\n" + " av->trim_threshold = value;\n" + " return 1;\n" + "\n" + " case M_TOP_PAD:\n" + " av->top_pad = value;\n" + " return 1;\n" + "\n" + " case M_MMAP_THRESHOLD:\n" + " av->mmap_threshold = value;\n" + " return 1;\n" + "\n" + " case M_MMAP_MAX:\n" + "#if !HAVE_MMAP\n" + " if (value != 0)\n" + " return 0;\n" + "#endif\n" + " av->n_mmaps_max = value;\n" + " return 1;\n" + "\n" + " default:\n" + " return 0;\n" + " }\n" + "}\n" + "\n" + "\n" + "/*\n" + " -------------------- Alternative MORECORE functions --------------------\n" + "*/\n" + "\n") + ( "\n" + "/*\n" + " General Requirements for MORECORE.\n" + "\n" + " The MORECORE function must have the following properties:\n" + "\n" + " If MORECORE_CONTIGUOUS is false:\n" + "\n" + " * MORECORE must allocate in multiples of pagesize. It will\n" + " only be called with arguments that are multiples of pagesize.\n" + "\n" + " * MORECORE(0) must return an address that is at least\n" + " MALLOC_ALIGNMENT aligned. (Page-aligning always suffices.)\n" + "\n" + " else (i.e. If MORECORE_CONTIGUOUS is true):\n" + "\n" + " * Consecutive calls to MORECORE with positive arguments\n" + " return increasing addresses, indicating that space has been\n" + " contiguously extended.\n" + "\n" + " * MORECORE need not allocate in multiples of pagesize.\n" + " Calls to MORECORE need not have args of multiples of pagesize.\n" + "\n" + " * MORECORE need not page-align.\n" + "\n" + " In either case:\n" + "\n" + " * MORECORE may allocate more memory than requested. (Or even less,\n" + " but this will generally result in a malloc failure.)\n" + "\n" + " * MORECORE must not allocate memory when given argument zero, but\n" + " instead return one past the end address of memory from previous\n" + " nonzero call. This malloc does NOT call MORECORE(0)\n" + " until at least one call with positive arguments is made, so\n" + " the initial value returned is not important.\n" + "\n" + " * Even though consecutive calls to MORECORE need not return contiguous\n" + " addresses, it must be OK for malloc'ed chunks to span multiple\n" + " regions in those cases where they do happen to be contiguous.\n" + "\n" + " * MORECORE need not handle negative arguments -- it may instead\n" + " just return MORECORE_FAILURE when given negative arguments.\n" + " Negative arguments are always multiples of pagesize. MORECORE\n" + " must not misinterpret negative args as large positive unsigned\n" + " args. You can suppress all such calls from even occurring by defining\n" + " MORECORE_CANNOT_TRIM,\n" + "\n" + " There is some variation across systems about the type of the\n" + " argument to sbrk/MORECORE. If size_t is unsigned, then it cannot\n" + " actually be size_t, because sbrk supports negative args, so it is\n" + " normally the signed type of the same width as size_t (sometimes\n" + " declared as \"intptr_t\", and sometimes \"ptrdiff_t\"). It doesn't much\n" + " matter though. Internally, we use \"long\" as arguments, which should\n" + " work across all reasonable possibilities.\n" + "\n" + " Additionally, if MORECORE ever returns failure for a positive\n" + " request, and HAVE_MMAP is true, then mmap is used as a noncontiguous\n" + " system allocator. This is a useful backup strategy for systems with\n" + " holes in address spaces -- in this case sbrk cannot contiguously\n" + " expand the heap, but mmap may be able to map noncontiguous space.\n" + "\n" + " If you'd like mmap to ALWAYS be used, you can define MORECORE to be\n" + " a function that always returns MORECORE_FAILURE.\n" + "\n" + " Malloc only has limited ability to detect failures of MORECORE\n" + " to supply contiguous space when it says it can. In particular,\n" + " multithreaded programs that do not use locks may result in\n" + " rece conditions across calls to MORECORE that result in gaps\n" + " that cannot be detected as such, and subsequent corruption.\n" + "\n" + " If you are using this malloc with something other than sbrk (or its\n" + " emulation) to supply memory regions, you probably want to set\n" + " MORECORE_CONTIGUOUS as false. As an example, here is a custom\n" + " allocator kindly contributed for pre-OSX macOS. It uses virtually\n" + " but not necessarily physically contiguous non-paged memory (locked\n" + " in, present and won't get swapped out). You can use it by\n" + " uncommenting this section, adding some #includes, and setting up the\n" + " appropriate defines above:\n" + "\n" + " #define MORECORE osMoreCore\n" + " #define MORECORE_CONTIGUOUS 0\n" + "\n" + " There is also a shutdown routine that should somehow be called for\n" + " cleanup upon program exit.\n" + "\n" + " #define MAX_POOL_ENTRIES 100\n" + " #define MINIMUM_MORECORE_SIZE (64 * 1024)\n" + " static int next_os_pool;\n" + " void *our_os_pools[MAX_POOL_ENTRIES];\n" + "\n" + " void *osMoreCore(int size)\n" + " {\n" + " void *ptr = 0;\n" + " static void *sbrk_top = 0;\n" + "\n" + " if (size > 0)\n" + " {\n" + " if (size < MINIMUM_MORECORE_SIZE)\n" + " size = MINIMUM_MORECORE_SIZE;\n" + " if (CurrentExecutionLevel() == kTaskLevel)\n" + " ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0);\n" + " if (ptr == 0)\n" + " {\n" + " return (void *) MORECORE_FAILURE;\n" + " }\n" + " // save ptrs so they can be freed during cleanup\n" + " our_os_pools[next_os_pool] = ptr;\n" + " next_os_pool++;\n" + " ptr = (void *) ((((CHUNK_SIZE_T) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK);\n" + " sbrk_top = (char *) ptr + size;\n" + " return ptr;\n" + " }\n" + " else if (size < 0)\n" + " {\n" + " // we don't currently support shrink behavior\n" + " return (void *) MORECORE_FAILURE;\n" + " }\n" + " else\n" + " {\n" + " return sbrk_top;\n" + " }\n" + " }\n" + "\n" + " // cleanup any allocated memory pools\n" + " // called as last thing before shutting down driver\n" + "\n" + " void osCleanupMem(void)\n" + " {\n" + " void **ptr;\n" + "\n" + " for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++)\n" + " if (*ptr)\n" + " {\n" + " PoolDeallocate(*ptr);\n" + " *ptr = 0;\n" + " }\n" + " }\n" + "\n" + "*/\n" + "\n" + "\n" + "/*\n" + " --------------------------------------------------------------\n" + "\n" + " Emulation of sbrk for win32.\n" + " Donated by J. Walter <Walter@GeNeSys-e.de>.\n" + " For additional information about this code, and malloc on Win32, see\n" + " http://www.genesys-e.de/jwalter/\n" + "*/\n" + "\n" + "\n") + ( "#ifdef WIN32\n" + "\n" + "#ifdef _DEBUG\n" + "/* #define TRACE */\n" + "#endif\n" + "\n" + "/* Support for USE_MALLOC_LOCK */\n" + "#ifdef USE_MALLOC_LOCK\n" + "\n" + "/* Wait for spin lock */\n" + "static int slwait (int *sl) {\n" + " while (InterlockedCompareExchange ((void **) sl, (void *) 1, (void *) 0) != 0)\n" + " Sleep (0);\n" + " return 0;\n" + "}\n" + "\n" + "/* Release spin lock */\n" + "static int slrelease (int *sl) {\n" + " InterlockedExchange (sl, 0);\n" + " return 0;\n" + "}\n" + "\n" + "#ifdef NEEDED\n" + "/* Spin lock for emulation code */\n" + "static int g_sl;\n" + "#endif\n" + "\n" + "#endif /* USE_MALLOC_LOCK */\n" + "\n" + "/* getpagesize for windows */\n" + "static long getpagesize (void) {\n" + " static long g_pagesize = 0;\n" + " if (! g_pagesize) {\n" + " SYSTEM_INFO system_info;\n" + " GetSystemInfo (&system_info);\n" + " g_pagesize = system_info.dwPageSize;\n" + " }\n" + " return g_pagesize;\n" + "}\n" + "static long getregionsize (void) {\n" + " static long g_regionsize = 0;\n" + " if (! g_regionsize) {\n" + " SYSTEM_INFO system_info;\n" + " GetSystemInfo (&system_info);\n" + " g_regionsize = system_info.dwAllocationGranularity;\n" + " }\n" + " return g_regionsize;\n" + "}\n" + "\n" + "/* A region list entry */\n" + "typedef struct _region_list_entry {\n" + " void *top_allocated;\n" + " void *top_committed;\n" + " void *top_reserved;\n" + " long reserve_size;\n" + " struct _region_list_entry *previous;\n" + "} region_list_entry;\n" + "\n" + "/* Allocate and link a region entry in the region list */\n" + "static int region_list_append (region_list_entry **last, void *base_reserved, long reserve_size) {\n" + " region_list_entry *next = HeapAlloc (GetProcessHeap (), 0, sizeof (region_list_entry));\n" + " if (! next)\n" + " return FALSE;\n" + " next->top_allocated = (char *) base_reserved;\n" + " next->top_committed = (char *) base_reserved;\n" + " next->top_reserved = (char *) base_reserved + reserve_size;\n" + " next->reserve_size = reserve_size;\n" + " next->previous = *last;\n" + " *last = next;\n" + " return TRUE;\n" + "}\n" + "/* Free and unlink the last region entry from the region list */\n" + "static int region_list_remove (region_list_entry **last) {\n" + " region_list_entry *previous = (*last)->previous;\n" + " if (! HeapFree (GetProcessHeap (), sizeof (region_list_entry), *last))\n" + " return FALSE;\n" + " *last = previous;\n" + " return TRUE;\n" + "}\n" + "\n" + "#define CEIL(size,to) (((size)+(to)-1)&~((to)-1))\n" + "#define FLOOR(size,to) ((size)&~((to)-1))\n" + "\n" + "#define SBRK_SCALE 0\n" + "/* #define SBRK_SCALE 1 */\n" + "/* #define SBRK_SCALE 2 */\n" + "/* #define SBRK_SCALE 4 */\n" + "\n" + "/* sbrk for windows */\n" + "static void *sbrk (long size) {\n" + " static long g_pagesize, g_my_pagesize;\n" + " static long g_regionsize, g_my_regionsize;\n" + " static region_list_entry *g_last;\n" + " void *result = (void *) MORECORE_FAILURE;\n" + "#ifdef TRACE\n" + " printf (\"sbrk %d\\n\", size);\n" + "#endif\n" + "#if defined (USE_MALLOC_LOCK) && defined (NEEDED)\n" + " /* Wait for spin lock */\n" + " slwait (&g_sl);\n" + "#endif\n" + " /* First time initialization */\n" + " if (! g_pagesize) {\n" + " g_pagesize = getpagesize ();\n" + " g_my_pagesize = g_pagesize << SBRK_SCALE;\n" + " }\n" + " if (! g_regionsize) {\n" + " g_regionsize = getregionsize ();\n" + " g_my_regionsize = g_regionsize << SBRK_SCALE;\n" + " }\n" + " if (! g_last) {\n" + " if (! region_list_append (&g_last, 0, 0))\n" + " goto sbrk_exit;\n" + " }\n" + " /* Assert invariants */\n" + " assert (g_last);\n" + " assert ((char *) g_last->top_reserved - g_last->reserve_size <= (char *) g_last->top_allocated &&\n" + " g_last->top_allocated <= g_last->top_committed);\n" + " assert ((char *) g_last->top_reserved - g_last->reserve_size <= (char *) g_last->top_committed &&\n" + " g_last->top_committed <= g_last->top_reserved &&\n" + " (unsigned) g_last->top_committed % g_pagesize == 0);\n" + " assert ((unsigned) g_last->top_reserved % g_regionsize == 0);\n" + " assert ((unsigned) g_last->reserve_size % g_regionsize == 0);\n" + " /* Allocation requested? */\n" + " if (size >= 0) {\n" + " /* Allocation size is the requested size */\n" + " long allocate_size = size;\n" + " /* Compute the size to commit */\n" + " long to_commit = (char *) g_last->top_allocated + allocate_size - (char *) g_last->top_committed;\n" + " /* Do we reach the commit limit? */\n" + " if (to_commit > 0) {\n" + " /* Round size to commit */\n" + " long commit_size = CEIL (to_commit, g_my_pagesize);\n" + " /* Compute the size to reserve */\n" + " long to_reserve = (char *) g_last->top_committed + commit_size - (char *) g_last->top_reserved;\n" + " /* Do we reach the reserve limit? */\n" + " if (to_reserve > 0) {\n" + " /* Compute the remaining size to commit in the current region */\n" + " long remaining_commit_size = (char *) g_last->top_reserved - (char *) g_last->top_committed;\n" + " if (remaining_commit_size > 0) {\n" + " /* Assert preconditions */\n" + " assert ((unsigned) g_last->top_committed % g_pagesize == 0);\n" + " assert (0 < remaining_commit_size && remaining_commit_size % g_pagesize == 0); {\n" + " /* Commit this */\n" + " void *base_committed = VirtualAlloc (g_last->top_committed, remaining_commit_size,\n" + " MEM_COMMIT, PAGE_READWRITE);\n" + " /* Check returned pointer for consistency */\n" + " if (base_committed != g_last->top_committed)\n" + " goto sbrk_exit;\n") + ( " /* Assert postconditions */\n" + " assert ((unsigned) base_committed % g_pagesize == 0);\n" + "#ifdef TRACE\n" + " printf (\"Commit %p %d\\n\", base_committed, remaining_commit_size);\n" + "#endif\n" + " /* Adjust the regions commit top */\n" + " g_last->top_committed = (char *) base_committed + remaining_commit_size;\n" + " }\n" + " } {\n" + " /* Now we are going to search and reserve. */\n" + " int contiguous = -1;\n" + " int found = FALSE;\n" + " MEMORY_BASIC_INFORMATION memory_info;\n" + " void *base_reserved;\n" + " long reserve_size;\n" + " do {\n" + " /* Assume contiguous memory */\n" + " contiguous = TRUE;\n" + " /* Round size to reserve */\n" + " reserve_size = CEIL (to_reserve, g_my_regionsize);\n" + " /* Start with the current region's top */\n" + " memory_info.BaseAddress = g_last->top_reserved;\n" + " /* Assert preconditions */\n" + " assert ((unsigned) memory_info.BaseAddress % g_pagesize == 0);\n" + " assert (0 < reserve_size && reserve_size % g_regionsize == 0);\n" + " while (VirtualQuery (memory_info.BaseAddress, &memory_info, sizeof (memory_info))) {\n" + " /* Assert postconditions */\n" + " assert ((unsigned) memory_info.BaseAddress % g_pagesize == 0);\n" + "#ifdef TRACE\n" + " printf (\"Query %p %d %s\\n\", memory_info.BaseAddress, memory_info.RegionSize,\n" + " memory_info.State == MEM_FREE ? \"FREE\":\n" + " (memory_info.State == MEM_RESERVE ? \"RESERVED\":\n" + " (memory_info.State == MEM_COMMIT ? \"COMMITTED\": \"?\")));\n" + "#endif\n" + " /* Region is free, well aligned and big enough: we are done */\n" + " if (memory_info.State == MEM_FREE &&\n" + " (unsigned) memory_info.BaseAddress % g_regionsize == 0 &&\n" + " memory_info.RegionSize >= (unsigned) reserve_size) {\n" + " found = TRUE;\n" + " break;\n" + " }\n" + " /* From now on we can't get contiguous memory! */\n" + " contiguous = FALSE;\n" + " /* Recompute size to reserve */\n" + " reserve_size = CEIL (allocate_size, g_my_regionsize);\n" + " memory_info.BaseAddress = (char *) memory_info.BaseAddress + memory_info.RegionSize;\n" + " /* Assert preconditions */\n" + " assert ((unsigned) memory_info.BaseAddress % g_pagesize == 0);\n" + " assert (0 < reserve_size && reserve_size % g_regionsize == 0);\n" + " }\n" + " /* Search failed? */\n" + " if (! found)\n" + " goto sbrk_exit;\n" + " /* Assert preconditions */\n" + " assert ((unsigned) memory_info.BaseAddress % g_regionsize == 0);\n" + " assert (0 < reserve_size && reserve_size % g_regionsize == 0);\n" + " /* Try to reserve this */\n" + " base_reserved = VirtualAlloc (memory_info.BaseAddress, reserve_size,\n" + " MEM_RESERVE, PAGE_NOACCESS);\n" + " if (! base_reserved) {\n" + " int rc = GetLastError ();\n" + " if (rc != ERROR_INVALID_ADDRESS)\n" + " goto sbrk_exit;\n" + " }\n" + " /* A null pointer signals (hopefully) a race condition with another thread. */\n" + " /* In this case, we try again. */\n" + " } while (! base_reserved);\n" + " /* Check returned pointer for consistency */\n" + " if (memory_info.BaseAddress && base_reserved != memory_info.BaseAddress)\n" + " goto sbrk_exit;\n" + " /* Assert postconditions */\n" + " assert ((unsigned) base_reserved % g_regionsize == 0);\n" + "#ifdef TRACE\n" + " printf (\"Reserve %p %d\\n\", base_reserved, reserve_size);\n" + "#endif\n" + " /* Did we get contiguous memory? */\n" + " if (contiguous) {\n" + " long start_size = (char *) g_last->top_committed - (char *) g_last->top_allocated;\n" + " /* Adjust allocation size */\n" + " allocate_size -= start_size;\n" + " /* Adjust the regions allocation top */\n" + " g_last->top_allocated = g_last->top_committed;\n" + " /* Recompute the size to commit */\n" + " to_commit = (char *) g_last->top_allocated + allocate_size - (char *) g_last->top_committed;\n" + " /* Round size to commit */\n" + " commit_size = CEIL (to_commit, g_my_pagesize);\n" + " }\n" + " /* Append the new region to the list */\n" + " if (! region_list_append (&g_last, base_reserved, reserve_size))\n" + " goto sbrk_exit;\n" + " /* Didn't we get contiguous memory? */\n" + " if (! contiguous) {\n" + " /* Recompute the size to commit */\n" + " to_commit = (char *) g_last->top_allocated + allocate_size - (char *) g_last->top_committed;\n" + " /* Round size to commit */\n" + " commit_size = CEIL (to_commit, g_my_pagesize);\n" + " }\n" + " }\n" + " }\n" + " /* Assert preconditions */\n" + " assert ((unsigned) g_last->top_committed % g_pagesize == 0);\n" + " assert (0 < commit_size && commit_size % g_pagesize == 0); {\n" + " /* Commit this */\n" + " void *base_committed = VirtualAlloc (g_last->top_committed, commit_size,\n" + " MEM_COMMIT, PAGE_READWRITE);\n" + " /* Check returned pointer for consistency */\n" + " if (base_committed != g_last->top_committed)\n" + " goto sbrk_exit;\n" + " /* Assert postconditions */\n" + " assert ((unsigned) base_committed % g_pagesize == 0);\n" + "#ifdef TRACE\n" + " printf (\"Commit %p %d\\n\", base_committed, commit_size);\n" + "#endif\n" + " /* Adjust the regions commit top */\n" + " g_last->top_committed = (char *) base_committed + commit_size;\n" + " }\n" + " }\n" + " /* Adjust the regions allocation top */\n" + " g_last->top_allocated = (char *) g_last->top_allocated + allocate_size;\n" + " result = (char *) g_last->top_allocated - size;\n" + " /* Deallocation requested? */\n" + " } else if (size < 0) {\n" + " long deallocate_size = - size;\n" + " /* As long as we have a region to release */\n" + " while ((char *) g_last->top_allocated - deallocate_size < (char *) g_last->top_reserved - g_last->reserve_size) {\n" + " /* Get the size to release */\n" + " long release_size = g_last->reserve_size;\n" + " /* Get the base address */\n" + " void *base_reserved = (char *) g_last->top_reserved - release_size;\n" + " /* Assert preconditions */\n" + " assert ((unsigned) base_reserved % g_regionsize == 0);\n" + " assert (0 < release_size && release_size % g_regionsize == 0); {\n" + " /* Release this */\n" + " int rc = VirtualFree (base_reserved, 0,\n" + " MEM_RELEASE);\n" + " /* Check returned code for consistency */\n" + " if (! rc)\n" + " goto sbrk_exit;\n" + "#ifdef TRACE\n" + " printf (\"Release %p %d\\n\", base_reserved, release_size);\n" + "#endif\n" + " }\n" + " /* Adjust deallocation size */\n" + " deallocate_size -= (char *) g_last->top_allocated - (char *) base_reserved;\n" + " /* Remove the old region from the list */\n" + " if (! region_list_remove (&g_last))\n" + " goto sbrk_exit;\n" + " } {\n") + ( " /* Compute the size to decommit */\n" + " long to_decommit = (char *) g_last->top_committed - ((char *) g_last->top_allocated - deallocate_size);\n" + " if (to_decommit >= g_my_pagesize) {\n" + " /* Compute the size to decommit */\n" + " long decommit_size = FLOOR (to_decommit, g_my_pagesize);\n" + " /* Compute the base address */\n" + " void *base_committed = (char *) g_last->top_committed - decommit_size;\n" + " /* Assert preconditions */\n" + " assert ((unsigned) base_committed % g_pagesize == 0);\n" + " assert (0 < decommit_size && decommit_size % g_pagesize == 0); {\n" + " /* Decommit this */\n" + " int rc = VirtualFree ((char *) base_committed, decommit_size,\n" + " MEM_DECOMMIT);\n" + " /* Check returned code for consistency */\n" + " if (! rc)\n" + " goto sbrk_exit;\n" + "#ifdef TRACE\n" + " printf (\"Decommit %p %d\\n\", base_committed, decommit_size);\n" + "#endif\n" + " }\n" + " /* Adjust deallocation size and regions commit and allocate top */\n" + " deallocate_size -= (char *) g_last->top_allocated - (char *) base_committed;\n" + " g_last->top_committed = base_committed;\n" + " g_last->top_allocated = base_committed;\n" + " }\n" + " }\n" + " /* Adjust regions allocate top */\n" + " g_last->top_allocated = (char *) g_last->top_allocated - deallocate_size;\n" + " /* Check for underflow */\n" + " if ((char *) g_last->top_reserved - g_last->reserve_size > (char *) g_last->top_allocated ||\n" + " g_last->top_allocated > g_last->top_committed) {\n" + " /* Adjust regions allocate top */\n" + " g_last->top_allocated = (char *) g_last->top_reserved - g_last->reserve_size;\n" + " goto sbrk_exit;\n" + " }\n" + " result = g_last->top_allocated;\n" + " }\n" + " /* Assert invariants */\n" + " assert (g_last);\n" + " assert ((char *) g_last->top_reserved - g_last->reserve_size <= (char *) g_last->top_allocated &&\n" + " g_last->top_allocated <= g_last->top_committed);\n" + " assert ((char *) g_last->top_reserved - g_last->reserve_size <= (char *) g_last->top_committed &&\n" + " g_last->top_committed <= g_last->top_reserved &&\n" + " (unsigned) g_last->top_committed % g_pagesize == 0);\n" + " assert ((unsigned) g_last->top_reserved % g_regionsize == 0);\n" + " assert ((unsigned) g_last->reserve_size % g_regionsize == 0);\n" + "\n" + "sbrk_exit:\n" + "#if defined (USE_MALLOC_LOCK) && defined (NEEDED)\n" + " /* Release spin lock */\n" + " slrelease (&g_sl);\n" + "#endif\n" + " return result;\n" + "}\n" + "\n" + "/* mmap for windows */\n" + "static void *mmap (void *ptr, long size, long prot, long type, long handle, long arg) {\n" + " static long g_pagesize;\n" + " static long g_regionsize;\n" + "#ifdef TRACE\n" + " printf (\"mmap %d\\n\", size);\n" + "#endif\n" + "#if defined (USE_MALLOC_LOCK) && defined (NEEDED)\n" + " /* Wait for spin lock */\n" + " slwait (&g_sl);\n" + "#endif\n" + " /* First time initialization */\n" + " if (! g_pagesize)\n" + " g_pagesize = getpagesize ();\n" + " if (! g_regionsize)\n" + " g_regionsize = getregionsize ();\n" + " /* Assert preconditions */\n" + " assert ((unsigned) ptr % g_regionsize == 0);\n" + " assert (size % g_pagesize == 0);\n" + " /* Allocate this */\n" + " ptr = VirtualAlloc (ptr, size,\n" + " MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE);\n" + " if (! ptr) {\n" + " ptr = (void *) MORECORE_FAILURE;\n" + " goto mmap_exit;\n" + " }\n" + " /* Assert postconditions */\n" + " assert ((unsigned) ptr % g_regionsize == 0);\n" + "#ifdef TRACE\n" + " printf (\"Commit %p %d\\n\", ptr, size);\n" + "#endif\n" + "mmap_exit:\n" + "#if defined (USE_MALLOC_LOCK) && defined (NEEDED)\n" + " /* Release spin lock */\n" + " slrelease (&g_sl);\n" + "#endif\n" + " return ptr;\n" + "}\n" + "\n" + "/* munmap for windows */\n" + "static long munmap (void *ptr, long size) {\n" + " static long g_pagesize;\n" + " static long g_regionsize;\n" + " int rc = MUNMAP_FAILURE;\n" + "#ifdef TRACE\n" + " printf (\"munmap %p %d\\n\", ptr, size);\n" + "#endif\n" + "#if defined (USE_MALLOC_LOCK) && defined (NEEDED)\n" + " /* Wait for spin lock */\n" + " slwait (&g_sl);\n" + "#endif\n" + " /* First time initialization */\n" + " if (! g_pagesize)\n" + " g_pagesize = getpagesize ();\n" + " if (! g_regionsize)\n" + " g_regionsize = getregionsize ();\n" + " /* Assert preconditions */\n" + " assert ((unsigned) ptr % g_regionsize == 0);\n" + " assert (size % g_pagesize == 0);\n" + " /* Free this */\n" + " if (! VirtualFree (ptr, 0,\n" + " MEM_RELEASE))\n" + " goto munmap_exit;\n" + " rc = 0;\n" + "#ifdef TRACE\n" + " printf (\"Release %p %d\\n\", ptr, size);\n" + "#endif\n" + "munmap_exit:\n" + "#if defined (USE_MALLOC_LOCK) && defined (NEEDED)\n" + " /* Release spin lock */\n" + " slrelease (&g_sl);\n" + "#endif\n" + " return rc;\n" + "}\n" + "\n" + "static void vminfo (CHUNK_SIZE_T *free, CHUNK_SIZE_T *reserved, CHUNK_SIZE_T *committed) {\n" + " MEMORY_BASIC_INFORMATION memory_info;\n" + " memory_info.BaseAddress = 0;\n" + " *free = *reserved = *committed = 0;\n" + " while (VirtualQuery (memory_info.BaseAddress, &memory_info, sizeof (memory_info))) {\n" + " switch (memory_info.State) {\n" + " case MEM_FREE:\n" + " *free += memory_info.RegionSize;\n" + " break;\n" + " case MEM_RESERVE:\n" + " *reserved += memory_info.RegionSize;\n" + " break;\n" + " case MEM_COMMIT:\n" + " *committed += memory_info.RegionSize;\n" + " break;\n" + " }\n" + " memory_info.BaseAddress = (char *) memory_info.BaseAddress + memory_info.RegionSize;\n" + " }\n" + "}\n" + "\n") + ( "static int cpuinfo (int whole, CHUNK_SIZE_T *kernel, CHUNK_SIZE_T *user) {\n" + " if (whole) {\n" + " __int64 creation64, exit64, kernel64, user64;\n" + " int rc = GetProcessTimes (GetCurrentProcess (),\n" + " (FILETIME *) &creation64,\n" + " (FILETIME *) &exit64,\n" + " (FILETIME *) &kernel64,\n" + " (FILETIME *) &user64);\n" + " if (! rc) {\n" + " *kernel = 0;\n" + " *user = 0;\n" + " return FALSE;\n" + " }\n" + " *kernel = (CHUNK_SIZE_T) (kernel64 / 10000);\n" + " *user = (CHUNK_SIZE_T) (user64 / 10000);\n" + " return TRUE;\n" + " } else {\n" + " __int64 creation64, exit64, kernel64, user64;\n" + " int rc = GetThreadTimes (GetCurrentThread (),\n" + " (FILETIME *) &creation64,\n" + " (FILETIME *) &exit64,\n" + " (FILETIME *) &kernel64,\n" + " (FILETIME *) &user64);\n" + " if (! rc) {\n" + " *kernel = 0;\n" + " *user = 0;\n" + " return FALSE;\n" + " }\n" + " *kernel = (CHUNK_SIZE_T) (kernel64 / 10000);\n" + " *user = (CHUNK_SIZE_T) (user64 / 10000);\n" + " return TRUE;\n" + " }\n" + "}\n" + "\n" + "#endif /* WIN32 */\n" + "\n" + "#endif // NDEBUG\n" + "\n" + "}; /* end of namespace KJS */\n"); var thai = "ประเทศไทย\n" + "จากวิกิพีเดีย สารานุกรมเสรี\n" + "ไปที่: ป้ายบอกทาง, ค้นหา\n" + " \n" + "\n" + "เนื่องจากบทความนี้ถูกล็อกเนื่องจาก ถูกก่อกวนหลายครั้งติดต่อกัน การแก้ไขจากผู้ที่ไม่ได้ลงทะเบียน หรือผู้ใช้ใหม่ไม่สามารถทำได้ขณะนี้\n" + "คุณสามารถแสดงความเห็น เสนอข้อความ หรือขอให้ยกเลิกการป้องกันได้ในหน้าอภิปราย หรือลงทะเบียนโดยสร้างชื่อผู้ใช้\n" + " \n" + "วิกิพีเดีย:บทความคัดสรร\n" + "\n" + " \"ไทย\" เปลี่ยนทางมาที่นี่ สำหรับความหมายอื่น ดูที่ ไทย (แก้ความกำกวม)\n" + "\n" + "ราชอาณาจักรไทย\n" + "ธงชาติไทย ตราแผ่นดินของไทย\n" + "ธงชาติ ตราแผ่นดิน\n" + "คำขวัญ: ชาติ ศาสนา พระมหากษัตริย์\n" + "เพลงชาติ: เพลงชาติไทย\n" + "แผนที่แสดงที่ตั้งของประเทศไทย\n" + "เมืองหลวง กรุงเทพมหานคร\n" + "13°44′N 100°30′E\n" + "เมืองใหญ่สุด กรุงเทพมหานคร\n" + "ภาษาราชการ ภาษาไทย\n" + "รัฐบาล เผด็จการทหาร\n" + " - ประมุขแห่งรัฐ พระบาทสมเด็จพระปรมินทรมหาภูมิพลอดุลยเดช\n" + " - นายกรัฐมนตรี พลเอกสุรยุทธ์ จุลานนท์\n" + " - ประธานคณะมนตรีความมั่นคงแห่งชาติ พลอากาศเอก ชลิต พุกผาสุข (รักษาการ)\n" + "สถาปนาเป็น\n" + "• สุโขทัย\n" + "• กรุงศรีอยุธยา\n" + "• กรุงธนบุรี\n" + "• กรุงรัตนโกสินทร์ \n" + "พ.ศ. 1781–1911\n" + "1893–2310\n" + "2310–6 เมษายน 2325\n" + "6 เมษายน 2325–ปัจจุบัน\n" + "เนื้อที่\n" + " - ทั้งหมด\n" + " \n" + " - พื้นน้ำ (%) \n" + "514,000 กม.² (อันดับที่ 49)\n" + "198,457 ไมล์² \n" + "0.4%\n" + "ประชากร\n" + " - 2548 ประมาณ\n" + " - 2543\n" + " - ความหนาแน่น \n" + "62,418,054 (อันดับที่ 19)\n" + "60,916,441\n" + "122/กม² (อันดับที่ 59)\n" + "{{{population_densitymi²}}}/ไมล์² \n" + "GDP (PPP)\n" + " - รวม\n" + " - ต่อประชากร 2548 ค่าประมาณ\n" + "$559.5 billion (อันดับที่ 21)\n" + "$8,542 (อันดับที่ 72)\n" + "HDI (2546) 0.778 (อันดับที่ 73) – ปานกลาง\n" + "สกุลเงิน บาท (฿) (THB)\n" + "เขตเวลา (UTC+7)\n" + "รหัสอินเทอร์เน็ต .th\n" + "รหัสโทรศัพท์ +66\n" + "\n" + "ประเทศไทย หรือ ราชอาณาจักรไทย ตั้งอยู่ในเอเชียตะวันออกเฉียงใต้ มีพรมแดนทางทิศตะวันออกติดลาวและกัมพูชา ทิศใต้ติดอ่าวไทยและมาเลเซีย ทิศตะวันตกติดทะเลอันดามันและพม่า และทิศเหนือติดพม่าและลาว โดยมีแม่น้ำโขงกั้นเป็นบางช่วง\n" + "\n" + "ประเทศไทยเป็นสมาชิกของสหประชาชาติ เอเปค และ อาเซียน มีศูนย์รวมการปกครองอยู่ที่ กรุงเทพมหานคร ซึ่งเป็นเมืองหลวงของประเทศ\n" + "\n" + "พระบาทสมเด็จพระปรมินทรมหาภูมิพลอดุลยเดช ทรงเป็นพระมหากษัตริย์ที่ครองราชย์ ในฐานะประมุขแห่งรัฐ ยาวนานที่สุดในโลกถึง 60 ปี\n" + "\n" + "\n" + "เนื้อหา\n" + "[ซ่อน]\n" + "\n" + " * 1 ประวัติศาสตร์\n" + " o 1.1 ชื่อประเทศไทย\n" + " * 2 การเมืองการปกครอง\n" + " o 2.1 เขตการปกครอง\n" + " o 2.2 เมืองใหญ่ / จังหวัดใหญ่\n" + " * 3 ภูมิอากาศและภูมิประเทศ\n" + " o 3.1 ภูมิประเทศ\n" + " o 3.2 ภูมิอากาศ\n" + " * 4 เศรษฐกิจ\n" + " o 4.1 เศรษฐกิจหลักของประเทศ\n" + " o 4.2 การคมนาคม\n" + " o 4.3 การสื่อสาร\n" + " * 5 สังคม\n" + " o 5.1 ชนชาติ\n" + " o 5.2 ศาสนา\n" + " o 5.3 การศึกษา\n" + " o 5.4 ภาษา\n" + " o 5.5 ศิลปะและวัฒนธรรม\n" + " o 5.6 กีฬา\n" + " o 5.7 วันสำคัญ\n" + " * 6 ลำดับที่สำคัญ\n" + " * 7 อ้างอิง\n" + " * 8 แหล่งข้อมูลอื่น\n" + "\n" + "ประวัติศาสตร์\n" + "\n" + " ดูบทความหลักที่ ประวัติศาสตร์ไทย\n" + "\n" + "ประเทศไทยมีประวัติศาสตร์ยาวนานมากนับเริ่มแต่การล่มสลายของราชอาณาจักรขอม-จักรวรรดินครวัต นครธม เมื่อต้นๆ คริสต์ศตวรรษที่ 13 [1]โดยมีความสืบเนื่องและคาบเกี่ยวระหว่างอาณาจักรโบราณหลายแห่ง เช่น อาณาจักรทวารวดี ศรีวิชัย ละโว้ เขมร ฯลฯ โดยเริ่มมีความชัดเจนในอาณาจักรสุโขทัยตั้งแต่ปี พ.ศ. 1781 อาณาจักรล้านนาทางภาคเหนือ กระทั่งเสื่อมอำนาจลงในช่วงต้นพุทธศตวรรษที่ 19 แล้วความรุ่งเรืองได้ปรากฏขึ้นในอาณาจักรทางใต้ ณ กรุงศรีอยุธยา โดยยังมีอาณาเขตที่ไม่แน่ชัด ครั้นเมื่อเสียกรุงศรีอยุธยาเป็นครั้งที่สองในปี พ.ศ. 2310 พระเจ้าตากสินจึงได้ย้ายราชธานีมาอยู่ที่กรุงธนบุรี\n" + "\n" + "ภายหลังสิ้นสุดอำนาจและมีการสถาปนากรุงรัตนโกสินทร์เมื่อ พ.ศ. 2325 อาณาจักรสยามเริ่มมีความเป็นปึกแผ่น มีการผนวกดินแดนบางส่วนของอาณาจักรล้านช้าง ครั้นในรัชกาลที่ 5 ได้ผนวกดินแดนของเมืองเชียงใหม่ หรืออาณาจักรล้านนาส่วนล่าง (ส่วนบนอยู่บริเวณเชียงตุง) เป็นการรวบรวมดินแดนครั้งใหญ่ครั้งสุดท้าย วันที่ 24 มิถุนายน พ.ศ. 2475 ได้เปลี่ยนแปลงการปกครองมาเป็นระบอบประชาธิปไตยแต่ก็ต้องรออีกถึง 41 ปี กว่าจะได้นายกรัฐมนตรีที่มาจากการเลือกตั้งครั้งแรกเมื่อ พ.ศ. 2516 หลังจากเหตุการณ์ 14 ตุลา หลังจากนั้นมีเหตุการณ์เรียกร้องประชาธิปไตยอีกสองครั้งคือ เหตุการณ์ 6 ตุลา และ เหตุการณ์พฤษภาทมิฬ ล่าสุดได้เกิดรัฐประหารขึ้นอีกครั้งในเดือนกันยายน พ.ศ. 2549 ซึ่งเป็นการยึดอำนาจจากรัฐบาลรักษาการ หลังจากได้มีการยุบสภาผู้แทนราษฎรเมื่อเดือนกุมภาพันธ์ 2549\n" + "\n" + "ชื่อประเทศไทย\n" + "\n" + "คำว่า ไทย มีความหมายในภาษาไทยว่า อิสรภาพ เสรีภาพ หรืออีกความหมายคือ ใหญ่ ยิ่งใหญ่ เพราะการจะเป็นอิสระได้จะต้องมีกำลังที่มากกว่า แข็งแกร่งกว่า เพื่อป้องกันการรุกรานจากข้าศึก เดิมประเทศไทยใช้ชื่อ สยาม (Siam) แต่ได้เปลี่ยนมาเป็นชื่อปัจจุบัน เมื่อปี พ.ศ. 2482 ตามประกาศรัฐนิยม ฉบับที่ 1 ของรัฐบาลจอมพล ป. พิบูลสงคราม ให้ใช้ชื่อ ประเทศ ประชาชน และสัญชาติว่า \"ไทย\" โดยในช่วงต่อมาได้เปลี่ยนกลับเป็นสยามเมื่อปี พ.ศ. 2488 ในช่วงเปลี่ยนนายกรัฐมนตรี แต่ในที่สุดได้เปลี่ยนกลับมาชื่อไทยอีกครั้งในปี พ.ศ. 2491 ซึ่งเป็นช่วงที่จอมพล ป. พิบูลสงครามเป็นนายกรัฐมนตรีในสมัยต่อมา ช่วงแรกเปลี่ยนเฉพาะชื่อภาษาไทยเท่านั้น ชื่อภาษาฝรั่งเศส[2]และอังกฤษคงยังเป็น \"Siam\" อยู่จนกระทั่งเดือนเมษายน พ.ศ. 2491 จึงได้เปลี่ยนชื่อภาษาฝรั่งเศสเป็น \"Thaïlande\" และภาษาอังกฤษเป็น \"Thailand\" อย่างในปัจจุบัน อย่างไรก็ตาม ชื่อ สยาม ยังเป็นที่รู้จักแพร่หลายทั้งในและต่างประเทศ.\n" + "\n" + "การเมืองการปกครอง\n" + "\n" + "เดิมประเทศไทยมีการปกครองระบอบสมบูรณาญาสิทธิราชย์ จนกระทั่งวันที่ 24 มิถุนายน พ.ศ. 2475 คณะราษฎรได้ทำการเปลี่ยนแปลงการปกครองเป็นราชาธิปไตยภายใต้รัฐธรรมนูญ โดยแบ่งอำนาจเป็นสามฝ่าย ได้แก่ ฝ่ายบริหาร ฝ่ายนิติบัญญัติและฝ่ายตุลาการ โดยฝ่ายบริหารจะมีนายกรัฐมนตรีเป็นหัวหน้ารัฐบาลซึ่งมากจากการแต่งตั้ง ฝ่ายนิติบัญญัติ ได้แก่ สภานิติบัญญัติแห่งชาติ และฝ่ายตุลาการ คือ ศาลยุติธรรม ศาลรัฐธรรมนูญ และศาลปกครอง\n" + "\n" + "ปัจจุบัน ประเทศไทยอยู่ภายใต้การปกครองระบอบเผด็จการทหาร โดยมีรัฐบาลชั่วคราวซึ่งแต่งตั้งโดยคณะมนตรีความมั่นคงแห่งชาติ หลังเกิดเหตุการณ์รัฐประหารเมื่อคืนวันที่ 19 กันยายน พ.ศ. 2549\n" + "\n" + "เขตการปกครอง\n" + "\n" + "ประเทศไทยแบ่งเขตการบริหารออกเป็น การบริหารราชการส่วนภูมิภาค ได้แก่จังหวัด 75 จังหวัด นอกจากนั้นยังมีการปกครองส่วนท้องถิ่น ได้แก่ กรุงเทพมหานคร เมืองพัทยา องค์การบริหารส่วนจังหวัด เทศบาล และองค์การบริหารส่วนตำบล ส่วน'สุขาภิบาล'นั้นถูกยกฐานะไปเป็นเทศบาลทั้งหมดในปี พ.ศ. 2542\n" + "\n" + " รายชื่อจังหวัดทั้งหมดดูเพิ่มเติมที่ จังหวัดในประเทศไทย\n" + "\n" + "เมืองใหญ่ / จังหวัดใหญ่\n" + "ประเทศไทย จังหวัดในประเทศไทย\n" + "ประเทศไทย จังหวัดในประเทศไทย\n" + "กรุงเทพมหานครริมแม่น้ำเจ้าพระยา\n" + "กรุงเทพมหานครริมแม่น้ำเจ้าพระยา\n" + "\n" + "นอกจากกรุงเทพมหานครแล้ว มีหลายเมืองที่มีประชากรอยู่เป็นจำนวนมาก (ข้อมูลเดือนตุลาคม พ.ศ. 2549 ของ กรมการปกครอง กระทรวงมหาดไทย ) โดยเรียงลำดับตามตารางด้านล่าง โดยดูจากจำนวนประชากรในเขตเทศบาลและกรุงเทพมหานคร ซึ่งจะแสดงประชากรในเขตเมืองได้อย่างแท้จริง\n" + "อันดับ เมือง / เทศบาล จำนวนประชากร จังหวัด\n" + "1 กรุงเทพมหานคร 6,121,672 กรุงเทพมหานคร\n" + "2 นนทบุรี 266,941 นนทบุรี\n" + "3 ปากเกร็ด 167,138 นนทบุรี\n" + "4 หาดใหญ่ 157,678 สงขลา\n" + "5 เชียงใหม่ 150,805 เชียงใหม่\n" + "6 นครราชสีมา 149,938 นครราชสีมา\n" + "7 อุดรธานี 142,670 อุดรธานี\n" + "8 สุราษฎร์ธานี 124,665 สุราษฎร์ธานี\n" + "9 ขอนแก่น 121,283 ขอนแก่น\n" + "10 นครศรีธรรมราช 106,293 นครศรีธรรมราช\n" + "\n" + "นอกจากนี้ยังมีการเรียงลำดับประชากรตามจังหวัดได้ดังต่อไปนี้\n" + "อันดับ จังหวัด จำนวนประชากร ภาค\n" + "1 กรุงเทพมหานคร 6,121,672 ภาคกลาง\n" + "2 นครราชสีมา 2,546,763 ภาคตะวันออกเฉียงเหนือ\n" + "3 อุบลราชธานี 1,774,808 ภาคตะวันออกเฉียงเหนือ\n" + "4 ขอนแก่น 1,747,542 ภาคตะวันออกเฉียงเหนือ\n" + "5 เชียงใหม่ 1,650,009 ภาคเหนือ\n" + "6 บุรีรัมย์ 1,531,430 ภาคตะวันออกเฉียงเหนือ\n" + "7 อุดรธานี 1,523,802 ภาคตะวันออกเฉียงเหนือ\n" + "8 นครศรีธรรมราช 1,504,420 ภาคใต้\n" + "9 ศรีสะเกษ 1,443,975 ภาคตะวันออกเฉียงเหนือ\n" + "10 สุรินทร์ 1,374,700 ภาคตะวันออกเฉียงเหนือ\n" + "\n" + " ดูข้อมูลทั้งหมดที่ เมืองใหญ่ของประเทศไทยเรียงตามจำนวนประชากร และ จังหวัดในประเทศไทยเรียงตามจำนวนประชากร\n" + "\n" + "ภูมิอากาศและภูมิประเทศ\n" + "\n" + "ภูมิประเทศ\n" + "ประเทศไทย สภาพทางภูมิศาสตร์\n" + "ประเทศไทย สภาพทางภูมิศาสตร์\n" + "\n" + "ประเทศไทยมีสภาพทางภูมิศาสตร์ที่หลากหลาย ภาคเหนือประกอบด้วยเทือกเขาจำนวนมาก จุดที่สูงที่สุด คือ ดอยอินทนนท์ (2,576 เมตร) ในจังหวัดเชียงใหม่ ภาคตะวันออกเฉียงเหนือเป็นที่ราบสูงโคราชติดกับแม่น้ำโขงทางด้านตะวันออก ภาคกลางเป็นที่ราบลุ่มแม่น้ำเจ้าพระยา ซึ่งสายน้ำไหลลงสู่อ่าวไทย ภาคใต้มีจุดที่แคบลง ณ คอคอดกระแล้วขยายใหญ่เป็นคาบสมุทรมลายู\n" + "\n" + " * เมื่อเปรียบเทียบพื้นที่ของประเทศไทย กับ ประเทศอื่น จะได้ดังนี้\n" + " o ประเทศพม่า ใหญ่กว่าประเทศไทยประมาณ 1.3 เท่า\n" + " o ประเทศอินโดนีเซีย ใหญ่กว่าประมาณ 3.7 เท่า\n" + " o ประเทศอินเดีย ใหญ่กว่าประมาณ 6.4 เท่า\n" + " o ประเทศจีน และ สหรัฐอเมริกา ใหญ่กว่าประมาณ 19 เท่า\n" + " o ประเทศรัสเซีย ใหญ่กว่าประมาณ 33 เท่า\n" + " o ขนาดใกล้เคียงกับ ประเทศฝรั่งเศส ประเทศสวีเดน และ ประเทศสเปน\n" + "\n" + "วันที่ 26 ธันวาคม พ.ศ. 2547 ได้มีเหตุการณ์คลื่นสึนามิเกิดขึ้นก่อความเสียหายในเขตภาคใต้ของประเทศไทย\n" + "\n" + "ภูมิอากาศ\n" + "\n" + "ภูมิอากาศของไทยเป็นแบบเขตร้อน อากาศร้อนที่สุดในเดือนเมษายน-พฤษภาคม โดยจะมีฝนตกและเมฆมากจากลมมรสุมตะวันตกเฉียงใต้ในช่วงกลางเดือนพฤษภาคม-เดือนตุลาคม ส่วนในเดือนพฤศจิกายนถึงกลางเดือนมีนาคม อากาศแห้ง และหนาวเย็นจากลมมรสุมตะวันออกเฉียงเหนือ ยกเว้นภาคใต้ที่มีอากาศร้อนชื้นตลอดทั้งปี\n" + "\n" + "เศรษฐกิจ\n" + "\n" + "เศรษฐกิจหลักของประเทศ\n" + "\n" + "เกษตรกรรม อุตสาหกรรม การท่องเที่ยว การบริการ และ ทรัพยากรธรรมชาติ ถือเป็นเศรษฐกิจหลักที่ทำรายได้ให้กับคนในประเทศ โดยภาพรวมทางเศรษฐกิจอ้างอิงเมื่อ พ.ศ. 2546 มี GDP 5,930.4 พันล้านบาท ส่งออกมูลค่า 78.1 พันล้านเหรียญสหรัฐ ในขณะที่นำเข้า 74.3 พันล้านเหรียญสหรัฐ[3]\n" + "ภาพพันธุ์ข้าวจากกรมวิชาการเกษตร\n" + "ภาพพันธุ์ข้าวจากกรมวิชาการเกษตร\n" + "ภาพยางพาราจากกรมวิชาการเกษตร\n" + "ภาพยางพาราจากกรมวิชาการเกษตร\n" + "\n" + "ในด้านเกษตรกรรม ข้าว ถือเป็นผลผลิตที่สำคัญที่สุด เป็นผู้ผลิตและส่งออกข้าว เป็นอันดับหนึ่งของโลก ด้วยสัดส่วนการส่งออก ร้อยละ 36 รองลงมาคือ เวียดนาม ร้อยละ 20 อินเดีย ร้อยละ 18 สหรัฐอเมริกา ร้อยละ14 ปากีสถาน ร้อยละ 12 ตามลำดับ [4] พืชผลทางการเกษตรอื่นๆ ได้แก่ ยางพารา ผักและผลไม้ต่างๆ มีการเพาะเลี้ยงปศุสัตว์เช่น วัว สุกร เป็ด ไก่ สัตว์น้ำทั้งปลาน้ำจืด ปลาน้ำเค็มในกระชัง นากุ้ง เลี้ยงหอย รวมถึงการประมงทางทะเล ปี 2549 ไทยมีการส่งออกกุ้งไปสหรัฐฯ 177,717.29 ตัน มูลค่า 45,434.57 ล้านบาท [5]\n" + "\n" + "อุตสาหกรรมที่สำคัญ ได้แก่ อุตสาหกรรมแปรรูปทางการเกษตร สิ่งทอ อิเล็กทรอนิกส์ รถยนต์ ส่วนทรัพยากรธรรมชาติที่สำคัญเช่น ดีบุก ก๊าซธรรมชาติ จากข้อมูลปี พ.ศ. 2547 มีการผลิตสิ่งทอมูลค่า 211.4 พันล้านบาท แผงวงจรรวม 196.4 พันล้านบาท อาหารทะเลกระป๋อง 36.5 พันล้านบาท สับปะรดกระป๋อง 11.1 พันล้านบาท รถยนต์ส่วนบุคคล 2.99 แสนคัน รถบรรทุก รถกระบะ และอื่นๆ รวม 6.28 แสนคัน จักรยานยนต์ 2.28 ล้านคัน ดีบุก 694 ตัน ก๊าซธรรมชาติ 789 พันล้านลูกบาศก์ฟุต น้ำมันดิบ]] 31.1 ล้านบาร์เรล [6]\n" + "เกาะพีพี สถานท่องเที่ยวที่สำคัญแห่งหนึ่งของประเทศ\n" + "เกาะพีพี สถานท่องเที่ยวที่สำคัญแห่งหนึ่งของประเทศ\n" + "\n" + "ส่วนด้านการท่องเที่ยว การบริการและโรงแรม ในปี พ.ศ. 2547 มีนักท่องเที่ยวรวม 11.65 ล้านคน 56.52% มาจากเอเชียตะวันออกและอาเซียน (โดยเฉพาะมาเลเซียคิดเป็น 11.97% ญี่ปุ่น 10.33%) ยุโรป 24.29% ทวีปอเมริกาเหนือและใต้รวมกัน 7.02% [7] สถานที่ท่องเที่ยวที่สำคัญได้แก่ กรุงเทพมหานคร พัทยา ภาคใต้ฝั่งทะเลอันดามัน จังหวัดเชียงใหม่\n" + "\n" + "การคมนาคม\n" + "\n" + "ดูบทความหลัก การคมนาคมในประเทศไทย\n" + "\n" + "การคมนาคมในประเทศไทย ส่วนใหญ่ประกอบด้วย การเดินทางโดยรถยนต์ และ จักรยานยนต์ ทางหลวงสายหลักในประเทศไทย ได้แก่ ถนนพหลโยธิน (ทางหลวงหมายเลข 1) ถนนมิตรภาพ (ทางหลวงหมายเลข 2) ถนนสุขุมวิท (ทางหลวงหมายเลข 3) และถนนเพชรเกษม (ทางหลวงหมายเลข 4) และยังมีทางหลวงพิเศษระหว่างเมือง (มอเตอร์เวย์) ใน 2 เส้นทางคือ มอเตอร์เวย์กรุงเทพฯ-ชลบุรี (ทางหลวงหมายเลข 7) และถนนกาญจนาภิเษก (วงแหวนรอบนอกกรุงเทพมหานคร - ทางหลวงหมายเลข 9) นอกจากนี้ระบบขนส่งมวลชนจะมีการบริการตามเมืองใหญ่ต่างๆ ได้แก่ระบบรถเมล์ และรถไฟ รวมถึงระบบที่เริ่มมีการใช้งาน รถไฟลอยฟ้า และรถไฟใต้ดิน และในหลายพื้นที่จะมีการบริการรถสองแถว รวมถึงรถรับจ้างต่างๆ ได้แก่ แท็กซี่ เมลเครื่อง มอเตอร์ไซค์รับจ้าง และ รถตุ๊กตุ๊ก ในบางพื้นที่ ที่อยู่ริมน้ำจะมีเรือรับจ้าง และแพข้ามฟาก บริการ\n" + "รถไฟฟ้าบีทีเอส สถานีอโศก\n" + "รถไฟฟ้าบีทีเอส สถานีอโศก\n" + "\n" + "สำหรับการคมนาคมทางอากาศนั้น ปัจจุบันประเทศไทยได้เปิดใช้ท่าอากาศยานสุวรรณภูมิ ซึ่งเป็นท่าอากาศยานที่มีขนาดตัวอาคารที่ใหญ่ที่สุดในโลก และมีหอบังคับการบินที่สูงที่สุดในโลก ด้วยความสูง 132.2 เมตร ซึ่งรองรับผู้โดยสารได้ 45 ล้านคนต่อปี โดยเปิดอย่างเป็นทางการตั้งแต่วันที่ 29 กันยายน พ.ศ. 2549 ทดแทนท่าอากาศยานนานาชาติกรุงเทพ (ดอนเมือง) ที่เปิดใช้งานมานานถึง 92 ปี\n" + "\n" + "ส่วนการคมนาคมทางน้ำ ประเทศไทยมีท่าเรือหลักๆ คือ ท่าเรือกรุงเทพ(คลองเตย) และท่าเรือแหลมฉบัง\n" + "\n" + "การสื่อสาร\n" + "\n" + " * ระบบโทรศัพท์ในประเทศไทยมีโทรศัพท์พื้นฐาน 7.035 ล้านหมายเลข (2548) และโทรศัพท์มือถือ 27.4 ล้านหมายเลข (2548) [8]\n" + " * สถานีวิทยุ: คลื่นเอฟเอ็ม 334 สถานี , คลื่นเอเอ็ม 204 สถานี และ คลื่นสั้น 6 สถานี (2542) โดยมีจำนวนผู้ใช้วิทยุ 13.96 ล้านคน (2540) [8]\n" + " * สถานีโทรทัศน์ มี 6 ช่องสถานี (โดยทุกช่องสถานีแม่ข่ายอยู่ในกรุงเทพ) มีสถานีเครือข่ายทั้งหมด 111 สถานี และจำนวนผู้ใช้โทรทัศน์ 15.19 ล้านคน (2540) [8]\n" + " * รหัสโดเมนอินเทอร์เน็ตใช้รหัส th\n" + "\n" + "สังคม\n" + "วัดพระศรีรัตนศาสดาราม กรุงเทพมหานคร\n" + "วัดพระศรีรัตนศาสดาราม กรุงเทพมหานคร\n" + "\n" + "ชนชาติ\n" + "\n" + "ในประเทศไทย ถือได้ว่า มีความหลากหลายทางเชื้อชาติ มีทั้ง ชาวไทย ชาวไทยเชื้อสายลาว ชาวไทยเชื้อสายมอญ ชาวไทยเชื้อสายเขมร รวมไปถึงกลุ่มชาวไทยเชื้อสายจีน ชาวไทยเชื้อสายมลายู ชาวชวา(แขกแพ) ชาวจาม(แขกจาม) ชาวเวียด ไปจนถึงชาวพม่า และชาวไทยภูเขาเผ่าต่างๆ เช่น ชาวกะเหรี่ยง ชาวลีซอ ชาวอ่าข่า ชาวอีก้อ ชาวม้ง ชาวเย้า รวมไปจนถึงชาวส่วย ชาวกูบ ชาวกวย ชาวจะราย ชาวระแดว์ ชาวข่า ชาวขมุ ซึ่งมีในปัจจุบันก็มีความสำคัญมาก ต่อวิถีชีวิต และวัฒนธรรมไทยในปัจจุบัน\n" + "\n" + "ประชากรชาวไทย 75% ชาวไทยเชื้อสายจีน 14% และอื่นๆ 11% [8]\n" + "\n" + " ดูเพิ่มที่ ชาวไทย\n" + "\n" + "ศาสนา\n" + "พระพุทธชินราช วัดพระศรีรัตนมหาธาตุวรมหาวิหาร จังหวัดพิษณุโลก\n" + "พระพุทธชินราช วัดพระศรีรัตนมหาธาตุวรมหาวิหาร จังหวัดพิษณุโลก\n" + "\n" + "ประมาณร้อยละ 95 ของประชากรไทยนับถือศาสนาพุทธซึ่งเป็นศาสนาประจำชาติ(โดยพฤตินัย) นิกายเถรวาท ศาสนาอิสลามประมาณร้อยละ 4 (ส่วนใหญ่เป็นชาวไทยทางภาคใต้ตอนล่าง) ศาสนาคริสต์และศาสนาอื่นประมาณร้อยละ 1\n" + "\n" + " ดูเพิ่มที่ พระพุทธศาสนาในประเทศไทย\n" + "\n" + "การศึกษา\n" + "\n" + "ในทางกฎหมาย รัฐบาลจะต้องจัดการศึกษาให้ขั้นพื้นฐานสิบสองปี แต่การศึกษาขั้นบังคับของประเทศไทยในปัจจุบันคือเก้าปี บุคคลทั่วไปจะเริ่มจากระดับชั้นอนุบาล เป็นการเตรียมความพร้อมก่อนการเรียนตามหลักสูตรพื้นฐาน ต่อเนื่องด้วยระดับประถมศึกษาและมัธยมศึกษาตอนต้น หลังจากจบการศึกษาระดับมัธยมต้น สามารถเลือกได้ระหว่างศึกษาต่อสายสามัญ ระดับมัธยมศึกษาตอนปลายเพื่อศึกษาต่อในระดับมหาวิทยาลัย หรือเลือกศึกษาต่อสายวิชาชีพ ในวิทยาลัยเทคนิค หรือพาณิชยการ หรือเลือกศึกษาต่อในสถาบันทางทหารหรือตำรวจ\n" + "\n" + "โรงเรียนและมหาวิทยาลัยในประเทศไทย แบ่งออกเป็น 2 ประเภทหลักได้แก่ โรงเรียนรัฐบาล และโรงเรียนเอกชน และ มหาวิทยาลัยรัฐบาล และมหาวิทยาลัยเอกชน โดยโรงเรียนรัฐบาลและมหาวิทยาลัยรัฐบาล จะเสียค่าเล่าเรียนน้อยกว่า โรงเรียนเอกชนและมหาวิทยาลัยเอกชน\n" + "\n" + " ดูเพิ่มที่ รายชื่อสถาบันอุดมศึกษาในประเทศไทย\n" + "\n" + "ภาษา\n" + "\n" + " ดูบทความหลักที่ ภาษาในประเทศไทย\n" + "\n" + "ภาษาไทย ประเทศไทยมีภาษาไทยเป็นภาษาราชการ ภาษาพูดของคนไทยมีมาแต่เมื่อไรยังไม่เป็นที่ทราบแน่ชัด แต่จากการสันนิฐานน่าจะมีมากว่า 4,000 ปีแล้ว ส่วนตัวอักษรนั้นเพิ่งมีการประดิษฐ์ขึ้นอย่างเป็นทางการในสมัยสุโขทัยโดย พ่อขุนรามคำแหงมหาราช ส่วนภาษาอื่นที่มีการใช้อยู่บ้าง เช่น ภาษาอังกฤษ ภาษาจีน เป็นต้น\n" + "\n" + "ศิลปะและวัฒนธรรม\n" + "พระที่นั่งไอศวรรย์ทิพย์อาสน์ พระราชวังบางปะอิน จังหวัดพระนครศรีอยุธยา\n" + "พระที่นั่งไอศวรรย์ทิพย์อาสน์ พระราชวังบางปะอิน จังหวัดพระนครศรีอยุธยา\n" + "\n" + "ศิลปะไทยมีลักษณะเฉพาะตัวค่อนข้างสูง โดยมีความกลมกลืนและคล้ายคลึงกับศิลปวัฒนธรรมเพื่อนบ้านอยู่บ้าง แต่ด้วยการสืบทอดและการสร้างสรรค์ใหม่ ทำให้ศิลปะไทยมีเอกลักษณ์สูง\n" + "\n" + " * จิตรกรรม งานจิตรกรรมไทยนับว่าเป็นงานศิลปะชั้นสูง ได้รับการสืบทอดมาช้านาน มักปรากฏในงานจิตรกรรมฝาผนัง ตามวัดวาอาราม รวมทั้งในสมุดข่อยโบราณ งานจิตรกรรมไทยยังเกี่ยวข้องกับงานศิลปะแขนงอื่นๆ เช่น งานลงรักปิดทอง ภาพวาดพระบฏ เป็นต้น\n" + " * ประติมากรรม เดิมนั้นช่างไทยทำงานประติมากรรมเฉพาะสิ่งศักดิ์สิทธิ์ เช่น พระพุทธรูป เทวรูป โดยมีสกุลช่างต่างๆ นับตั้งแต่ก่อนสมัยสุโขทัย เรียกว่า สกุลช่างเชียงแสน สกุลช่างสุโขทัย อยุธยา และกระทั่งรัตนโกสินทร์ โดยใช้ทองสำริดเป็นวัสดุหลักในงานประติมากรรม เนื่องจากสามารถแกะแบบด้วยขี้ผึ้งและตกแต่งได้ แล้วจึงนำไปหล่อโลหะ เมื่อเทียบกับประติมากรรมศิลาในยุคก่อนนั้น งานสำริดนับว่าอ่อนช้อยงดงามกว่ามาก\n" + " * สถาปัตยกรรม สถาปัตยกรรมไทยมีปรากฏให้เห็นในชั้นหลัง เนื่องจากงานสถาปัตยกรรมส่วนใหญ่ชำรุดทรุดโทรมได้ง่าย โดยเฉพาะงานไม้ ไม่ปรากฏร่องรอยสมัยโบราณเลย สถาปัตยกรรมไทยมีให้เห็นอยู่ในรูปของบ้านเรือนไทย โบสถ์ วัด และปราสาทราชวัง ซึ่งล้วนแต่สร้างขึ้นให้เหมาะสมกับสภาพอากาศและการใช้สอยจริง\n" + "\n" + " ดูเพิ่มที่ ศิลปะไทย\n" + "\n" + "กีฬา\n" + "ราชมังคลากีฬาสถาน การกีฬาแห่งประเทศไทย\n" + "ราชมังคลากีฬาสถาน การกีฬาแห่งประเทศไทย\n" + "\n" + "กีฬาที่นิยมมากที่สุดในประเทศไทยได้แก่ ฟุตบอล โดยในการแข่งขันระหว่างประเทศ ทีมชาติไทยได้เข้าเล่นและได้อันดับสูงสุดในเอเชียนคัพ ได้อันดับ 3 ใน เอเชียนคัพ 1972 กีฬาอื่นที่นิยมเล่นได้แก่ บาสเกตบอล มวย และแบดมินตัน โดยในประเทศไทยมีการจัดฟุตบอลอาชีพ โดยแบ่งแยกตามทีมประจำจังหวัด สำหรับกีฬาไทย ได้แก่ มวยไทย และ ตะกร้อ แม้จะมีความนิยมไม่เท่ากีฬาทั่วไป แต่ยังมีการเล่นโดยทั่วไปรวมถึงการเปิดสอนในโรงเรียน\n" + "\n" + "ประเทศไทยเป็นตัวแทนจัดงานเอเชียนเกมส์ 4 ครั้ง และซีเกมส์ ทั้งหมด 5 ครั้ง โดยจัดครั้งแรกที่ประเทศไทย\n" + "\n" + "นักกีฬาไทยที่มีชื่อเสียงมาก ได้แก่\n" + "\n" + " * นักมวย - เขาทราย แกแล็คซี่, สด จิตรลดา, สามารถ พยัคฆ์อรุณ, สมรักษ์ คำสิงห์\n" + " * นักเทนนิส - ภราดร ศรีชาพันธุ์, แทมมารีน ธนสุกาญจน์, ดนัย อุดมโชค\n" + " * นักว่ายน้ำ - รัฐพงษ์ ศิริสานนท์(ฉลามนุ้ก), ต่อวัย เสฎฐโสธร, ต่อลาภ เสฎฐโสธร\n" + " * นักฟุตบอล - ปิยะพงษ์ ผิวอ่อน, เกียรติศักดิ์ เสนาเมือง\n" + " * นักสนุกเกอร์ - ต๋อง ศิษย์ฉ่อย\n" + " * นักกรีฑา - เรวดี ศรีท้าว\n" + " * นักเทควันโด - เยาวภา บุรพลชัย\n" + " * นักยกน้ำหนัก - อุดมพร พลศักดิ์, ปวีณา ทองสุก\n" + " * นักกอล์ฟ - ธงชัย ใจดี\n" + "\n" + "วันสำคัญ\n" + "\n" + "วันสำคัญในประเทศไทยจะมีจำนวนมากโดยเฉพาะวันที่ไม่ใช่วันหยุดราชการ ซึ่งจะตั้งขึ้นหลังจากมีเหตุการณ์สำคัญเกิดขึ้น โดยวันชาติของประเทศไทยตรงกับวันที่ 5 ธันวาคม เป็น ตามวันพระราชสมภพ ของพระบาทสมเด็จพระเจ้าอยู่หัว ภูมิพลอดุลยเดช\n" + "\n" + " ดูบทความหลักที่ วันสำคัญในประเทศไทย\n" + "\n" + "ลำดับที่สำคัญ\n" + "\n" + " * พระมหากษัตริย์ไทยพระบาทสมเด็จพระปรมินทรมหาภูมิพลอดุลยเดช เป็นพระมหากษัตริย์ที่ครองราชย์ในฐานะประมุขแห่งรัฐที่นานที่สุดในโลก\n" + " * กรุงเทพฯ เป็นเมืองหลวงที่มีชื่อยาวที่สุดในโลก (169 ตัวอักษร)\n" + " * ดัชนีเศรษฐกิจของประเทศไทย อยู่อันดับที่ 71 จาก 155 เขตเศรษฐกิจ ตาม Index of Economic Freedom\n" + " * จังหวัดหนองคายได้รับการจัดอันดับจากนิตยสาร Modern Maturity ของสหรัฐเมื่อ พ.ศ. 2544 ว่าเป็นเมืองที่น่าอยู่สำหรับผู้สูงอายุชาวอเมริกันอันดับที่ 7 ของโลก [9]\n" + " * Growth Competitiveness Index Ranking พ.ศ. 2546 อยู่อันดับที่ 34 จาก 104 [10]\n" + " * ตึกใบหยก 2 เป็นตึกที่สูงที่สุดในประเทศไทย และสูงเป็นอันดับ 30 ของโลก พ.ศ. 2549\n" + "\n" + "อ้างอิง\n" + "\n" + " 1. ↑ 4th edition \"ANKOR an introduction to the temples\" Dawn Rooney ISBN: 962-217-683-6\n" + " 2. ↑ ในสมัยก่อนนั้น (ตั้งแต่คริสต์ศตวรรษที่ 17 ในยุโรป) ภาษาสากลในการติดต่อระหว่างประเทศ (lingua franca) คือ ภาษาฝรั่งเศส เอกสารระหว่างประเทศจะใช้ภาษาฝรั่งเศสเป็นหลัก รวมถึงหนังสือเดินทางไทยรุ่นแรกๆ ด้วย\n" + " 3. ↑ ดัชนีเศรษฐกิจประเทศไทย จากเว็บไซต์ธนาคารแห่งประเทศไทย\n" + " 4. ↑ ข้าวไทย ย่างก้าวพัฒนา สร้างไทยเป็นศูนย์กลางข้าวโลก โดย เทคโนโลยีชาวบ้าน มติชน วันที่ 01 มิถุนายน พ.ศ. 2550 ปีที่ 19 ฉบับที่ 408\n" + " 5. ↑ http://www.thairath.co.th/news.php?section=agriculture&content=52868\n" + " 6. ↑ ผลผลิตของประเทศไทย จากเว็บไซต์ธนาคารแห่งประเทศไทย\n" + " 7. ↑ ข้อมูลการท่องเที่ยว จากการท่องเที่ยวแห่งประเทศไทย (ข้อมูลเป็นไฟล์เอกเซล)\n" + " 8. ↑ 8.0 8.1 8.2 8.3 รายละเอียดประเทศไทยจากเว็บซีไอเอ\n" + " 9. ↑ http://207.5.46.81/tat_news/detail.asp?id=963\n" + " 10. ↑ ข้อมูลจาก Webforum.org พ.ศ. 2546\n" + "\n" + "แหล่งข้อมูลอื่น\n" + "Commons\n" + "คอมมอนส์ มีภาพและสื่ออื่นๆ เกี่ยวกับ:\n" + "ประเทศไทย\n" + "ฟลิคเกอร์\n" + "ฟลิคเกอร์ มีรูปภาพเกี่ยวกับ: ประเทศไทย\n" + "\n" + " * รัฐบาลไทย\n" + " * การท่องเที่ยวแห่งประเทศไทย\n" + " * ประเทศไทยศึกษา ห้องสมุดรัฐสภา สหรัฐอเมริกา\n" + " * พจนานุกรมท่องเที่ยวไทย\n" + " * แผนที่ประเทศไทย Longdo Map\n"; function get_most_popular(text) { var i; var frequencies = new Object(); var letter; for (i = 0; i < text.length; i++) { letter = text.charAt(i); if (typeof(frequencies[letter]) == 'undefined') frequencies[letter] = 0; frequencies[letter]++; } var most = []; for (letter in frequencies) { if (frequencies[letter] > 50) { most.push(letter); } } most.sort(); return most; } var languages = new Array( chinese, // 1 cyrillic, // 2 devanagari, // 3 english, // 4 greek, // 5 hebrew, // 6 japanese, // 7 korean, // 8 persian, // 9 source, // 10 thai); // 11 var number_re = /[0-9]/; var latin_lc = "[a-zA\u0631]"; assertEquals(7, latin_lc.length); var latin_lc_re = new RegExp(latin_lc); var latin_lc_re2 = new RegExp(/[a-zA\u0631]/); assertEquals(13793, chinese.length, "chinese utf8 in source"); assertEquals(60606, cyrillic.length, "cyrillic utf8 in source"); assertEquals(20203, devanagari.length, "devanagari utf8 in source"); assertEquals(37505, english.length, "english utf8 in source"); assertEquals(30052, greek.length, "greek utf8 in source"); assertEquals(25640, hebrew.length, "hebrew utf8 in source"); assertEquals(31082, japanese.length, "japanese utf8 in source"); assertEquals(12291, korean.length, "korean utf8 in source"); assertEquals(13851, persian.length, "persian utf8 in source"); assertEquals(177470, source.length, "source utf8 in source"); assertEquals(18315, thai.length, "thai utf8 in source"); munged_sizes = new Array(17197, 2511, 2645, 3820, 3086, 2609, 27231, 12972, 2014, 24943, 2773); var i = 0; for (idx in languages) { i++; var text = languages[idx]; assertTrue(latin_lc_re.test(text), "latin_lc" + i); assertTrue(latin_lc_re2.test(text), "latin_lc" + i); assertTrue(number_re.test(text), "number " + i); var most_popular = get_most_popular(text); var idx; var re = "([x"; var last_c = -9999; for (idx in most_popular) { var c = most_popular[idx]; if ("^]-\n\\".indexOf(c) == -1) { if (c.charCodeAt(0) > last_c && c.charCodeAt(0) - 20 < last_c) { re += "-" + c; last_c = -9999; } else { re += c; last_c = c.charCodeAt(0); } } } re += "]+)"; var char_class = new RegExp(re, "g"); var munged = text.replace(char_class, "foo"); assertEquals(munged_sizes[i - 1], munged.length, "munged size " + i); } function hex(x) { x &= 15; if (x < 10) { return String.fromCharCode(x + 48); } else { return String.fromCharCode(x + 97 - 10); } } function dump_re(re) { var out = ""; for (var i = 0; i < re.length; i++) { var c = re.charCodeAt(i); if (c >= 32 && c <= 126) { out += re[i]; } else if (c < 256) { out += "\\x" + hex(c >> 4) + hex(c); } else { out += "\\u" + hex(c >> 12) + hex(c >> 8) + hex(c >> 4) + hex(c); } } print ("re = " + out); } var thai_l_thingy = "\u0e44"; var thai_l_regexp = new RegExp(thai_l_thingy); var thai_l_regexp2 = new RegExp("[" + thai_l_thingy + "]"); assertTrue(thai_l_regexp.test(thai_l_thingy)); assertTrue(thai_l_regexp2.test(thai_l_thingy));
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/FlowNone.js
JonathanUsername/flow
import React from 'react'; class MyComponent extends React.Component { static defaultProps: DefaultProps = {}; props: Props; state: State = {}; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} } const expression = () => class extends React.Component { static defaultProps: DefaultProps = {}; props: Props; state: State = {}; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} }
webpack.config.js
yangyxu/zeanium-react-web
var ExtractTextPlugin = require("extract-text-webpack-plugin"); var UglifyJsPlugin = require('uglifyjs-webpack-plugin'); var optimizeCss = require('optimize-css-assets-webpack-plugin'); var path = require('path'); var config = require('./webpack.init.js'); var _overwrite = function (target){ var _target = target||{}; for(var i = 1, _len = arguments.length; i < _len; i++){ var _args = arguments[i]; for(var _key in _args){ if(_args.hasOwnProperty(_key) && _target[_key]===undefined){ _target[_key] = _args[_key]; } } } return _target; } module.exports = _overwrite({ context: path.join(process.cwd(), 'src'), mode: process.env.NODE_ENV || 'production', entry: { "index": './core/index.js', "index.web": './web/index.js', "index.wap": './wap/index.js' }, output: { path: path.join(process.cwd(), 'dist'), filename: '[name].js', chunkFilename: '[name].js' }, externals: { "react": "React", "react-dom": "ReactDOM" }, module: { // Disable handling of unknown requires unknownContextRegExp: /$^/, unknownContextCritical: false, // Disable handling of requires with a single expression //exprContextRegExp: /$^/, exprContextCritical: false, // Warn for every expression in require //wrappedContextCritical: true, rules: [ { test: /\.js[x]?$/, exclude: /(node_modules)/, use: { loader: 'babel-loader' } }, { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: [ { loader: "css-loader" } ] }) }, { test:/\.less$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: ["raw-loader", "less-loader"] }) }, { test: /\.scss$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', 'sass-loader'] }) }, { test: /\.(jpe?g|png|gif|svg)$/, use: [ { loader: 'file-loader' }, { loader: 'url-loader' } ] } ] }, plugins: [ new ExtractTextPlugin({ filename: "[name].css", disable: false, allChunks: true }), new optimizeCss({ assetNameRegExp: /\.style\.css$/g, cssProcessor: require('cssnano'), cssProcessorOptions: { discardComments: { removeAll: true } }, canPrint: true }) ], performance: { hints: process.env.NODE_ENV === 'production' ? "warning" : false }, optimization: { minimizer: [ /* new UglifyJsPlugin({ uglifyOptions: { compress: false } }),*/ new optimizeCss({ }) ] } }, config);
node_modules/react-bootstrap/es/Glyphicon.js
superKaigon/TheCave
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * An icon name without "glyphicon-" prefix. See e.g. http://getbootstrap.com/components/#glyphicons */ glyph: PropTypes.string.isRequired }; var Glyphicon = function (_React$Component) { _inherits(Glyphicon, _React$Component); function Glyphicon() { _classCallCheck(this, Glyphicon); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Glyphicon.prototype.render = function render() { var _extends2; var _props = this.props, glyph = _props.glyph, className = _props.className, props = _objectWithoutProperties(_props, ['glyph', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, glyph)] = true, _extends2)); return React.createElement('span', _extends({}, elementProps, { className: classNames(className, classes) })); }; return Glyphicon; }(React.Component); Glyphicon.propTypes = propTypes; export default bsClass('glyphicon', Glyphicon);
pkg/metrics/index.js
deryni/cockpit
/* * This file is part of Cockpit. * * Copyright (C) 2017 Red Hat, Inc. * * Cockpit is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * Cockpit is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Cockpit; If not, see <http://www.gnu.org/licenses/>. */ import "../lib/patternfly/patternfly-4-cockpit.scss"; import React from 'react'; import ReactDOM from 'react-dom'; import { Application } from './metrics.jsx'; /* * PF4 overrides need to come after the JSX components imports because * these are importing CSS stylesheets that we are overriding * Having the overrides here will ensure that when mini-css-extract-plugin will extract the CSS * out of the dist/index.js and since it will maintain the order of the imported CSS, * the overrides will be correctly in the end of our stylesheet. */ import "../lib/patternfly/patternfly-4-overrides.scss"; import './metrics.scss'; document.addEventListener("DOMContentLoaded", function () { ReactDOM.render(React.createElement(Application, {}), document.getElementById('app')); });
public/js/cat_source/es6/components/header/cattol/search/Search.js
riccio82/MateCat
import React from 'react' import CattolConstants from '../../../../constants/CatToolConstants' import SegmentStore from '../../../../stores/SegmentStore' import CatToolStore from '../../../../stores/CatToolStore' import SearchUtils from './searchUtils' import SegmentConstants from '../../../../constants/SegmentConstants' import SegmentActions from '../../../../actions/SegmentActions' class Search extends React.Component { constructor(props) { super(props) this.defaultState = { isReview: props.isReview, searchable_statuses: props.searchable_statuses, showReplaceOptionsInSearch: true, search: { enableReplace: false, matchCase: false, exactMatch: false, replaceTarget: '', selectStatus: 'all', searchTarget: '', searchSource: '', }, focus: true, funcFindButton: true, // true=find / false=next total: null, searchReturn: false, searchResults: [], occurrencesList: [], searchResultsDictionary: {}, featuredSearchResult: null, } this.state = _.cloneDeep(this.defaultState) this.handleSubmit = this.handleSubmit.bind(this) this.handleCancelClick = this.handleCancelClick.bind(this) this.handleInputChange = this.handleInputChange.bind(this) this.handleReplaceAllClick = this.handleReplaceAllClick.bind(this) this.handleReplaceClick = this.handleReplaceClick.bind(this) this.replaceTargetOnFocus = this.replaceTargetOnFocus.bind(this) this.handelKeydownFunction = this.handelKeydownFunction.bind(this) this.updateSearch = this.updateSearch.bind(this) this.dropdownInit = false } resetSearch() { this.setState({ total: null, searchReturn: false, searchResults: [], occurrencesList: [], searchResultsDictionary: {}, featuredSearchResult: null, }) } handleSubmit() { if (this.state.funcFindButton) { SearchUtils.execFind(this.state.search) } this.setState({ funcFindButton: false, }) } setResults(data) { this.setState({ total: data.total, searchResults: data.searchResults, occurrencesList: data.occurrencesList, searchResultsDictionary: data.searchResultsDictionary, featuredSearchResult: data.featuredSearchResult, searchReturn: true, }) setTimeout(() => { !_.isUndefined(this.state.occurrencesList[data.featuredSearchResult]) && SegmentActions.openSegment( this.state.occurrencesList[data.featuredSearchResult], ) }) } updateSearch() { if (this.props.active) { setTimeout(() => { const searchObject = SearchUtils.updateSearchObject() this.setState({ searchResults: searchObject.searchResults, occurrencesList: searchObject.occurrencesList, searchResultsDictionary: searchObject.searchResultsDictionary, featuredSearchResult: searchObject.featuredSearchResult, }) setTimeout(() => SegmentActions.addSearchResultToSegments( searchObject.occurrencesList, searchObject.searchResultsDictionary, this.state.featuredSearchResult, searchObject.searchParams, ), ) }) } } updateAfterReplace(sid) { let {searchResults} = this.state let itemReplaced = _.find(searchResults, (item) => item.id === sid) let total = this.state.total total-- if (itemReplaced.occurrences.length === 1) { _.remove(searchResults, (item) => item.id === sid) } let newResultArray = _.map(searchResults, (item) => item.id) const searchObject = SearchUtils.updateSearchObjectAfterReplace( newResultArray, ) this.setState({ total: total, searchResults: searchObject.searchResults, occurrencesList: searchObject.occurrencesList, searchResultsDictionary: searchObject.searchResultsDictionary, }) CatToolActions.storeSearchResults({ total: total, searchResults: searchObject.searchResults, occurrencesList: searchObject.occurrencesList, searchResultsDictionary: searchObject.searchResultsDictionary, featuredSearchResult: this.state.featuredSearchResult, }) SegmentActions.addSearchResultToSegments( searchObject.occurrencesList, searchObject.searchResultsDictionary, this.state.featuredSearchResult, searchObject.searchParams, ) } goToNext() { this.setFeatured(this.state.featuredSearchResult + 1) } goToPrev() { this.setFeatured(this.state.featuredSearchResult - 1) } setFeatured(value) { if (this.state.occurrencesList.length > 1) { let module = this.state.occurrencesList.length value = this.mod(value, module) } else { value = 0 } SearchUtils.updateFeaturedResult(value) CatToolActions.storeSearchResults({ total: this.state.total, searchResults: this.state.searchResults, occurrencesList: this.state.occurrencesList, searchResultsDictionary: this.state.searchResultsDictionary, featuredSearchResult: value, }) SegmentActions.changeCurrentSearchSegment(value) } // handling module mod(n, m) { return ((n % m) + m) % m } handleCancelClick() { this.dropdownInit = false UI.body.removeClass('searchActive') this.handleClearClick() if (UI.segmentIsLoaded(UI.currentSegmentId)) { setTimeout(() => SegmentActions.scrollToSegment(UI.currentSegmentId)) } else { UI.render({ firstLoad: false, segmentToOpen: UI.currentSegmentId, }) } this.resetStatusFilter() setTimeout(() => { CatToolActions.closeSubHeader() SegmentActions.removeSearchResultToSegments() this.setState(_.cloneDeep(this.defaultState)) }) } handleClearClick() { this.dropdownInit = false // SearchUtils.clearSearchMarkers(); this.resetStatusFilter() setTimeout(() => { this.setState(_.cloneDeep(this.defaultState)) SegmentActions.removeSearchResultToSegments() }) } resetStatusFilter() { $(this.statusDropDown).dropdown('restore defaults') } handleReplaceAllClick(event) { event.preventDefault() let self = this let props = { modalName: 'confirmReplace', text: 'Do you really want to replace this text in all search results? <br>(The page will be refreshed after confirm)', successText: 'Continue', successCallback: function () { SearchUtils.execReplaceAll(self.state.search).then((d) => { if (d.errors.length) { APP.alert({msg: d.errors[0].message}) return false } const currentId = SegmentStore.getCurrentSegmentId() UI.unmountSegments() UI.render({ firstLoad: false, segmentToOpen: currentId, }) }) APP.ModalWindow.onCloseModal() CatToolActions.storeSearchResults({ total: 0, searchResults: [], occurrencesList: [], searchResultsDictionary: {}, featuredSearchResult: null, }) }, cancelText: 'Cancel', cancelCallback: function () { APP.ModalWindow.onCloseModal() }, } APP.ModalWindow.showModalComponent( ConfirmMessageModal, props, 'Confirmation required', ) } handleReplaceClick() { if (this.state.search.searchTarget === this.state.search.replaceTarget) { APP.alert({msg: 'Attention: you are replacing the same text!'}) return false } SegmentActions.replaceCurrentSearch(this.state.search.replaceTarget) setTimeout(() => { const segment = SegmentStore.getSegmentByIdToJS( this.state.occurrencesList[this.state.featuredSearchResult], ) this.updateAfterReplace(segment.original_sid) // let next = this.state.occurrencesList[this.state.featuredSearchResult]; UI.setTranslation({ id_segment: segment.original_sid, status: segment.status, caller: 'replace', }) }) } handleStatusChange(value) { let search = _.cloneDeep(this.state.search) search['selectStatus'] = value if (value === 'APPROVED-2') { search.revisionNumber = 2 search['selectStatus'] = 'APPROVED' } else { search.revisionNumber = null } this.setState({ search: search, funcFindButton: true, }) } handleInputChange(name, event) { //serch model const target = event.target const value = target.type === 'checkbox' ? target.checked : target.value let search = this.state.search search[name] = value if (name !== 'enableReplace') { this.setState({ search: search, funcFindButton: true, total: null, searchReturn: false, searchResults: [], occurrencesList: [], searchResultsDictionary: {}, featuredSearchResult: null, }) } else { this.setState({ search: search, }) } } replaceTargetOnFocus() { let search = this.state.search search.enableReplace = true this.setState({ search: search, }) } componentDidUpdate(prevProps, prevState, snapshot) { if (this.props.active) { if (!prevProps.active) { if (this.sourceEl && this.state.focus) { this.sourceEl.focus() this.setState({ focus: false, }) } } $('body').addClass('search-open') let self = this if (!this.dropdownInit) { this.dropdownInit = true $(this.statusDropDown).dropdown({ onChange: function (value, text, $selectedItem) { value = value === '' ? 'all' : value self.handleStatusChange(value) }, }) } } else { $('body').removeClass('search-open') if (!this.state.focus) { this.setState({ focus: true, }) } this.dropdownInit = false } } getResultsHtml() { var html = '' const { featuredSearchResult, searchReturn, occurrencesList, searchResults, } = this.state const segmentIndex = _.findIndex( searchResults, (item) => item.id === occurrencesList[featuredSearchResult], ) //Waiting for results if (!this.state.funcFindButton && !searchReturn) { html = ( <div className="search-display"> <p className="searching">Searching ...</p> </div> ) } else if (!this.state.funcFindButton && searchReturn) { let query = [] if (this.state.search.exactMatch) query.push(' exactly') if (this.state.search.searchSource) query.push( <span key="source" className="query"> <span className="param">{this.state.search.searchSource}</span>in source{' '} </span>, ) if (this.state.search.searchTarget) query.push( <span key="target" className="query"> <span className="param">{this.state.search.searchTarget}</span>in target{' '} </span>, ) if (this.state.search.selectStatus !== 'all') { let statusLabel = ( <span key="status"> {' '} and status{' '} <span className="param">{this.state.search.selectStatus}</span> </span> ) query.push(statusLabel) } let caseLabel = ' (' + (this.state.search.matchCase ? 'case sensitive' : 'case insensitive') + ')' query.push(caseLabel) let searchMode = this.state.search.searchSource !== '' && this.state.search.searchTarget !== '' ? 'source&target' : 'normal' let numbers = '' let totalResults = this.state.searchResults.length if (searchMode === 'source&target') { let total = this.state.searchResults.length ? this.state.searchResults.length : 0 let label = total === 1 ? 'segment' : 'segments' numbers = total > 0 ? ( <span key="numbers" className="numbers"> Found{' '} <span className="segments"> {this.state.searchResults.length} </span>{' '} {label} </span> ) : ( <span key="numbers" className="numbers"> No segments found </span> ) } else { let total = this.state.total ? parseInt(this.state.total) : 0 let label = total === 1 ? 'result' : 'results' let label2 = total === 1 ? 'segment' : 'segments' numbers = total > 0 ? ( <span key="numbers" className="numbers"> Found <span className="results">{' ' + this.state.total}</span>{' '} <span>{label}</span> in <span className="segments"> {' ' + this.state.searchResults.length} </span>{' '} <span>{label2}</span> </span> ) : ( <span key="numbers" className="numbers"> No segments found </span> ) } html = ( <div className="search-display"> <p className="found"> {numbers} having {query} </p> {this.state.searchResults.length > 0 ? ( <div className="search-result-buttons"> <p>{segmentIndex + 1 + ' of ' + totalResults + ' segments'}</p> <button className="ui basic tiny button" onClick={this.goToPrev.bind(this)} > <i className="icon-chevron-left" /> <span> Find Previous (Shift + F3)</span> </button> <button className="ui basic tiny button" onClick={this.goToNext.bind(this)} > <i className="icon-chevron-right" /> <span> Find Next (F3)</span> </button> </div> ) : null} </div> ) } return html } handelKeydownFunction(event) { if (this.props.active) { if (event.keyCode === 27) { this.handleCancelClick() } else if ( event.keyCode === 13 && $(event.target).closest('.find-container').length > 0 ) { if ( this.state.search.searchTarget !== '' || this.state.search.searchSource !== '' ) { event.preventDefault() this.handleSubmit() } } else if (event.key === 'F3' && event.shiftKey) { event.preventDefault() this.goToPrev() } else if (event.key === 'F3') { event.preventDefault() this.goToNext() } } } componentDidMount() { document.addEventListener('keydown', this.handelKeydownFunction, false) CatToolStore.addListener( CattolConstants.STORE_SEARCH_RESULT, this.setResults.bind(this), ) CatToolStore.addListener( CattolConstants.CLOSE_SEARCH, this.handleCancelClick, ) SegmentStore.addListener(SegmentConstants.UPDATE_SEARCH, this.updateSearch) } componentWillUnmount() { document.removeEventListener('keydown', this.handelKeydownFunction, false) CatToolStore.removeListener( CattolConstants.STORE_SEARCH_RESULT, this.setResults, ) CatToolStore.removeListener( CattolConstants.CLOSE_SEARCH, this.handleCancelClick, ) SegmentStore.removeListener( SegmentConstants.UPDATE_SEARCH, this.updateSearch, ) } render() { let options = config.searchable_statuses.map(function (item, index) { return ( <React.Fragment key={index}> <div className="item" key={index} data-value={item.value}> <div className={ 'ui ' + item.label.toLowerCase() + '-color empty circular label' } /> {item.label} </div> {config.secondRevisionsCount && item.value === 'APPROVED' ? ( <div className="item" key={index + '-2'} data-value={'APPROVED-2'}> <div className={ 'ui ' + item.label.toLowerCase() + '-2ndpass-color empty circular label' } /> {item.label} </div> ) : null} </React.Fragment> ) }) let findIsDisabled = true if ( this.state.search.searchTarget !== '' || this.state.search.searchSource !== '' ) { findIsDisabled = false } let findButtonClassDisabled = !this.state.funcFindButton || findIsDisabled ? 'disabled' : '' let statusDropdownClass = this.state.search.selectStatus !== '' && this.state.search.selectStatus !== 'all' ? 'filtered' : 'not-filtered' let statusDropdownDisabled = this.state.search.searchTarget !== '' || this.state.search.searchSource !== '' ? '' : 'disabled' let replaceCheckboxClass = this.state.search.searchTarget ? '' : 'disabled' let replaceButtonsClass = this.state.search.enableReplace && this.state.search.searchTarget && !this.state.funcFindButton ? '' : 'disabled' let replaceAllButtonsClass = this.state.search.enableReplace && this.state.search.searchTarget ? '' : 'disabled' let clearVisible = this.state.search.searchTarget !== '' || this.state.search.searchSource !== '' || (this.state.search.selectStatus !== '' && this.state.search.selectStatus !== 'all') return this.props.active ? ( <div className="ui form"> <div className="find-wrapper"> <div className="find-container"> <div className="find-container-inside"> <div className="find-list"> <div className="find-element ui input"> <div className="find-in-source"> <input type="text" tabIndex={1} value={this.state.search.searchSource} placeholder="Find in source" onChange={this.handleInputChange.bind( this, 'searchSource', )} ref={(input) => (this.sourceEl = input)} /> </div> <div className="find-exact-match"> <div className="exact-match"> <input type="checkbox" tabIndex={3} checked={this.state.search.matchCase} onChange={this.handleInputChange.bind( this, 'matchCase', )} ref={(checkbox) => (this.matchCaseCheck = checkbox)} /> <label> Match Case</label> </div> <div className="exact-match"> <input type="checkbox" tabIndex={4} checked={this.state.search.exactMatch} onChange={this.handleInputChange.bind( this, 'exactMatch', )} /> <label> Whole word</label> </div> </div> </div> <div className="find-element-container"> <div className="find-element ui input"> <div className="find-in-target"> <input type="text" tabIndex={2} placeholder="Find in target" value={this.state.search.searchTarget} onChange={this.handleInputChange.bind( this, 'searchTarget', )} className={ !this.state.search.searchTarget && this.state.search.enableReplace ? 'warn' : null } /> {this.state.showReplaceOptionsInSearch ? ( <div className={ 'enable-replace-check ' + replaceCheckboxClass } > <input type="checkbox" tabIndex={5} checked={this.state.search.enableReplace} onChange={this.handleInputChange.bind( this, 'enableReplace', )} /> <label> Replace with</label> </div> ) : null} </div> </div> {this.state.showReplaceOptionsInSearch && this.state.search.enableReplace ? ( <div className="find-element ui input"> <div className="find-in-replace"> <input type="text" placeholder="Replace in target" value={this.state.search.replaceTarget} onChange={this.handleInputChange.bind( this, 'replaceTarget', )} /> </div> </div> ) : null} </div> <div className="find-element find-dropdown-status"> <div className={ 'find-dropdown ' + statusDropdownClass + ' ' + statusDropdownDisabled } > <div className="ui top left pointing dropdown basic tiny button" ref={(dropdown) => (this.statusDropDown = dropdown)} > <div className="text"> <div>Status Segment</div> </div> <div className="ui cancel label" onClick={this.resetStatusFilter.bind(this)} > <i className="icon-cancel3" /> </div> <div className="menu">{options}</div> </div> </div> </div> <div className="find-element find-clear-all"> {clearVisible ? ( <div className="find-clear"> <button type="button" className="" onClick={this.handleClearClick.bind(this)} > Clear </button> </div> ) : null} </div> </div> {this.state.showReplaceOptionsInSearch ? ( <div className="find-actions"> <button className={ 'ui basic tiny button ' + findButtonClassDisabled } onClick={this.handleSubmit.bind(this)} > FIND </button> <button className={'ui basic tiny button ' + replaceButtonsClass} onClick={this.handleReplaceClick.bind(this)} > REPLACE </button> <button className={'ui basic tiny button ' + replaceAllButtonsClass} onClick={this.handleReplaceAllClick.bind(this)} > REPLACE ALL </button> </div> ) : ( <div className="find-actions"> <button type="button" className={ 'ui basic tiny button ' + findButtonClassDisabled } onClick={this.handleSubmit.bind(this)} > FIND </button> </div> )} </div> {this.getResultsHtml()} </div> </div> </div> ) : null } } export default Search
src/svg-icons/image/tag-faces.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageTagFaces = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/> </SvgIcon> ); ImageTagFaces = pure(ImageTagFaces); ImageTagFaces.displayName = 'ImageTagFaces'; export default ImageTagFaces;
networknt/src/app/components/cart/CheckoutCart.js
networknt/light
/** * Created by steve on 04/09/15. */ var React = require('react'); var ReactPropTypes = React.PropTypes; var CartStore = require('../../stores/CartStore'); var CartActionCreators = require('../../actions/CartActionCreators'); var Cart = require('./Cart'); var CheckoutCart = React.createClass({ render: function() { console.log('rendering Checkoutcart'); return ( <Cart cartItems={ this.props.cartItems } totalPrice={ this.props.totalPrice } /> ) } }); module.exports = CheckoutCart;
stories-src/EdgeLabelSample.js
dunnock/react-sigma
import React from 'react' import { Sigma, RandomizeNodePositions, RelativeSize, EdgeShapes, ForceAtlas2 } from '../src/index'; class EdgeLabelSample extends React.Component { render() { let graph = { nodes: [ {id: 'a', label: 'A'}, {id: 'b', label: 'B'}, {id: 'c', label: 'C'} ], edges: [ {id: 'a_to_b', source: 'a', target: 'b', label: 'A -> B' }, {id: 'b_to_c', source: 'b', target: 'c', label: 'B -> C' }, {id: 'c_to_a', source: 'c', target: 'a', label: 'C -> A' }, {id: 'b_to_a', source: 'b', target: 'a', label: 'B -> A' } ] }; return <div> <Sigma renderer="canvas" graph={graph} settings={{ drawEdges: true, drawEdgeLabels: true}}> <EdgeShapes default="curvedArrow"/> <RandomizeNodePositions> <ForceAtlas2 iterationsPerRender={1} timeout={10000}/> <RelativeSize initialSize={15}/> </RandomizeNodePositions> </Sigma> </div> } } export default EdgeLabelSample;
src/Main/Results/ResultsWarning.js
hasseboulen/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import Warning from 'common/Alert/Warning'; class ResultsWarning extends React.PureComponent { static propTypes = { warning: PropTypes.node, }; render() { const { warning } = this.props; if (!warning) { return null; } return ( <div style={{ borderBottom: '1px solid #000', boxShadow: '0 1px 0 0 rgba(255, 255, 255, .1)' }}> <Warning> {warning} </Warning> </div> ); } } export default ResultsWarning;
src/index.js
Eol217/redux-course
import React from 'react'; import ReactDOM from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import App from './App'; const render = Component => { ReactDOM.render( <AppContainer> <Component /> </AppContainer>, document.getElementById('root') ) } render(App) if (module.hot) { module.hot.accept('./App', () => { render(App) }) }
src/svg-icons/device/nfc.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceNfc = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 18H4V4h16v16zM18 6h-5c-1.1 0-2 .9-2 2v2.28c-.6.35-1 .98-1 1.72 0 1.1.9 2 2 2s2-.9 2-2c0-.74-.4-1.38-1-1.72V8h3v8H8V8h2V6H6v12h12V6z"/> </SvgIcon> ); DeviceNfc = pure(DeviceNfc); DeviceNfc.displayName = 'DeviceNfc'; export default DeviceNfc;
src/svg-icons/action/build.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionBuild = (props) => ( <SvgIcon {...props}> <path d="M22.7 19l-9.1-9.1c.9-2.3.4-5-1.5-6.9-2-2-5-2.4-7.4-1.3L9 6 6 9 1.6 4.7C.4 7.1.9 10.1 2.9 12.1c1.9 1.9 4.6 2.4 6.9 1.5l9.1 9.1c.4.4 1 .4 1.4 0l2.3-2.3c.5-.4.5-1.1.1-1.4z"/> </SvgIcon> ); ActionBuild = pure(ActionBuild); ActionBuild.displayName = 'ActionBuild'; ActionBuild.muiName = 'SvgIcon'; export default ActionBuild;
admin/client/components/ItemsTableRow.js
Redmart/keystone
import React from 'react'; import classnames from 'classnames'; import Columns from '../columns'; import CurrentListStore from '../stores/CurrentListStore'; import ListControl from './ListControl'; import { DropTarget, DragSource } from 'react-dnd'; const ItemsRow = React.createClass({ propTypes: { columns: React.PropTypes.array, items: React.PropTypes.object, list: React.PropTypes.object, index: React.PropTypes.number, id: React.PropTypes.any, // Injected by React DnD: isDragging: React.PropTypes.bool, connectDragSource: React.PropTypes.func, connectDropTarget: React.PropTypes.func, connectDragPreview: React.PropTypes.func, }, renderRow (item) { let itemId = item.id; let rowClassname = classnames({ 'ItemList__row--dragging': this.props.isDragging, 'ItemList__row--selected': this.props.checkedItems[itemId], 'ItemList__row--manage': this.props.manageMode, 'ItemList__row--success': this.props.rowAlert.success === itemId, 'ItemList__row--failure': this.props.rowAlert.fail === itemId, }); // item fields var cells = this.props.columns.map((col, i) => { var ColumnType = Columns[col.type] || Columns.__unrecognised__; var linkTo = !i ? `${Keystone.adminPath}/${this.props.list.path}/${itemId}` : undefined; return <ColumnType key={col.path} list={this.props.list} col={col} data={item} linkTo={linkTo} />; }); // add sortable icon when applicable if (this.props.list.sortable) { cells.unshift(<ListControl key="_sort" type="sortable" dragSource={this.props.connectDragSource} />); } // add delete/check icon when applicable if (!this.props.list.nodelete) { cells.unshift(this.props.manageMode ? ( <ListControl key="_check" type="check" active={this.props.checkedItems[itemId]} /> ) : ( <ListControl key="_delete" onClick={(e) => this.props.deleteTableItem(item, e)} type="delete" /> )); } var addRow = (<tr key={'i' + item.id} onClick={this.props.manageMode ? (e) => this.props.checkTableItem(item, e) : null} className={rowClassname}>{cells}</tr>); if(this.props.list.sortable) { return ( // we could add a preview container/image // this.props.connectDragPreview(this.props.connectDropTarget(addRow)) this.props.connectDropTarget(addRow) ); } else { return (addRow); } }, render () { return this.renderRow(this.props.item); }, }); module.exports = exports = ItemsRow; // Expose Sortable /** * Implements drag source. */ const dragItem = { beginDrag (props) { let send = { ...props }; CurrentListStore.setDragBase(props.item, props.index); return { ...send }; }, endDrag (props, monitor, component) { if (!monitor.didDrop()) { return CurrentListStore.resetItems(CurrentListStore.findClonedItemById(props.id).index); } const base = CurrentListStore.getDragBase(); const page = CurrentListStore.getCurrentPage(); const droppedOn = monitor.getDropResult(); // some drops provide the data for us in prevSortOrder const prevSortOrder = droppedOn.prevSortOrder ? droppedOn.prevSortOrder : props.sortOrder; // use a given newSortOrder prop or retrieve from the cloned items list let newSortOrder = droppedOn.newSortOrder ? droppedOn.newSortOrder : CurrentListStore.findClonedItemByIndex(droppedOn.index).sortOrder; // self if (prevSortOrder === newSortOrder) { if(base.page !== page) { // we were dropped on ourself, but not on our original page if(droppedOn.index === 0) { // item is first in the list // save to the sortOrder of the 2nd item - 1 newSortOrder = CurrentListStore.findClonedItemByIndex(1).sortOrder - 1; droppedOn.goToPage = Number(page) - 1; } else { // item is last in the list // save to the sortOrder of the 2nd to last item - 1 newSortOrder = CurrentListStore.findClonedItemByIndex(droppedOn.index - 1).sortOrder + 1; droppedOn.goToPage = Number(page) + 1; } if (!newSortOrder || !droppedOn.goToPage) { // something is wrong so reset return CurrentListStore.resetItems(CurrentListStore.findClonedItemById(props.id).index); } } else { return CurrentListStore.resetItems(CurrentListStore.findClonedItemById(props.id).index); } } // dropped on a target // droppedOn.goToPage is an optional page override for dropping items on a new page target CurrentListStore.reorderItems(props.item, prevSortOrder, newSortOrder, Number(droppedOn.goToPage)); }, }; /** * Implements drag target. */ const dropItem = { drop (props, monitor, component) { return { ...props }; }, hover (props, monitor, component) { // reset row alerts if (props.rowAlert.success || props.rowAlert.fail) { CurrentListStore.rowAlert('reset'); } const dragged = monitor.getItem().index; const over = props.index; // self if (dragged === over) { return; } CurrentListStore.moveItem(dragged, over, props); monitor.getItem().index = over; }, }; /** * Specifies the props to inject into your component. */ function dragProps (connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), connectDragPreview: connect.dragPreview(), }; } function dropProps (connect) { return { connectDropTarget: connect.dropTarget(), }; }; exports.Sortable = DragSource('item', dragItem, dragProps)(DropTarget('item', dropItem, dropProps)(ItemsRow));
test/CardTitleSpec.js
mattBlackDesign/react-materialize
/* global describe, it */ import React from 'react'; import { shallow } from 'enzyme'; import { assert } from 'chai'; import CardTitle from '../src/CardTitle'; let wrapper = shallow( <CardTitle image=''> I am a very simple card </CardTitle> ); describe('<CardTitle />', () => { it('should render', () => { assert(wrapper.find('.card-title').length, 'with a card-title className'); }); wrapper = shallow( <CardTitle image='' reveal> I am a very simple card </CardTitle> ); it('requires an image prop', () => { assert(wrapper.find('img.activator').length, 'with a truthy value'); }); });
client/containers/addNewWordForm/AddNewWordFormContainer.js
intanta/go-words
import React from 'react' import { connect } from 'react-redux' import * as actionCreators from '../../actions/words' import { bindActionCreators } from 'redux' import Loader from 'react-loader'; import AddNewWordForm from '../../components/addNewWordForm/AddNewWordForm'; class AddNewWordFormContainer extends React.Component { handleSave = (wordPair) => { this.props.actions.addWord(wordPair); } render () { return ( <Loader loaded={!this.props.isLoading}> <AddNewWordForm onSave={this.handleSave} /> </Loader> ) } } AddNewWordFormContainer.contextTypes = { router: React.PropTypes.object.isRequired } const mapStateToProps = (state) => { const { isLoading } = state.words; return { isLoading }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actionCreators, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(AddNewWordFormContainer);
src/containers/HomeBladeVertical.js
pjkarlik/ReactUI
import React from 'react'; import { resolve } from '../styles'; import { withRouter } from 'react-router'; import BladeVertical from '../components/BladeVertical'; import BladeStyles from '../components/BladeVertical.less'; import AssetManager from '../components/AssetManager'; import SiteStyles from '../styles/Site.less'; import Panel1 from './BVwhatIs.js'; import Panel2 from './BVmyName.js'; import Panel4 from './BVsecret.js'; /** Comments here */ class Home extends React.Component { static displayName = 'Home'; static propTypes = { classes: React.PropTypes.object, router: React.PropTypes.shape({ push: React.PropTypes.func.isRequired, }).isRequired, }; static defaultProps = { classes: SiteStyles, }; constructor(props) { super(props); this.assetManager = new AssetManager(); this.assetManager.downloadAll(); this.sounds = this.assetManager.assets; this.background = `home${7 + ~~(Math.random() * 2)}`; this.state = { bladeConfig: { blades: [ { name: 'what i do', child: <Panel1 /> }, { name: 'who am i', child: <Panel2 /> }, { name: 'what is this', child: <Panel4 /> }, { name: 'go home', path: '/' }, ], }, }; } componentDidMount() { setTimeout(() => { this.startLoop(); }, 400); } componentWillUnmount() { setTimeout(() => { this.stopLoop(); }, 400); } onClick = (path) => { this.stopLoop(); const { router } = this.props; router.push(path); } startLoop = () => { const checkSound = this.sounds.bit.data.playing(); if (!checkSound) { this.sounds.bit.data.play(); this.sounds.bit.data.fade(0, 0.4, 3000); } }; stopLoop = () => { this.sounds.bit.data.fade(0.4, 0, 6000); setTimeout(() => { this.sounds.bit.data.stop(); }, 6000); }; render() { return ( <div {...resolve(this.props, 'container', this.background)}> <BladeVertical items = {this.state.bladeConfig} classes = {BladeStyles} onClick = {this.onClick} /> </div> ); } } export default withRouter(Home);
src/containers/Home/Home.js
chadoh/isoredux
import React, { Component } from 'react'; import { Link } from 'react-router'; import { CounterButton, GithubButton } from 'components'; import config from '../../config'; export default class Home extends Component { render() { const styles = require('./Home.scss'); // require the logo image both from client and server const logoImage = require('./logo.png'); return ( <div className={styles.home}> <div className={styles.masthead}> <div className="container"> <div className={styles.logo}> <p> <img src={logoImage}/> </p> </div> <h1>{config.app.title}</h1> <h2>{config.app.description}</h2> <p> <a className={styles.github} href="https://github.com/erikras/react-redux-universal-hot-example" target="_blank"> <i className="fa fa-github"/> View on Github </a> </p> <GithubButton user="erikras" repo="react-redux-universal-hot-example" type="star" width={160} height={30} count large/> <GithubButton user="erikras" repo="react-redux-universal-hot-example" type="fork" width={160} height={30} count large/> <p className={styles.humility}> Created and maintained by <a href="https://twitter.com/erikras" target="_blank">@erikras</a>. </p> </div> </div> <div className="container"> <div className={styles.counterContainer}> <CounterButton multireducerKey="counter1"/> <CounterButton multireducerKey="counter2"/> <CounterButton multireducerKey="counter3"/> </div> <p>This starter boilerplate app uses the following technologies:</p> <ul> <li> <del>Isomorphic</del> {' '} <a href="https://medium.com/@mjackson/universal-javascript-4761051b7ae9">Universal</a> rendering </li> <li>Both client and server make calls to load data from separate API server</li> <li><a href="https://github.com/facebook/react" target="_blank">React</a></li> <li><a href="https://github.com/rackt/react-router" target="_blank">React Router</a></li> <li><a href="http://expressjs.com" target="_blank">Express</a></li> <li><a href="http://babeljs.io" target="_blank">Babel</a> for ES6 and ES7 magic</li> <li><a href="http://webpack.github.io" target="_blank">Webpack</a> for bundling</li> <li><a href="http://webpack.github.io/docs/webpack-dev-middleware.html" target="_blank">Webpack Dev Middleware</a> </li> <li><a href="https://github.com/glenjamin/webpack-hot-middleware" target="_blank">Webpack Hot Middleware</a></li> <li><a href="https://github.com/rackt/redux" target="_blank">Redux</a>'s futuristic <a href="https://facebook.github.io/react/blog/2014/05/06/flux.html" target="_blank">Flux</a> implementation </li> <li><a href="https://github.com/gaearon/redux-devtools" target="_blank">Redux Dev Tools</a> for next generation DX (developer experience). Watch <a href="https://www.youtube.com/watch?v=xsSnOQynTHs" target="_blank">Dan Abramov's talk</a>. </li> <li><a href="https://github.com/rackt/redux-router" target="_blank">Redux Router</a> Keep your router state in your Redux store </li> <li><a href="http://eslint.org" target="_blank">ESLint</a> to maintain a consistent code style</li> <li><a href="https://github.com/erikras/redux-form" target="_blank">redux-form</a> to manage form state in Redux </li> <li><a href="https://github.com/erikras/multireducer" target="_blank">multireducer</a> combine several identical reducer states into one key-based reducer</li> <li><a href="https://github.com/webpack/style-loader" target="_blank">style-loader</a> and <a href="https://github.com/jtangelder/sass-loader" target="_blank">sass-loader</a> to allow import of stylesheets </li> <li><a href="https://github.com/shakacode/bootstrap-sass-loader" target="_blank">bootstrap-sass-loader</a> and <a href="https://github.com/gowravshekar/font-awesome-webpack" target="_blank">font-awesome-webpack</a> to customize Bootstrap and FontAwesome </li> <li><a href="http://socket.io/">socket.io</a> for real-time communication</li> </ul> <h3>Features demonstrated in this project</h3> <dl> <dt>Multiple components subscribing to same redux store slice</dt> <dd> The <code>App.js</code> that wraps all the pages contains an <code>InfoBar</code> component that fetches data from the server initially, but allows for the user to refresh the data from the client. <code>About.js</code> contains a <code>MiniInfoBar</code> that displays the same data. </dd> <dt>Server-side data loading</dt> <dd> The <Link to="/widgets">Widgets page</Link> demonstrates how to fetch data asynchronously from some source that is needed to complete the server-side rendering. <code>Widgets.js</code>'s <code>fetchData()</code> function is called before the widgets page is loaded, on either the server or the client, allowing all the widget data to be loaded and ready for the page to render. </dd> <dt>Data loading errors</dt> <dd> The <Link to="/widgets">Widgets page</Link> also demonstrates how to deal with data loading errors in Redux. The API endpoint that delivers the widget data intentionally fails 33% of the time to highlight this. The <code>clientMiddleware</code> sends an error action which the <code>widgets</code> reducer picks up and saves to the Redux state for presenting to the user. </dd> <dt>Session based login</dt> <dd> On the <Link to="/login">Login page</Link> you can submit a username which will be sent to the server and stored in the session. Subsequent refreshes will show that you are still logged in. </dd> <dt>Redirect after state change</dt> <dd> After you log in, you will be redirected to a Login Success page. This <strike>magic</strike> logic is performed in <code>componentWillReceiveProps()</code> in <code>App.js</code>, but it could be done in any component that listens to the appropriate store slice, via Redux's <code>@connect</code>, and pulls the router from the context. </dd> <dt>Auth-required views</dt> <dd> The aforementioned Login Success page is only visible to you if you are logged in. If you try to <Link to="/loginSuccess">go there</Link> when you are not logged in, you will be forwarded back to this home page. This <strike>magic</strike> logic is performed by the <code>onEnter</code> hook within <code>routes.js</code>. </dd> <dt>Forms</dt> <dd> The <Link to="/survey">Survey page</Link> uses the still-experimental <a href="https://github.com/erikras/redux-form" target="_blank">redux-form</a> to manage form state inside the Redux store. This includes immediate client-side validation. </dd> <dt>WebSockets / socket.io</dt> <dd> The <Link to="/chat">Chat</Link> uses the socket.io technology for real-time communication between clients. You need to <Link to="/login">login</Link> first. </dd> </dl> <h3>From the author</h3> <p> I cobbled this together from a wide variety of similar "starter" repositories. As I post this in June 2015, all of these libraries are right at the bleeding edge of web development. They may fall out of fashion as quickly as they have come into it, but I personally believe that this stack is the future of web development and will survive for several years. I'm building my new projects like this, and I recommend that you do, too. </p> <p>Thanks for taking the time to check this out.</p> <p>– Erik Rasmussen</p> </div> </div> ); } }
src/svg-icons/action/thumb-up.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionThumbUp = (props) => ( <SvgIcon {...props}> <path d="M1 21h4V9H1v12zm22-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L14.17 1 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-1.91l-.01-.01L23 10z"/> </SvgIcon> ); ActionThumbUp = pure(ActionThumbUp); ActionThumbUp.displayName = 'ActionThumbUp'; ActionThumbUp.muiName = 'SvgIcon'; export default ActionThumbUp;
src/landing/index.js
jimboslicethat/rpi-home-dashboard
import React from 'react' import CssModules from 'react-css-modules' import css from './index.css' function Landing(props) { return ( <div styleName="container"> Home Dashboard </div> ) } export default CssModules(Landing, css)
node_modules/react-icons/io/ios-sunny-outline.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const IoIosSunnyOutline = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m19.3 11.9v-4.4h1.4v4.4h-1.4z m0 20.6v-4.7h1.4v4.7h-1.4z m8.8-11.8v-1.4h4.4v1.4h-4.4z m-20.6 0v-1.4h4.7v1.4h-4.7z m18.8 4.1l2.6 2.7-0.9 0.9-2.6-2.6z m-13.8-13.7l2.7 2.6-1 0.9-2.6-2.6z m12.9 2.7l2.6-2.7 0.9 0.9-2.6 2.6z m-13.8 13.7l2.6-2.7 0.9 1-2.6 2.6z m8.4-1.6c-3.3 0-5.9-2.6-5.9-5.9s2.6-5.9 5.9-5.9 5.9 2.6 5.9 5.9-2.6 5.9-5.9 5.9z m0-10.5c-2.5 0-4.6 2.1-4.6 4.6s2.1 4.6 4.6 4.6 4.6-2.1 4.6-4.6-2.1-4.6-4.6-4.6z"/></g> </Icon> ) export default IoIosSunnyOutline
tools/start.js
ziedAb/PVMourakiboun
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import browserSync from 'browser-sync'; import webpack from 'webpack'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; import WriteFilePlugin from 'write-file-webpack-plugin'; import run from './run'; import runServer from './runServer'; import webpackConfig from './webpack.config'; import clean from './clean'; import copy from './copy'; const isDebug = !process.argv.includes('--release'); process.argv.push('--watch'); const [clientConfig, serverConfig] = webpackConfig; /** * Launches a development web server with "live reload" functionality - * synchronizing URLs, interactions and code changes across multiple devices. */ async function start() { await run(clean); await run(copy); await new Promise((resolve) => { // Save the server-side bundle files to the file system after compilation // https://github.com/webpack/webpack-dev-server/issues/62 serverConfig.plugins.push(new WriteFilePlugin({ log: false })); // Hot Module Replacement (HMR) + React Hot Reload if (isDebug) { clientConfig.entry.client = [...new Set([ 'babel-polyfill', 'react-hot-loader/patch', 'webpack-hot-middleware/client', ].concat(clientConfig.entry.client))]; clientConfig.output.filename = clientConfig.output.filename.replace('[chunkhash', '[hash'); clientConfig.output.chunkFilename = clientConfig.output.chunkFilename.replace('[chunkhash', '[hash'); const { query } = clientConfig.module.rules.find(x => x.loader === 'babel-loader'); query.plugins = ['react-hot-loader/babel'].concat(query.plugins || []); clientConfig.plugins.push(new webpack.HotModuleReplacementPlugin()); clientConfig.plugins.push(new webpack.NoEmitOnErrorsPlugin()); } const bundler = webpack(webpackConfig); const wpMiddleware = webpackDevMiddleware(bundler, { // IMPORTANT: webpack middleware can't access config, // so we should provide publicPath by ourselves publicPath: clientConfig.output.publicPath, // Pretty colored output stats: clientConfig.stats, // For other settings see // https://webpack.github.io/docs/webpack-dev-middleware }); const hotMiddleware = webpackHotMiddleware(bundler.compilers[0]); let handleBundleComplete = async () => { handleBundleComplete = stats => !stats.stats[1].compilation.errors.length && runServer(); const server = await runServer(); const bs = browserSync.create(); bs.init({ ...isDebug ? {} : { notify: false, ui: false }, proxy: { target: server.host, middleware: [wpMiddleware, hotMiddleware], proxyOptions: { xfwd: true, }, }, }, resolve); }; bundler.plugin('done', stats => handleBundleComplete(stats)); }); } export default start;
app/javascript/mastodon/features/hashtag_timeline/index.js
hyuki0000/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { refreshHashtagTimeline, expandHashtagTimeline, } from '../../actions/timelines'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import { FormattedMessage } from 'react-intl'; import { connectHashtagStream } from '../../actions/streaming'; const mapStateToProps = (state, props) => ({ hasUnread: state.getIn(['timelines', `hashtag:${props.params.id}`, 'unread']) > 0, }); @connect(mapStateToProps) export default class HashtagTimeline extends React.PureComponent { static propTypes = { params: PropTypes.object.isRequired, columnId: PropTypes.string, dispatch: PropTypes.func.isRequired, hasUnread: PropTypes.bool, multiColumn: PropTypes.bool, }; handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('HASHTAG', { id: this.props.params.id })); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } _subscribe (dispatch, id) { this.disconnect = dispatch(connectHashtagStream(id)); } _unsubscribe () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } componentDidMount () { const { dispatch } = this.props; const { id } = this.props.params; dispatch(refreshHashtagTimeline(id)); this._subscribe(dispatch, id); } componentWillReceiveProps (nextProps) { if (nextProps.params.id !== this.props.params.id) { this.props.dispatch(refreshHashtagTimeline(nextProps.params.id)); this._unsubscribe(); this._subscribe(this.props.dispatch, nextProps.params.id); } } componentWillUnmount () { this._unsubscribe(); } setRef = c => { this.column = c; } handleLoadMore = () => { this.props.dispatch(expandHashtagTimeline(this.props.params.id)); } render () { const { hasUnread, columnId, multiColumn } = this.props; const { id } = this.props.params; const pinned = !!columnId; return ( <Column ref={this.setRef}> <ColumnHeader icon='hashtag' active={hasUnread} title={id} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} showBackButton /> <StatusListContainer trackScroll={!pinned} scrollKey={`hashtag_timeline-${columnId}`} timelineId={`hashtag:${id}`} loadMore={this.handleLoadMore} emptyMessage={<FormattedMessage id='empty_column.hashtag' defaultMessage='There is nothing in this hashtag yet.' />} /> </Column> ); } }
src/TableViewHeader.js
aksonov/react-native-tableview
import React from 'react'; import { requireNativeComponent } from 'react-native'; const RNHeaderView = requireNativeComponent('RNTableHeaderView', null); export default class TableViewHeader extends React.Component { constructor(props) { super(props); this.state = { width: 0, height: 0 }; } render() { return ( <RNHeaderView onLayout={event => { this.setState(event.nativeEvent.layout); }} {...this.props} componentWidth={this.state.width} componentHeight={this.state.height} /> ); } }
src/components/LinkButton/index.js
simpaa/s-andersson-site
import React from 'react'; import './LinkButton.css'; const LinkButton = ({ link, text, target }) => ( <div className="link-button"> <a href={link} target={target}>{text}</a> </div> ); export default LinkButton;
src/App.js
Lechus/learninginthecloud
import React, { Component } from 'react'; import ThreadDisplay from './ThreadDisplay/components/ThreadDisplay'; import { firebaseConfig } from './core/firebase/config'; import * as firebase from 'firebase'; import './App.css'; class App extends Component { constructor(props) { super(props); this.app = firebase.initializeApp(firebaseConfig); this.database = this.app.database(); } render() { return ( <ThreadDisplay database={this.database} /> ); } } export default App;
admin/client/App/screens/List/components/ItemsTable/ItemsTableRow.js
linhanyang/keystone
import React from 'react'; import classnames from 'classnames'; import ListControl from '../ListControl'; import { Columns } from 'FieldTypes'; import { DropTarget, DragSource } from 'react-dnd'; import { setDragBase, resetItems, reorderItems, setRowAlert, moveItem, } from '../../actions'; const ItemsRow = React.createClass({ propTypes: { columns: React.PropTypes.array, id: React.PropTypes.any, index: React.PropTypes.number, items: React.PropTypes.object, list: React.PropTypes.object, // Injected by React DnD: isDragging: React.PropTypes.bool, // eslint-disable-line react/sort-prop-types connectDragSource: React.PropTypes.func, // eslint-disable-line react/sort-prop-types connectDropTarget: React.PropTypes.func, // eslint-disable-line react/sort-prop-types connectDragPreview: React.PropTypes.func, // eslint-disable-line react/sort-prop-types }, renderRow (item) { const itemId = item.id; const rowClassname = classnames({ 'ItemList__row--dragging': this.props.isDragging, 'ItemList__row--selected': this.props.checkedItems[itemId], 'ItemList__row--manage': this.props.manageMode, 'ItemList__row--success': this.props.rowAlert.success === itemId, 'ItemList__row--failure': this.props.rowAlert.fail === itemId, }); // item fields var cells = this.props.columns.map((col, i) => { var ColumnType = Columns[col.type] || Columns.__unrecognised__; var linkTo = !i ? `${Keystone.adminPath}/${this.props.list.path}/${itemId}` : undefined; return <ColumnType key={col.path} list={this.props.list} col={col} data={item} linkTo={linkTo} />; }); // add sortable icon when applicable if (this.props.list.sortable) { cells.unshift(<ListControl key="_sort" type="sortable" dragSource={this.props.connectDragSource} />); } // add delete/check icon when applicable if (!this.props.list.nodelete) { cells.unshift(this.props.manageMode ? ( <ListControl key="_check" type="check" active={this.props.checkedItems[itemId]} /> ) : ( <ListControl key="_delete" onClick={(e) => this.props.deleteTableItem(item, e)} type="delete" /> )); } var addRow = (<tr key={'i' + item.id} onClick={this.props.manageMode ? (e) => this.props.checkTableItem(item, e) : null} className={rowClassname}>{cells}</tr>); if (this.props.list.sortable) { return ( // we could add a preview container/image // this.props.connectDragPreview(this.props.connectDropTarget(addRow)) this.props.connectDropTarget(addRow) ); } else { return (addRow); } }, render () { return this.renderRow(this.props.item); }, }); module.exports = exports = ItemsRow; // Expose Sortable /** * Implements drag source. */ const dragItem = { beginDrag (props) { const send = { ...props }; props.dispatch(setDragBase(props.item, props.index)); return { ...send }; }, endDrag (props, monitor, component) { if (!monitor.didDrop()) { props.dispatch(resetItems(props.id)); return; } const page = props.currentPage; const pageSize = props.pageSize; // If we were dropped onto a page change target, then droppedOn.prevSortOrder etc will be // set by that target, and we should use those values. If we were just dropped onto a new row // then we need to calculate these values ourselves. const droppedOn = monitor.getDropResult(); const prevSortOrder = droppedOn.prevSortOrder || props.sortOrder; // To explain the following line, suppose we are on page 3 and there are 10 items per page. // Previous to this page, there are (3 - 1)*10 = 20 items before us. If we have index 6 // on this page, then we're the 7th item to display (index starts from 0), and so we // want to update the display order to 20 + 7 = 27. const newSortOrder = droppedOn.newSortOrder || (page - 1) * pageSize + droppedOn.index + 1; // If we were dropped on a page change target, then droppedOn.gotToPage will be set, and we should // pass this to reorderItems, which will then change the page for the user. props.dispatch(reorderItems(props.item, prevSortOrder, newSortOrder, Number(droppedOn.goToPage))); }, }; /** * Implements drag target. */ const dropItem = { drop (props, monitor, component) { return { ...props }; }, hover (props, monitor, component) { // reset row alerts if (props.rowAlert.success || props.rowAlert.fail) { props.dispatch(setRowAlert({ reset: true, })); } const dragged = monitor.getItem().index; const over = props.index; // self if (dragged === over) { return; } props.dispatch(moveItem(dragged, over, props)); monitor.getItem().index = over; }, }; /** * Specifies the props to inject into your component. */ function dragProps (connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), connectDragPreview: connect.dragPreview(), }; } function dropProps (connect) { return { connectDropTarget: connect.dropTarget(), }; }; exports.Sortable = DragSource('item', dragItem, dragProps)(DropTarget('item', dropItem, dropProps)(ItemsRow));
packages/react-scripts/fixtures/kitchensink/src/features/env/ShellEnvVariables.js
ontruck/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; export default () => ( <span id="feature-shell-env-variables"> {process.env.REACT_APP_SHELL_ENV_MESSAGE}. </span> );
src/provider/api-connect.js
gugamm/redux-api-mapper
import React, { Component } from 'react'; import PropTypes from 'prop-types'; /** * Connect a component to api functions * @param {Function} apiToProps * @returns {Function} - Returns a connected component */ function apiConnect(apiToProps) { return function (ConnectComponent) { class ApiConnected extends Component { constructor(props, context) { super(props, context); this.apiProps = apiToProps(context.api, Object.assign({}, props)); } render() { return <ConnectComponent {...this.apiProps} {...this.props} /> } } ApiConnected.contextTypes = { api : PropTypes.object }; return ApiConnected; }; } export default apiConnect;
srcForIOS/components/ButtonRedBorder.js
designrad/Jotunheimen-tracking
import React, { Component } from 'react'; import ReactNative from 'react-native'; const { StyleSheet, Text, View, TouchableOpacity } = ReactNative; /** * ButtonRedBorder component */ export default class ButtonRedBorder extends Component { /** * Render ButtonRedBorder * @return {jsxresult} result in jsx format */ render() { return ( <TouchableOpacity style={styles.button} onPress={this.props.onPress}> <Text style={styles.whiteFont}>{this.props.children}</Text> </TouchableOpacity> ); } } const styles = StyleSheet.create({ button: { padding: 10, alignItems: 'center', borderWidth: 1, borderColor: '#E4151F', marginLeft:20, marginRight:20 }, whiteFont: { color: '#E4151F', fontFamily: 'Roboto-Bold', fontSize: 32 } });
ajax/libs/es6-shim/0.15.0/es6-shim.js
tjbp/cdnjs
// ES6-shim 0.15.0 (c) 2013-2014 Paul Miller (http://paulmillr.com) // ES6-shim may be freely distributed under the MIT license. // For more details and documentation: // https://github.com/paulmillr/es6-shim/ (function(undefined) { 'use strict'; var isCallableWithoutNew = function(func) { try { func(); } catch (e) { return false; } return true; }; var supportsSubclassing = function(C, f) { /* jshint proto:true */ try { var Sub = function() { C.apply(this, arguments); }; if (!Sub.__proto__) { return false; /* skip test on IE < 11 */ } Object.setPrototypeOf(Sub, C); Sub.prototype = Object.create(C.prototype, { constructor: { value: C } }); return f(Sub); } catch (e) { return false; } }; var arePropertyDescriptorsSupported = function() { try { Object.defineProperty({}, 'x', {}); return true; } catch (e) { /* this is IE 8. */ return false; } }; var startsWithRejectsRegex = function() { var rejectsRegex = false; if (String.prototype.startsWith) { try { '/a/'.startsWith(/a/); } catch (e) { /* this is spec compliant */ rejectsRegex = true; } } return rejectsRegex; }; /*jshint evil: true */ var getGlobal = new Function('return this;'); /*jshint evil: false */ var main = function() { var globals = getGlobal(); var global_isFinite = globals.isFinite; var supportsDescriptors = !!Object.defineProperty && arePropertyDescriptorsSupported(); var startsWithIsCompliant = startsWithRejectsRegex(); var _slice = Array.prototype.slice; var _indexOf = String.prototype.indexOf; var _toString = Object.prototype.toString; var _hasOwnProperty = Object.prototype.hasOwnProperty; var ArrayIterator; // make our implementation private // Define configurable, writable and non-enumerable props // if they don’t exist. var defineProperties = function(object, map) { Object.keys(map).forEach(function(name) { var method = map[name]; if (name in object) return; if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, writable: true, value: method }); } else { object[name] = method; } }); }; // Simple shim for Object.create on ES3 browsers // (unlike real shim, no attempt to support `prototype === null`) var create = Object.create || function(prototype, properties) { function Type() {} Type.prototype = prototype; var object = new Type(); if (typeof properties !== "undefined") { defineProperties(object, properties); } return object; }; // This is a private name in the es6 spec, equal to '[Symbol.iterator]' // we're going to use an arbitrary _-prefixed name to make our shims // work properly with each other, even though we don't have full Iterator // support. That is, `Array.from(map.keys())` will work, but we don't // pretend to export a "real" Iterator interface. var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (globals.Set && typeof new globals.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var addIterator = function(prototype, impl) { if (!impl) { impl = function iterator() { return this; }; } var o = {}; o[$iterator$] = impl; defineProperties(prototype, o); }; // taken directly from https://github.com/ljharb/is-arguments/blob/master/index.js // can be replaced with require('is-arguments') if we ever use a build process instead var isArguments = function isArguments(value) { var str = _toString.call(value); var result = str === '[object Arguments]'; if (!result) { result = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && _toString.call(value.callee) === '[object Function]'; } return result; }; var emulateES6construct = function(o) { if (!ES.TypeIsObject(o)) throw new TypeError('bad object'); // es5 approximation to es6 subclass semantics: in es6, 'new Foo' // would invoke Foo.@@create to allocation/initialize the new object. // In es5 we just get the plain object. So if we detect an // uninitialized object, invoke o.constructor.@@create if (!o._es6construct) { if (o.constructor && ES.IsCallable(o.constructor['@@create'])) { o = o.constructor['@@create'](o); } defineProperties(o, { _es6construct: true }); } return o; }; var ES = { CheckObjectCoercible: function(x, optMessage) { /* jshint eqnull:true */ if (x == null) throw new TypeError(optMessage || ('Cannot call method on ' + x)); return x; }, TypeIsObject: function(x) { /* jshint eqnull:true */ // this is expensive when it returns false; use this function // when you expect it to return true in the common case. return x != null && Object(x) === x; }, ToObject: function(o, optMessage) { return Object(ES.CheckObjectCoercible(o, optMessage)); }, IsCallable: function(x) { return typeof x === 'function' && // some versions of IE say that typeof /abc/ === 'function' _toString.call(x) === '[object Function]'; }, ToInt32: function(x) { return x >> 0; }, ToUint32: function(x) { return x >>> 0; }, ToInteger: function(value) { var number = +value; if (Number.isNaN(number)) return 0; if (number === 0 || !Number.isFinite(number)) return number; return Math.sign(number) * Math.floor(Math.abs(number)); }, ToLength: function(value) { var len = ES.ToInteger(value); if (len <= 0) return 0; // includes converting -0 to +0 if (len > Number.MAX_SAFE_INTEGER) return Number.MAX_SAFE_INTEGER; return len; }, SameValue: function(a, b) { if (a === b) { // 0 === -0, but they are not identical. if (a === 0) return 1 / a === 1 / b; return true; } return Number.isNaN(a) && Number.isNaN(b); }, SameValueZero: function(a, b) { // same as SameValue except for SameValueZero(+0, -0) == true return (a === b) || (Number.isNaN(a) && Number.isNaN(b)); }, IsIterable: function(o) { return ES.TypeIsObject(o) && (o[$iterator$] !== undefined || isArguments(o)); }, GetIterator: function(o) { if (isArguments(o)) { // special case support for `arguments` return new ArrayIterator(o, "value"); } var it = o[$iterator$](); if (!ES.TypeIsObject(it)) { throw new TypeError('bad iterator'); } return it; }, IteratorNext: function(it) { var result = (arguments.length > 1) ? it.next(arguments[1]) : it.next(); if (!ES.TypeIsObject(result)) { throw new TypeError('bad iterator'); } return result; }, Construct: function(C, args) { // CreateFromConstructor var obj; if (ES.IsCallable(C['@@create'])) { obj = C['@@create'](); } else { // OrdinaryCreateFromConstructor obj = create(C.prototype || null); } // Mark that we've used the es6 construct path // (see emulateES6construct) defineProperties(obj, { _es6construct: true }); // Call the constructor. var result = C.apply(obj, args); return ES.TypeIsObject(result) ? result : obj; } }; var numberConversion = (function () { // from https://github.com/inexorabletash/polyfill/blob/master/typedarray.js#L176-L266 // with permission and license, per https://twitter.com/inexorabletash/status/372206509540659200 function roundToEven(n) { var w = Math.floor(n), f = n - w; if (f < 0.5) { return w; } if (f > 0.5) { return w + 1; } return w % 2 ? w + 1 : w; } function packIEEE754(v, ebits, fbits) { var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str, bytes; // Compute sign, exponent, fraction if (v !== v) { // NaN // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping e = (1 << ebits) - 1; f = Math.pow(2, fbits - 1); s = 0; } else if (v === Infinity || v === -Infinity) { e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; } else if (v === 0) { e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; } else { s = v < 0; v = Math.abs(v); if (v >= Math.pow(2, 1 - bias)) { e = Math.min(Math.floor(Math.log(v) / Math.LN2), 1023); f = roundToEven(v / Math.pow(2, e) * Math.pow(2, fbits)); if (f / Math.pow(2, fbits) >= 2) { e = e + 1; f = 1; } if (e > bias) { // Overflow e = (1 << ebits) - 1; f = 0; } else { // Normal e = e + bias; f = f - Math.pow(2, fbits); } } else { // Subnormal e = 0; f = roundToEven(v / Math.pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); str = bits.join(''); // Bits to bytes bytes = []; while (str.length) { bytes.push(parseInt(str.slice(0, 8), 2)); str = str.slice(8); } return bytes; } function unpackIEEE754(bytes, ebits, fbits) { // Bytes to bits var bits = [], i, j, b, str, bias, s, e, f; for (i = bytes.length; i; i -= 1) { b = bytes[i - 1]; for (j = 8; j; j -= 1) { bits.push(b % 2 ? 1 : 0); b = b >> 1; } } bits.reverse(); str = bits.join(''); // Unpack sign, exponent, fraction bias = (1 << (ebits - 1)) - 1; s = parseInt(str.slice(0, 1), 2) ? -1 : 1; e = parseInt(str.slice(1, 1 + ebits), 2); f = parseInt(str.slice(1 + ebits), 2); // Produce number if (e === (1 << ebits) - 1) { return f !== 0 ? NaN : s * Infinity; } else if (e > 0) { // Normalized return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits)); } else if (f !== 0) { // Denormalized return s * Math.pow(2, -(bias - 1)) * (f / Math.pow(2, fbits)); } else { return s < 0 ? -0 : 0; } } function unpackFloat64(b) { return unpackIEEE754(b, 11, 52); } function packFloat64(v) { return packIEEE754(v, 11, 52); } function unpackFloat32(b) { return unpackIEEE754(b, 8, 23); } function packFloat32(v) { return packIEEE754(v, 8, 23); } var conversions = { toFloat32: function (num) { return unpackFloat32(packFloat32(num)); } }; if (typeof Float32Array !== 'undefined') { var float32array = new Float32Array(1); conversions.toFloat32 = function (num) { float32array[0] = num; return float32array[0]; }; } return conversions; }()); defineProperties(String, { fromCodePoint: function(_) { // length = 1 var points = _slice.call(arguments, 0, arguments.length); var result = []; var next; for (var i = 0, length = points.length; i < length; i++) { next = Number(points[i]); if (!ES.SameValue(next, ES.ToInteger(next)) || next < 0 || next > 0x10FFFF) { throw new RangeError('Invalid code point ' + next); } if (next < 0x10000) { result.push(String.fromCharCode(next)); } else { next -= 0x10000; result.push(String.fromCharCode((next >> 10) + 0xD800)); result.push(String.fromCharCode((next % 0x400) + 0xDC00)); } } return result.join(''); }, raw: function(callSite) { // raw.length===1 var substitutions = _slice.call(arguments, 1, arguments.length); var cooked = ES.ToObject(callSite, 'bad callSite'); var rawValue = cooked.raw; var raw = ES.ToObject(rawValue, 'bad raw value'); var len = Object.keys(raw).length; var literalsegments = ES.ToLength(len); if (literalsegments === 0) { return ''; } var stringElements = []; var nextIndex = 0; var nextKey, next, nextSeg, nextSub; while (nextIndex < literalsegments) { nextKey = String(nextIndex); next = raw[nextKey]; nextSeg = String(next); stringElements.push(nextSeg); if (nextIndex + 1 >= literalsegments) { break; } next = substitutions[nextKey]; if (next === undefined) { break; } nextSub = String(next); stringElements.push(nextSub); nextIndex++; } return stringElements.join(''); } }); var StringShims = { // Fast repeat, uses the `Exponentiation by squaring` algorithm. // Perf: http://jsperf.com/string-repeat2/2 repeat: (function() { var repeat = function(s, times) { if (times < 1) return ''; if (times % 2) return repeat(s, times - 1) + s; var half = repeat(s, times / 2); return half + half; }; return function(times) { var thisStr = String(ES.CheckObjectCoercible(this)); times = ES.ToInteger(times); if (times < 0 || times === Infinity) { throw new RangeError('Invalid String#repeat value'); } return repeat(thisStr, times); }; })(), startsWith: function(searchStr) { var thisStr = String(ES.CheckObjectCoercible(this)); if (_toString.call(searchStr) === '[object RegExp]') throw new TypeError('Cannot call method "startsWith" with a regex'); searchStr = String(searchStr); var startArg = arguments.length > 1 ? arguments[1] : undefined; var start = Math.max(ES.ToInteger(startArg), 0); return thisStr.slice(start, start + searchStr.length) === searchStr; }, endsWith: function(searchStr) { var thisStr = String(ES.CheckObjectCoercible(this)); if (_toString.call(searchStr) === '[object RegExp]') throw new TypeError('Cannot call method "endsWith" with a regex'); searchStr = String(searchStr); var thisLen = thisStr.length; var posArg = arguments.length > 1 ? arguments[1] : undefined; var pos = posArg === undefined ? thisLen : ES.ToInteger(posArg); var end = Math.min(Math.max(pos, 0), thisLen); return thisStr.slice(end - searchStr.length, end) === searchStr; }, contains: function(searchString) { var position = arguments.length > 1 ? arguments[1] : undefined; // Somehow this trick makes method 100% compat with the spec. return _indexOf.call(this, searchString, position) !== -1; }, codePointAt: function(pos) { var thisStr = String(ES.CheckObjectCoercible(this)); var position = ES.ToInteger(pos); var length = thisStr.length; if (position < 0 || position >= length) return undefined; var first = thisStr.charCodeAt(position); var isEnd = (position + 1 === length); if (first < 0xD800 || first > 0xDBFF || isEnd) return first; var second = thisStr.charCodeAt(position + 1); if (second < 0xDC00 || second > 0xDFFF) return first; return ((first - 0xD800) * 1024) + (second - 0xDC00) + 0x10000; } }; defineProperties(String.prototype, StringShims); var hasStringTrimBug = '\u0085'.trim().length !== 1; if (hasStringTrimBug) { var originalStringTrim = String.prototype.trim; delete String.prototype.trim; // whitespace from: http://es5.github.io/#x15.5.4.20 // implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324 var ws = [ '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', '\u2029\uFEFF' ].join(''); var trimBeginRegexp = new RegExp('^[' + ws + '][' + ws + ']*'); var trimEndRegexp = new RegExp('[' + ws + '][' + ws + ']*$'); defineProperties(String.prototype, { trim: function() { if (this === undefined || this === null) { throw new TypeError("can't convert " + this + " to object"); } return String(this) .replace(trimBeginRegexp, "") .replace(trimEndRegexp, ""); } }); } // see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype-@@iterator var StringIterator = function(s) { this._s = String(ES.CheckObjectCoercible(s)); this._i = 0; }; StringIterator.prototype.next = function() { var s = this._s, i = this._i; if (s === undefined || i >= s.length) { this._s = undefined; return { value: undefined, done: true }; } var first = s.charCodeAt(i), second, len; if (first < 0xD800 || first > 0xDBFF || (i+1) == s.length) { len = 1; } else { second = s.charCodeAt(i+1); len = (second < 0xDC00 || second > 0xDFFF) ? 1 : 2; } this._i = i + len; return { value: s.substr(i, len), done: false }; }; addIterator(StringIterator.prototype); addIterator(String.prototype, function() { return new StringIterator(this); }); if (!startsWithIsCompliant) { // Firefox has a noncompliant startsWith implementation String.prototype.startsWith = StringShims.startsWith; String.prototype.endsWith = StringShims.endsWith; } defineProperties(Array, { from: function(iterable) { var mapFn = arguments.length > 1 ? arguments[1] : undefined; var thisArg = arguments.length > 2 ? arguments[2] : undefined; var list = ES.ToObject(iterable, 'bad iterable'); if (mapFn !== undefined && !ES.IsCallable(mapFn)) { throw new TypeError('Array.from: when provided, the second argument must be a function'); } var usingIterator = ES.IsIterable(list); // does the spec really mean that Arrays should use ArrayIterator? // https://bugs.ecmascript.org/show_bug.cgi?id=2416 //if (Array.isArray(list)) { usingIterator=false; } var length = usingIterator ? 0 : ES.ToLength(list.length); var result = ES.IsCallable(this) ? Object(usingIterator ? new this() : new this(length)) : new Array(length); var it = usingIterator ? ES.GetIterator(list) : null; var value; for (var i = 0; usingIterator || (i < length); i++) { if (usingIterator) { value = ES.IteratorNext(it); if (value.done) { length = i; break; } value = value.value; } else { value = list[i]; } if (mapFn) { result[i] = thisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i); } else { result[i] = value; } } result.length = length; return result; }, of: function() { return Array.from(arguments); } }); // Our ArrayIterator is private; see // https://github.com/paulmillr/es6-shim/issues/252 ArrayIterator = function(array, kind) { this.i = 0; this.array = array; this.kind = kind; }; defineProperties(ArrayIterator.prototype, { next: function() { var i = this.i, array = this.array; if (i === undefined || this.kind === undefined) { throw new TypeError('Not an ArrayIterator'); } if (array!==undefined) { var len = ES.ToLength(array.length); for (; i < len; i++) { var kind = this.kind; var retval; if (kind === "key") { retval = i; } else if (kind === "value") { retval = array[i]; } else if (kind === "entry") { retval = [i, array[i]]; } this.i = i + 1; return { value: retval, done: false }; } } this.array = undefined; return { value: undefined, done: true }; } }); addIterator(ArrayIterator.prototype); defineProperties(Array.prototype, { copyWithin: function(target, start) { var end = arguments[2]; // copyWithin.length must be 2 var o = ES.ToObject(this); var len = ES.ToLength(o.length); target = ES.ToInteger(target); start = ES.ToInteger(start); var to = target < 0 ? Math.max(len + target, 0) : Math.min(target, len); var from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); end = (end===undefined) ? len : ES.ToInteger(end); var fin = end < 0 ? Math.max(len + end, 0) : Math.min(end, len); var count = Math.min(fin - from, len - to); var direction = 1; if (from < to && to < (from + count)) { direction = -1; from += count - 1; to += count - 1; } while (count > 0) { if (_hasOwnProperty.call(o, from)) { o[to] = o[from]; } else { delete o[from]; } from += direction; to += direction; count -= 1; } return o; }, fill: function(value) { var start = arguments.length > 1 ? arguments[1] : undefined; var end = arguments.length > 2 ? arguments[2] : undefined; var O = ES.ToObject(this); var len = ES.ToLength(O.length); start = ES.ToInteger(start === undefined ? 0 : start); end = ES.ToInteger(end === undefined ? len : end); var relativeStart = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); var relativeEnd = end < 0 ? len + end : end; for (var i = relativeStart; i < len && i < relativeEnd; ++i) { O[i] = value; } return O; }, find: function(predicate) { var list = ES.ToObject(this); var length = ES.ToLength(list.length); if (!ES.IsCallable(predicate)) { throw new TypeError('Array#find: predicate must be a function'); } var thisArg = arguments[1]; for (var i = 0, value; i < length; i++) { if (i in list) { value = list[i]; if (predicate.call(thisArg, value, i, list)) return value; } } return undefined; }, findIndex: function(predicate) { var list = ES.ToObject(this); var length = ES.ToLength(list.length); if (!ES.IsCallable(predicate)) { throw new TypeError('Array#findIndex: predicate must be a function'); } var thisArg = arguments[1]; for (var i = 0; i < length; i++) { if (i in list) { if (predicate.call(thisArg, list[i], i, list)) return i; } } return -1; }, keys: function() { return new ArrayIterator(this, "key"); }, values: function() { return new ArrayIterator(this, "value"); }, entries: function() { return new ArrayIterator(this, "entry"); } }); addIterator(Array.prototype, function() { return this.values(); }); // Chrome defines keys/values/entries on Array, but doesn't give us // any way to identify its iterator. So add our own shimmed field. if (Object.getPrototypeOf) { addIterator(Object.getPrototypeOf([].values())); } var maxSafeInteger = Math.pow(2, 53) - 1; defineProperties(Number, { MAX_SAFE_INTEGER: maxSafeInteger, MIN_SAFE_INTEGER: -maxSafeInteger, EPSILON: 2.220446049250313e-16, parseInt: globals.parseInt, parseFloat: globals.parseFloat, isFinite: function(value) { return typeof value === 'number' && global_isFinite(value); }, isInteger: function(value) { return Number.isFinite(value) && ES.ToInteger(value) === value; }, isSafeInteger: function(value) { return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER; }, isNaN: function(value) { // NaN !== NaN, but they are identical. // NaNs are the only non-reflexive value, i.e., if x !== x, // then x is NaN. // isNaN is broken: it converts its argument to number, so // isNaN('foo') => true return value !== value; } }); if (supportsDescriptors) { defineProperties(Object, { getPropertyDescriptor: function(subject, name) { var pd = Object.getOwnPropertyDescriptor(subject, name); var proto = Object.getPrototypeOf(subject); while (pd === undefined && proto !== null) { pd = Object.getOwnPropertyDescriptor(proto, name); proto = Object.getPrototypeOf(proto); } return pd; }, getPropertyNames: function(subject) { var result = Object.getOwnPropertyNames(subject); var proto = Object.getPrototypeOf(subject); var addProperty = function(property) { if (result.indexOf(property) === -1) { result.push(property); } }; while (proto !== null) { Object.getOwnPropertyNames(proto).forEach(addProperty); proto = Object.getPrototypeOf(proto); } return result; } }); defineProperties(Object, { // 19.1.3.1 assign: function(target, source) { if (!ES.TypeIsObject(target)) { throw new TypeError('target must be an object'); } return Array.prototype.reduce.call(arguments, function(target, source) { return Object.keys(Object(source)).reduce(function(target, key) { target[key] = source[key]; return target; }, target); }); }, is: function(a, b) { return ES.SameValue(a, b); }, // 19.1.3.9 // shim from https://gist.github.com/WebReflection/5593554 setPrototypeOf: (function(Object, magic) { var set; var checkArgs = function(O, proto) { if (!ES.TypeIsObject(O)) { throw new TypeError('cannot set prototype on a non-object'); } if (!(proto===null || ES.TypeIsObject(proto))) { throw new TypeError('can only set prototype to an object or null'+proto); } }; var setPrototypeOf = function(O, proto) { checkArgs(O, proto); set.call(O, proto); return O; }; try { // this works already in Firefox and Safari set = Object.getOwnPropertyDescriptor(Object.prototype, magic).set; set.call({}, null); } catch (e) { if (Object.prototype !== {}[magic]) { // IE < 11 cannot be shimmed return; } // probably Chrome or some old Mobile stock browser set = function(proto) { this[magic] = proto; }; // please note that this will **not** work // in those browsers that do not inherit // __proto__ by mistake from Object.prototype // in these cases we should probably throw an error // or at least be informed about the issue setPrototypeOf.polyfill = setPrototypeOf( setPrototypeOf({}, null), Object.prototype ) instanceof Object; // setPrototypeOf.polyfill === true means it works as meant // setPrototypeOf.polyfill === false means it's not 100% reliable // setPrototypeOf.polyfill === undefined // or // setPrototypeOf.polyfill == null means it's not a polyfill // which means it works as expected // we can even delete Object.prototype.__proto__; } return setPrototypeOf; })(Object, '__proto__') }); } // Workaround bug in Opera 12 where setPrototypeOf(x, null) doesn't work, // but Object.create(null) does. if (Object.setPrototypeOf && Object.getPrototypeOf && Object.getPrototypeOf(Object.setPrototypeOf({}, null)) !== null && Object.getPrototypeOf(Object.create(null)) === null) { (function() { var FAKENULL = Object.create(null); var gpo = Object.getPrototypeOf, spo = Object.setPrototypeOf; Object.getPrototypeOf = function(o) { var result = gpo(o); return result === FAKENULL ? null : result; }; Object.setPrototypeOf = function(o, p) { if (p === null) { p = FAKENULL; } return spo(o, p); }; Object.setPrototypeOf.polyfill = false; })(); } try { Object.keys('foo'); } catch (e) { var originalObjectKeys = Object.keys; Object.keys = function (obj) { return originalObjectKeys(ES.ToObject(obj)); }; } var MathShims = { acosh: function(value) { value = Number(value); if (Number.isNaN(value) || value < 1) return NaN; if (value === 1) return 0; if (value === Infinity) return value; return Math.log(value + Math.sqrt(value * value - 1)); }, asinh: function(value) { value = Number(value); if (value === 0 || !global_isFinite(value)) { return value; } return value < 0 ? -Math.asinh(-value) : Math.log(value + Math.sqrt(value * value + 1)); }, atanh: function(value) { value = Number(value); if (Number.isNaN(value) || value < -1 || value > 1) { return NaN; } if (value === -1) return -Infinity; if (value === 1) return Infinity; if (value === 0) return value; return 0.5 * Math.log((1 + value) / (1 - value)); }, cbrt: function(value) { value = Number(value); if (value === 0) return value; var negate = value < 0, result; if (negate) value = -value; result = Math.pow(value, 1/3); return negate ? -result : result; }, clz32: function(value) { // See https://bugs.ecmascript.org/show_bug.cgi?id=2465 value = Number(value); var number = ES.ToUint32(value); if (number === 0) { return 32; } return 32 - (number).toString(2).length; }, cosh: function(value) { value = Number(value); if (value === 0) return 1; // +0 or -0 if (Number.isNaN(value)) return NaN; if (!global_isFinite(value)) return Infinity; if (value < 0) value = -value; if (value > 21) return Math.exp(value) / 2; return (Math.exp(value) + Math.exp(-value)) / 2; }, expm1: function(value) { value = Number(value); if (value === -Infinity) return -1; if (!global_isFinite(value) || value === 0) return value; return Math.exp(value) - 1; }, hypot: function(x, y) { var anyNaN = false; var allZero = true; var anyInfinity = false; var numbers = []; Array.prototype.every.call(arguments, function(arg) { var num = Number(arg); if (Number.isNaN(num)) anyNaN = true; else if (num === Infinity || num === -Infinity) anyInfinity = true; else if (num !== 0) allZero = false; if (anyInfinity) { return false; } else if (!anyNaN) { numbers.push(Math.abs(num)); } return true; }); if (anyInfinity) return Infinity; if (anyNaN) return NaN; if (allZero) return 0; numbers.sort(function (a, b) { return b - a; }); var largest = numbers[0]; var divided = numbers.map(function (number) { return number / largest; }); var sum = divided.reduce(function (sum, number) { return sum += number * number; }, 0); return largest * Math.sqrt(sum); }, log2: function(value) { return Math.log(value) * Math.LOG2E; }, log10: function(value) { return Math.log(value) * Math.LOG10E; }, log1p: function(value) { value = Number(value); if (value < -1 || Number.isNaN(value)) return NaN; if (value === 0 || value === Infinity) return value; if (value === -1) return -Infinity; var result = 0; var n = 50; if (value < 0 || value > 1) return Math.log(1 + value); for (var i = 1; i < n; i++) { if ((i % 2) === 0) { result -= Math.pow(value, i) / i; } else { result += Math.pow(value, i) / i; } } return result; }, sign: function(value) { var number = +value; if (number === 0) return number; if (Number.isNaN(number)) return number; return number < 0 ? -1 : 1; }, sinh: function(value) { value = Number(value); if (!global_isFinite(value) || value === 0) return value; return (Math.exp(value) - Math.exp(-value)) / 2; }, tanh: function(value) { value = Number(value); if (Number.isNaN(value) || value === 0) return value; if (value === Infinity) return 1; if (value === -Infinity) return -1; return (Math.exp(value) - Math.exp(-value)) / (Math.exp(value) + Math.exp(-value)); }, trunc: function(value) { var number = Number(value); return number < 0 ? -Math.floor(-number) : Math.floor(number); }, imul: function(x, y) { // taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul x = ES.ToUint32(x); y = ES.ToUint32(y); var ah = (x >>> 16) & 0xffff; var al = x & 0xffff; var bh = (y >>> 16) & 0xffff; var bl = y & 0xffff; // the shift by 0 fixes the sign on the high part // the final |0 converts the unsigned value into a signed value return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0)|0); }, fround: function(x) { if (x === 0 || x === Infinity || x === -Infinity || Number.isNaN(x)) { return x; } var num = Number(x); return numberConversion.toFloat32(num); } }; defineProperties(Math, MathShims); if (Math.imul(0xffffffff, 5) !== -5) { // Safari 6.1, at least, reports "0" for this value Math.imul = MathShims.imul; } // Promises // Simplest possible implementation; use a 3rd-party library if you // want the best possible speed and/or long stack traces. var PromiseShim = (function() { var Promise, Promise$prototype; ES.IsPromise = function(promise) { if (!ES.TypeIsObject(promise)) { return false; } if (!promise._promiseConstructor) { // _promiseConstructor is a bit more unique than _status, so we'll // check that instead of the [[PromiseStatus]] internal field. return false; } if (promise._status === undefined) { return false; // uninitialized } return true; }; // "PromiseCapability" in the spec is what most promise implementations // call a "deferred". var PromiseCapability = function(C) { if (!ES.IsCallable(C)) { throw new TypeError('bad promise constructor'); } var capability = this; var resolver = function(resolve, reject) { capability.resolve = resolve; capability.reject = reject; }; capability.promise = ES.Construct(C, [resolver]); // see https://bugs.ecmascript.org/show_bug.cgi?id=2478 if (!capability.promise._es6construct) { throw new TypeError('bad promise constructor'); } if (!(ES.IsCallable(capability.resolve) && ES.IsCallable(capability.reject))) { throw new TypeError('bad promise constructor'); } }; // find an appropriate setImmediate-alike var setTimeout = globals.setTimeout; var makeZeroTimeout; if (typeof window !== 'undefined' && ES.IsCallable(window.postMessage)) { makeZeroTimeout = function() { // from http://dbaron.org/log/20100309-faster-timeouts var timeouts = []; var messageName = "zero-timeout-message"; var setZeroTimeout = function(fn) { timeouts.push(fn); window.postMessage(messageName, "*"); }; var handleMessage = function(event) { if (event.source == window && event.data == messageName) { event.stopPropagation(); if (timeouts.length === 0) { return; } var fn = timeouts.shift(); fn(); } }; window.addEventListener("message", handleMessage, true); return setZeroTimeout; }; } var makePromiseAsap = function() { // An efficient task-scheduler based on a pre-existing Promise // implementation, which we can use even if we override the // global Promise below (in order to workaround bugs) // https://github.com/Raynos/observ-hash/issues/2#issuecomment-35857671 var P = globals.Promise; return P && P.resolve && function(task) { return P.resolve().then(task); }; }; var enqueue = ES.IsCallable(globals.setImmediate) ? globals.setImmediate.bind(globals) : typeof process === 'object' && process.nextTick ? process.nextTick : makePromiseAsap() || (ES.IsCallable(makeZeroTimeout) ? makeZeroTimeout() : function(task) { setTimeout(task, 0); }); // fallback var triggerPromiseReactions = function(reactions, x) { reactions.forEach(function(reaction) { enqueue(function() { // PromiseReactionTask var handler = reaction.handler; var capability = reaction.capability; var resolve = capability.resolve; var reject = capability.reject; try { var result = handler(x); if (result === capability.promise) { throw new TypeError('self resolution'); } var updateResult = updatePromiseFromPotentialThenable(result, capability); if (!updateResult) { resolve(result); } } catch (e) { reject(e); } }); }); }; var updatePromiseFromPotentialThenable = function(x, capability) { if (!ES.TypeIsObject(x)) { return false; } var resolve = capability.resolve; var reject = capability.reject; try { var then = x.then; // only one invocation of accessor if (!ES.IsCallable(then)) { return false; } then.call(x, resolve, reject); } catch(e) { reject(e); } return true; }; var promiseResolutionHandler = function(promise, onFulfilled, onRejected){ return function(x) { if (x === promise) { return onRejected(new TypeError('self resolution')); } var C = promise._promiseConstructor; var capability = new PromiseCapability(C); var updateResult = updatePromiseFromPotentialThenable(x, capability); if (updateResult) { return capability.promise.then(onFulfilled, onRejected); } else { return onFulfilled(x); } }; }; Promise = function(resolver) { var promise = this; promise = emulateES6construct(promise); if (!promise._promiseConstructor) { // we use _promiseConstructor as a stand-in for the internal // [[PromiseStatus]] field; it's a little more unique. throw new TypeError('bad promise'); } if (promise._status !== undefined) { throw new TypeError('promise already initialized'); } // see https://bugs.ecmascript.org/show_bug.cgi?id=2482 if (!ES.IsCallable(resolver)) { throw new TypeError('not a valid resolver'); } promise._status = 'unresolved'; promise._resolveReactions = []; promise._rejectReactions = []; var resolve = function(resolution) { if (promise._status !== 'unresolved') { return; } var reactions = promise._resolveReactions; promise._result = resolution; promise._resolveReactions = undefined; promise._rejectReactions = undefined; promise._status = 'has-resolution'; triggerPromiseReactions(reactions, resolution); }; var reject = function(reason) { if (promise._status !== 'unresolved') { return; } var reactions = promise._rejectReactions; promise._result = reason; promise._resolveReactions = undefined; promise._rejectReactions = undefined; promise._status = 'has-rejection'; triggerPromiseReactions(reactions, reason); }; try { resolver(resolve, reject); } catch (e) { reject(e); } return promise; }; Promise$prototype = Promise.prototype; defineProperties(Promise, { '@@create': function(obj) { var constructor = this; // AllocatePromise // The `obj` parameter is a hack we use for es5 // compatibility. var prototype = constructor.prototype || Promise$prototype; obj = obj || create(prototype); defineProperties(obj, { _status: undefined, _result: undefined, _resolveReactions: undefined, _rejectReactions: undefined, _promiseConstructor: undefined }); obj._promiseConstructor = constructor; return obj; } }); var _promiseAllResolver = function(index, values, capability, remaining) { var done = false; return function(x) { if (done) { return; } // protect against being called multiple times done = true; values[index] = x; if ((--remaining.count) === 0) { var resolve = capability.resolve; resolve(values); // call w/ this===undefined } }; }; Promise.all = function(iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); var values = [], remaining = { count: 1 }; for (var index = 0; ; index++) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextPromise = C.resolve(next.value); var resolveElement = _promiseAllResolver( index, values, capability, remaining ); remaining.count++; nextPromise.then(resolveElement, capability.reject); } if ((--remaining.count) === 0) { resolve(values); // call w/ this===undefined } } catch (e) { reject(e); } return capability.promise; }; Promise.race = function(iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); while (true) { var next = ES.IteratorNext(it); if (next.done) { // If iterable has no items, resulting promise will never // resolve; see: // https://github.com/domenic/promises-unwrapping/issues/75 // https://bugs.ecmascript.org/show_bug.cgi?id=2515 break; } var nextPromise = C.resolve(next.value); nextPromise.then(resolve, reject); } } catch (e) { reject(e); } return capability.promise; }; Promise.reject = function(reason) { var C = this; var capability = new PromiseCapability(C); var reject = capability.reject; reject(reason); // call with this===undefined return capability.promise; }; Promise.resolve = function(v) { var C = this; if (ES.IsPromise(v)) { var constructor = v._promiseConstructor; if (constructor === C) { return v; } } var capability = new PromiseCapability(C); var resolve = capability.resolve; resolve(v); // call with this===undefined return capability.promise; }; Promise.prototype['catch'] = function( onRejected ) { return this.then(undefined, onRejected); }; Promise.prototype.then = function( onFulfilled, onRejected ) { var promise = this; if (!ES.IsPromise(promise)) { throw new TypeError('not a promise'); } // this.constructor not this._promiseConstructor; see // https://bugs.ecmascript.org/show_bug.cgi?id=2513 var C = this.constructor; var capability = new PromiseCapability(C); if (!ES.IsCallable(onRejected)) { onRejected = function(e) { throw e; }; } if (!ES.IsCallable(onFulfilled)) { onFulfilled = function(x) { return x; }; } var resolutionHandler = promiseResolutionHandler(promise, onFulfilled, onRejected); var resolveReaction = { capability: capability, handler: resolutionHandler }; var rejectReaction = { capability: capability, handler: onRejected }; switch (promise._status) { case 'unresolved': promise._resolveReactions.push(resolveReaction); promise._rejectReactions.push(rejectReaction); break; case 'has-resolution': triggerPromiseReactions([resolveReaction], promise._result); break; case 'has-rejection': triggerPromiseReactions([rejectReaction], promise._result); break; default: throw new TypeError('unexpected'); } return capability.promise; }; return Promise; })(); // export the Promise constructor. defineProperties(globals, { Promise: PromiseShim }); // In Chrome 33 (and thereabouts) Promise is defined, but the // implementation is buggy in a number of ways. Let's check subclassing // support to see if we have a buggy implementation. var promiseSupportsSubclassing = supportsSubclassing(globals.Promise, function(S) { return S.resolve(42) instanceof S; }); var promiseIgnoresNonFunctionThenCallbacks = (function () { try { globals.Promise.reject(42).then(null, 5).then(null, function () {}); return true; } catch (ex) { return false; } }()); if (!promiseSupportsSubclassing || !promiseIgnoresNonFunctionThenCallbacks) { globals.Promise = PromiseShim; } // Map and Set require a true ES5 environment if (supportsDescriptors) { var fastkey = function fastkey(key) { var type = typeof key; if (type === 'string') { return '$' + key; } else if (type === 'number') { // note that -0 will get coerced to "0" when used as a property key return key; } return null; }; var emptyObject = function emptyObject() { // accomodate some older not-quite-ES5 browsers return Object.create ? Object.create(null) : {}; }; var collectionShims = { Map: (function() { var empty = {}; function MapEntry(key, value) { this.key = key; this.value = value; this.next = null; this.prev = null; } MapEntry.prototype.isRemoved = function() { return this.key === empty; }; function MapIterator(map, kind) { this.head = map._head; this.i = this.head; this.kind = kind; } MapIterator.prototype = { next: function() { var i = this.i, kind = this.kind, head = this.head, result; if (this.i === undefined) { return { value: undefined, done: true }; } while (i.isRemoved() && i !== head) { // back up off of removed entries i = i.prev; } // advance to next unreturned element. while (i.next !== head) { i = i.next; if (!i.isRemoved()) { if (kind === "key") { result = i.key; } else if (kind === "value") { result = i.value; } else { result = [i.key, i.value]; } this.i = i; return { value: result, done: false }; } } // once the iterator is done, it is done forever. this.i = undefined; return { value: undefined, done: true }; } }; addIterator(MapIterator.prototype); function Map(iterable) { var map = this; map = emulateES6construct(map); if (!map._es6map) { throw new TypeError('bad map'); } var head = new MapEntry(null, null); // circular doubly-linked list. head.next = head.prev = head; defineProperties(map, { '_head': head, '_storage': emptyObject(), '_size': 0 }); // Optionally initialize map from iterable if (iterable !== undefined && iterable !== null) { var it = ES.GetIterator(iterable); var adder = map.set; if (!ES.IsCallable(adder)) { throw new TypeError('bad map'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; if (!ES.TypeIsObject(nextItem)) { throw new TypeError('expected iterable of pairs'); } adder.call(map, nextItem[0], nextItem[1]); } } return map; } var Map$prototype = Map.prototype; defineProperties(Map, { '@@create': function(obj) { var constructor = this; var prototype = constructor.prototype || Map$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6map: true }); return obj; } }); Object.defineProperty(Map.prototype, 'size', { configurable: true, enumerable: false, get: function() { if (typeof this._size === 'undefined') { throw new TypeError('size method called on incompatible Map'); } return this._size; } }); defineProperties(Map.prototype, { get: function(key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path var entry = this._storage[fkey]; return entry ? entry.value : undefined; } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return i.value; } } return undefined; }, has: function(key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path return typeof this._storage[fkey] !== 'undefined'; } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return true; } } return false; }, set: function(key, value) { var head = this._head, i = head, entry; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] !== 'undefined') { this._storage[fkey].value = value; return; } else { entry = this._storage[fkey] = new MapEntry(key, value); i = head.prev; // fall through } } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.value = value; return; } } entry = entry || new MapEntry(key, value); if (ES.SameValue(-0, key)) { entry.key = +0; // coerce -0 to +0 in entry } entry.next = this._head; entry.prev = this._head.prev; entry.prev.next = entry; entry.next.prev = entry; this._size += 1; }, 'delete': function(key) { var head = this._head, i = head; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] === 'undefined') { return false; } i = this._storage[fkey].prev; delete this._storage[fkey]; // fall through } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.key = i.value = empty; i.prev.next = i.next; i.next.prev = i.prev; this._size -= 1; return true; } } return false; }, clear: function() { this._size = 0; this._storage = emptyObject(); var head = this._head, i = head, p = i.next; while ((i = p) !== head) { i.key = i.value = empty; p = i.next; i.next = i.prev = head; } head.next = head.prev = head; }, keys: function() { return new MapIterator(this, "key"); }, values: function() { return new MapIterator(this, "value"); }, entries: function() { return new MapIterator(this, "key+value"); }, forEach: function(callback) { var context = arguments.length > 1 ? arguments[1] : null; var it = this.entries(); for (var entry = it.next(); !entry.done; entry = it.next()) { callback.call(context, entry.value[1], entry.value[0], this); } } }); addIterator(Map.prototype, function() { return this.entries(); }); return Map; })(), Set: (function() { // Creating a Map is expensive. To speed up the common case of // Sets containing only string or numeric keys, we use an object // as backing storage and lazily create a full Map only when // required. var SetShim = function Set(iterable) { var set = this; set = emulateES6construct(set); if (!set._es6set) { throw new TypeError('bad set'); } defineProperties(set, { '[[SetData]]': null, '_storage': emptyObject() }); // Optionally initialize map from iterable if (iterable !== undefined && iterable !== null) { var it = ES.GetIterator(iterable); var adder = set.add; if (!ES.IsCallable(adder)) { throw new TypeError('bad set'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; adder.call(set, nextItem); } } return set; }; var Set$prototype = SetShim.prototype; defineProperties(SetShim, { '@@create': function(obj) { var constructor = this; var prototype = constructor.prototype || Set$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6set: true }); return obj; } }); // Switch from the object backing storage to a full Map. var ensureMap = function ensureMap(set) { if (!set['[[SetData]]']) { var m = set['[[SetData]]'] = new collectionShims.Map(); Object.keys(set._storage).forEach(function(k) { // fast check for leading '$' if (k.charCodeAt(0) === 36) { k = k.slice(1); } else { k = +k; } m.set(k, k); }); set._storage = null; // free old backing storage } }; Object.defineProperty(SetShim.prototype, 'size', { configurable: true, enumerable: false, get: function() { if (typeof this._storage === 'undefined') { // https://github.com/paulmillr/es6-shim/issues/176 throw new TypeError('size method called on incompatible Set'); } ensureMap(this); return this['[[SetData]]'].size; } }); defineProperties(SetShim.prototype, { has: function(key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { return !!this._storage[fkey]; } ensureMap(this); return this['[[SetData]]'].has(key); }, add: function(key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { this._storage[fkey]=true; return; } ensureMap(this); return this['[[SetData]]'].set(key, key); }, 'delete': function(key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { delete this._storage[fkey]; return; } ensureMap(this); return this['[[SetData]]']['delete'](key); }, clear: function() { if (this._storage) { this._storage = emptyObject(); return; } return this['[[SetData]]'].clear(); }, keys: function() { ensureMap(this); return this['[[SetData]]'].keys(); }, values: function() { ensureMap(this); return this['[[SetData]]'].values(); }, entries: function() { ensureMap(this); return this['[[SetData]]'].entries(); }, forEach: function(callback) { var context = arguments.length > 1 ? arguments[1] : null; var entireSet = this; ensureMap(this); this['[[SetData]]'].forEach(function(value, key) { callback.call(context, key, key, entireSet); }); } }); addIterator(SetShim.prototype, function() { return this.values(); }); return SetShim; })() }; defineProperties(globals, collectionShims); if (globals.Map || globals.Set) { /* - In Firefox < 23, Map#size is a function. - In all current Firefox, Set#entries/keys/values & Map#clear do not exist - https://bugzilla.mozilla.org/show_bug.cgi?id=869996 - In Firefox 24, Map and Set do not implement forEach - In Firefox 25 at least, Map and Set are callable without "new" */ if ( typeof globals.Map.prototype.clear !== 'function' || new globals.Set().size !== 0 || new globals.Map().size !== 0 || typeof globals.Map.prototype.keys !== 'function' || typeof globals.Set.prototype.keys !== 'function' || typeof globals.Map.prototype.forEach !== 'function' || typeof globals.Set.prototype.forEach !== 'function' || isCallableWithoutNew(globals.Map) || isCallableWithoutNew(globals.Set) || !supportsSubclassing(globals.Map, function(M) { return (new M([])) instanceof M; }) ) { globals.Map = collectionShims.Map; globals.Set = collectionShims.Set; } } // Shim incomplete iterator implementations. addIterator(Object.getPrototypeOf((new globals.Map()).keys())); addIterator(Object.getPrototypeOf((new globals.Set()).keys())); } }; if (typeof define === 'function' && define.amd) { define(main); // RequireJS } else { main(); // CommonJS and <script> } })();
src/components/Common/ResourceCheckBox.js
shinja/react-redux-c3
import React from 'react' import CSSModules from 'react-css-modules' import styles from './resourcecheckbox.cssmodule.scss' const ResourceCheckBox = ({ resource, toggle }) => ( <li styleName='li'> <span styleName={resource.name.toUpperCase()} onClick={() => toggle(resource.name)}> <i className='fa fa-check' styleName={!resource.checked && 'UnSelected'} aria-hidden='true' /> </span> {resource.name.toUpperCase()} </li> ) ResourceCheckBox.propTypes = { resource: React.PropTypes.object.isRequired, toggle: React.PropTypes.func } export default CSSModules(ResourceCheckBox, styles)
lib/MultiColumnList/stories/Formatter.js
folio-org/stripes-components
import React from 'react'; import { action } from '@storybook/addon-actions'; import MultiColumnList from '../MultiColumnList'; import Button from '../../Button'; import data from './dummyData'; export default class Formatter extends React.Component { constructor() { super(); this.state = { selected: data[3], mclKey: 0, }; this.listFormatter = { action: ({ active, rowIndex }) => ( <Button buttonStyle="primary" disabled={!active} marginBottom0 onClick={() => alert(`Row ${rowIndex} action clicked!`)} // eslint-disable-line > Send Invoice </Button> ) }; } onRowClick = (e, row) => { action('button-click'); this.setState({ selected: row }); } resetMCL = () => { this.setState(curState => ({ mclKey: curState.mclKey + 1 })); } render() { return ( <> <Button onClick={this.resetMCL}>Reinitialize</Button> <MultiColumnList striped key={this.state.mclKey} contentData={data} formatter={this.listFormatter} selectedRow={this.state.selected} onRowClick={this.onRowClick} visibleColumns={['name', 'patronGroup', 'phone', 'action']} columnMapping={{ name: 'Name', patronGroup: 'Patron group', phone: 'Phone', action: 'Action' }} /> </> ); } }
assets/js/vendor/jquery-1.9.1.min.js
wujackjack/wujackjack.github.io
/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery.min.map */(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&&gt(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) }b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
ajax/libs/forerunnerdb/1.3.590/fdb-core+views.min.js
tonytomov/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./core");a("../lib/View");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/View":33,"./core":2}],2:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":7,"../lib/Shim.IE8":32}],3:[function(a,b,c){"use strict";var d,e=a("./Shared"),f=a("./Path"),g=function(a){this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0,this._keyArr=d.parse(a,!0)};e.addModule("ActiveBucket",g),e.mixin(g.prototype,"Mixin.Sorting"),d=new f,e.synthesize(g.prototype,"primaryKey"),g.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},g.prototype._sortFunc=function(a,b,c,e){var f,g,h,i=c.split(".:."),j=e.split(".:."),k=a._keyArr,l=k.length;for(f=0;l>f;f++)if(g=k[f],h=typeof d.get(b,g.path),"number"===h&&(i[f]=Number(i[f]),j[f]=Number(j[f])),i[f]!==j[f]){if(1===g.value)return a.sortAsc(i[f],j[f]);if(-1===g.value)return a.sortDesc(i[f],j[f])}},g.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},g.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},g.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},g.prototype.documentKey=function(a){var b,c,e="",f=this._keyArr,g=f.length;for(b=0;g>b;b++)c=f[b],e&&(e+=".:."),e+=d.get(a,c.path);return e+=".:."+a[this._primaryKey]},g.prototype.count=function(){return this._count},e.finishModule("ActiveBucket"),b.exports=g},{"./Path":28,"./Shared":31}],4:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c){var d=this._compareFunc(this._data,a);return c=c||[],0===d&&(this._left&&this._left.lookup(a,b,c),c.push(this._data),this._right&&this._right.lookup(a,b,c)),-1===d&&this._right&&this._right.lookup(a,b,c),1===d&&this._left&&this._left.lookup(a,b,c),c},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return c=c||new RegExp("^"+b),d=d||[],void 0===d._visited&&(d._visited=0),d._visited++,g=this.sortAsc(h,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":28,"./Shared":31}],5:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n,o;d=a("./Shared");var p=function(a,b){this.init.apply(this,arguments)};p.prototype.init=function(a,b){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",p),d.mixin(p.prototype,"Mixin.Common"),d.mixin(p.prototype,"Mixin.Events"),d.mixin(p.prototype,"Mixin.ChainReactor"),d.mixin(p.prototype,"Mixin.CRUD"),d.mixin(p.prototype,"Mixin.Constants"),d.mixin(p.prototype,"Mixin.Triggers"),d.mixin(p.prototype,"Mixin.Sorting"),d.mixin(p.prototype,"Mixin.Matching"),d.mixin(p.prototype,"Mixin.Updating"),d.mixin(p.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),l=a("./Crc"),e=d.modules.Db,m=a("./Overload"),n=a("./ReactorIO"),o=new h,p.prototype.crc=l,d.synthesize(p.prototype,"deferredCalls"),d.synthesize(p.prototype,"state"),d.synthesize(p.prototype,"name"),d.synthesize(p.prototype,"metaData"),d.synthesize(p.prototype,"capped"),d.synthesize(p.prototype,"cappedSize"),p.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},p.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},p.prototype.data=function(){return this._data},p.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,delete this._listeners,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},p.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",a,{oldData:b})}return this}return this._primaryKey},p.prototype._onInsert=function(a,b){this.emit("insert",a,b)},p.prototype._onUpdate=function(a){this.emit("update",a)},p.prototype._onRemove=function(a){this.emit("remove",a)},p.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(p.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(p.prototype,"mongoEmulation"),p.prototype.setData=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this._onChange(),this.emit("setData",this._data,e)}return c&&c(!1),this},p.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.jStringify(d),i.set(d[k],e),j.set(e,d)}},p.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},p.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.deferEmit("change",{type:"truncate"}),this},p.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},p.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},p.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},p.prototype.update=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";b=this.decouple(b),this.mongoEmulation()&&(this.convertToFdb(a),this.convertToFdb(b)),b=this.transformIn(b);var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i,j=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e=f.decouple(d),h={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},i=f.updateObject(e,h.update,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_BEFORE,d,e)!==!1?(i=f.updateObject(d,e,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_AFTER,j,e)):i=!1):i=f.updateObject(d,b,a,c,""),f._updateIndexes(j,d),i};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:e},c),g.time("Resolve chains"),this._onUpdate(e),this._onChange(),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},p.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},p.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},p.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":(!(a[s]instanceof Object)||a[s]instanceof Array)&&(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},p.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},p.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.deferEmit("change",{type:"remove",data:g}))}return c&&c(!1,g),g},p.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},p.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},p.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},p.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},p.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.deferEmit("change",{type:"insert",data:i}),e},p.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainSend("insert",a,{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},p.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},p.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},p.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},p.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.jStringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},p.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.jStringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},p.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},p.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},p.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new p,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(p.prototype,"subsetOf"),p.prototype.isSubsetOf=function(a){return this._subsetOf===a},p.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},p.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},p.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new p,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},p.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},p.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},p.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},p.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L=this._metrics.create("find"),M=this.primaryKey(),N=this,O=!0,P={},Q=[],R=[],S=[],T={},U={};if(b instanceof Array||(b=this.options(b)),K=function(c){return N._match(c,a,b,"and",T)},L.start(),a){if(a instanceof Array){for(J=this,A=0;A<a.length;A++)J=J.subset(a[A],b&&b[A]?b[A]:{});return J.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(L.time("analyseQuery"),c=this._analyseQuery(N.decouple(a),b,L),L.time("analyseQuery"),L.data("analysis",c),c.hasJoin&&c.queriesJoin){for(L.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],P[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];L.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(L.data("index.potential",c.indexMatch),L.data("index.used",c.indexMatch[0].index),L.time("indexLookup"),e=c.indexMatch[0].lookup||[],L.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(O=!1)):L.flag("usedIndex",!1),O&&(e&&e.length?(d=e.length,L.time("tableScan: "+d),e=e.filter(K)):(d=this._data.length,L.time("tableScan: "+d),e=this._data.filter(K)),L.time("tableScan: "+d)),b.$orderBy&&(L.time("sort"),e=this.sort(b.$orderBy,e),L.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(U.page=b.$page,U.pages=Math.ceil(e.length/b.$limit),U.records=e.length,b.$page&&b.$limit>0&&(L.data("cursor",U),e.splice(0,b.$page*b.$limit))),b.$skip&&(U.skip=b.$skip,e.splice(0,b.$skip),L.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(U.limit=b.$limit,e.length=b.$limit,L.data("limit",b.$limit)),b.$decouple&&(L.time("decouple"),e=this.decouple(e),L.time("decouple"),L.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(x=k,l=P[k]?P[k]:this._db.collection(k),m=b.$join[f][k],y=0;y<e.length;y++){o={},q=!1,r=!1,v="";for(n in m)if(m.hasOwnProperty(n))if(w=m[n],"$"===n.substr(0,1))switch(n){case"$where":if(!w.$query&&!w.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';w.$query&&(o=N._resolveDynamicQuery(w.$query,e[y])),w.$options&&(p=w.$options);break;case"$as":x=w;break;case"$multi":q=w;break;case"$require":r=w;break;case"$prefix":v=w}else o[n]=N._resolveDynamicQuery(w,e[y]);if(s=l.find(o,p),!r||r&&s[0])if("$root"===x){if(q!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';t=s[0],u=e[y];for(D in t)t.hasOwnProperty(D)&&void 0===u[v+D]&&(u[v+D]=t[D])}else e[y][x]=q===!1?s[0]:s;else Q.push(e[y])}L.data("flag.join",!0)}if(Q.length){for(L.time("removalQueue"),A=0;A<Q.length;A++)z=e.indexOf(Q[A]),z>-1&&e.splice(z,1);L.time("removalQueue")}if(b.$transform){for(L.time("transform"),A=0;A<e.length;A++)e.splice(A,1,b.$transform(e[A]));L.time("transform"),L.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(L.time("transformOut"),e=this.transformOut(e),L.time("transformOut")),L.data("results",e.length)}else e=[];if(!b.$aggregate){L.time("scanFields");for(A in b)b.hasOwnProperty(A)&&0!==A.indexOf("$")&&(1===b[A]?R.push(A):0===b[A]&&S.push(A));if(L.time("scanFields"),R.length||S.length){for(L.data("flag.limitFields",!0),L.data("limitFields.on",R),L.data("limitFields.off",S),L.time("limitFields"),A=0;A<e.length;A++){H=e[A];for(B in H)H.hasOwnProperty(B)&&(R.length&&B!==M&&-1===R.indexOf(B)&&delete H[B],S.length&&S.indexOf(B)>-1&&delete H[B])}L.time("limitFields")}if(b.$elemMatch){L.data("flag.elemMatch",!0),L.time("projection-elemMatch");for(A in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(A))for(E=new h(A),B=0;B<e.length;B++)if(F=E.value(e[B])[0],F&&F.length)for(C=0;C<F.length;C++)if(N._match(F[C],b.$elemMatch[A],b,"",{})){E.set(e[B],A,[F[C]]);break}L.time("projection-elemMatch")}if(b.$elemsMatch){L.data("flag.elemsMatch",!0),L.time("projection-elemsMatch");for(A in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(A))for(E=new h(A),B=0;B<e.length;B++)if(F=E.value(e[B])[0],F&&F.length){for(G=[],C=0;C<F.length;C++)N._match(F[C],b.$elemsMatch[A],b,"",{})&&G.push(F[C]);E.set(e[B],A,G)}L.time("projection-elemsMatch")}}return b.$aggregate&&(L.data("flag.aggregate",!0),L.time("aggregate"),I=new h(b.$aggregate),e=I.value(e),L.time("aggregate")),L.stop(),e.__fdbOp=L,e.$cursor=U,e},p.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g,i=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b):new h(a).value(b),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=new h(e.substr(3,e.length-3)).value(b)[0]:c[g]=e;break;case"object":c[g]=i._resolveDynamicQuery(e,b);break;default:c[g]=e}return c},p.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},p.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},p.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},p.prototype.removeByIndex=function(a){ var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},p.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},p.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},p.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},p.prototype.sort=function(a,b){var c=this,d=o.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(o.get(a,f.path),o.get(b,f.path)):-1===f.value&&(g=c.sortDesc(o.get(a,f.path),o.get(b,f.path))),0!==g)return g;return g}),b},p.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},p.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},s=[],t=[];if(c.time("checkIndexes"),m=new h,n=m.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(o=typeof a[this._primaryKey],("string"===o||"number"===o||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),p=this._primaryIndex.lookup(a,b),r.indexMatch.push({lookup:p,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(q in this._indexById)if(this._indexById.hasOwnProperty(q)&&(j=this._indexById[q],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),r.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),r.indexMatch.length>1&&(c.time("findOptimalIndex"),r.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(r.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(s.push(e),"$as"in b.$join[d][e]?t.push(b.$join[d][e].$as):t.push(e));for(g=0;g<t.length;g++)f=this._queryReferencesCollection(a,t[g],""),f&&(r.joinQueries[s[g]]=f,r.queriesJoin=!0);r.joinsOn=s,r.queriesOn=r.queriesOn.concat(s)}return r},p.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},p.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},p.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},p.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new p("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;j>e;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},p.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},p.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},p.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;case"2d":c=new k(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},p.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},p.prototype.lastOp=function(){return this._metrics.list()},p.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},p.prototype.collateAdd=new m({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new n(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),p.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new m({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof p?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new p(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=p},{"./Crc":8,"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":29,"./Shared":31}],6:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),delete this._listeners,a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?a instanceof h?a:(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":5,"./Shared":31}],7:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":9,"./Metrics.js":15,"./Overload":27,"./Shared":31}],8:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],9:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":15,"./Overload":27,"./Shared":31}],10:[function(a,b,c){"use strict";var d,e,f,g;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var h=function(){};h.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},h.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},h.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},h.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;5>g;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{latitude:l,longitude:m}},h.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,4>j?j++:(l+=e[k],j=0,k=0);return l},b.exports=h},{}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b){var c,d,e,f,g=this._btree.keys();for(f=0;f<g.length;f++)if(c=g[f].path,d=h.get(a,c),"object"==typeof d)return d.$near&&(e=[],e=e.concat(this.near(c,d.$near,b))),d.$geoWithin&&(e=[],e=e.concat(this.geoWithin(c,d.$geoWithin,b))),e;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c){var d,e,f,g,k,l,m,n,o,p,q,r=this,s=[],t=this._collection.primaryKey();if("km"===b.$distanceUnits){for(m=b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}else if("miles"===b.$distanceUnits){for(m=1.60934*b.$maxDistance,q=0;q<j.length;q++)if(m>j[q]){l=q;break}0===l&&(l=1)}for(d=i.encode(b.$point[0],b.$point[1],l),e=i.calculateNeighbours(d,{type:"array"}),k=[],f=0,q=0;9>q;q++)g=this._btree.startsWith(a,e[q]),f+=g._visited,k=k.concat(g);if(k=this._collection._primaryIndex.lookup(k),k.length){for(n={},q=0;q<k.length;q++)p=h.get(k[q],a),o=n[k[q][t]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],p[0],p[1]),m>=o&&s.push(k[q]);s.sort(function(a,b){return r.sortAsc(n[a[t]],n[b[t]])})}return s},k.prototype.geoWithin=function(a,b,c){return[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":4,"./GeoHash":10,"./Path":28,"./Shared":31}],12:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b){return this._btree.lookup(a,b)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":4,"./Path":28,"./Shared":31}],13:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a]); },f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":28,"./Shared":31}],14:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":31}],15:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":26,"./Shared":31}],16:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};this.debug&&this.debug()&&console.log(this.logIdentifier()+"Received data from parent reactor node"),(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],18:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return h.parse(a)},jStringify:function(a){return h.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return this.classIdentifier()+": "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state}},b.exports=d},{"./Overload":27,"./Serialiser":30}],19:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],20:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":27}],21:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}if("object"==typeof c)return this._match(b,c,d,"and",e);throw this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a;case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}if("object"==typeof c)return this._match(b,c,d,"and",e);throw this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a;case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1}};b.exports=d},{}],22:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],23:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],24:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":27}],25:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],26:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":28,"./Shared":31}],27:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f,g=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)g.push(e);if(d=g.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=g.length;b>=0;b--)if(d=g.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw f="function"==typeof this.name?this.name():"Unknown",console.log("Overload: ",a),'ForerunnerDB.Overload "'+f+'": Overloaded method does not have a matching signature "'+d+'" for the passed arguments: '+this.jStringify(g)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],28:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&-1===b.indexOf("."))return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":31}],29:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":31}],30:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){this._encoder=[],this._decoder={},this.registerEncoder("$date",function(a){return a instanceof Date?a.toISOString():void 0}),this.registerDecoder("$date",function(a){return new Date(a)}),this.registerEncoder("$regexp",function(a){return a instanceof RegExp?{source:a.source,params:""+(a.global?"g":"")+(a.ignoreCase?"i":"")}:void 0}),this.registerDecoder("$regexp",function(a){var b=typeof a;return"object"===b?new RegExp(a.source,a.params):"string"===b?new RegExp(a):void 0})},d.prototype.registerEncoder=function(a,b){this._encoder.push(function(c){var d,e=b(c);return void 0!==e&&(d={},d[a]=e),d})},d.prototype.registerDecoder=function(a,b){this._decoder[a]=b},d.prototype._encode=function(a){for(var b,c=this._encoder.length;c--&&!b;)b=this._encoder[c](a);return b},d.prototype.parse=function(a){return this._parse(JSON.parse(a))},d.prototype._parse=function(a,b){var c;if("object"==typeof a&&null!==a){b=a instanceof Array?b||[]:b||{};for(c in a)if(a.hasOwnProperty(c)){if("$"===c.substr(0,1)&&this._decoder[c])return this._decoder[c](a[c]);b[c]=this._parse(a[c],b[c])}}else b=a;return b},d.prototype.stringify=function(a){return JSON.stringify(this._stringify(a))},d.prototype._stringify=function(a,b){var c,d;if("object"==typeof a&&null!==a){if(c=this._encode(a))return c;b=a instanceof Array?b||[]:b||{};for(d in a)a.hasOwnProperty(d)&&(b[d]=this._stringify(a[d],b[d]))}else b=a;return b},b.exports=d},{}],31:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.590",modules:{},plugins:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":27}],32:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}],33:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l=a("./Overload");d=a("./Shared");var m=function(a,b,c){this.init.apply(this,arguments)};m.prototype.init=function(a,b,c){var d=this;this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f(this.name()+"_internalPrivate")},d.addModule("View",m),d.mixin(m.prototype,"Mixin.Common"),d.mixin(m.prototype,"Mixin.ChainReactor"),d.mixin(m.prototype,"Mixin.Constants"),d.mixin(m.prototype,"Mixin.Triggers"),d.mixin(m.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,d.synthesize(m.prototype,"state"),d.synthesize(m.prototype,"name"),d.synthesize(m.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),m.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},m.prototype.update=function(){this._from.update.apply(this._from,arguments)},m.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},m.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},m.prototype.find=function(a,b){return this.publicData().find(a,b)},m.prototype.findOne=function(a,b){return this.publicData().findOne(a,b)},m.prototype.findById=function(a,b){return this.publicData().findById(a,b)},m.prototype.findSub=function(a,b,c,d){return this.publicData().findSub(a,b,c,d)},m.prototype.findSubOne=function(a,b,c,d){return this.publicData().findSubOne(a,b,c,d)},m.prototype.data=function(){return this._privateData},m.prototype.from=function(a,b){var c=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from), this._io&&(this._io.drop(),delete this._io),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(a,this,function(a){var b,d,e,f,g,h,i;if(c&&!c.isDropped()&&c._querySettings.query){if("insert"===a.type){if(b=a.data,b instanceof Array)for(f=[],i=0;i<b.length;i++)c._privateData._match(b[i],c._querySettings.query,c._querySettings.options,"and",{})&&(f.push(b[i]),g=!0);else c._privateData._match(b,c._querySettings.query,c._querySettings.options,"and",{})&&(f=b,g=!0);return g&&this.chainSend("insert",f),!0}if("update"===a.type){if(d=c._privateData.diff(c._from.subset(c._querySettings.query,c._querySettings.options)),d.insert.length||d.remove.length){if(d.insert.length&&this.chainSend("insert",d.insert),d.update.length)for(h=c._privateData.primaryKey(),i=0;i<d.update.length;i++)e={},e[h]=d.update[i][h],this.chainSend("update",{query:e,update:d.update[i]});if(d.remove.length){h=c._privateData.primaryKey();var j=[],k={query:{$or:j}};for(i=0;i<d.remove.length;i++)j.push({_id:d.remove[i][h]});this.chainSend("remove",k)}return!0}return!1}}return!1});var d=a.find(this._querySettings.query,this._querySettings.options);return this._privateData.primaryKey(a.primaryKey()),this._privateData.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},m.prototype._collectionDropped=function(a){a&&delete this._from},m.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData,arguments)},m.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data"),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._privateData.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._privateData.setData(j);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)h=f[d],this._activeBucket.remove(h),i=this._privateData._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._privateData._updateSpliceMove(this._privateData._data,i,e);break;case"remove":this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._privateData.name()+'"'),this._privateData.remove(a.data.query,a.options)}},m.prototype.on=function(){return this._privateData.on.apply(this._privateData,arguments)},m.prototype.off=function(){return this._privateData.off.apply(this._privateData,arguments)},m.prototype.emit=function(){return this._privateData.emit.apply(this._privateData,arguments)},m.prototype.distinct=function(a,b,c){var d=this.publicData();return d.distinct.apply(d,arguments)},m.prototype.primaryKey=function(){return this.publicData().primaryKey()},m.prototype.drop=function(a){return this.isDropped()?!1:(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._privateData&&this._privateData.drop(),this._publicData&&this._publicData!==this._privateData&&this._publicData.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._privateData,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},d.synthesize(m.prototype,"db",function(a){return a&&(this.privateData().db(a),this.publicData().db(a),this.debug(a.debug()),this.privateData().debug(a.debug()),this.publicData().debug(a.debug())),this.$super.apply(this,arguments)}),m.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._privateData.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._privateData.name())),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings},m.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);(void 0===c||c===!0)&&this.refresh()},m.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];(void 0===b||b===!0)&&this.refresh()}},m.prototype.query=new l({"":function(){return this._querySettings.query},object:function(a){return this.$main.call(this,a,void 0,!0)},"*, boolean":function(a,b){return this.$main.call(this,a,void 0,b)},"object, object":function(a,b){return this.$main.call(this,a,b,!0)},"*, *, boolean":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._privateData.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._privateData.name())),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings}}),m.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},m.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},m.prototype.pageFirst=function(){return this.page(0)},m.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},m.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},m.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),this):this._querySettings.options},m.prototype.rebuildActiveBucket=function(a){if(a){var b=this._privateData._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._privateData.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},m.prototype.refresh=function(){if(this._from){var a,b=this.publicData();this._privateData.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._privateData.insert(a),this._privateData._data.$cursor=a.$cursor,b._data.$cursor=a.$cursor}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},m.prototype.count=function(){return this.publicData()?this.publicData().count.apply(this.publicData(),arguments):0},m.prototype.subset=function(){return this.publicData().subset.apply(this._privateData,arguments)},m.prototype.transform=function(a){var b=this;return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this._transformEnabled?(this._publicData||(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._transformIo=new j(this._privateData,this._publicData,function(a){var c=a.data;switch(a.type){case"primaryKey":b._publicData.primaryKey(c),this.chainSend("primaryKey",c);break;case"setData":b._publicData.setData(c),this.chainSend("setData",c);break;case"insert":b._publicData.insert(c),this.chainSend("insert",c);break;case"update":b._publicData.update(c.query,c.update,c.options),this.chainSend("update",c);break;case"remove":b._publicData.remove(c.query,a.options),this.chainSend("remove",c)}})),this._publicData.primaryKey(this.privateData().primaryKey()),this._publicData.setData(this.privateData().find())):this._publicData&&(this._publicData.drop(),delete this._publicData,this._transformIo&&(this._transformIo.drop(),delete this._transformIo)),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},m.prototype.filter=function(a,b,c){return this.publicData().filter(a,b,c)},m.prototype.privateData=function(){return this._privateData},m.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new m(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){var b=this;return a instanceof m?a:this._view[a]?this._view[a]:((this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=this._view[a]||new m(a).db(this),b.emit("create",[b._view[a],"view",a]),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("View"),b.exports=m},{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./Overload":27,"./ReactorIO":29,"./Shared":31}]},{},[1]);
test/multi-section/AutosuggestApp.js
moroshko/react-autosuggest
import React, { Component } from 'react'; import sinon from 'sinon'; import Autosuggest from '../../src/Autosuggest'; import languages from './languages'; import { escapeRegexCharacters } from '../../demo/src/components/utils/utils.js'; const getMatchingLanguages = value => { const escapedValue = escapeRegexCharacters(value.trim()); const regex = new RegExp('^' + escapedValue, 'i'); return languages .map(section => { return { title: section.title, languages: section.languages.filter(language => regex.test(language.name) ) }; }) .filter(section => section.languages.length > 0); }; let app = null; export const getSuggestionValue = sinon.spy(suggestion => { return suggestion.name; }); export const renderSuggestion = sinon.spy(suggestion => { return <span>{suggestion.name}</span>; }); const alwaysTrue = () => true; export const onChange = sinon.spy((event, { newValue }) => { app.setState({ value: newValue }); }); export const onBlur = sinon.spy(); export const onSuggestionsFetchRequested = sinon.spy(({ value }) => { app.setState({ suggestions: getMatchingLanguages(value) }); }); export const onSuggestionsClearRequested = sinon.spy(() => { app.setState({ suggestions: [] }); }); export const onSuggestionSelected = sinon.spy(); export const onSuggestionHighlighted = sinon.spy(); export const renderSectionTitle = sinon.spy(section => { return <strong>{section.title}</strong>; }); export const getSectionSuggestions = sinon.spy(section => { return section.languages; }); let highlightFirstSuggestion = false; export const setHighlightFirstSuggestion = value => { highlightFirstSuggestion = value; }; export default class AutosuggestApp extends Component { constructor() { super(); app = this; this.state = { value: '', suggestions: [] }; } onClearMouseDown = event => { event.preventDefault(); this.setState({ value: '', suggestions: getMatchingLanguages('') }); }; render() { const { value, suggestions } = this.state; const inputProps = { value, onChange, onBlur }; return ( <div> <button onMouseDown={this.onClearMouseDown}>Clear</button> <Autosuggest multiSection={true} suggestions={suggestions} onSuggestionsFetchRequested={onSuggestionsFetchRequested} onSuggestionsClearRequested={onSuggestionsClearRequested} onSuggestionSelected={onSuggestionSelected} onSuggestionHighlighted={onSuggestionHighlighted} getSuggestionValue={getSuggestionValue} renderSuggestion={renderSuggestion} inputProps={inputProps} shouldRenderSuggestions={alwaysTrue} renderSectionTitle={renderSectionTitle} getSectionSuggestions={getSectionSuggestions} highlightFirstSuggestion={highlightFirstSuggestion} /> </div> ); } }
web-server-v3/tests/routes/Counter/components/Counter.spec.js
SparxoOpenSource/SparxoShareMusic
import React from 'react' import { bindActionCreators } from 'redux' import { Counter } from 'routes/Counter/components/Counter' import { shallow } from 'enzyme' describe('(Component) Counter', () => { let _props, _spies, _wrapper beforeEach(() => { _spies = {} _props = { counter : 5, ...bindActionCreators({ doubleAsync : (_spies.doubleAsync = sinon.spy()), increment : (_spies.increment = sinon.spy()) }, _spies.dispatch = sinon.spy()) } _wrapper = shallow(<Counter {..._props} />) }) it('Should render as a <div>.', () => { expect(_wrapper.is('div')).to.equal(true) }) it('Should render with an <h2> that includes Sample Counter text.', () => { expect(_wrapper.find('h2').text()).to.match(/Counter:/) }) it('Should render props.counter at the end of the sample counter <h2>.', () => { expect(_wrapper.find('h2').text()).to.match(/5$/) _wrapper.setProps({ counter: 8 }) expect(_wrapper.find('h2').text()).to.match(/8$/) }) it('Should render exactly two buttons.', () => { expect(_wrapper.find('button')).to.have.length(2) }) describe('An increment button...', () => { let _button beforeEach(() => { _button = _wrapper.find('button').filterWhere(a => a.text() === 'Increment') }) it('has bootstrap classes', () => { expect(_button.hasClass('btn btn-default')).to.be.true }) it('Should dispatch a `increment` action when clicked', () => { _spies.dispatch.should.have.not.been.called _button.simulate('click') _spies.dispatch.should.have.been.called _spies.increment.should.have.been.called }) }) describe('A Double (Async) button...', () => { let _button beforeEach(() => { _button = _wrapper.find('button').filterWhere(a => a.text() === 'Double (Async)') }) it('has bootstrap classes', () => { expect(_button.hasClass('btn btn-default')).to.be.true }) it('Should dispatch a `doubleAsync` action when clicked', () => { _spies.dispatch.should.have.not.been.called _button.simulate('click') _spies.dispatch.should.have.been.called _spies.doubleAsync.should.have.been.called }) }) })
src/components/Html.js
OlegVitiuk/Majsternia
import React from 'react'; import PropTypes from 'prop-types'; import serialize from 'serialize-javascript'; import config from '../config'; /* eslint-disable react/no-danger */ class Html extends React.Component { static propTypes = { title: PropTypes.string.isRequired, description: PropTypes.string.isRequired, styles: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string.isRequired, cssText: PropTypes.string.isRequired, }).isRequired), scripts: PropTypes.arrayOf(PropTypes.string.isRequired), // eslint-disable-next-line react/forbid-prop-types app: PropTypes.object.isRequired, children: PropTypes.string.isRequired, }; static defaultProps = { styles: [], scripts: [], }; render() { const { title, description, styles, scripts, app, children } = this.props; return ( <html className="no-js" lang={app.lang}> <head> <meta charSet="utf-8" /> <meta httpEquiv="x-ua-compatible" content="ie=edge" /> <title>{title}</title> <meta name="description" content={description} /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="apple-touch-icon" href="apple-touch-icon.png" /> {styles.map(style => ( <style key={style.id} id={style.id} dangerouslySetInnerHTML={{ __html: style.cssText }} /> ))} </head> <body> <div id="app" dangerouslySetInnerHTML={{ __html: children }} /> <script dangerouslySetInnerHTML={{ __html: `window.App=${serialize(app)}` }} /> {scripts.map(script => <script key={script} src={script} />)} {config.analytics.googleTrackingId && <script dangerouslySetInnerHTML={{ __html: 'window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;' + `ga('create','${config.analytics.googleTrackingId}','auto');ga('send','pageview')` }} /> } {config.analytics.googleTrackingId && <script src="https://www.google-analytics.com/analytics.js" async defer /> } </body> </html> ); } } export default Html;
wp-includes/js/jquery/jquery.js
T-Jain/WordPress
/*! jQuery v1.11.3 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1; return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?m.queue(this[0],a):void 0===b?this:this.each(function(){var c=m.queue(this,a,b);m._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&m.dequeue(this,a)})},dequeue:function(a){return this.each(function(){m.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=m.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=m._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=["Top","Right","Bottom","Left"],U=function(a,b){return a=b||a,"none"===m.css(a,"display")||!m.contains(a.ownerDocument,a)},V=m.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===m.type(c)){e=!0;for(h in c)m.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,m.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(m(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav></:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function aa(){return!0}function ba(){return!1}function ca(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[m.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=Z.test(e)?this.mouseHooks:Y.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new m.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||y),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||y,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ca()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ca()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return m.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return m.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=m.extend(new m.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?m.event.trigger(e,null,b):m.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},m.removeEvent=y.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===K&&(a[d]=null),a.detachEvent(d,c))},m.Event=function(a,b){return this instanceof m.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?aa:ba):this.type=a,b&&m.extend(this,b),this.timeStamp=a&&a.timeStamp||m.now(),void(this[m.expando]=!0)):new m.Event(a,b)},m.Event.prototype={isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=aa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=aa,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=aa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},m.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){m.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!m.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.submitBubbles||(m.event.special.submit={setup:function(){return m.nodeName(this,"form")?!1:void m.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=m.nodeName(b,"input")||m.nodeName(b,"button")?b.form:void 0;c&&!m._data(c,"submitBubbles")&&(m.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),m._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&m.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return m.nodeName(this,"form")?!1:void m.event.remove(this,"._submit")}}),k.changeBubbles||(m.event.special.change={setup:function(){return X.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(m.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),m.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),m.event.simulate("change",this,a,!0)})),!1):void m.event.add(this,"beforeactivate._change",function(a){var b=a.target;X.test(b.nodeName)&&!m._data(b,"changeBubbles")&&(m.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||m.event.simulate("change",this.parentNode,a,!0)}),m._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return m.event.remove(this,"._change"),!X.test(this.nodeName)}}),k.focusinBubbles||m.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){m.event.simulate(b,a.target,m.event.fix(a),!0)};m.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=m._data(d,b);e||d.addEventListener(a,c,!0),m._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=m._data(d,b)-1;e?m._data(d,b,e):(d.removeEventListener(a,c,!0),m._removeData(d,b))}}}),m.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=ba;else if(!d)return this;return 1===e&&(g=d,d=function(a){return m().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=m.guid++)),this.each(function(){m.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,m(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=ba),this.each(function(){m.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){m.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?m.event.trigger(a,b,c,!0):void 0}});function da(a){var b=ea.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var ea="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",fa=/ jQuery\d+="(?:null|\d+)"/g,ga=new RegExp("<(?:"+ea+")[\\s/>]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/<tbody/i,la=/<|&#?\w+;/,ma=/<(?:script|style|link)/i,na=/checked\s*(?:[^=]|=\s*.checked.)/i,oa=/^$|\/(?:java|ecma)script/i,pa=/^true\/(.*)/,qa=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ra={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:k.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Ba(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xa(b).text=a.text,ya(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=da(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1></$2>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?"<table>"!==l[1]||ka.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ua(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ua(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&na.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qa,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Ca,Da={};function Ea(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ca[0].contentWindow||Ca[0].contentDocument).document,b.write(),b.close(),c=Ea(a,b),Ca.detach()),Da[a]=c),c}!function(){var a;k.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,d;return c=y.getElementsByTagName("body")[0],c&&c.style?(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(y.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(d),a):void 0}}();var Ga=/^margin/,Ha=new RegExp("^("+S+")(?!px)[a-z%]+$","i"),Ia,Ja,Ka=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ia=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||m.contains(a.ownerDocument,a)||(g=m.style(a,b)),Ha.test(g)&&Ga.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):y.documentElement.currentStyle&&(Ia=function(a){return a.currentStyle},Ja=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ia(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ha.test(g)&&!Ka.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function La(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h;if(b=y.createElement("div"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=d&&d.style){c.cssText="float:left;opacity:.5",k.opacity="0.5"===c.opacity,k.cssFloat=!!c.cssFloat,b.style.backgroundClip="content-box",b.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===b.style.backgroundClip,k.boxSizing=""===c.boxSizing||""===c.MozBoxSizing||""===c.WebkitBoxSizing,m.extend(k,{reliableHiddenOffsets:function(){return null==g&&i(),g},boxSizingReliable:function(){return null==f&&i(),f},pixelPosition:function(){return null==e&&i(),e},reliableMarginRight:function(){return null==h&&i(),h}});function i(){var b,c,d,i;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),b.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",e=f=!1,h=!0,a.getComputedStyle&&(e="1%"!==(a.getComputedStyle(b,null)||{}).top,f="4px"===(a.getComputedStyle(b,null)||{width:"4px"}).width,i=b.appendChild(y.createElement("div")),i.style.cssText=b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",b.style.width="1px",h=!parseFloat((a.getComputedStyle(i,null)||{}).marginRight),b.removeChild(i)),b.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=b.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",g=0===i[0].offsetHeight,g&&(i[0].style.display="",i[1].style.display="none",g=0===i[0].offsetHeight),c.removeChild(d))}}}(),m.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Ma=/alpha\([^)]*\)/i,Na=/opacity\s*=\s*([^)]*)/,Oa=/^(none|table(?!-c[ea]).+)/,Pa=new RegExp("^("+S+")(.*)$","i"),Qa=new RegExp("^([+-])=("+S+")","i"),Ra={position:"absolute",visibility:"hidden",display:"block"},Sa={letterSpacing:"0",fontWeight:"400"},Ta=["Webkit","O","Moz","ms"];function Ua(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ta.length;while(e--)if(b=Ta[e]+c,b in a)return b;return d}function Va(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=m._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&U(d)&&(f[g]=m._data(d,"olddisplay",Fa(d.nodeName)))):(e=U(d),(c&&"none"!==c||!e)&&m._data(d,"olddisplay",e?c:m.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Wa(a,b,c){var d=Pa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Xa(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=m.css(a,c+T[f],!0,e)),d?("content"===c&&(g-=m.css(a,"padding"+T[f],!0,e)),"margin"!==c&&(g-=m.css(a,"border"+T[f]+"Width",!0,e))):(g+=m.css(a,"padding"+T[f],!0,e),"padding"!==c&&(g+=m.css(a,"border"+T[f]+"Width",!0,e)));return g}function Ya(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ia(a),g=k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Ja(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ha.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Xa(a,b,c||(g?"border":"content"),d,f)+"px"}m.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ja(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":k.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=m.camelCase(b),i=a.style;if(b=m.cssProps[h]||(m.cssProps[h]=Ua(i,h)),g=m.cssHooks[b]||m.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Qa.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(m.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||m.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=m.camelCase(b);return b=m.cssProps[h]||(m.cssProps[h]=Ua(a.style,h)),g=m.cssHooks[b]||m.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Ja(a,b,d)),"normal"===f&&b in Sa&&(f=Sa[b]),""===c||c?(e=parseFloat(f),c===!0||m.isNumeric(e)?e||0:f):f}}),m.each(["height","width"],function(a,b){m.cssHooks[b]={get:function(a,c,d){return c?Oa.test(m.css(a,"display"))&&0===a.offsetWidth?m.swap(a,Ra,function(){return Ya(a,b,d)}):Ya(a,b,d):void 0},set:function(a,c,d){var e=d&&Ia(a);return Wa(a,c,d?Xa(a,b,d,k.boxSizing&&"border-box"===m.css(a,"boxSizing",!1,e),e):0)}}}),k.opacity||(m.cssHooks.opacity={get:function(a,b){return Na.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=m.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===m.trim(f.replace(Ma,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Ma.test(f)?f.replace(Ma,e):f+" "+e)}}),m.cssHooks.marginRight=La(k.reliableMarginRight,function(a,b){return b?m.swap(a,{display:"inline-block"},Ja,[a,"marginRight"]):void 0}),m.each({margin:"",padding:"",border:"Width"},function(a,b){m.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+T[d]+b]=f[d]||f[d-2]||f[0];return e}},Ga.test(a)||(m.cssHooks[a+b].set=Wa)}),m.fn.extend({css:function(a,b){return V(this,function(a,b,c){var d,e,f={},g=0;if(m.isArray(b)){for(d=Ia(a),e=b.length;e>g;g++)f[b[g]]=m.css(a,b[g],!1,d);return f}return void 0!==c?m.style(a,b,c):m.css(a,b)},a,b,arguments.length>1)},show:function(){return Va(this,!0)},hide:function(){return Va(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){U(this)?m(this).show():m(this).hide()})}});function Za(a,b,c,d,e){ return new Za.prototype.init(a,b,c,d,e)}m.Tween=Za,Za.prototype={constructor:Za,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(m.cssNumber[c]?"":"px")},cur:function(){var a=Za.propHooks[this.prop];return a&&a.get?a.get(this):Za.propHooks._default.get(this)},run:function(a){var b,c=Za.propHooks[this.prop];return this.options.duration?this.pos=b=m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Za.propHooks._default.set(this),this}},Za.prototype.init.prototype=Za.prototype,Za.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=m.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){m.fx.step[a.prop]?m.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[m.cssProps[a.prop]]||m.cssHooks[a.prop])?m.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Za.propHooks.scrollTop=Za.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},m.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},m.fx=Za.prototype.init,m.fx.step={};var $a,_a,ab=/^(?:toggle|show|hide)$/,bb=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),cb=/queueHooks$/,db=[ib],eb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=bb.exec(b),f=e&&e[3]||(m.cssNumber[a]?"":"px"),g=(m.cssNumber[a]||"px"!==f&&+d)&&bb.exec(m.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,m.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function fb(){return setTimeout(function(){$a=void 0}),$a=m.now()}function gb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=T[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function hb(a,b,c){for(var d,e=(eb[b]||[]).concat(eb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ib(a,b,c){var d,e,f,g,h,i,j,l,n=this,o={},p=a.style,q=a.nodeType&&U(a),r=m._data(a,"fxshow");c.queue||(h=m._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,n.always(function(){n.always(function(){h.unqueued--,m.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=m.css(a,"display"),l="none"===j?m._data(a,"olddisplay")||Fa(a.nodeName):j,"inline"===l&&"none"===m.css(a,"float")&&(k.inlineBlockNeedsLayout&&"inline"!==Fa(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",k.shrinkWrapBlocks()||n.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],ab.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||m.style(a,d)}else j=void 0;if(m.isEmptyObject(o))"inline"===("none"===j?Fa(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=m._data(a,"fxshow",{}),f&&(r.hidden=!q),q?m(a).show():n.done(function(){m(a).hide()}),n.done(function(){var b;m._removeData(a,"fxshow");for(b in o)m.style(a,b,o[b])});for(d in o)g=hb(q?r[d]:0,d,n),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function jb(a,b){var c,d,e,f,g;for(c in a)if(d=m.camelCase(c),e=b[d],f=a[c],m.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=m.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kb(a,b,c){var d,e,f=0,g=db.length,h=m.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=$a||fb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:m.extend({},b),opts:m.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:$a||fb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=m.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jb(k,j.opts.specialEasing);g>f;f++)if(d=db[f].call(j,a,k,j.opts))return d;return m.map(k,hb,j),m.isFunction(j.opts.start)&&j.opts.start.call(a,j),m.fx.timer(m.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}m.Animation=m.extend(kb,{tweener:function(a,b){m.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],eb[c]=eb[c]||[],eb[c].unshift(b)},prefilter:function(a,b){b?db.unshift(a):db.push(a)}}),m.speed=function(a,b,c){var d=a&&"object"==typeof a?m.extend({},a):{complete:c||!c&&b||m.isFunction(a)&&a,duration:a,easing:c&&b||b&&!m.isFunction(b)&&b};return d.duration=m.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in m.fx.speeds?m.fx.speeds[d.duration]:m.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){m.isFunction(d.old)&&d.old.call(this),d.queue&&m.dequeue(this,d.queue)},d},m.fn.extend({fadeTo:function(a,b,c,d){return this.filter(U).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=m.isEmptyObject(a),f=m.speed(b,c,d),g=function(){var b=kb(this,m.extend({},a),f);(e||m._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=m.timers,g=m._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&cb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&m.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=m._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=m.timers,g=d?d.length:0;for(c.finish=!0,m.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),m.each(["toggle","show","hide"],function(a,b){var c=m.fn[b];m.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gb(b,!0),a,d,e)}}),m.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){m.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),m.timers=[],m.fx.tick=function(){var a,b=m.timers,c=0;for($a=m.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||m.fx.stop(),$a=void 0},m.fx.timer=function(a){m.timers.push(a),a()?m.fx.start():m.timers.pop()},m.fx.interval=13,m.fx.start=function(){_a||(_a=setInterval(m.fx.tick,m.fx.interval))},m.fx.stop=function(){clearInterval(_a),_a=null},m.fx.speeds={slow:600,fast:200,_default:400},m.fn.delay=function(a,b){return a=m.fx?m.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e;b=y.createElement("div"),b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",d=b.getElementsByTagName("a")[0],c=y.createElement("select"),e=c.appendChild(y.createElement("option")),a=b.getElementsByTagName("input")[0],d.style.cssText="top:1px",k.getSetAttribute="t"!==b.className,k.style=/top/.test(d.getAttribute("style")),k.hrefNormalized="/a"===d.getAttribute("href"),k.checkOn=!!a.value,k.optSelected=e.selected,k.enctype=!!y.createElement("form").enctype,c.disabled=!0,k.optDisabled=!e.disabled,a=y.createElement("input"),a.setAttribute("value",""),k.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),k.radioValue="t"===a.value}();var lb=/\r/g;m.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=m.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,m(this).val()):a,null==e?e="":"number"==typeof e?e+="":m.isArray(e)&&(e=m.map(e,function(a){return null==a?"":a+""})),b=m.valHooks[this.type]||m.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=m.valHooks[e.type]||m.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(lb,""):null==c?"":c)}}}),m.extend({valHooks:{option:{get:function(a){var b=m.find.attr(a,"value");return null!=b?b:m.trim(m.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&m.nodeName(c.parentNode,"optgroup"))){if(b=m(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=m.makeArray(b),g=e.length;while(g--)if(d=e[g],m.inArray(m.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),m.each(["radio","checkbox"],function(){m.valHooks[this]={set:function(a,b){return m.isArray(b)?a.checked=m.inArray(m(a).val(),b)>=0:void 0}},k.checkOn||(m.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var mb,nb,ob=m.expr.attrHandle,pb=/^(?:checked|selected)$/i,qb=k.getSetAttribute,rb=k.input;m.fn.extend({attr:function(a,b){return V(this,m.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){m.removeAttr(this,a)})}}),m.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===K?m.prop(a,b,c):(1===f&&m.isXMLDoc(a)||(b=b.toLowerCase(),d=m.attrHooks[b]||(m.expr.match.bool.test(b)?nb:mb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=m.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void m.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=m.propFix[c]||c,m.expr.match.bool.test(c)?rb&&qb||!pb.test(c)?a[d]=!1:a[m.camelCase("default-"+c)]=a[d]=!1:m.attr(a,c,""),a.removeAttribute(qb?c:d)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&m.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),nb={set:function(a,b,c){return b===!1?m.removeAttr(a,c):rb&&qb||!pb.test(c)?a.setAttribute(!qb&&m.propFix[c]||c,c):a[m.camelCase("default-"+c)]=a[c]=!0,c}},m.each(m.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ob[b]||m.find.attr;ob[b]=rb&&qb||!pb.test(b)?function(a,b,d){var e,f;return d||(f=ob[b],ob[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,ob[b]=f),e}:function(a,b,c){return c?void 0:a[m.camelCase("default-"+b)]?b.toLowerCase():null}}),rb&&qb||(m.attrHooks.value={set:function(a,b,c){return m.nodeName(a,"input")?void(a.defaultValue=b):mb&&mb.set(a,b,c)}}),qb||(mb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},ob.id=ob.name=ob.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},m.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:mb.set},m.attrHooks.contenteditable={set:function(a,b,c){mb.set(a,""===b?!1:b,c)}},m.each(["width","height"],function(a,b){m.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),k.style||(m.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var sb=/^(?:input|select|textarea|button|object)$/i,tb=/^(?:a|area)$/i;m.fn.extend({prop:function(a,b){return V(this,m.prop,a,b,arguments.length>1)},removeProp:function(a){return a=m.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),m.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!m.isXMLDoc(a),f&&(b=m.propFix[b]||b,e=m.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=m.find.attr(a,"tabindex");return b?parseInt(b,10):sb.test(a.nodeName)||tb.test(a.nodeName)&&a.href?0:-1}}}}),k.hrefNormalized||m.each(["href","src"],function(a,b){m.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),k.optSelected||(m.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),m.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){m.propFix[this.toLowerCase()]=this}),k.enctype||(m.propFix.enctype="encoding");var ub=/[\t\r\n\f]/g;m.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=m.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(m.isFunction(a))return this.each(function(b){m(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(E)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ub," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?m.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(m.isFunction(a)?function(c){m(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=m(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===K||"boolean"===c)&&(this.className&&m._data(this,"__className__",this.className),this.className=this.className||a===!1?"":m._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ub," ").indexOf(b)>=0)return!0;return!1}}),m.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){m.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),m.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var vb=m.now(),wb=/\?/,xb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;m.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=m.trim(b+"");return e&&!m.trim(e.replace(xb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():m.error("Invalid JSON: "+b)},m.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||m.error("Invalid XML: "+b),c};var yb,zb,Ab=/#.*$/,Bb=/([?&])_=[^&]*/,Cb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Db=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Eb=/^(?:GET|HEAD)$/,Fb=/^\/\//,Gb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Hb={},Ib={},Jb="*/".concat("*");try{zb=location.href}catch(Kb){zb=y.createElement("a"),zb.href="",zb=zb.href}yb=Gb.exec(zb.toLowerCase())||[];function Lb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(m.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Mb(a,b,c,d){var e={},f=a===Ib;function g(h){var i;return e[h]=!0,m.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Nb(a,b){var c,d,e=m.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&m.extend(!0,a,c),a}function Ob(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Pb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}m.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:zb,type:"GET",isLocal:Db.test(yb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Jb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":m.parseJSON,"text xml":m.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Nb(Nb(a,m.ajaxSettings),b):Nb(m.ajaxSettings,a)},ajaxPrefilter:Lb(Hb),ajaxTransport:Lb(Ib),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=m.ajaxSetup({},b),l=k.context||k,n=k.context&&(l.nodeType||l.jquery)?m(l):m.event,o=m.Deferred(),p=m.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Cb.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||zb)+"").replace(Ab,"").replace(Fb,yb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=m.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(c=Gb.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===yb[1]&&c[2]===yb[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(yb[3]||("http:"===yb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=m.param(k.data,k.traditional)),Mb(Hb,k,b,v),2===t)return v;h=m.event&&k.global,h&&0===m.active++&&m.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Eb.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(wb.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Bb.test(e)?e.replace(Bb,"$1_="+vb++):e+(wb.test(e)?"&":"?")+"_="+vb++)),k.ifModified&&(m.lastModified[e]&&v.setRequestHeader("If-Modified-Since",m.lastModified[e]),m.etag[e]&&v.setRequestHeader("If-None-Match",m.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Jb+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Mb(Ib,k,b,v)){v.readyState=1,h&&n.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Ob(k,v,c)),u=Pb(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(m.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(m.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&n.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(n.trigger("ajaxComplete",[v,k]),--m.active||m.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return m.get(a,b,c,"json")},getScript:function(a,b){return m.get(a,void 0,b,"script")}}),m.each(["get","post"],function(a,b){m[b]=function(a,c,d,e){return m.isFunction(c)&&(e=e||d,d=c,c=void 0),m.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),m._evalUrl=function(a){return m.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},m.fn.extend({wrapAll:function(a){if(m.isFunction(a))return this.each(function(b){m(this).wrapAll(a.call(this,b))});if(this[0]){var b=m(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(m.isFunction(a)?function(b){m(this).wrapInner(a.call(this,b))}:function(){var b=m(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=m.isFunction(a);return this.each(function(c){m(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){m.nodeName(this,"body")||m(this).replaceWith(this.childNodes)}).end()}}),m.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!k.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||m.css(a,"display"))},m.expr.filters.visible=function(a){return!m.expr.filters.hidden(a)};var Qb=/%20/g,Rb=/\[\]$/,Sb=/\r?\n/g,Tb=/^(?:submit|button|image|reset|file)$/i,Ub=/^(?:input|select|textarea|keygen)/i;function Vb(a,b,c,d){var e;if(m.isArray(b))m.each(b,function(b,e){c||Rb.test(a)?d(a,e):Vb(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==m.type(b))d(a,b);else for(e in b)Vb(a+"["+e+"]",b[e],c,d)}m.param=function(a,b){var c,d=[],e=function(a,b){b=m.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=m.ajaxSettings&&m.ajaxSettings.traditional),m.isArray(a)||a.jquery&&!m.isPlainObject(a))m.each(a,function(){e(this.name,this.value)});else for(c in a)Vb(c,a[c],b,e);return d.join("&").replace(Qb,"+")},m.fn.extend({serialize:function(){return m.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=m.prop(this,"elements");return a?m.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!m(this).is(":disabled")&&Ub.test(this.nodeName)&&!Tb.test(a)&&(this.checked||!W.test(a))}).map(function(a,b){var c=m(this).val();return null==c?null:m.isArray(c)?m.map(c,function(a){return{name:b.name,value:a.replace(Sb,"\r\n")}}):{name:b.name,value:c.replace(Sb,"\r\n")}}).get()}}),m.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&Zb()||$b()}:Zb;var Wb=0,Xb={},Yb=m.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Xb)Xb[a](void 0,!0)}),k.cors=!!Yb&&"withCredentials"in Yb,Yb=k.ajax=!!Yb,Yb&&m.ajaxTransport(function(a){if(!a.crossDomain||k.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Wb;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Xb[g],b=void 0,f.onreadystatechange=m.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Xb[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function Zb(){try{return new a.XMLHttpRequest}catch(b){}}function $b(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}m.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return m.globalEval(a),a}}}),m.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),m.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=y.head||m("head")[0]||y.documentElement;return{send:function(d,e){b=y.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var _b=[],ac=/(=)\?(?=&|$)|\?\?/;m.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=_b.pop()||m.expando+"_"+vb++;return this[a]=!0,a}}),m.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(ac.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&ac.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=m.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(ac,"$1"+e):b.jsonp!==!1&&(b.url+=(wb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||m.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,_b.push(e)),g&&m.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),m.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||y;var d=u.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=m.buildFragment([a],b,e),e&&e.length&&m(e).remove(),m.merge([],d.childNodes))};var bc=m.fn.load;m.fn.load=function(a,b,c){if("string"!=typeof a&&bc)return bc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=m.trim(a.slice(h,a.length)),a=a.slice(0,h)),m.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&m.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?m("<div>").append(m.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},m.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){m.fn[b]=function(a){return this.on(b,a)}}),m.expr.filters.animated=function(a){return m.grep(m.timers,function(b){return a===b.elem}).length};var cc=a.document.documentElement;function dc(a){return m.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}m.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=m.css(a,"position"),l=m(a),n={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=m.css(a,"top"),i=m.css(a,"left"),j=("absolute"===k||"fixed"===k)&&m.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),m.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(n.top=b.top-h.top+g),null!=b.left&&(n.left=b.left-h.left+e),"using"in b?b.using.call(a,n):l.css(n)}},m.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){m.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,m.contains(b,e)?(typeof e.getBoundingClientRect!==K&&(d=e.getBoundingClientRect()),c=dc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===m.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),m.nodeName(a[0],"html")||(c=a.offset()),c.top+=m.css(a[0],"borderTopWidth",!0),c.left+=m.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-m.css(d,"marginTop",!0),left:b.left-c.left-m.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||cc;while(a&&!m.nodeName(a,"html")&&"static"===m.css(a,"position"))a=a.offsetParent;return a||cc})}}),m.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);m.fn[a]=function(d){return V(this,function(a,d,e){var f=dc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?m(f).scrollLeft():e,c?e:m(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),m.each(["top","left"],function(a,b){m.cssHooks[b]=La(k.pixelPosition,function(a,c){return c?(c=Ja(a,b),Ha.test(c)?m(a).position()[b]+"px":c):void 0})}),m.each({Height:"height",Width:"width"},function(a,b){m.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){m.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return V(this,function(b,c,d){var e;return m.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?m.css(b,c,g):m.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),m.fn.size=function(){return this.length},m.fn.andSelf=m.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return m});var ec=a.jQuery,fc=a.$;return m.noConflict=function(b){return a.$===m&&(a.$=fc),b&&a.jQuery===m&&(a.jQuery=ec),m},typeof b===K&&(a.jQuery=a.$=m),m}); jQuery.noConflict();
app/javascript/mastodon/components/missing_indicator.js
SerCom-KC/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; const MissingIndicator = () => ( <div className='regeneration-indicator missing-indicator'> <div> <div className='regeneration-indicator__figure' /> <div className='regeneration-indicator__label'> <FormattedMessage id='missing_indicator.label' tagName='strong' defaultMessage='Not found' /> <FormattedMessage id='missing_indicator.sublabel' defaultMessage='This resource could not be found' /> </div> </div> </div> ); export default MissingIndicator;
docs/src/app/components/pages/components/Card/Page.js
kasra-co/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import cardReadmeText from './README'; import cardExampleWithAvatarCode from '!raw!./ExampleWithAvatar'; import CardExampleWithAvatar from './ExampleWithAvatar'; import cardExampleExpandableCode from '!raw!./ExampleExpandable'; import CardExampleExpandable from './ExampleExpandable'; import cardExampleControlledCode from '!raw!./ExampleControlled'; import CardExampleControlled from './ExampleControlled'; import cardCode from '!raw!material-ui/Card/Card'; import cardActionsCode from '!raw!material-ui/Card/CardActions'; import cardHeaderCode from '!raw!material-ui/Card/CardHeader'; import cardMediaCode from '!raw!material-ui/Card/CardMedia'; import cardTextCode from '!raw!material-ui/Card/CardText'; import cardTitleCode from '!raw!material-ui/Card/CardTitle'; const descriptions = { avatar: 'A `Card` containing each of the card components: `CardHeader` (with avatar), `CardMedia` (with overlay), ' + '`CardTitle`, `CardText` & `CardActions`.', simple: 'An expandable `Card` with `CardHeader`, `CardText` and `CardActions`. ' + 'Use the icon to expand the card.', controlled: 'A controlled expandable `Card`. Use the icon, the toggle or the ' + 'buttons to control the expanded state of the card.', }; const CardPage = () => ( <div> <Title render={(previousTitle) => `Card - ${previousTitle}`} /> <MarkdownElement text={cardReadmeText} /> <CodeExample title="Card components example" description={descriptions.avatar} code={cardExampleWithAvatarCode} > <CardExampleWithAvatar /> </CodeExample> <CodeExample title="Expandable example" description={descriptions.simple} code={cardExampleExpandableCode} > <CardExampleExpandable /> </CodeExample> <CodeExample title="Controlled example" description={descriptions.controlled} code={cardExampleControlledCode} > <CardExampleControlled /> </CodeExample> <PropTypeDescription code={cardCode} header="### Card properties" /> <PropTypeDescription code={cardActionsCode} header="### CardActions properties" /> <PropTypeDescription code={cardHeaderCode} header="### CardHeader properties" /> <PropTypeDescription code={cardMediaCode} header="### CardMedia properties" /> <PropTypeDescription code={cardTextCode} header="### CardText properties" /> <PropTypeDescription code={cardTitleCode} header="### CardTitle properties" /> </div> ); export default CardPage;
ajax/libs/jquery-mobile/1.4.1/jquery.mobile.js
solojavier/cdnjs
/*! * jQuery Mobile 1.4.1 * Git HEAD hash: 18c1e32bfc4e0e92756dedc105d799131607f5bb <> Date: Wed Feb 12 2014 22:15:20 UTC * http://jquerymobile.com * * Copyright 2010, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license. * http://jquery.org/license * */ (function ( root, doc, factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery" ], function ( $ ) { factory( $, root, doc ); return $.mobile; }); } else { // Browser globals factory( root.jQuery, root, doc ); } }( this, document, function ( jQuery, window, document, undefined ) { (function( $ ) { $.mobile = {}; }( jQuery )); (function( $, window, undefined ) { $.extend( $.mobile, { // Version of the jQuery Mobile Framework version: "1.4.1", // Deprecated and no longer used in 1.4 remove in 1.5 // Define the url parameter used for referencing widget-generated sub-pages. // Translates to example.html&ui-page=subpageIdentifier // hash segment before &ui-page= is used to make Ajax request subPageUrlKey: "ui-page", hideUrlBar: true, // Keepnative Selector keepNative: ":jqmData(role='none'), :jqmData(role='nojs')", // Deprecated in 1.4 remove in 1.5 // Class assigned to page currently in view, and during transitions activePageClass: "ui-page-active", // Deprecated in 1.4 remove in 1.5 // Class used for "active" button state, from CSS framework activeBtnClass: "ui-btn-active", // Deprecated in 1.4 remove in 1.5 // Class used for "focus" form element state, from CSS framework focusClass: "ui-focus", // Automatically handle clicks and form submissions through Ajax, when same-domain ajaxEnabled: true, // Automatically load and show pages based on location.hash hashListeningEnabled: true, // disable to prevent jquery from bothering with links linkBindingEnabled: true, // Set default page transition - 'none' for no transitions defaultPageTransition: "fade", // Set maximum window width for transitions to apply - 'false' for no limit maxTransitionWidth: false, // Minimum scroll distance that will be remembered when returning to a page // Deprecated remove in 1.5 minScrollBack: 0, // Set default dialog transition - 'none' for no transitions defaultDialogTransition: "pop", // Error response message - appears when an Ajax page request fails pageLoadErrorMessage: "Error Loading Page", // For error messages, which theme does the box uses? pageLoadErrorMessageTheme: "a", // replace calls to window.history.back with phonegaps navigation helper // where it is provided on the window object phonegapNavigationEnabled: false, //automatically initialize the DOM when it's ready autoInitializePage: true, pushStateEnabled: true, // allows users to opt in to ignoring content by marking a parent element as // data-ignored ignoreContentEnabled: false, buttonMarkup: { hoverDelay: 200 }, // disable the alteration of the dynamic base tag or links in the case // that a dynamic base tag isn't supported dynamicBaseEnabled: true, // default the property to remove dependency on assignment in init module pageContainer: $(), //enable cross-domain page support allowCrossDomainPages: false, dialogHashKey: "&ui-state=dialog" }); })( jQuery, this ); (function( $, window, undefined ) { var nsNormalizeDict = {}, oldFind = $.find, rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, jqmDataRE = /:jqmData\(([^)]*)\)/g; $.extend( $.mobile, { // Namespace used framework-wide for data-attrs. Default is no namespace ns: "", // Retrieve an attribute from an element and perform some massaging of the value getAttribute: function( element, key ) { var data; element = element.jquery ? element[0] : element; if ( element && element.getAttribute ) { data = element.getAttribute( "data-" + $.mobile.ns + key ); } // Copied from core's src/data.js:dataAttr() // Convert from a string to a proper data type 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 ) ? JSON.parse( data ) : data; } catch( err ) {} return data; }, // Expose our cache for testing purposes. nsNormalizeDict: nsNormalizeDict, // Take a data attribute property, prepend the namespace // and then camel case the attribute string. Add the result // to our nsNormalizeDict so we don't have to do this again. nsNormalize: function( prop ) { return nsNormalizeDict[ prop ] || ( nsNormalizeDict[ prop ] = $.camelCase( $.mobile.ns + prop ) ); }, // Find the closest javascript page element to gather settings data jsperf test // http://jsperf.com/single-complex-selector-vs-many-complex-selectors/edit // possibly naive, but it shows that the parsing overhead for *just* the page selector vs // the page and dialog selector is negligable. This could probably be speed up by // doing a similar parent node traversal to the one found in the inherited theme code above closestPageData: function( $target ) { return $target .closest( ":jqmData(role='page'), :jqmData(role='dialog')" ) .data( "mobile-page" ); } }); // Mobile version of data and removeData and hasData methods // ensures all data is set and retrieved using jQuery Mobile's data namespace $.fn.jqmData = function( prop, value ) { var result; if ( typeof prop !== "undefined" ) { if ( prop ) { prop = $.mobile.nsNormalize( prop ); } // undefined is permitted as an explicit input for the second param // in this case it returns the value and does not set it to undefined if ( arguments.length < 2 || value === undefined ) { result = this.data( prop ); } else { result = this.data( prop, value ); } } return result; }; $.jqmData = function( elem, prop, value ) { var result; if ( typeof prop !== "undefined" ) { result = $.data( elem, prop ? $.mobile.nsNormalize( prop ) : prop, value ); } return result; }; $.fn.jqmRemoveData = function( prop ) { return this.removeData( $.mobile.nsNormalize( prop ) ); }; $.jqmRemoveData = function( elem, prop ) { return $.removeData( elem, $.mobile.nsNormalize( prop ) ); }; $.find = function( selector, context, ret, extra ) { if ( selector.indexOf( ":jqmData" ) > -1 ) { selector = selector.replace( jqmDataRE, "[data-" + ( $.mobile.ns || "" ) + "$1]" ); } return oldFind.call( this, selector, context, ret, extra ); }; $.extend( $.find, oldFind ); })( jQuery, this ); /*! * jQuery UI Core c0ab71056b936627e8a7821f03c044aec6280a40 * http://jqueryui.com * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/ui-core/ */ (function( $, undefined ) { var uuid = 0, runiqueId = /^ui-id-\d+$/; // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "c0ab71056b936627e8a7821f03c044aec6280a40", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ focus: (function( orig ) { return function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : orig.apply( this, arguments ); }; })( $.fn.focus ), scrollParent: function() { var scrollParent; if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) { scrollParent = this.parents().filter(function() { return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } else { scrollParent = this.parents().filter(function() { return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } return ( /fixed/ ).test( this.css( "position") ) || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent; }, uniqueId: function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + (++uuid); } }); }, removeUniqueId: function() { return this.each(function() { if ( runiqueId.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap=#" + mapName + "]" )[0]; return !!img && visible( img ); } return ( /input|select|textarea|button|object/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.support.selectstart = "onselectstart" in document.createElement( "div" ); $.fn.extend({ disableSelection: function() { return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }, enableSelection: function() { return this.unbind( ".ui-disableSelection" ); }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; } }); // $.ui.plugin is deprecated. Use $.widget() extensions instead. $.ui.plugin = { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args, allowDisconnected ) { var i, set = instance.plugins[ name ]; if ( !set ) { return; } if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }; })( jQuery ); (function( $, window, undefined ) { $.extend( $.mobile, { // define the window and the document objects window: $( window ), document: $( document ), // TODO: Remove and use $.ui.keyCode directly keyCode: $.ui.keyCode, // Place to store various widget extensions behaviors: {}, // Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value silentScroll: function( ypos ) { if ( $.type( ypos ) !== "number" ) { ypos = $.mobile.defaultHomeScroll; } // prevent scrollstart and scrollstop events $.event.special.scrollstart.enabled = false; setTimeout(function() { window.scrollTo( 0, ypos ); $.mobile.document.trigger( "silentscroll", { x: 0, y: ypos }); }, 20 ); setTimeout(function() { $.event.special.scrollstart.enabled = true; }, 150 ); }, getClosestBaseUrl: function( ele ) { // Find the closest page and extract out its url. var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ), base = $.mobile.path.documentBase.hrefNoHash; if ( !$.mobile.dynamicBaseEnabled || !url || !$.mobile.path.isPath( url ) ) { url = base; } return $.mobile.path.makeUrlAbsolute( url, base ); }, removeActiveLinkClass: function( forceRemoval ) { if ( !!$.mobile.activeClickedLink && ( !$.mobile.activeClickedLink.closest( "." + $.mobile.activePageClass ).length || forceRemoval ) ) { $.mobile.activeClickedLink.removeClass( $.mobile.activeBtnClass ); } $.mobile.activeClickedLink = null; }, // DEPRECATED in 1.4 // Find the closest parent with a theme class on it. Note that // we are not using $.fn.closest() on purpose here because this // method gets called quite a bit and we need it to be as fast // as possible. getInheritedTheme: function( el, defaultTheme ) { var e = el[ 0 ], ltr = "", re = /ui-(bar|body|overlay)-([a-z])\b/, c, m; while ( e ) { c = e.className || ""; if ( c && ( m = re.exec( c ) ) && ( ltr = m[ 2 ] ) ) { // We found a parent with a theme class // on it so bail from this loop. break; } e = e.parentNode; } // Return the theme letter we found, if none, return the // specified default. return ltr || defaultTheme || "a"; }, enhanceable: function( elements ) { return this.haveParents( elements, "enhance" ); }, hijackable: function( elements ) { return this.haveParents( elements, "ajax" ); }, haveParents: function( elements, attr ) { if ( !$.mobile.ignoreContentEnabled ) { return elements; } var count = elements.length, $newSet = $(), e, $element, excluded, i, c; for ( i = 0; i < count; i++ ) { $element = elements.eq( i ); excluded = false; e = elements[ i ]; while ( e ) { c = e.getAttribute ? e.getAttribute( "data-" + $.mobile.ns + attr ) : ""; if ( c === "false" ) { excluded = true; break; } e = e.parentNode; } if ( !excluded ) { $newSet = $newSet.add( $element ); } } return $newSet; }, getScreenHeight: function() { // Native innerHeight returns more accurate value for this across platforms, // jQuery version is here as a normalized fallback for platforms like Symbian return window.innerHeight || $.mobile.window.height(); }, //simply set the active page's minimum height to screen height, depending on orientation resetActivePageHeight: function( height ) { var page = $( "." + $.mobile.activePageClass ), pageHeight = page.height(), pageOuterHeight = page.outerHeight( true ); height = ( typeof height === "number" ) ? height : $.mobile.getScreenHeight(); page.css( "min-height", height - ( pageOuterHeight - pageHeight ) ); }, loading: function() { // If this is the first call to this function, instantiate a loader widget var loader = this.loading._widget || $( $.mobile.loader.prototype.defaultHtml ).loader(), // Call the appropriate method on the loader returnValue = loader.loader.apply( loader, arguments ); // Make sure the loader is retained for future calls to this function. this.loading._widget = loader; return returnValue; } }); $.addDependents = function( elem, newDependents ) { var $elem = $( elem ), dependents = $elem.jqmData( "dependents" ) || $(); $elem.jqmData( "dependents", $( dependents ).add( newDependents ) ); }; // plugins $.fn.extend({ removeWithDependents: function() { $.removeWithDependents( this ); }, // Enhance child elements enhanceWithin: function() { var index, widgetElements = {}, keepNative = $.mobile.page.prototype.keepNativeSelector(), that = this; // Add no js class to elements if ( $.mobile.nojs ) { $.mobile.nojs( this ); } // Bind links for ajax nav if ( $.mobile.links ) { $.mobile.links( this ); } // Degrade inputs for styleing if ( $.mobile.degradeInputsWithin ) { $.mobile.degradeInputsWithin( this ); } // Run buttonmarkup if ( $.fn.buttonMarkup ) { this.find( $.fn.buttonMarkup.initSelector ).not( keepNative ) .jqmEnhanceable().buttonMarkup(); } // Add classes for fieldContain if ( $.fn.fieldcontain ) { this.find( ":jqmData(role='fieldcontain')" ).not( keepNative ) .jqmEnhanceable().fieldcontain(); } // Enhance widgets $.each( $.mobile.widgets, function( name, constructor ) { // If initSelector not false find elements if ( constructor.initSelector ) { // Filter elements that should not be enhanced based on parents var elements = $.mobile.enhanceable( that.find( constructor.initSelector ) ); // If any matching elements remain filter ones with keepNativeSelector if ( elements.length > 0 ) { // $.mobile.page.prototype.keepNativeSelector is deprecated this is just for backcompat // Switch to $.mobile.keepNative in 1.5 which is just a value not a function elements = elements.not( keepNative ); } // Enhance whatever is left if ( elements.length > 0 ) { widgetElements[ constructor.prototype.widgetName ] = elements; } } }); for ( index in widgetElements ) { widgetElements[ index ][ index ](); } return this; }, addDependents: function( newDependents ) { $.addDependents( this, newDependents ); }, // note that this helper doesn't attempt to handle the callback // or setting of an html element's text, its only purpose is // to return the html encoded version of the text in all cases. (thus the name) getEncodedText: function() { return $( "<a>" ).text( this.text() ).html(); }, // fluent helper function for the mobile namespaced equivalent jqmEnhanceable: function() { return $.mobile.enhanceable( this ); }, jqmHijackable: function() { return $.mobile.hijackable( this ); } }); $.removeWithDependents = function( nativeElement ) { var element = $( nativeElement ); ( element.jqmData( "dependents" ) || $() ).remove(); element.remove(); }; $.addDependents = function( nativeElement, newDependents ) { var element = $( nativeElement ), dependents = element.jqmData( "dependents" ) || $(); element.jqmData( "dependents", $( dependents ).add( newDependents ) ); }; $.find.matches = function( expr, set ) { return $.find( expr, null, null, set ); }; $.find.matchesSelector = function( node, expr ) { return $.find( expr, null, null, [ node ] ).length > 0; }; })( jQuery, this ); /*! * jQuery UI Widget c0ab71056b936627e8a7821f03c044aec6280a40 * http://jqueryui.com * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/jQuery.widget/ */ (function( $, undefined ) { var uuid = 0, slice = Array.prototype.slice, _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } _cleanData( elems ); }; $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); return constructor; }; $.widget.extend = function( target ) { var input = slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( options === "instance" ) { returnValue = instance; return false; } if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( value === undefined ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( value === undefined ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled", !!value ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } return this; }, enable: function() { return this._setOptions({ disabled: false }); }, disable: function() { return this._setOptions({ disabled: true }); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { // accept selectors, DOM elements element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^(\w+)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); })( jQuery ); (function( $, undefined ) { var rcapitals = /[A-Z]/g, replaceFunction = function( c ) { return "-" + c.toLowerCase(); }; $.extend( $.Widget.prototype, { _getCreateOptions: function() { var option, value, elem = this.element[ 0 ], options = {}; // if ( !$.mobile.getAttribute( elem, "defaults" ) ) { for ( option in this.options ) { value = $.mobile.getAttribute( elem, option.replace( rcapitals, replaceFunction ) ); if ( value != null ) { options[ option ] = value; } } } return options; } }); //TODO: Remove in 1.5 for backcompat only $.mobile.widget = $.Widget; })( jQuery ); (function( $ ) { // TODO move loader class down into the widget settings var loaderClass = "ui-loader", $html = $( "html" ); $.widget( "mobile.loader", { // NOTE if the global config settings are defined they will override these // options options: { // the theme for the loading message theme: "a", // whether the text in the loading message is shown textVisible: false, // custom html for the inner content of the loading message html: "", // the text to be displayed when the popup is shown text: "loading" }, defaultHtml: "<div class='" + loaderClass + "'>" + "<span class='ui-icon-loading'></span>" + "<h1></h1>" + "</div>", // For non-fixed supportin browsers. Position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top fakeFixLoader: function() { var activeBtn = $( "." + $.mobile.activeBtnClass ).first(); this.element .css({ top: $.support.scrollTop && this.window.scrollTop() + this.window.height() / 2 || activeBtn.length && activeBtn.offset().top || 100 }); }, // check position of loader to see if it appears to be "fixed" to center // if not, use abs positioning checkLoaderPosition: function() { var offset = this.element.offset(), scrollTop = this.window.scrollTop(), screenHeight = $.mobile.getScreenHeight(); if ( offset.top < scrollTop || ( offset.top - scrollTop ) > screenHeight ) { this.element.addClass( "ui-loader-fakefix" ); this.fakeFixLoader(); this.window .unbind( "scroll", this.checkLoaderPosition ) .bind( "scroll", $.proxy( this.fakeFixLoader, this ) ); } }, resetHtml: function() { this.element.html( $( this.defaultHtml ).html() ); }, // Turn on/off page loading message. Theme doubles as an object argument // with the following shape: { theme: '', text: '', html: '', textVisible: '' } // NOTE that the $.mobile.loading* settings and params past the first are deprecated // TODO sweet jesus we need to break some of this out show: function( theme, msgText, textonly ) { var textVisible, message, loadSettings; this.resetHtml(); // use the prototype options so that people can set them globally at // mobile init. Consistency, it's what's for dinner if ( $.type( theme ) === "object" ) { loadSettings = $.extend( {}, this.options, theme ); theme = loadSettings.theme; } else { loadSettings = this.options; // here we prefer the theme value passed as a string argument, then // we prefer the global option because we can't use undefined default // prototype options, then the prototype option theme = theme || loadSettings.theme; } // set the message text, prefer the param, then the settings object // then loading message message = msgText || ( loadSettings.text === false ? "" : loadSettings.text ); // prepare the dom $html.addClass( "ui-loading" ); textVisible = loadSettings.textVisible; // add the proper css given the options (theme, text, etc) // Force text visibility if the second argument was supplied, or // if the text was explicitly set in the object args this.element.attr("class", loaderClass + " ui-corner-all ui-body-" + theme + " ui-loader-" + ( textVisible || msgText || theme.text ? "verbose" : "default" ) + ( loadSettings.textonly || textonly ? " ui-loader-textonly" : "" ) ); // TODO verify that jquery.fn.html is ok to use in both cases here // this might be overly defensive in preventing unknowing xss // if the html attribute is defined on the loading settings, use that // otherwise use the fallbacks from above if ( loadSettings.html ) { this.element.html( loadSettings.html ); } else { this.element.find( "h1" ).text( message ); } // attach the loader to the DOM this.element.appendTo( $.mobile.pageContainer ); // check that the loader is visible this.checkLoaderPosition(); // on scroll check the loader position this.window.bind( "scroll", $.proxy( this.checkLoaderPosition, this ) ); }, hide: function() { $html.removeClass( "ui-loading" ); if ( this.options.text ) { this.element.removeClass( "ui-loader-fakefix" ); } $.mobile.window.unbind( "scroll", this.fakeFixLoader ); $.mobile.window.unbind( "scroll", this.checkLoaderPosition ); } }); })(jQuery, this); /*! * jQuery hashchange event - v1.3 - 7/21/2010 * http://benalman.com/projects/jquery-hashchange-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Script: jQuery hashchange event // // *Version: 1.3, Last updated: 7/21/2010* // // Project Home - http://benalman.com/projects/jquery-hashchange-plugin/ // GitHub - http://github.com/cowboy/jquery-hashchange/ // Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js // (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // These working examples, complete with fully commented code, illustrate a few // ways in which this plugin can be used. // // hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/ // document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5, // Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5. // Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/ // // About: Known issues // // While this jQuery hashchange event implementation is quite stable and // robust, there are a few unfortunate browser bugs surrounding expected // hashchange event-based behaviors, independent of any JavaScript // window.onhashchange abstraction. See the following examples for more // information: // // Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/ // Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/ // WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/ // Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/ // // Also note that should a browser natively support the window.onhashchange // event, but not report that it does, the fallback polling loop will be used. // // About: Release History // // 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more // "removable" for mobile-only development. Added IE6/7 document.title // support. Attempted to make Iframe as hidden as possible by using // techniques from http://www.paciellogroup.com/blog/?p=604. Added // support for the "shortcut" format $(window).hashchange( fn ) and // $(window).hashchange() like jQuery provides for built-in events. // Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and // lowered its default value to 50. Added <jQuery.fn.hashchange.domain> // and <jQuery.fn.hashchange.src> properties plus document-domain.html // file to address access denied issues when setting document.domain in // IE6/7. // 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin // from a page on another domain would cause an error in Safari 4. Also, // IE6/7 Iframe is now inserted after the body (this actually works), // which prevents the page from scrolling when the event is first bound. // Event can also now be bound before DOM ready, but it won't be usable // before then in IE6/7. // 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug // where browser version is incorrectly reported as 8.0, despite // inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag. // 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special // window.onhashchange functionality into a separate plugin for users // who want just the basic event & back button support, without all the // extra awesomeness that BBQ provides. This plugin will be included as // part of jQuery BBQ, but also be available separately. (function($,window,undefined){ '$:nomunge'; // Used by YUI compressor. // Reused string. var str_hashchange = 'hashchange', // Method / object references. doc = document, fake_onhashchange, special = $.event.special, // Does the browser support window.onhashchange? Note that IE8 running in // IE7 compatibility mode reports true for 'onhashchange' in window, even // though the event isn't supported, so also test document.documentMode. doc_mode = doc.documentMode, supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 ); // Get location.hash (or what you'd expect location.hash to be) sans any // leading #. Thanks for making this necessary, Firefox! function get_fragment( url ) { url = url || location.href; return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' ); }; // Method: jQuery.fn.hashchange // // Bind a handler to the window.onhashchange event or trigger all bound // window.onhashchange event handlers. This behavior is consistent with // jQuery's built-in event handlers. // // Usage: // // > jQuery(window).hashchange( [ handler ] ); // // Arguments: // // handler - (Function) Optional handler to be bound to the hashchange // event. This is a "shortcut" for the more verbose form: // jQuery(window).bind( 'hashchange', handler ). If handler is omitted, // all bound window.onhashchange event handlers will be triggered. This // is a shortcut for the more verbose // jQuery(window).trigger( 'hashchange' ). These forms are described in // the <hashchange event> section. // // Returns: // // (jQuery) The initial jQuery collection of elements. // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and // $(elem).hashchange() for triggering, like jQuery does for built-in events. $.fn[ str_hashchange ] = function( fn ) { return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange ); }; // Property: jQuery.fn.hashchange.delay // // The numeric interval (in milliseconds) at which the <hashchange event> // polling loop executes. Defaults to 50. // Property: jQuery.fn.hashchange.domain // // If you're setting document.domain in your JavaScript, and you want hash // history to work in IE6/7, not only must this property be set, but you must // also set document.domain BEFORE jQuery is loaded into the page. This // property is only applicable if you are supporting IE6/7 (or IE8 operating // in "IE7 compatibility" mode). // // In addition, the <jQuery.fn.hashchange.src> property must be set to the // path of the included "document-domain.html" file, which can be renamed or // modified if necessary (note that the document.domain specified must be the // same in both your main JavaScript as well as in this file). // // Usage: // // jQuery.fn.hashchange.domain = document.domain; // Property: jQuery.fn.hashchange.src // // If, for some reason, you need to specify an Iframe src file (for example, // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can // do so using this property. Note that when using this property, history // won't be recorded in IE6/7 until the Iframe src file loads. This property // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7 // compatibility" mode). // // Usage: // // jQuery.fn.hashchange.src = 'path/to/file.html'; $.fn[ str_hashchange ].delay = 50; /* $.fn[ str_hashchange ].domain = null; $.fn[ str_hashchange ].src = null; */ // Event: hashchange event // // Fired when location.hash changes. In browsers that support it, the native // HTML5 window.onhashchange event is used, otherwise a polling loop is // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7 // compatibility" mode), a hidden Iframe is created to allow the back button // and hash-based history to work. // // Usage as described in <jQuery.fn.hashchange>: // // > // Bind an event handler. // > jQuery(window).hashchange( function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).hashchange(); // // A more verbose usage that allows for event namespacing: // // > // Bind an event handler. // > jQuery(window).bind( 'hashchange', function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).trigger( 'hashchange' ); // // Additional Notes: // // * The polling loop and Iframe are not created until at least one handler // is actually bound to the 'hashchange' event. // * If you need the bound handler(s) to execute immediately, in cases where // a location.hash exists on page load, via bookmark or page refresh for // example, use jQuery(window).hashchange() or the more verbose // jQuery(window).trigger( 'hashchange' ). // * The event can be bound before DOM ready, but since it won't be usable // before then in IE6/7 (due to the necessary Iframe), recommended usage is // to bind it inside a DOM ready handler. // Override existing $.event.special.hashchange methods (allowing this plugin // to be defined after jQuery BBQ in BBQ's source code). special[ str_hashchange ] = $.extend( special[ str_hashchange ], { // Called only when the first 'hashchange' event is bound to window. setup: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to create our own. And we don't want to call this // until the user binds to the event, just in case they never do, since it // will create a polling loop and possibly even a hidden Iframe. $( fake_onhashchange.start ); }, // Called only when the last 'hashchange' event is unbound from window. teardown: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to stop ours (if possible). $( fake_onhashchange.stop ); } }); // fake_onhashchange does all the work of triggering the window.onhashchange // event for browsers that don't natively support it, including creating a // polling loop to watch for hash changes and in IE 6/7 creating a hidden // Iframe to enable back and forward. fake_onhashchange = (function(){ var self = {}, timeout_id, // Remember the initial hash so it doesn't get triggered immediately. last_hash = get_fragment(), fn_retval = function(val){ return val; }, history_set = fn_retval, history_get = fn_retval; // Start the polling loop. self.start = function() { timeout_id || poll(); }; // Stop the polling loop. self.stop = function() { timeout_id && clearTimeout( timeout_id ); timeout_id = undefined; }; // This polling loop checks every $.fn.hashchange.delay milliseconds to see // if location.hash has changed, and triggers the 'hashchange' event on // window when necessary. function poll() { var hash = get_fragment(), history_hash = history_get( last_hash ); if ( hash !== last_hash ) { history_set( last_hash = hash, history_hash ); $(window).trigger( str_hashchange ); } else if ( history_hash !== last_hash ) { location.href = location.href.replace( /#.*/, '' ) + history_hash; } timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay ); }; // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv window.attachEvent && !window.addEventListener && !supports_onhashchange && (function(){ // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8 // when running in "IE7 compatibility" mode. var iframe, iframe_src; // When the event is bound and polling starts in IE 6/7, create a hidden // Iframe for history handling. self.start = function(){ if ( !iframe ) { iframe_src = $.fn[ str_hashchange ].src; iframe_src = iframe_src && iframe_src + get_fragment(); // Create hidden Iframe. Attempt to make Iframe as hidden as possible // by using techniques from http://www.paciellogroup.com/blog/?p=604. iframe = $('<iframe tabindex="-1" title="empty"/>').hide() // When Iframe has completely loaded, initialize the history and // start polling. .one( 'load', function(){ iframe_src || history_set( get_fragment() ); poll(); }) // Load Iframe src if specified, otherwise nothing. .attr( 'src', iframe_src || 'javascript:0' ) // Append Iframe after the end of the body to prevent unnecessary // initial page scrolling (yes, this works). .insertAfter( 'body' )[0].contentWindow; // Whenever `document.title` changes, update the Iframe's title to // prettify the back/next history menu entries. Since IE sometimes // errors with "Unspecified error" the very first time this is set // (yes, very useful) wrap this with a try/catch block. doc.onpropertychange = function(){ try { if ( event.propertyName === 'title' ) { iframe.document.title = doc.title; } } catch(e) {} }; } }; // Override the "stop" method since an IE6/7 Iframe was created. Even // if there are no longer any bound event handlers, the polling loop // is still necessary for back/next to work at all! self.stop = fn_retval; // Get history by looking at the hidden Iframe's location.hash. history_get = function() { return get_fragment( iframe.location.href ); }; // Set a new history item by opening and then closing the Iframe // document, *then* setting its location.hash. If document.domain has // been set, update that as well. history_set = function( hash, history_hash ) { var iframe_doc = iframe.document, domain = $.fn[ str_hashchange ].domain; if ( hash !== history_hash ) { // Update Iframe with any initial `document.title` that might be set. iframe_doc.title = doc.title; // Opening the Iframe's document after it has been closed is what // actually adds a history entry. iframe_doc.open(); // Set document.domain for the Iframe document as well, if necessary. domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' ); iframe_doc.close(); // Update the Iframe's hash, for great justice. iframe.location.hash = hash; } }; })(); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return self; })(); })(jQuery,this); (function( $, undefined ) { /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ window.matchMedia = window.matchMedia || (function( doc, undefined ) { var bool, docElem = doc.documentElement, refNode = docElem.firstElementChild || docElem.firstChild, // fakeBody required for <FF4 when executed in <head> fakeBody = doc.createElement( "body" ), div = doc.createElement( "div" ); div.id = "mq-test-1"; div.style.cssText = "position:absolute;top:-100em"; fakeBody.style.background = "none"; fakeBody.appendChild(div); return function(q){ div.innerHTML = "&shy;<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>"; docElem.insertBefore( fakeBody, refNode ); bool = div.offsetWidth === 42; docElem.removeChild( fakeBody ); return { matches: bool, media: q }; }; }( document )); // $.mobile.media uses matchMedia to return a boolean. $.mobile.media = function( q ) { return window.matchMedia( q ).matches; }; })(jQuery); (function( $, undefined ) { var support = { touch: "ontouchend" in document }; $.mobile.support = $.mobile.support || {}; $.extend( $.support, support ); $.extend( $.mobile.support, support ); }( jQuery )); (function( $, undefined ) { $.extend( $.support, { orientation: "orientation" in window && "onorientationchange" in window }); }( jQuery )); (function( $, undefined ) { // thx Modernizr function propExists( prop ) { var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ), props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " ), v; for ( v in props ) { if ( fbCSS[ props[ v ] ] !== undefined ) { return true; } } } var fakeBody = $( "<body>" ).prependTo( "html" ), fbCSS = fakeBody[ 0 ].style, vendors = [ "Webkit", "Moz", "O" ], webos = "palmGetResource" in window, //only used to rule out scrollTop operamini = window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]", bb = window.blackberry && !propExists( "-webkit-transform" ), //only used to rule out box shadow, as it's filled opaque on BB 5 and lower nokiaLTE7_3; // inline SVG support test function inlineSVG() { // Thanks Modernizr & Erik Dahlstrom var w = window, svg = !!w.document.createElementNS && !!w.document.createElementNS( "http://www.w3.org/2000/svg", "svg" ).createSVGRect && !( w.opera && navigator.userAgent.indexOf( "Chrome" ) === -1 ), support = function( data ) { if ( !( data && svg ) ) { $( "html" ).addClass( "ui-nosvg" ); } }, img = new w.Image(); img.onerror = function() { support( false ); }; img.onload = function() { support( img.width === 1 && img.height === 1 ); }; img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; } function transform3dTest() { var mqProp = "transform-3d", // Because the `translate3d` test below throws false positives in Android: ret = $.mobile.media( "(-" + vendors.join( "-" + mqProp + "),(-" ) + "-" + mqProp + "),(" + mqProp + ")" ), el, transforms, t; if ( ret ) { return !!ret; } el = document.createElement( "div" ); transforms = { // We’re omitting Opera for the time being; MS uses unprefixed. "MozTransform": "-moz-transform", "transform": "transform" }; fakeBody.append( el ); for ( t in transforms ) { if ( el.style[ t ] !== undefined ) { el.style[ t ] = "translate3d( 100px, 1px, 1px )"; ret = window.getComputedStyle( el ).getPropertyValue( transforms[ t ] ); } } return ( !!ret && ret !== "none" ); } // Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting ) function baseTagTest() { var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/", base = $( "head base" ), fauxEle = null, href = "", link, rebase; if ( !base.length ) { base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" ); } else { href = base.attr( "href" ); } link = $( "<a href='testurl' />" ).prependTo( fakeBody ); rebase = link[ 0 ].href; base[ 0 ].href = href || location.pathname; if ( fauxEle ) { fauxEle.remove(); } return rebase.indexOf( fauxBase ) === 0; } // Thanks Modernizr function cssPointerEventsTest() { var element = document.createElement( "x" ), documentElement = document.documentElement, getComputedStyle = window.getComputedStyle, supports; if ( !( "pointerEvents" in element.style ) ) { return false; } element.style.pointerEvents = "auto"; element.style.pointerEvents = "x"; documentElement.appendChild( element ); supports = getComputedStyle && getComputedStyle( element, "" ).pointerEvents === "auto"; documentElement.removeChild( element ); return !!supports; } function boundingRect() { var div = document.createElement( "div" ); return typeof div.getBoundingClientRect !== "undefined"; } // non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683 // allows for inclusion of IE 6+, including Windows Mobile 7 $.extend( $.mobile, { browser: {} } ); $.mobile.browser.oldIE = (function() { var v = 3, div = document.createElement( "div" ), a = div.all || []; do { div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->"; } while( a[0] ); return v > 4 ? v : !v; })(); function fixedPosition() { var w = window, ua = navigator.userAgent, platform = navigator.platform, // Rendering engine is Webkit, and capture major version wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ), wkversion = !!wkmatch && wkmatch[ 1 ], ffmatch = ua.match( /Fennec\/([0-9]+)/ ), ffversion = !!ffmatch && ffmatch[ 1 ], operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ ), omversion = !!operammobilematch && operammobilematch[ 1 ]; if ( // iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5) ( ( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534 ) || // Opera Mini ( w.operamini && ({}).toString.call( w.operamini ) === "[object OperaMini]" ) || ( operammobilematch && omversion < 7458 ) || //Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2) ( ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533 ) || // Firefox Mobile before 6.0 - ( ffversion && ffversion < 6 ) || // WebOS less than 3 ( "palmGetResource" in window && wkversion && wkversion < 534 ) || // MeeGo ( ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1 ) ) { return false; } return true; } $.extend( $.support, { // Note, Chrome for iOS has an extremely quirky implementation of popstate. // We've chosen to take the shortest path to a bug fix here for issue #5426 // See the following link for information about the regex chosen // https://developers.google.com/chrome/mobile/docs/user-agent#chrome_for_ios_user-agent pushState: "pushState" in history && "replaceState" in history && // When running inside a FF iframe, calling replaceState causes an error !( window.navigator.userAgent.indexOf( "Firefox" ) >= 0 && window.top !== window ) && ( window.navigator.userAgent.search(/CriOS/) === -1 ), mediaquery: $.mobile.media( "only all" ), cssPseudoElement: !!propExists( "content" ), touchOverflow: !!propExists( "overflowScrolling" ), cssTransform3d: transform3dTest(), boxShadow: !!propExists( "boxShadow" ) && !bb, fixedPosition: fixedPosition(), scrollTop: ("pageXOffset" in window || "scrollTop" in document.documentElement || "scrollTop" in fakeBody[ 0 ]) && !webos && !operamini, dynamicBaseTag: baseTagTest(), cssPointerEvents: cssPointerEventsTest(), boundingRect: boundingRect(), inlineSVG: inlineSVG }); fakeBody.remove(); // $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian) // or that generally work better browsing in regular http for full page refreshes (Opera Mini) // Note: This detection below is used as a last resort. // We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible nokiaLTE7_3 = (function() { var ua = window.navigator.userAgent; //The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older return ua.indexOf( "Nokia" ) > -1 && ( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) && ua.indexOf( "AppleWebKit" ) > -1 && ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ ); })(); // Support conditions that must be met in order to proceed // default enhanced qualifications are media query support OR IE 7+ $.mobile.gradeA = function() { return ( ( $.support.mediaquery && $.support.cssPseudoElement ) || $.mobile.browser.oldIE && $.mobile.browser.oldIE >= 8 ) && ( $.support.boundingRect || $.fn.jquery.match(/1\.[0-7+]\.[0-9+]?/) !== null ); }; $.mobile.ajaxBlacklist = // BlackBerry browsers, pre-webkit window.blackberry && !window.WebKitPoint || // Opera Mini operamini || // Symbian webkits pre 7.3 nokiaLTE7_3; // Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices // to render the stylesheets when they're referenced before this script, as we'd recommend doing. // This simply reappends the CSS in place, which for some reason makes it apply if ( nokiaLTE7_3 ) { $(function() { $( "head link[rel='stylesheet']" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" ); }); } // For ruling out shadows via css if ( !$.support.boxShadow ) { $( "html" ).addClass( "ui-noboxshadow" ); } })( jQuery ); (function( $, undefined ) { var $win = $.mobile.window, self, dummyFnToInitNavigate = function() { }; $.event.special.beforenavigate = { setup: function() { $win.on( "navigate", dummyFnToInitNavigate ); }, teardown: function() { $win.off( "navigate", dummyFnToInitNavigate ); } }; $.event.special.navigate = self = { bound: false, pushStateEnabled: true, originalEventName: undefined, // If pushstate support is present and push state support is defined to // be true on the mobile namespace. isPushStateEnabled: function() { return $.support.pushState && $.mobile.pushStateEnabled === true && this.isHashChangeEnabled(); }, // !! assumes mobile namespace is present isHashChangeEnabled: function() { return $.mobile.hashListeningEnabled === true; }, // TODO a lot of duplication between popstate and hashchange popstate: function( event ) { var newEvent = new $.Event( "navigate" ), beforeNavigate = new $.Event( "beforenavigate" ), state = event.originalEvent.state || {}; beforeNavigate.originalEvent = event; $win.trigger( beforeNavigate ); if ( beforeNavigate.isDefaultPrevented() ) { return; } if ( event.historyState ) { $.extend(state, event.historyState); } // Make sure the original event is tracked for the end // user to inspect incase they want to do something special newEvent.originalEvent = event; // NOTE we let the current stack unwind because any assignment to // location.hash will stop the world and run this event handler. By // doing this we create a similar behavior to hashchange on hash // assignment setTimeout(function() { $win.trigger( newEvent, { state: state }); }, 0); }, hashchange: function( event /*, data */ ) { var newEvent = new $.Event( "navigate" ), beforeNavigate = new $.Event( "beforenavigate" ); beforeNavigate.originalEvent = event; $win.trigger( beforeNavigate ); if ( beforeNavigate.isDefaultPrevented() ) { return; } // Make sure the original event is tracked for the end // user to inspect incase they want to do something special newEvent.originalEvent = event; // Trigger the hashchange with state provided by the user // that altered the hash $win.trigger( newEvent, { // Users that want to fully normalize the two events // will need to do history management down the stack and // add the state to the event before this binding is fired // TODO consider allowing for the explicit addition of callbacks // to be fired before this value is set to avoid event timing issues state: event.hashchangeState || {} }); }, // TODO We really only want to set this up once // but I'm not clear if there's a beter way to achieve // this with the jQuery special event structure setup: function( /* data, namespaces */ ) { if ( self.bound ) { return; } self.bound = true; if ( self.isPushStateEnabled() ) { self.originalEventName = "popstate"; $win.bind( "popstate.navigate", self.popstate ); } else if ( self.isHashChangeEnabled() ) { self.originalEventName = "hashchange"; $win.bind( "hashchange.navigate", self.hashchange ); } } }; })( jQuery ); (function( $, undefined ) { var path, $base, dialogHashKey = "&ui-state=dialog"; $.mobile.path = path = { uiStateKey: "&ui-state", // This scary looking regular expression parses an absolute URL or its relative // variants (protocol, site, document, query, and hash), into the various // components (protocol, host, path, query, fragment, etc that make up the // URL as well as some other commonly used sub-parts. When used with RegExp.exec() // or String.match, it parses the URL into a results array that looks like this: // // [0]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread#msg-content // [1]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread // [2]: http://jblas:password@mycompany.com:8080/mail/inbox // [3]: http://jblas:password@mycompany.com:8080 // [4]: http: // [5]: // // [6]: jblas:password@mycompany.com:8080 // [7]: jblas:password // [8]: jblas // [9]: password // [10]: mycompany.com:8080 // [11]: mycompany.com // [12]: 8080 // [13]: /mail/inbox // [14]: /mail/ // [15]: inbox // [16]: ?msg=1234&type=unread // [17]: #msg-content // urlParseRE: /^\s*(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/, // Abstraction to address xss (Issue #4787) by removing the authority in // browsers that auto decode it. All references to location.href should be // replaced with a call to this method so that it can be dealt with properly here getLocation: function( url ) { var uri = url ? this.parseUrl( url ) : location, hash = this.parseUrl( url || location.href ).hash; // mimic the browser with an empty string when the hash is empty hash = hash === "#" ? "" : hash; // Make sure to parse the url or the location object for the hash because using location.hash // is autodecoded in firefox, the rest of the url should be from the object (location unless // we're testing) to avoid the inclusion of the authority return uri.protocol + "//" + uri.host + uri.pathname + uri.search + hash; }, //return the original document url getDocumentUrl: function( asParsedObject ) { return asParsedObject ? $.extend( {}, path.documentUrl ) : path.documentUrl.href; }, parseLocation: function() { return this.parseUrl( this.getLocation() ); }, //Parse a URL into a structure that allows easy access to //all of the URL components by name. parseUrl: function( url ) { // If we're passed an object, we'll assume that it is // a parsed url object and just return it back to the caller. if ( $.type( url ) === "object" ) { return url; } var matches = path.urlParseRE.exec( url || "" ) || []; // Create an object that allows the caller to access the sub-matches // by name. Note that IE returns an empty string instead of undefined, // like all other browsers do, so we normalize everything so its consistent // no matter what browser we're running on. return { href: matches[ 0 ] || "", hrefNoHash: matches[ 1 ] || "", hrefNoSearch: matches[ 2 ] || "", domain: matches[ 3 ] || "", protocol: matches[ 4 ] || "", doubleSlash: matches[ 5 ] || "", authority: matches[ 6 ] || "", username: matches[ 8 ] || "", password: matches[ 9 ] || "", host: matches[ 10 ] || "", hostname: matches[ 11 ] || "", port: matches[ 12 ] || "", pathname: matches[ 13 ] || "", directory: matches[ 14 ] || "", filename: matches[ 15 ] || "", search: matches[ 16 ] || "", hash: matches[ 17 ] || "" }; }, //Turn relPath into an asbolute path. absPath is //an optional absolute path which describes what //relPath is relative to. makePathAbsolute: function( relPath, absPath ) { var absStack, relStack, i, d; if ( relPath && relPath.charAt( 0 ) === "/" ) { return relPath; } relPath = relPath || ""; absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : ""; absStack = absPath ? absPath.split( "/" ) : []; relStack = relPath.split( "/" ); for ( i = 0; i < relStack.length; i++ ) { d = relStack[ i ]; switch ( d ) { case ".": break; case "..": if ( absStack.length ) { absStack.pop(); } break; default: absStack.push( d ); break; } } return "/" + absStack.join( "/" ); }, //Returns true if both urls have the same domain. isSameDomain: function( absUrl1, absUrl2 ) { return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain; }, //Returns true for any relative variant. isRelativeUrl: function( url ) { // All relative Url variants have one thing in common, no protocol. return path.parseUrl( url ).protocol === ""; }, //Returns true for an absolute url. isAbsoluteUrl: function( url ) { return path.parseUrl( url ).protocol !== ""; }, //Turn the specified realtive URL into an absolute one. This function //can handle all relative variants (protocol, site, document, query, fragment). makeUrlAbsolute: function( relUrl, absUrl ) { if ( !path.isRelativeUrl( relUrl ) ) { return relUrl; } if ( absUrl === undefined ) { absUrl = this.documentBase; } var relObj = path.parseUrl( relUrl ), absObj = path.parseUrl( absUrl ), protocol = relObj.protocol || absObj.protocol, doubleSlash = relObj.protocol ? relObj.doubleSlash : ( relObj.doubleSlash || absObj.doubleSlash ), authority = relObj.authority || absObj.authority, hasPath = relObj.pathname !== "", pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ), search = relObj.search || ( !hasPath && absObj.search ) || "", hash = relObj.hash; return protocol + doubleSlash + authority + pathname + search + hash; }, //Add search (aka query) params to the specified url. addSearchParams: function( url, params ) { var u = path.parseUrl( url ), p = ( typeof params === "object" ) ? $.param( params ) : params, s = u.search || "?"; return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" ); }, convertUrlToDataUrl: function( absUrl ) { var u = path.parseUrl( absUrl ); if ( path.isEmbeddedPage( u ) ) { // For embedded pages, remove the dialog hash key as in getFilePath(), // and remove otherwise the Data Url won't match the id of the embedded Page. return u.hash .split( dialogHashKey )[0] .replace( /^#/, "" ) .replace( /\?.*$/, "" ); } else if ( path.isSameDomain( u, this.documentBase ) ) { return u.hrefNoHash.replace( this.documentBase.domain, "" ).split( dialogHashKey )[0]; } return window.decodeURIComponent(absUrl); }, //get path from current hash, or from a file path get: function( newPath ) { if ( newPath === undefined ) { newPath = path.parseLocation().hash; } return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, "" ); }, //set location hash to path set: function( path ) { location.hash = path; }, //test if a given url (string) is a path //NOTE might be exceptionally naive isPath: function( url ) { return ( /\// ).test( url ); }, //return a url path with the window's location protocol/hostname/pathname removed clean: function( url ) { return url.replace( this.documentBase.domain, "" ); }, //just return the url without an initial # stripHash: function( url ) { return url.replace( /^#/, "" ); }, stripQueryParams: function( url ) { return url.replace( /\?.*$/, "" ); }, //remove the preceding hash, any query params, and dialog notations cleanHash: function( hash ) { return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) ); }, isHashValid: function( hash ) { return ( /^#[^#]+$/ ).test( hash ); }, //check whether a url is referencing the same domain, or an external domain or different protocol //could be mailto, etc isExternal: function( url ) { var u = path.parseUrl( url ); return u.protocol && u.domain !== this.documentUrl.domain ? true : false; }, hasProtocol: function( url ) { return ( /^(:?\w+:)/ ).test( url ); }, isEmbeddedPage: function( url ) { var u = path.parseUrl( url ); //if the path is absolute, then we need to compare the url against //both the this.documentUrl and the documentBase. The main reason for this //is that links embedded within external documents will refer to the //application document, whereas links embedded within the application //document will be resolved against the document base. if ( u.protocol !== "" ) { return ( !this.isPath(u.hash) && u.hash && ( u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ) ) ); } return ( /^#/ ).test( u.href ); }, squash: function( url, resolutionUrl ) { var href, cleanedUrl, search, stateIndex, isPath = this.isPath( url ), uri = this.parseUrl( url ), preservedHash = uri.hash, uiState = ""; // produce a url against which we can resole the provided path resolutionUrl = resolutionUrl || (path.isPath(url) ? path.getLocation() : path.getDocumentUrl()); // If the url is anything but a simple string, remove any preceding hash // eg #foo/bar -> foo/bar // #foo -> #foo cleanedUrl = isPath ? path.stripHash( url ) : url; // If the url is a full url with a hash check if the parsed hash is a path // if it is, strip the #, and use it otherwise continue without change cleanedUrl = path.isPath( uri.hash ) ? path.stripHash( uri.hash ) : cleanedUrl; // Split the UI State keys off the href stateIndex = cleanedUrl.indexOf( this.uiStateKey ); // store the ui state keys for use if ( stateIndex > -1 ) { uiState = cleanedUrl.slice( stateIndex ); cleanedUrl = cleanedUrl.slice( 0, stateIndex ); } // make the cleanedUrl absolute relative to the resolution url href = path.makeUrlAbsolute( cleanedUrl, resolutionUrl ); // grab the search from the resolved url since parsing from // the passed url may not yield the correct result search = this.parseUrl( href ).search; // TODO all this crap is terrible, clean it up if ( isPath ) { // reject the hash if it's a path or it's just a dialog key if ( path.isPath( preservedHash ) || preservedHash.replace("#", "").indexOf( this.uiStateKey ) === 0) { preservedHash = ""; } // Append the UI State keys where it exists and it's been removed // from the url if ( uiState && preservedHash.indexOf( this.uiStateKey ) === -1) { preservedHash += uiState; } // make sure that pound is on the front of the hash if ( preservedHash.indexOf( "#" ) === -1 && preservedHash !== "" ) { preservedHash = "#" + preservedHash; } // reconstruct each of the pieces with the new search string and hash href = path.parseUrl( href ); href = href.protocol + "//" + href.host + href.pathname + search + preservedHash; } else { href += href.indexOf( "#" ) > -1 ? uiState : "#" + uiState; } return href; }, isPreservableHash: function( hash ) { return hash.replace( "#", "" ).indexOf( this.uiStateKey ) === 0; }, // Escape weird characters in the hash if it is to be used as a selector hashToSelector: function( hash ) { var hasHash = ( hash.substring( 0, 1 ) === "#" ); if ( hasHash ) { hash = hash.substring( 1 ); } return ( hasHash ? "#" : "" ) + hash.replace( /([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g, "\\$1" ); }, // return the substring of a filepath before the sub-page key, for making // a server request getFilePath: function( path ) { var splitkey = "&" + $.mobile.subPageUrlKey; return path && path.split( splitkey )[0].split( dialogHashKey )[0]; }, // check if the specified url refers to the first page in the main // application document. isFirstPageUrl: function( url ) { // We only deal with absolute paths. var u = path.parseUrl( path.makeUrlAbsolute( url, this.documentBase ) ), // Does the url have the same path as the document? samePath = u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ), // Get the first page element. fp = $.mobile.firstPage, // Get the id of the first page element if it has one. fpId = fp && fp[0] ? fp[0].id : undefined; // The url refers to the first page if the path matches the document and // it either has no hash value, or the hash is exactly equal to the id // of the first page element. return samePath && ( !u.hash || u.hash === "#" || ( fpId && u.hash.replace( /^#/, "" ) === fpId ) ); }, // Some embedded browsers, like the web view in Phone Gap, allow // cross-domain XHR requests if the document doing the request was loaded // via the file:// protocol. This is usually to allow the application to // "phone home" and fetch app specific data. We normally let the browser // handle external/cross-domain urls, but if the allowCrossDomainPages // option is true, we will allow cross-domain http/https requests to go // through our page loading logic. isPermittedCrossDomainRequest: function( docUrl, reqUrl ) { return $.mobile.allowCrossDomainPages && (docUrl.protocol === "file:" || docUrl.protocol === "content:") && reqUrl.search( /^https?:/ ) !== -1; } }; path.documentUrl = path.parseLocation(); $base = $( "head" ).find( "base" ); path.documentBase = $base.length ? path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), path.documentUrl.href ) ) : path.documentUrl; path.documentBaseDiffers = (path.documentUrl.hrefNoHash !== path.documentBase.hrefNoHash); //return the original document base url path.getDocumentBase = function( asParsedObject ) { return asParsedObject ? $.extend( {}, path.documentBase ) : path.documentBase.href; }; // DEPRECATED as of 1.4.0 - remove in 1.5.0 $.extend( $.mobile, { //return the original document url getDocumentUrl: path.getDocumentUrl, //return the original document base url getDocumentBase: path.getDocumentBase }); })( jQuery ); (function( $, undefined ) { $.mobile.History = function( stack, index ) { this.stack = stack || []; this.activeIndex = index || 0; }; $.extend($.mobile.History.prototype, { getActive: function() { return this.stack[ this.activeIndex ]; }, getLast: function() { return this.stack[ this.previousIndex ]; }, getNext: function() { return this.stack[ this.activeIndex + 1 ]; }, getPrev: function() { return this.stack[ this.activeIndex - 1 ]; }, // addNew is used whenever a new page is added add: function( url, data ) { data = data || {}; //if there's forward history, wipe it if ( this.getNext() ) { this.clearForward(); } // if the hash is included in the data make sure the shape // is consistent for comparison if ( data.hash && data.hash.indexOf( "#" ) === -1) { data.hash = "#" + data.hash; } data.url = url; this.stack.push( data ); this.activeIndex = this.stack.length - 1; }, //wipe urls ahead of active index clearForward: function() { this.stack = this.stack.slice( 0, this.activeIndex + 1 ); }, find: function( url, stack, earlyReturn ) { stack = stack || this.stack; var entry, i, length = stack.length, index; for ( i = 0; i < length; i++ ) { entry = stack[i]; if ( decodeURIComponent(url) === decodeURIComponent(entry.url) || decodeURIComponent(url) === decodeURIComponent(entry.hash) ) { index = i; if ( earlyReturn ) { return index; } } } return index; }, closest: function( url ) { var closest, a = this.activeIndex; // First, take the slice of the history stack before the current index and search // for a url match. If one is found, we'll avoid avoid looking through forward history // NOTE the preference for backward history movement is driven by the fact that // most mobile browsers only have a dedicated back button, and users rarely use // the forward button in desktop browser anyhow closest = this.find( url, this.stack.slice(0, a) ); // If nothing was found in backward history check forward. The `true` // value passed as the third parameter causes the find method to break // on the first match in the forward history slice. The starting index // of the slice must then be added to the result to get the element index // in the original history stack :( :( // // TODO this is hyper confusing and should be cleaned up (ugh so bad) if ( closest === undefined ) { closest = this.find( url, this.stack.slice(a), true ); closest = closest === undefined ? closest : closest + a; } return closest; }, direct: function( opts ) { var newActiveIndex = this.closest( opts.url ), a = this.activeIndex; // save new page index, null check to prevent falsey 0 result // record the previous index for reference if ( newActiveIndex !== undefined ) { this.activeIndex = newActiveIndex; this.previousIndex = a; } // invoke callbacks where appropriate // // TODO this is also convoluted and confusing if ( newActiveIndex < a ) { ( opts.present || opts.back || $.noop )( this.getActive(), "back" ); } else if ( newActiveIndex > a ) { ( opts.present || opts.forward || $.noop )( this.getActive(), "forward" ); } else if ( newActiveIndex === undefined && opts.missing ) { opts.missing( this.getActive() ); } } }); })( jQuery ); (function( $, undefined ) { var path = $.mobile.path, initialHref = location.href; $.mobile.Navigator = function( history ) { this.history = history; this.ignoreInitialHashChange = true; $.mobile.window.bind({ "popstate.history": $.proxy( this.popstate, this ), "hashchange.history": $.proxy( this.hashchange, this ) }); }; $.extend($.mobile.Navigator.prototype, { squash: function( url, data ) { var state, href, hash = path.isPath(url) ? path.stripHash(url) : url; href = path.squash( url ); // make sure to provide this information when it isn't explicitly set in the // data object that was passed to the squash method state = $.extend({ hash: hash, url: href }, data); // replace the current url with the new href and store the state // Note that in some cases we might be replacing an url with the // same url. We do this anyways because we need to make sure that // all of our history entries have a state object associated with // them. This allows us to work around the case where $.mobile.back() // is called to transition from an external page to an embedded page. // In that particular case, a hashchange event is *NOT* generated by the browser. // Ensuring each history entry has a state object means that onPopState() // will always trigger our hashchange callback even when a hashchange event // is not fired. window.history.replaceState( state, state.title || document.title, href ); return state; }, hash: function( url, href ) { var parsed, loc, hash, resolved; // Grab the hash for recording. If the passed url is a path // we used the parsed version of the squashed url to reconstruct, // otherwise we assume it's a hash and store it directly parsed = path.parseUrl( url ); loc = path.parseLocation(); if ( loc.pathname + loc.search === parsed.pathname + parsed.search ) { // If the pathname and search of the passed url is identical to the current loc // then we must use the hash. Otherwise there will be no event // eg, url = "/foo/bar?baz#bang", location.href = "http://example.com/foo/bar?baz" hash = parsed.hash ? parsed.hash : parsed.pathname + parsed.search; } else if ( path.isPath(url) ) { resolved = path.parseUrl( href ); // If the passed url is a path, make it domain relative and remove any trailing hash hash = resolved.pathname + resolved.search + (path.isPreservableHash( resolved.hash )? resolved.hash.replace( "#", "" ) : ""); } else { hash = url; } return hash; }, // TODO reconsider name go: function( url, data, noEvents ) { var state, href, hash, popstateEvent, isPopStateEvent = $.event.special.navigate.isPushStateEnabled(); // Get the url as it would look squashed on to the current resolution url href = path.squash( url ); // sort out what the hash sould be from the url hash = this.hash( url, href ); // Here we prevent the next hash change or popstate event from doing any // history management. In the case of hashchange we don't swallow it // if there will be no hashchange fired (since that won't reset the value) // and will swallow the following hashchange if ( noEvents && hash !== path.stripHash(path.parseLocation().hash) ) { this.preventNextHashChange = noEvents; } // IMPORTANT in the case where popstate is supported the event will be triggered // directly, stopping further execution - ie, interupting the flow of this // method call to fire bindings at this expression. Below the navigate method // there is a binding to catch this event and stop its propagation. // // We then trigger a new popstate event on the window with a null state // so that the navigate events can conclude their work properly // // if the url is a path we want to preserve the query params that are available on // the current url. this.preventHashAssignPopState = true; window.location.hash = hash; // If popstate is enabled and the browser triggers `popstate` events when the hash // is set (this often happens immediately in browsers like Chrome), then the // this flag will be set to false already. If it's a browser that does not trigger // a `popstate` on hash assignement or `replaceState` then we need avoid the branch // that swallows the event created by the popstate generated by the hash assignment // At the time of this writing this happens with Opera 12 and some version of IE this.preventHashAssignPopState = false; state = $.extend({ url: href, hash: hash, title: document.title }, data); if ( isPopStateEvent ) { popstateEvent = new $.Event( "popstate" ); popstateEvent.originalEvent = { type: "popstate", state: null }; this.squash( url, state ); // Trigger a new faux popstate event to replace the one that we // caught that was triggered by the hash setting above. if ( !noEvents ) { this.ignorePopState = true; $.mobile.window.trigger( popstateEvent ); } } // record the history entry so that the information can be included // in hashchange event driven navigate events in a similar fashion to // the state that's provided by popstate this.history.add( state.url, state ); }, // This binding is intended to catch the popstate events that are fired // when execution of the `$.navigate` method stops at window.location.hash = url; // and completely prevent them from propagating. The popstate event will then be // retriggered after execution resumes // // TODO grab the original event here and use it for the synthetic event in the // second half of the navigate execution that will follow this binding popstate: function( event ) { var hash, state; // Partly to support our test suite which manually alters the support // value to test hashchange. Partly to prevent all around weirdness if ( !$.event.special.navigate.isPushStateEnabled() ) { return; } // If this is the popstate triggered by the actual alteration of the hash // prevent it completely. History is tracked manually if ( this.preventHashAssignPopState ) { this.preventHashAssignPopState = false; event.stopImmediatePropagation(); return; } // if this is the popstate triggered after the `replaceState` call in the go // method, then simply ignore it. The history entry has already been captured if ( this.ignorePopState ) { this.ignorePopState = false; return; } // If there is no state, and the history stack length is one were // probably getting the page load popstate fired by browsers like chrome // avoid it and set the one time flag to false. // TODO: Do we really need all these conditions? Comparing location hrefs // should be sufficient. if ( !event.originalEvent.state && this.history.stack.length === 1 && this.ignoreInitialHashChange ) { this.ignoreInitialHashChange = false; if ( location.href === initialHref ) { event.preventDefault(); return; } } // account for direct manipulation of the hash. That is, we will receive a popstate // when the hash is changed by assignment, and it won't have a state associated. We // then need to squash the hash. See below for handling of hash assignment that // matches an existing history entry // TODO it might be better to only add to the history stack // when the hash is adjacent to the active history entry hash = path.parseLocation().hash; if ( !event.originalEvent.state && hash ) { // squash the hash that's been assigned on the URL with replaceState // also grab the resulting state object for storage state = this.squash( hash ); // record the new hash as an additional history entry // to match the browser's treatment of hash assignment this.history.add( state.url, state ); // pass the newly created state information // along with the event event.historyState = state; // do not alter history, we've added a new history entry // so we know where we are return; } // If all else fails this is a popstate that comes from the back or forward buttons // make sure to set the state of our history stack properly, and record the directionality this.history.direct({ url: (event.originalEvent.state || {}).url || hash, // When the url is either forward or backward in history include the entry // as data on the event object for merging as data in the navigate event present: function( historyEntry, direction ) { // make sure to create a new object to pass down as the navigate event data event.historyState = $.extend({}, historyEntry); event.historyState.direction = direction; } }); }, // NOTE must bind before `navigate` special event hashchange binding otherwise the // navigation data won't be attached to the hashchange event in time for those // bindings to attach it to the `navigate` special event // TODO add a check here that `hashchange.navigate` is bound already otherwise it's // broken (exception?) hashchange: function( event ) { var history, hash; // If hashchange listening is explicitly disabled or pushstate is supported // avoid making use of the hashchange handler. if (!$.event.special.navigate.isHashChangeEnabled() || $.event.special.navigate.isPushStateEnabled() ) { return; } // On occasion explicitly want to prevent the next hash from propogating because we only // with to alter the url to represent the new state do so here if ( this.preventNextHashChange ) { this.preventNextHashChange = false; event.stopImmediatePropagation(); return; } history = this.history; hash = path.parseLocation().hash; // If this is a hashchange caused by the back or forward button // make sure to set the state of our history stack properly this.history.direct({ url: hash, // When the url is either forward or backward in history include the entry // as data on the event object for merging as data in the navigate event present: function( historyEntry, direction ) { // make sure to create a new object to pass down as the navigate event data event.hashchangeState = $.extend({}, historyEntry); event.hashchangeState.direction = direction; }, // When we don't find a hash in our history clearly we're aiming to go there // record the entry as new for future traversal // // NOTE it's not entirely clear that this is the right thing to do given that we // can't know the users intention. It might be better to explicitly _not_ // support location.hash assignment in preference to $.navigate calls // TODO first arg to add should be the href, but it causes issues in identifying // embeded pages missing: function() { history.add( hash, { hash: hash, title: document.title }); } }); } }); })( jQuery ); (function( $, undefined ) { // TODO consider queueing navigation activity until previous activities have completed // so that end users don't have to think about it. Punting for now // TODO !! move the event bindings into callbacks on the navigate event $.mobile.navigate = function( url, data, noEvents ) { $.mobile.navigate.navigator.go( url, data, noEvents ); }; // expose the history on the navigate method in anticipation of full integration with // existing navigation functionalty that is tightly coupled to the history information $.mobile.navigate.history = new $.mobile.History(); // instantiate an instance of the navigator for use within the $.navigate method $.mobile.navigate.navigator = new $.mobile.Navigator( $.mobile.navigate.history ); var loc = $.mobile.path.parseLocation(); $.mobile.navigate.history.add( loc.href, {hash: loc.hash} ); })( jQuery ); (function( $, undefined ) { var props = { "animation": {}, "transition": {} }, testElement = document.createElement( "a" ), vendorPrefixes = [ "", "webkit-", "moz-", "o-" ]; $.each( [ "animation", "transition" ], function( i, test ) { // Get correct name for test var testName = ( i === 0 ) ? test + "-" + "name" : test; $.each( vendorPrefixes, function( j, prefix ) { if ( testElement.style[ $.camelCase( prefix + testName ) ] !== undefined ) { props[ test ][ "prefix" ] = prefix; return false; } }); // Set event and duration names for later use props[ test ][ "duration" ] = $.camelCase( props[ test ][ "prefix" ] + test + "-" + "duration" ); props[ test ][ "event" ] = $.camelCase( props[ test ][ "prefix" ] + test + "-" + "end" ); // All lower case if not a vendor prop if ( props[ test ][ "prefix" ] === "" ) { props[ test ][ "duration" ] = props[ test ][ "duration" ].toLowerCase(); props[ test ][ "event" ] = props[ test ][ "event" ].toLowerCase(); } }); // If a valid prefix was found then the it is supported by the browser $.support.cssTransitions = ( props[ "transition" ][ "prefix" ] !== undefined ); $.support.cssAnimations = ( props[ "animation" ][ "prefix" ] !== undefined ); // Remove the testElement $( testElement ).remove(); // Animation complete callback $.fn.animationComplete = function( callback, type, fallbackTime ) { var timer, duration, that = this, animationType = ( !type || type === "animation" ) ? "animation" : "transition"; // Make sure selected type is supported by browser if ( ( $.support.cssTransitions && animationType === "transition" ) || ( $.support.cssAnimations && animationType === "animation" ) ) { // If a fallback time was not passed set one if ( fallbackTime === undefined ) { // Make sure the was not bound to document before checking .css if ( $( this ).context !== document ) { // Parse the durration since its in second multiple by 1000 for milliseconds // Multiply by 3 to make sure we give the animation plenty of time. duration = parseFloat( $( this ).css( props[ animationType ].duration ) ) * 3000; } // If we could not read a duration use the default if ( duration === 0 || duration === undefined ) { duration = $.fn.animationComplete.default; } } // Sets up the fallback if event never comes timer = setTimeout( function() { $( that ).off( props[ animationType ].event ); callback.apply( that ); }, duration ); // Bind the event return $( this ).one( props[ animationType ].event, function() { // Clear the timer so we dont call callback twice clearTimeout( timer ); callback.call( this, arguments ); }); } else { // CSS animation / transitions not supported // Defer execution for consistency between webkit/non webkit setTimeout( $.proxy( callback, this ), 0 ); return $( this ); } }; // Allow default callback to be configured on mobileInit $.fn.animationComplete.default = 1000; })( jQuery ); // This plugin is an experiment for abstracting away the touch and mouse // events so that developers don't have to worry about which method of input // the device their document is loaded on supports. // // The idea here is to allow the developer to register listeners for the // basic mouse events, such as mousedown, mousemove, mouseup, and click, // and the plugin will take care of registering the correct listeners // behind the scenes to invoke the listener at the fastest possible time // for that device, while still retaining the order of event firing in // the traditional mouse environment, should multiple handlers be registered // on the same element for different events. // // The current version exposes the following virtual events to jQuery bind methods: // "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel" (function( $, window, document, undefined ) { var dataPropertyName = "virtualMouseBindings", touchTargetPropertyName = "virtualTouchID", virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ), touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ), mouseHookProps = $.event.mouseHooks ? $.event.mouseHooks.props : [], mouseEventProps = $.event.props.concat( mouseHookProps ), activeDocHandlers = {}, resetTimerID = 0, startX = 0, startY = 0, didScroll = false, clickBlockList = [], blockMouseTriggers = false, blockTouchTriggers = false, eventCaptureSupported = "addEventListener" in document, $document = $( document ), nextTouchID = 1, lastTouchID = 0, threshold, i; $.vmouse = { moveDistanceThreshold: 10, clickDistanceThreshold: 10, resetTimerDuration: 1500 }; function getNativeEvent( event ) { while ( event && typeof event.originalEvent !== "undefined" ) { event = event.originalEvent; } return event; } function createVirtualEvent( event, eventType ) { var t = event.type, oe, props, ne, prop, ct, touch, i, j, len; event = $.Event( event ); event.type = eventType; oe = event.originalEvent; props = $.event.props; // addresses separation of $.event.props in to $.event.mouseHook.props and Issue 3280 // https://github.com/jquery/jquery-mobile/issues/3280 if ( t.search( /^(mouse|click)/ ) > -1 ) { props = mouseEventProps; } // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if ( oe ) { for ( i = props.length, prop; i; ) { prop = props[ --i ]; event[ prop ] = oe[ prop ]; } } // make sure that if the mouse and click virtual events are generated // without a .which one is defined if ( t.search(/mouse(down|up)|click/) > -1 && !event.which ) { event.which = 1; } if ( t.search(/^touch/) !== -1 ) { ne = getNativeEvent( oe ); t = ne.touches; ct = ne.changedTouches; touch = ( t && t.length ) ? t[0] : ( ( ct && ct.length ) ? ct[ 0 ] : undefined ); if ( touch ) { for ( j = 0, len = touchEventProps.length; j < len; j++) { prop = touchEventProps[ j ]; event[ prop ] = touch[ prop ]; } } } return event; } function getVirtualBindingFlags( element ) { var flags = {}, b, k; while ( element ) { b = $.data( element, dataPropertyName ); for ( k in b ) { if ( b[ k ] ) { flags[ k ] = flags.hasVirtualBinding = true; } } element = element.parentNode; } return flags; } function getClosestElementWithVirtualBinding( element, eventType ) { var b; while ( element ) { b = $.data( element, dataPropertyName ); if ( b && ( !eventType || b[ eventType ] ) ) { return element; } element = element.parentNode; } return null; } function enableTouchBindings() { blockTouchTriggers = false; } function disableTouchBindings() { blockTouchTriggers = true; } function enableMouseBindings() { lastTouchID = 0; clickBlockList.length = 0; blockMouseTriggers = false; // When mouse bindings are enabled, our // touch bindings are disabled. disableTouchBindings(); } function disableMouseBindings() { // When mouse bindings are disabled, our // touch bindings are enabled. enableTouchBindings(); } function startResetTimer() { clearResetTimer(); resetTimerID = setTimeout( function() { resetTimerID = 0; enableMouseBindings(); }, $.vmouse.resetTimerDuration ); } function clearResetTimer() { if ( resetTimerID ) { clearTimeout( resetTimerID ); resetTimerID = 0; } } function triggerVirtualEvent( eventType, event, flags ) { var ve; if ( ( flags && flags[ eventType ] ) || ( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) { ve = createVirtualEvent( event, eventType ); $( event.target).trigger( ve ); } return ve; } function mouseEventCallback( event ) { var touchID = $.data( event.target, touchTargetPropertyName ), ve; if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ) { ve = triggerVirtualEvent( "v" + event.type, event ); if ( ve ) { if ( ve.isDefaultPrevented() ) { event.preventDefault(); } if ( ve.isPropagationStopped() ) { event.stopPropagation(); } if ( ve.isImmediatePropagationStopped() ) { event.stopImmediatePropagation(); } } } } function handleTouchStart( event ) { var touches = getNativeEvent( event ).touches, target, flags, t; if ( touches && touches.length === 1 ) { target = event.target; flags = getVirtualBindingFlags( target ); if ( flags.hasVirtualBinding ) { lastTouchID = nextTouchID++; $.data( target, touchTargetPropertyName, lastTouchID ); clearResetTimer(); disableMouseBindings(); didScroll = false; t = getNativeEvent( event ).touches[ 0 ]; startX = t.pageX; startY = t.pageY; triggerVirtualEvent( "vmouseover", event, flags ); triggerVirtualEvent( "vmousedown", event, flags ); } } } function handleScroll( event ) { if ( blockTouchTriggers ) { return; } if ( !didScroll ) { triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) ); } didScroll = true; startResetTimer(); } function handleTouchMove( event ) { if ( blockTouchTriggers ) { return; } var t = getNativeEvent( event ).touches[ 0 ], didCancel = didScroll, moveThreshold = $.vmouse.moveDistanceThreshold, flags = getVirtualBindingFlags( event.target ); didScroll = didScroll || ( Math.abs( t.pageX - startX ) > moveThreshold || Math.abs( t.pageY - startY ) > moveThreshold ); if ( didScroll && !didCancel ) { triggerVirtualEvent( "vmousecancel", event, flags ); } triggerVirtualEvent( "vmousemove", event, flags ); startResetTimer(); } function handleTouchEnd( event ) { if ( blockTouchTriggers ) { return; } disableTouchBindings(); var flags = getVirtualBindingFlags( event.target ), ve, t; triggerVirtualEvent( "vmouseup", event, flags ); if ( !didScroll ) { ve = triggerVirtualEvent( "vclick", event, flags ); if ( ve && ve.isDefaultPrevented() ) { // The target of the mouse events that follow the touchend // event don't necessarily match the target used during the // touch. This means we need to rely on coordinates for blocking // any click that is generated. t = getNativeEvent( event ).changedTouches[ 0 ]; clickBlockList.push({ touchID: lastTouchID, x: t.clientX, y: t.clientY }); // Prevent any mouse events that follow from triggering // virtual event notifications. blockMouseTriggers = true; } } triggerVirtualEvent( "vmouseout", event, flags); didScroll = false; startResetTimer(); } function hasVirtualBindings( ele ) { var bindings = $.data( ele, dataPropertyName ), k; if ( bindings ) { for ( k in bindings ) { if ( bindings[ k ] ) { return true; } } } return false; } function dummyMouseHandler() {} function getSpecialEventObject( eventType ) { var realType = eventType.substr( 1 ); return { setup: function(/* data, namespace */) { // If this is the first virtual mouse binding for this element, // add a bindings object to its data. if ( !hasVirtualBindings( this ) ) { $.data( this, dataPropertyName, {} ); } // If setup is called, we know it is the first binding for this // eventType, so initialize the count for the eventType to zero. var bindings = $.data( this, dataPropertyName ); bindings[ eventType ] = true; // If this is the first virtual mouse event for this type, // register a global handler on the document. activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1; if ( activeDocHandlers[ eventType ] === 1 ) { $document.bind( realType, mouseEventCallback ); } // Some browsers, like Opera Mini, won't dispatch mouse/click events // for elements unless they actually have handlers registered on them. // To get around this, we register dummy handlers on the elements. $( this ).bind( realType, dummyMouseHandler ); // For now, if event capture is not supported, we rely on mouse handlers. if ( eventCaptureSupported ) { // If this is the first virtual mouse binding for the document, // register our touchstart handler on the document. activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1; if ( activeDocHandlers[ "touchstart" ] === 1 ) { $document.bind( "touchstart", handleTouchStart ) .bind( "touchend", handleTouchEnd ) // On touch platforms, touching the screen and then dragging your finger // causes the window content to scroll after some distance threshold is // exceeded. On these platforms, a scroll prevents a click event from being // dispatched, and on some platforms, even the touchend is suppressed. To // mimic the suppression of the click event, we need to watch for a scroll // event. Unfortunately, some platforms like iOS don't dispatch scroll // events until *AFTER* the user lifts their finger (touchend). This means // we need to watch both scroll and touchmove events to figure out whether // or not a scroll happenens before the touchend event is fired. .bind( "touchmove", handleTouchMove ) .bind( "scroll", handleScroll ); } } }, teardown: function(/* data, namespace */) { // If this is the last virtual binding for this eventType, // remove its global handler from the document. --activeDocHandlers[ eventType ]; if ( !activeDocHandlers[ eventType ] ) { $document.unbind( realType, mouseEventCallback ); } if ( eventCaptureSupported ) { // If this is the last virtual mouse binding in existence, // remove our document touchstart listener. --activeDocHandlers[ "touchstart" ]; if ( !activeDocHandlers[ "touchstart" ] ) { $document.unbind( "touchstart", handleTouchStart ) .unbind( "touchmove", handleTouchMove ) .unbind( "touchend", handleTouchEnd ) .unbind( "scroll", handleScroll ); } } var $this = $( this ), bindings = $.data( this, dataPropertyName ); // teardown may be called when an element was // removed from the DOM. If this is the case, // jQuery core may have already stripped the element // of any data bindings so we need to check it before // using it. if ( bindings ) { bindings[ eventType ] = false; } // Unregister the dummy event handler. $this.unbind( realType, dummyMouseHandler ); // If this is the last virtual mouse binding on the // element, remove the binding data from the element. if ( !hasVirtualBindings( this ) ) { $this.removeData( dataPropertyName ); } } }; } // Expose our custom events to the jQuery bind/unbind mechanism. for ( i = 0; i < virtualEventNames.length; i++ ) { $.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] ); } // Add a capture click handler to block clicks. // Note that we require event capture support for this so if the device // doesn't support it, we punt for now and rely solely on mouse events. if ( eventCaptureSupported ) { document.addEventListener( "click", function( e ) { var cnt = clickBlockList.length, target = e.target, x, y, ele, i, o, touchID; if ( cnt ) { x = e.clientX; y = e.clientY; threshold = $.vmouse.clickDistanceThreshold; // The idea here is to run through the clickBlockList to see if // the current click event is in the proximity of one of our // vclick events that had preventDefault() called on it. If we find // one, then we block the click. // // Why do we have to rely on proximity? // // Because the target of the touch event that triggered the vclick // can be different from the target of the click event synthesized // by the browser. The target of a mouse/click event that is synthesized // from a touch event seems to be implementation specific. For example, // some browsers will fire mouse/click events for a link that is near // a touch event, even though the target of the touchstart/touchend event // says the user touched outside the link. Also, it seems that with most // browsers, the target of the mouse/click event is not calculated until the // time it is dispatched, so if you replace an element that you touched // with another element, the target of the mouse/click will be the new // element underneath that point. // // Aside from proximity, we also check to see if the target and any // of its ancestors were the ones that blocked a click. This is necessary // because of the strange mouse/click target calculation done in the // Android 2.1 browser, where if you click on an element, and there is a // mouse/click handler on one of its ancestors, the target will be the // innermost child of the touched element, even if that child is no where // near the point of touch. ele = target; while ( ele ) { for ( i = 0; i < cnt; i++ ) { o = clickBlockList[ i ]; touchID = 0; if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) || $.data( ele, touchTargetPropertyName ) === o.touchID ) { // XXX: We may want to consider removing matches from the block list // instead of waiting for the reset timer to fire. e.preventDefault(); e.stopPropagation(); return; } } ele = ele.parentNode; } } }, true); } })( jQuery, window, document ); (function( $, window, undefined ) { var $document = $( document ), supportTouch = $.mobile.support.touch, scrollEvent = "touchmove scroll", touchStartEvent = supportTouch ? "touchstart" : "mousedown", touchStopEvent = supportTouch ? "touchend" : "mouseup", touchMoveEvent = supportTouch ? "touchmove" : "mousemove"; // setup new event shortcuts $.each( ( "touchstart touchmove touchend " + "tap taphold " + "swipe swipeleft swiperight " + "scrollstart scrollstop" ).split( " " ), function( i, name ) { $.fn[ name ] = function( fn ) { return fn ? this.bind( name, fn ) : this.trigger( name ); }; // jQuery < 1.8 if ( $.attrFn ) { $.attrFn[ name ] = true; } }); function triggerCustomEvent( obj, eventType, event, bubble ) { var originalType = event.type; event.type = eventType; if ( bubble ) { $.event.trigger( event, undefined, obj ); } else { $.event.dispatch.call( obj, event ); } event.type = originalType; } // also handles scrollstop $.event.special.scrollstart = { enabled: true, setup: function() { var thisObject = this, $this = $( thisObject ), scrolling, timer; function trigger( event, state ) { scrolling = state; triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event ); } // iPhone triggers scroll after a small delay; use touchmove instead $this.bind( scrollEvent, function( event ) { if ( !$.event.special.scrollstart.enabled ) { return; } if ( !scrolling ) { trigger( event, true ); } clearTimeout( timer ); timer = setTimeout( function() { trigger( event, false ); }, 50 ); }); }, teardown: function() { $( this ).unbind( scrollEvent ); } }; // also handles taphold $.event.special.tap = { tapholdThreshold: 750, emitTapOnTaphold: true, setup: function() { var thisObject = this, $this = $( thisObject ), isTaphold = false; $this.bind( "vmousedown", function( event ) { isTaphold = false; if ( event.which && event.which !== 1 ) { return false; } var origTarget = event.target, timer; function clearTapTimer() { clearTimeout( timer ); } function clearTapHandlers() { clearTapTimer(); $this.unbind( "vclick", clickHandler ) .unbind( "vmouseup", clearTapTimer ); $document.unbind( "vmousecancel", clearTapHandlers ); } function clickHandler( event ) { clearTapHandlers(); // ONLY trigger a 'tap' event if the start target is // the same as the stop target. if ( !isTaphold && origTarget === event.target ) { triggerCustomEvent( thisObject, "tap", event ); } else if ( isTaphold ) { event.stopPropagation(); } } $this.bind( "vmouseup", clearTapTimer ) .bind( "vclick", clickHandler ); $document.bind( "vmousecancel", clearTapHandlers ); timer = setTimeout( function() { if ( !$.event.special.tap.emitTapOnTaphold ) { isTaphold = true; } triggerCustomEvent( thisObject, "taphold", $.Event( "taphold", { target: origTarget } ) ); }, $.event.special.tap.tapholdThreshold ); }); }, teardown: function() { $( this ).unbind( "vmousedown" ).unbind( "vclick" ).unbind( "vmouseup" ); $document.unbind( "vmousecancel" ); } }; // Also handles swipeleft, swiperight $.event.special.swipe = { // More than this horizontal displacement, and we will suppress scrolling. scrollSupressionThreshold: 30, // More time than this, and it isn't a swipe. durationThreshold: 1000, // Swipe horizontal displacement must be more than this. horizontalDistanceThreshold: 30, // Swipe vertical displacement must be less than this. verticalDistanceThreshold: 30, getLocation: function ( event ) { var winPageX = window.pageXOffset, winPageY = window.pageYOffset, x = event.clientX, y = event.clientY; if ( event.pageY === 0 && Math.floor( y ) > Math.floor( event.pageY ) || event.pageX === 0 && Math.floor( x ) > Math.floor( event.pageX ) ) { // iOS4 clientX/clientY have the value that should have been // in pageX/pageY. While pageX/page/ have the value 0 x = x - winPageX; y = y - winPageY; } else if ( y < ( event.pageY - winPageY) || x < ( event.pageX - winPageX ) ) { // Some Android browsers have totally bogus values for clientX/Y // when scrolling/zooming a page. Detectable since clientX/clientY // should never be smaller than pageX/pageY minus page scroll x = event.pageX - winPageX; y = event.pageY - winPageY; } return { x: x, y: y }; }, start: function( event ) { var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event, location = $.event.special.swipe.getLocation( data ); return { time: ( new Date() ).getTime(), coords: [ location.x, location.y ], origin: $( event.target ) }; }, stop: function( event ) { var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event, location = $.event.special.swipe.getLocation( data ); return { time: ( new Date() ).getTime(), coords: [ location.x, location.y ] }; }, handleSwipe: function( start, stop, thisObject, origTarget ) { if ( stop.time - start.time < $.event.special.swipe.durationThreshold && Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold && Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) { var direction = start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight"; triggerCustomEvent( thisObject, "swipe", $.Event( "swipe", { target: origTarget, swipestart: start, swipestop: stop }), true ); triggerCustomEvent( thisObject, direction,$.Event( direction, { target: origTarget, swipestart: start, swipestop: stop } ), true ); return true; } return false; }, // This serves as a flag to ensure that at most one swipe event event is // in work at any given time eventInProgress: false, setup: function() { var events, thisObject = this, $this = $( thisObject ), context = {}; // Retrieve the events data for this element and add the swipe context events = $.data( this, "mobile-events" ); if ( !events ) { events = { length: 0 }; $.data( this, "mobile-events", events ); } events.length++; events.swipe = context; context.start = function( event ) { // Bail if we're already working on a swipe event if ( $.event.special.swipe.eventInProgress ) { return; } $.event.special.swipe.eventInProgress = true; var stop, start = $.event.special.swipe.start( event ), origTarget = event.target, emitted = false; context.move = function( event ) { if ( !start ) { return; } stop = $.event.special.swipe.stop( event ); if ( !emitted ) { emitted = $.event.special.swipe.handleSwipe( start, stop, thisObject, origTarget ); if ( emitted ) { // Reset the context to make way for the next swipe event $.event.special.swipe.eventInProgress = false; } } // prevent scrolling if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) { event.preventDefault(); } }; context.stop = function() { emitted = true; // Reset the context to make way for the next swipe event $.event.special.swipe.eventInProgress = false; $document.off( touchMoveEvent, context.move ); context.move = null; }; $document.on( touchMoveEvent, context.move ) .one( touchStopEvent, context.stop ); }; $this.on( touchStartEvent, context.start ); }, teardown: function() { var events, context; events = $.data( this, "mobile-events" ); if ( events ) { context = events.swipe; delete events.swipe; events.length--; if ( events.length === 0 ) { $.removeData( this, "mobile-events" ); } } if ( context ) { if ( context.start ) { $( this ).off( touchStartEvent, context.start ); } if ( context.move ) { $document.off( touchMoveEvent, context.move ); } if ( context.stop ) { $document.off( touchStopEvent, context.stop ); } } } }; $.each({ scrollstop: "scrollstart", taphold: "tap", swipeleft: "swipe", swiperight: "swipe" }, function( event, sourceEvent ) { $.event.special[ event ] = { setup: function() { $( this ).bind( sourceEvent, $.noop ); }, teardown: function() { $( this ).unbind( sourceEvent ); } }; }); })( jQuery, this ); // throttled resize event (function( $ ) { $.event.special.throttledresize = { setup: function() { $( this ).bind( "resize", handler ); }, teardown: function() { $( this ).unbind( "resize", handler ); } }; var throttle = 250, handler = function() { curr = ( new Date() ).getTime(); diff = curr - lastCall; if ( diff >= throttle ) { lastCall = curr; $( this ).trigger( "throttledresize" ); } else { if ( heldCall ) { clearTimeout( heldCall ); } // Promise a held call will still execute heldCall = setTimeout( handler, throttle - diff ); } }, lastCall = 0, heldCall, curr, diff; })( jQuery ); (function( $, window ) { var win = $( window ), event_name = "orientationchange", get_orientation, last_orientation, initial_orientation_is_landscape, initial_orientation_is_default, portrait_map = { "0": true, "180": true }, ww, wh, landscape_threshold; // It seems that some device/browser vendors use window.orientation values 0 and 180 to // denote the "default" orientation. For iOS devices, and most other smart-phones tested, // the default orientation is always "portrait", but in some Android and RIM based tablets, // the default orientation is "landscape". The following code attempts to use the window // dimensions to figure out what the current orientation is, and then makes adjustments // to the to the portrait_map if necessary, so that we can properly decode the // window.orientation value whenever get_orientation() is called. // // Note that we used to use a media query to figure out what the orientation the browser // thinks it is in: // // initial_orientation_is_landscape = $.mobile.media("all and (orientation: landscape)"); // // but there was an iPhone/iPod Touch bug beginning with iOS 4.2, up through iOS 5.1, // where the browser *ALWAYS* applied the landscape media query. This bug does not // happen on iPad. if ( $.support.orientation ) { // Check the window width and height to figure out what the current orientation // of the device is at this moment. Note that we've initialized the portrait map // values to 0 and 180, *AND* we purposely check for landscape so that if we guess // wrong, , we default to the assumption that portrait is the default orientation. // We use a threshold check below because on some platforms like iOS, the iPhone // form-factor can report a larger width than height if the user turns on the // developer console. The actual threshold value is somewhat arbitrary, we just // need to make sure it is large enough to exclude the developer console case. ww = window.innerWidth || win.width(); wh = window.innerHeight || win.height(); landscape_threshold = 50; initial_orientation_is_landscape = ww > wh && ( ww - wh ) > landscape_threshold; // Now check to see if the current window.orientation is 0 or 180. initial_orientation_is_default = portrait_map[ window.orientation ]; // If the initial orientation is landscape, but window.orientation reports 0 or 180, *OR* // if the initial orientation is portrait, but window.orientation reports 90 or -90, we // need to flip our portrait_map values because landscape is the default orientation for // this device/browser. if ( ( initial_orientation_is_landscape && initial_orientation_is_default ) || ( !initial_orientation_is_landscape && !initial_orientation_is_default ) ) { portrait_map = { "-90": true, "90": true }; } } $.event.special.orientationchange = $.extend( {}, $.event.special.orientationchange, { setup: function() { // If the event is supported natively, return false so that jQuery // will bind to the event using DOM methods. if ( $.support.orientation && !$.event.special.orientationchange.disabled ) { return false; } // Get the current orientation to avoid initial double-triggering. last_orientation = get_orientation(); // Because the orientationchange event doesn't exist, simulate the // event by testing window dimensions on resize. win.bind( "throttledresize", handler ); }, teardown: function() { // If the event is not supported natively, return false so that // jQuery will unbind the event using DOM methods. if ( $.support.orientation && !$.event.special.orientationchange.disabled ) { return false; } // Because the orientationchange event doesn't exist, unbind the // resize event handler. win.unbind( "throttledresize", handler ); }, add: function( handleObj ) { // Save a reference to the bound event handler. var old_handler = handleObj.handler; handleObj.handler = function( event ) { // Modify event object, adding the .orientation property. event.orientation = get_orientation(); // Call the originally-bound event handler and return its result. return old_handler.apply( this, arguments ); }; } }); // If the event is not supported natively, this handler will be bound to // the window resize event to simulate the orientationchange event. function handler() { // Get the current orientation. var orientation = get_orientation(); if ( orientation !== last_orientation ) { // The orientation has changed, so trigger the orientationchange event. last_orientation = orientation; win.trigger( event_name ); } } // Get the current page orientation. This method is exposed publicly, should it // be needed, as jQuery.event.special.orientationchange.orientation() $.event.special.orientationchange.orientation = get_orientation = function() { var isPortrait = true, elem = document.documentElement; // prefer window orientation to the calculation based on screensize as // the actual screen resize takes place before or after the orientation change event // has been fired depending on implementation (eg android 2.3 is before, iphone after). // More testing is required to determine if a more reliable method of determining the new screensize // is possible when orientationchange is fired. (eg, use media queries + element + opacity) if ( $.support.orientation ) { // if the window orientation registers as 0 or 180 degrees report // portrait, otherwise landscape isPortrait = portrait_map[ window.orientation ]; } else { isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1; } return isPortrait ? "portrait" : "landscape"; }; $.fn[ event_name ] = function( fn ) { return fn ? this.bind( event_name, fn ) : this.trigger( event_name ); }; // jQuery < 1.8 if ( $.attrFn ) { $.attrFn[ event_name ] = true; } }( jQuery, this )); (function( $, undefined ) { // existing base tag? var baseElement = $( "head" ).children( "base" ), // base element management, defined depending on dynamic base tag support // TODO move to external widget base = { // define base element, for use in routing asset urls that are referenced // in Ajax-requested markup element: ( baseElement.length ? baseElement : $( "<base>", { href: $.mobile.path.documentBase.hrefNoHash } ).prependTo( $( "head" ) ) ), linkSelector: "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]", // set the generated BASE element's href to a new page's base path set: function( href ) { // we should do nothing if the user wants to manage their url base // manually if ( !$.mobile.dynamicBaseEnabled ) { return; } // we should use the base tag if we can manipulate it dynamically if ( $.support.dynamicBaseTag ) { base.element.attr( "href", $.mobile.path.makeUrlAbsolute( href, $.mobile.path.documentBase ) ); } }, rewrite: function( href, page ) { var newPath = $.mobile.path.get( href ); page.find( base.linkSelector ).each(function( i, link ) { var thisAttr = $( link ).is( "[href]" ) ? "href" : $( link ).is( "[src]" ) ? "src" : "action", thisUrl = $( link ).attr( thisAttr ); // XXX_jblas: We need to fix this so that it removes the document // base URL, and then prepends with the new page URL. // if full path exists and is same, chop it - helps IE out thisUrl = thisUrl.replace( location.protocol + "//" + location.host + location.pathname, "" ); if ( !/^(\w+:|#|\/)/.test( thisUrl ) ) { $( link ).attr( thisAttr, newPath + thisUrl ); } }); }, // set the generated BASE element's href to a new page's base path reset: function(/* href */) { base.element.attr( "href", $.mobile.path.documentBase.hrefNoSearch ); } }; $.mobile.base = base; })( jQuery ); (function( $, undefined ) { $.mobile.widgets = {}; var originalWidget = $.widget, // Record the original, non-mobileinit-modified version of $.mobile.keepNative // so we can later determine whether someone has modified $.mobile.keepNative keepNativeFactoryDefault = $.mobile.keepNative; $.widget = (function( orig ) { return function() { var constructor = orig.apply( this, arguments ), name = constructor.prototype.widgetName; constructor.initSelector = ( ( constructor.prototype.initSelector !== undefined ) ? constructor.prototype.initSelector : ":jqmData(role='" + name + "')" ); $.mobile.widgets[ name ] = constructor; return constructor; }; })( $.widget ); // Make sure $.widget still has bridge and extend methods $.extend( $.widget, originalWidget ); // For backcompat remove in 1.5 $.mobile.document.on( "create", function( event ) { $( event.target ).enhanceWithin(); }); $.widget( "mobile.page", { options: { theme: "a", domCache: false, // Deprecated in 1.4 remove in 1.5 keepNativeDefault: $.mobile.keepNative, // Deprecated in 1.4 remove in 1.5 contentTheme: null, enhanced: false }, // DEPRECATED for > 1.4 // TODO remove at 1.5 _createWidget: function() { $.Widget.prototype._createWidget.apply( this, arguments ); this._trigger( "init" ); }, _create: function() { // If false is returned by the callbacks do not create the page if ( this._trigger( "beforecreate" ) === false ) { return false; } if ( !this.options.enhanced ) { this._enhance(); } this._on( this.element, { pagebeforehide: "removeContainerBackground", pagebeforeshow: "_handlePageBeforeShow" }); this.element.enhanceWithin(); // Dialog widget is deprecated in 1.4 remove this in 1.5 if ( $.mobile.getAttribute( this.element[0], "role" ) === "dialog" && $.mobile.dialog ) { this.element.dialog(); } }, _enhance: function () { var attrPrefix = "data-" + $.mobile.ns, self = this; if ( this.options.role ) { this.element.attr( "data-" + $.mobile.ns + "role", this.options.role ); } this.element .attr( "tabindex", "0" ) .addClass( "ui-page ui-page-theme-" + this.options.theme ); // Manipulation of content os Deprecated as of 1.4 remove in 1.5 this.element.find( "[" + attrPrefix + "role='content']" ).each( function() { var $this = $( this ), theme = this.getAttribute( attrPrefix + "theme" ) || undefined; self.options.contentTheme = theme || self.options.contentTheme || ( self.options.dialog && self.options.theme ) || ( self.element.jqmData("role") === "dialog" && self.options.theme ); $this.addClass( "ui-content" ); if ( self.options.contentTheme ) { $this.addClass( "ui-body-" + ( self.options.contentTheme ) ); } // Add ARIA role $this.attr( "role", "main" ).addClass( "ui-content" ); }); }, bindRemove: function( callback ) { var page = this.element; // when dom caching is not enabled or the page is embedded bind to remove the page on hide if ( !page.data( "mobile-page" ).options.domCache && page.is( ":jqmData(external-page='true')" ) ) { // TODO use _on - that is, sort out why it doesn't work in this case page.bind( "pagehide.remove", callback || function( e, data ) { //check if this is a same page transition and if so don't remove the page if( !data.samePage ){ var $this = $( this ), prEvent = new $.Event( "pageremove" ); $this.trigger( prEvent ); if ( !prEvent.isDefaultPrevented() ) { $this.removeWithDependents(); } } }); } }, _setOptions: function( o ) { if ( o.theme !== undefined ) { this.element.removeClass( "ui-page-theme-" + this.options.theme ).addClass( "ui-page-theme-" + o.theme ); } if ( o.contentTheme !== undefined ) { this.element.find( "[data-" + $.mobile.ns + "='content']" ).removeClass( "ui-body-" + this.options.contentTheme ) .addClass( "ui-body-" + o.contentTheme ); } }, _handlePageBeforeShow: function(/* e */) { this.setContainerBackground(); }, // Deprecated in 1.4 remove in 1.5 removeContainerBackground: function() { this.element.closest( ":mobile-pagecontainer" ).pagecontainer({ "theme": "none" }); }, // Deprecated in 1.4 remove in 1.5 // set the page container background to the page theme setContainerBackground: function( theme ) { this.element.parent().pagecontainer( { "theme": theme || this.options.theme } ); }, // Deprecated in 1.4 remove in 1.5 keepNativeSelector: function() { var options = this.options, keepNative = $.trim( options.keepNative || "" ), globalValue = $.trim( $.mobile.keepNative ), optionValue = $.trim( options.keepNativeDefault ), // Check if $.mobile.keepNative has changed from the factory default newDefault = ( keepNativeFactoryDefault === globalValue ? "" : globalValue ), // If $.mobile.keepNative has not changed, use options.keepNativeDefault oldDefault = ( newDefault === "" ? optionValue : "" ); // Concatenate keepNative selectors from all sources where the value has // changed or, if nothing has changed, return the default return ( ( keepNative ? [ keepNative ] : [] ) .concat( newDefault ? [ newDefault ] : [] ) .concat( oldDefault ? [ oldDefault ] : [] ) .join( ", " ) ); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.pagecontainer", { options: { theme: "a" }, initSelector: false, _create: function() { this.setLastScrollEnabled = true; // TODO consider moving the navigation handler OUT of widget into // some other object as glue between the navigate event and the // content widget load and change methods this._on( this.window, { navigate: "_filterNavigateEvents" }); this._on( this.window, { // disable an scroll setting when a hashchange has been fired, // this only works because the recording of the scroll position // is delayed for 100ms after the browser might have changed the // position because of the hashchange navigate: "_disableRecordScroll", // bind to scrollstop for the first page, "pagechange" won't be // fired in that case scrollstop: "_delayedRecordScroll" }); // TODO move from page* events to content* events this._on({ pagechange: "_afterContentChange" }); // handle initial hashchange from chrome :( this.window.one( "navigate", $.proxy(function() { this.setLastScrollEnabled = true; }, this)); }, _setOptions: function( options ) { if ( options.theme !== undefined && options.theme !== "none" ) { this.element.removeClass( "ui-overlay-" + this.options.theme ) .addClass( "ui-overlay-" + options.theme ); } else if ( options.theme !== undefined ) { this.element.removeClass( "ui-overlay-" + this.options.theme ); } this._super( options ); }, _disableRecordScroll: function() { this.setLastScrollEnabled = false; }, _enableRecordScroll: function() { this.setLastScrollEnabled = true; }, // TODO consider the name here, since it's purpose specific _afterContentChange: function() { // once the page has changed, re-enable the scroll recording this.setLastScrollEnabled = true; // remove any binding that previously existed on the get scroll // which may or may not be different than the scroll element // determined for this page previously this._off( this.window, "scrollstop" ); // determine and bind to the current scoll element which may be the // window or in the case of touch overflow the element touch overflow this._on( this.window, { scrollstop: "_delayedRecordScroll" }); }, _recordScroll: function() { // this barrier prevents setting the scroll value based on // the browser scrolling the window based on a hashchange if ( !this.setLastScrollEnabled ) { return; } var active = this._getActiveHistory(), currentScroll, minScroll, defaultScroll; if ( active ) { currentScroll = this._getScroll(); minScroll = this._getMinScroll(); defaultScroll = this._getDefaultScroll(); // Set active page's lastScroll prop. If the location we're // scrolling to is less than minScrollBack, let it go. active.lastScroll = currentScroll < minScroll ? defaultScroll : currentScroll; } }, _delayedRecordScroll: function() { setTimeout( $.proxy(this, "_recordScroll"), 100 ); }, _getScroll: function() { return this.window.scrollTop(); }, _getMinScroll: function() { return $.mobile.minScrollBack; }, _getDefaultScroll: function() { return $.mobile.defaultHomeScroll; }, _filterNavigateEvents: function( e, data ) { var url; if ( e.originalEvent && e.originalEvent.isDefaultPrevented() ) { return; } url = e.originalEvent.type.indexOf( "hashchange" ) > -1 ? data.state.hash : data.state.url; if ( !url ) { url = this._getHash(); } if ( !url || url === "#" || url.indexOf( "#" + $.mobile.path.uiStateKey ) === 0 ) { url = location.href; } this._handleNavigate( url, data.state ); }, _getHash: function() { return $.mobile.path.parseLocation().hash; }, // TODO active page should be managed by the container (ie, it should be a property) getActivePage: function() { return this.activePage; }, // TODO the first page should be a property set during _create using the logic // that currently resides in init _getInitialContent: function() { return $.mobile.firstPage; }, // TODO each content container should have a history object _getHistory: function() { return $.mobile.navigate.history; }, // TODO use _getHistory _getActiveHistory: function() { return $.mobile.navigate.history.getActive(); }, // TODO the document base should be determined at creation _getDocumentBase: function() { return $.mobile.path.documentBase; }, back: function() { this.go( -1 ); }, forward: function() { this.go( 1 ); }, go: function( steps ) { //if hashlistening is enabled use native history method if ( $.mobile.hashListeningEnabled ) { window.history.go( steps ); } else { //we are not listening to the hash so handle history internally var activeIndex = $.mobile.navigate.history.activeIndex, index = activeIndex + parseInt( steps, 10 ), url = $.mobile.navigate.history.stack[ index ].url, direction = ( steps >= 1 )? "forward" : "back"; //update the history object $.mobile.navigate.history.activeIndex = index; $.mobile.navigate.history.previousIndex = activeIndex; //change to the new page this.change( url, { direction: direction, changeHash: false, fromHashChange: true } ); } }, // TODO rename _handleDestination _handleDestination: function( to ) { var history; // clean the hash for comparison if it's a url if ( $.type(to) === "string" ) { to = $.mobile.path.stripHash( to ); } if ( to ) { history = this._getHistory(); // At this point, 'to' can be one of 3 things, a cached page // element from a history stack entry, an id, or site-relative / // absolute URL. If 'to' is an id, we need to resolve it against // the documentBase, not the location.href, since the hashchange // could've been the result of a forward/backward navigation // that crosses from an external page/dialog to an internal // page/dialog. // // TODO move check to history object or path object? to = !$.mobile.path.isPath( to ) ? ( $.mobile.path.makeUrlAbsolute( "#" + to, this._getDocumentBase() ) ) : to; // If we're about to go to an initial URL that contains a // reference to a non-existent internal page, go to the first // page instead. We know that the initial hash refers to a // non-existent page, because the initial hash did not end // up in the initial history entry // TODO move check to history object? if ( to === $.mobile.path.makeUrlAbsolute( "#" + history.initialDst, this._getDocumentBase() ) && history.stack.length && history.stack[0].url !== history.initialDst.replace( $.mobile.dialogHashKey, "" ) ) { to = this._getInitialContent(); } } return to || this._getInitialContent(); }, _handleDialog: function( changePageOptions, data ) { var to, active, activeContent = this.getActivePage(); // If current active page is not a dialog skip the dialog and continue // in the same direction if ( activeContent && !activeContent.hasClass( "ui-dialog" ) ) { // determine if we're heading forward or backward and continue // accordingly past the current dialog if ( data.direction === "back" ) { this.back(); } else { this.forward(); } // prevent changePage call return false; } else { // if the current active page is a dialog and we're navigating // to a dialog use the dialog objected saved in the stack to = data.pageUrl; active = this._getActiveHistory(); // make sure to set the role, transition and reversal // as most of this is lost by the domCache cleaning $.extend( changePageOptions, { role: active.role, transition: active.transition, reverse: data.direction === "back" }); } return to; }, _handleNavigate: function( url, data ) { //find first page via hash // TODO stripping the hash twice with handleUrl var to = $.mobile.path.stripHash( url ), history = this._getHistory(), // transition is false if it's the first page, undefined // otherwise (and may be overridden by default) transition = history.stack.length === 0 ? "none" : undefined, // default options for the changPage calls made after examining // the current state of the page and the hash, NOTE that the // transition is derived from the previous history entry changePageOptions = { changeHash: false, fromHashChange: true, reverse: data.direction === "back" }; $.extend( changePageOptions, data, { transition: ( history.getLast() || {} ).transition || transition }); // TODO move to _handleDestination ? // If this isn't the first page, if the current url is a dialog hash // key, and the initial destination isn't equal to the current target // page, use the special dialog handling if ( history.activeIndex > 0 && to.indexOf( $.mobile.dialogHashKey ) > -1 && history.initialDst !== to ) { to = this._handleDialog( changePageOptions, data ); if ( to === false ) { return; } } this._changeContent( this._handleDestination( to ), changePageOptions ); }, _changeContent: function( to, opts ) { $.mobile.changePage( to, opts ); }, _getBase: function() { return $.mobile.base; }, _getNs: function() { return $.mobile.ns; }, _enhance: function( content, role ) { // TODO consider supporting a custom callback, and passing in // the settings which includes the role return content.page({ role: role }); }, _include: function( page, settings ) { // append to page and enhance page.appendTo( this.element ); // use the page widget to enhance this._enhance( page, settings.role ); // remove page on hide page.page( "bindRemove" ); }, _find: function( absUrl ) { // TODO consider supporting a custom callback var fileUrl = this._createFileUrl( absUrl ), dataUrl = this._createDataUrl( absUrl ), page, initialContent = this._getInitialContent(); // Check to see if the page already exists in the DOM. // NOTE do _not_ use the :jqmData pseudo selector because parenthesis // are a valid url char and it breaks on the first occurence page = this.element .children( "[data-" + this._getNs() +"url='" + dataUrl + "']" ); // If we failed to find the page, check to see if the url is a // reference to an embedded page. If so, it may have been dynamically // injected by a developer, in which case it would be lacking a // data-url attribute and in need of enhancement. if ( page.length === 0 && dataUrl && !$.mobile.path.isPath( dataUrl ) ) { page = this.element.children( $.mobile.path.hashToSelector("#" + dataUrl) ) .attr( "data-" + this._getNs() + "url", dataUrl ) .jqmData( "url", dataUrl ); } // If we failed to find a page in the DOM, check the URL to see if it // refers to the first page in the application. Also check to make sure // our cached-first-page is actually in the DOM. Some user deployed // apps are pruning the first page from the DOM for various reasons. // We check for this case here because we don't want a first-page with // an id falling through to the non-existent embedded page error case. if ( page.length === 0 && $.mobile.path.isFirstPageUrl( fileUrl ) && initialContent && initialContent.parent().length ) { page = $( initialContent ); } return page; }, _getLoader: function() { return $.mobile.loading(); }, _showLoading: function( delay, theme, msg, textonly ) { // This configurable timeout allows cached pages a brief // delay to load without showing a message if ( this._loadMsg ) { return; } this._loadMsg = setTimeout($.proxy(function() { this._getLoader().loader( "show", theme, msg, textonly ); this._loadMsg = 0; }, this), delay ); }, _hideLoading: function() { // Stop message show timer clearTimeout( this._loadMsg ); this._loadMsg = 0; // Hide loading message this._getLoader().loader( "hide" ); }, _showError: function() { // make sure to remove the current loading message this._hideLoading(); // show the error message this._showLoading( 0, $.mobile.pageLoadErrorMessageTheme, $.mobile.pageLoadErrorMessage, true ); // hide the error message after a delay // TODO configuration setTimeout( $.proxy(this, "_hideLoading"), 1500 ); }, _parse: function( html, fileUrl ) { // TODO consider allowing customization of this method. It's very JQM specific var page, all = $( "<div></div>" ); //workaround to allow scripts to execute when included in page divs all.get( 0 ).innerHTML = html; page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first(); //if page elem couldn't be found, create one and insert the body element's contents if ( !page.length ) { page = $( "<div data-" + this._getNs() + "role='page'>" + ( html.split( /<\/?body[^>]*>/gmi )[1] || "" ) + "</div>" ); } // TODO tagging a page with external to make sure that embedded pages aren't // removed by the various page handling code is bad. Having page handling code // in many places is bad. Solutions post 1.0 page.attr( "data-" + this._getNs() + "url", $.mobile.path.convertUrlToDataUrl(fileUrl) ) .attr( "data-" + this._getNs() + "external-page", true ); return page; }, _setLoadedTitle: function( page, html ) { //page title regexp var newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1; if ( newPageTitle && !page.jqmData("title") ) { newPageTitle = $( "<div>" + newPageTitle + "</div>" ).text(); page.jqmData( "title", newPageTitle ); } }, _isRewritableBaseTag: function() { return $.mobile.dynamicBaseEnabled && !$.support.dynamicBaseTag; }, _createDataUrl: function( absoluteUrl ) { return $.mobile.path.convertUrlToDataUrl( absoluteUrl ); }, _createFileUrl: function( absoluteUrl ) { return $.mobile.path.getFilePath( absoluteUrl ); }, _triggerWithDeprecated: function( name, data, page ) { var deprecatedEvent = $.Event( "page" + name ), newEvent = $.Event( this.widgetName + name ); // DEPRECATED // trigger the old deprecated event on the page if it's provided ( page || this.element ).trigger( deprecatedEvent, data ); // use the widget trigger method for the new content* event this.element.trigger( newEvent, data ); return { deprecatedEvent: deprecatedEvent, event: newEvent }; }, // TODO it would be nice to split this up more but everything appears to be "one off" // or require ordering such that other bits are sprinkled in between parts that // could be abstracted out as a group _loadSuccess: function( absUrl, triggerData, settings, deferred ) { var fileUrl = this._createFileUrl( absUrl ), dataUrl = this._createDataUrl( absUrl ); return $.proxy(function( html, textStatus, xhr ) { //pre-parse html to check for a data-url, //use it as the new fileUrl, base path, etc var content, // TODO handle dialogs again pageElemRegex = new RegExp( "(<[^>]+\\bdata-" + this._getNs() + "role=[\"']?page[\"']?[^>]*>)" ), dataUrlRegex = new RegExp( "\\bdata-" + this._getNs() + "url=[\"']?([^\"'>]*)[\"']?" ); // data-url must be provided for the base tag so resource requests // can be directed to the correct url. loading into a temprorary // element makes these requests immediately if ( pageElemRegex.test( html ) && RegExp.$1 && dataUrlRegex.test( RegExp.$1 ) && RegExp.$1 ) { fileUrl = $.mobile.path.getFilePath( $("<div>" + RegExp.$1 + "</div>").text() ); } //dont update the base tag if we are prefetching if ( settings.prefetch === undefined ) { this._getBase().set( fileUrl ); } content = this._parse( html, fileUrl ); this._setLoadedTitle( content, html ); // Add the content reference and xhr to our triggerData. triggerData.xhr = xhr; triggerData.textStatus = textStatus; // DEPRECATED triggerData.page = content; triggerData.content = content; // If the default behavior is prevented, stop here! // Note that it is the responsibility of the listener/handler // that called preventDefault(), to resolve/reject the // deferred object within the triggerData. if ( !this._trigger( "load", undefined, triggerData ) ) { return; } // rewrite src and href attrs to use a base url if the base tag won't work if ( this._isRewritableBaseTag() && content ) { this._getBase().rewrite( fileUrl, content ); } this._include( content, settings ); // Enhancing the content may result in new dialogs/sub content being inserted // into the DOM. If the original absUrl refers to a sub-content, that is the // real content we are interested in. if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) { content = this.element.children( "[data-" + this._getNs() +"url='" + dataUrl + "']" ); } // Remove loading message. if ( settings.showLoadMsg ) { this._hideLoading(); } // BEGIN DEPRECATED --------------------------------------------------- // Let listeners know the content loaded successfully. this.element.trigger( "pageload" ); // END DEPRECATED ----------------------------------------------------- deferred.resolve( absUrl, settings, content ); }, this); }, _loadDefaults: { type: "get", data: undefined, // DEPRECATED reloadPage: false, reload: false, // By default we rely on the role defined by the @data-role attribute. role: undefined, showLoadMsg: false, // This delay allows loads that pull from browser cache to // occur without showing the loading message. loadMsgDelay: 50 }, load: function( url, options ) { // This function uses deferred notifications to let callers // know when the content is done loading, or if an error has occurred. var deferred = ( options && options.deferred ) || $.Deferred(), // The default load options with overrides specified by the caller. settings = $.extend( {}, this._loadDefaults, options ), // The DOM element for the content after it has been loaded. content = null, // The absolute version of the URL passed into the function. This // version of the URL may contain dialog/subcontent params in it. absUrl = $.mobile.path.makeUrlAbsolute( url, this._findBaseWithDefault() ), fileUrl, dataUrl, pblEvent, triggerData; // DEPRECATED reloadPage settings.reload = settings.reloadPage; // If the caller provided data, and we're using "get" request, // append the data to the URL. if ( settings.data && settings.type === "get" ) { absUrl = $.mobile.path.addSearchParams( absUrl, settings.data ); settings.data = undefined; } // If the caller is using a "post" request, reload must be true if ( settings.data && settings.type === "post" ) { settings.reload = true; } // The absolute version of the URL minus any dialog/subcontent params. // In otherwords the real URL of the content to be loaded. fileUrl = this._createFileUrl( absUrl ); // The version of the Url actually stored in the data-url attribute of // the content. For embedded content, it is just the id of the page. For // content within the same domain as the document base, it is the site // relative path. For cross-domain content (Phone Gap only) the entire // absolute Url is used to load the content. dataUrl = this._createDataUrl( absUrl ); content = this._find( absUrl ); // If it isn't a reference to the first content and refers to missing // embedded content reject the deferred and return if ( content.length === 0 && $.mobile.path.isEmbeddedPage(fileUrl) && !$.mobile.path.isFirstPageUrl(fileUrl) ) { deferred.reject( absUrl, settings ); return; } // Reset base to the default document base // TODO figure out why we doe this this._getBase().reset(); // If the content we are interested in is already in the DOM, // and the caller did not indicate that we should force a // reload of the file, we are done. Resolve the deferrred so that // users can bind to .done on the promise if ( content.length && !settings.reload ) { this._enhance( content, settings.role ); deferred.resolve( absUrl, settings, content ); //if we are reloading the content make sure we update // the base if its not a prefetch if ( !settings.prefetch ) { this._getBase().set(url); } return; } triggerData = { url: url, absUrl: absUrl, dataUrl: dataUrl, deferred: deferred, options: settings }; // Let listeners know we're about to load content. pblEvent = this._triggerWithDeprecated( "beforeload", triggerData ); // If the default behavior is prevented, stop here! if ( pblEvent.deprecatedEvent.isDefaultPrevented() || pblEvent.event.isDefaultPrevented() ) { return; } if ( settings.showLoadMsg ) { this._showLoading( settings.loadMsgDelay ); } // Reset base to the default document base. // only reset if we are not prefetching if ( settings.prefetch === undefined ) { this._getBase().reset(); } if ( !( $.mobile.allowCrossDomainPages || $.mobile.path.isSameDomain($.mobile.path.documentUrl, absUrl ) ) ) { deferred.reject( absUrl, settings ); return; } // Load the new content. $.ajax({ url: fileUrl, type: settings.type, data: settings.data, contentType: settings.contentType, dataType: "html", success: this._loadSuccess( absUrl, triggerData, settings, deferred ), error: this._loadError( absUrl, triggerData, settings, deferred ) }); }, _loadError: function( absUrl, triggerData, settings, deferred ) { return $.proxy(function( xhr, textStatus, errorThrown ) { //set base back to current path this._getBase().set( $.mobile.path.get() ); // Add error info to our triggerData. triggerData.xhr = xhr; triggerData.textStatus = textStatus; triggerData.errorThrown = errorThrown; // Let listeners know the page load failed. var plfEvent = this._triggerWithDeprecated( "loadfailed", triggerData ); // If the default behavior is prevented, stop here! // Note that it is the responsibility of the listener/handler // that called preventDefault(), to resolve/reject the // deferred object within the triggerData. if ( plfEvent.deprecatedEvent.isDefaultPrevented() || plfEvent.event.isDefaultPrevented() ) { return; } // Remove loading message. if ( settings.showLoadMsg ) { this._showError(); } deferred.reject( absUrl, settings ); }, this); }, _getTransitionHandler: function( transition ) { transition = $.mobile._maybeDegradeTransition( transition ); //find the transition handler for the specified transition. If there //isn't one in our transitionHandlers dictionary, use the default one. //call the handler immediately to kick-off the transition. return $.mobile.transitionHandlers[ transition ] || $.mobile.defaultTransitionHandler; }, // TODO move into transition handlers? _triggerCssTransitionEvents: function( to, from, prefix ) { var samePage = false; prefix = prefix || ""; // TODO decide if these events should in fact be triggered on the container if ( from ) { //Check if this is a same page transition and tell the handler in page if( to[0] === from[0] ){ samePage = true; } //trigger before show/hide events // TODO deprecate nextPage in favor of next this._triggerWithDeprecated( prefix + "hide", { nextPage: to, samePage: samePage }, from ); } // TODO deprecate prevPage in favor of previous this._triggerWithDeprecated( prefix + "show", { prevPage: from || $( "" ) }, to ); }, // TODO make private once change has been defined in the widget _cssTransition: function( to, from, options ) { var transition = options.transition, reverse = options.reverse, deferred = options.deferred, TransitionHandler, promise; this._triggerCssTransitionEvents( to, from, "before" ); // TODO put this in a binding to events *outside* the widget this._hideLoading(); TransitionHandler = this._getTransitionHandler( transition ); promise = ( new TransitionHandler( transition, reverse, to, from ) ).transition(); // TODO temporary accomodation of argument deferred promise.done(function() { deferred.resolve.apply( deferred, arguments ); }); promise.done($.proxy(function() { this._triggerCssTransitionEvents( to, from ); }, this)); }, _releaseTransitionLock: function() { //release transition lock so navigation is free again isPageTransitioning = false; if ( pageTransitionQueue.length > 0 ) { $.mobile.changePage.apply( null, pageTransitionQueue.pop() ); } }, _removeActiveLinkClass: function( force ) { //clear out the active button state $.mobile.removeActiveLinkClass( force ); }, _loadUrl: function( to, triggerData, settings ) { // preserve the original target as the dataUrl value will be // simplified eg, removing ui-state, and removing query params // from the hash this is so that users who want to use query // params have access to them in the event bindings for the page // life cycle See issue #5085 settings.target = to; settings.deferred = $.Deferred(); this.load( to, settings ); settings.deferred.done($.proxy(function( url, options, content ) { isPageTransitioning = false; // store the original absolute url so that it can be provided // to events in the triggerData of the subsequent changePage call options.absUrl = triggerData.absUrl; this.transition( content, triggerData, options ); }, this)); settings.deferred.fail($.proxy(function(/* url, options */) { this._removeActiveLinkClass( true ); this._releaseTransitionLock(); this._triggerWithDeprecated( "changefailed", triggerData ); }, this)); }, _triggerPageBeforeChange: function( to, triggerData, settings ) { var pbcEvent = new $.Event( "pagebeforechange" ); $.extend(triggerData, { toPage: to, options: settings }); // NOTE: preserve the original target as the dataUrl value will be // simplified eg, removing ui-state, and removing query params from // the hash this is so that users who want to use query params have // access to them in the event bindings for the page life cycle // See issue #5085 if ( $.type(to) === "string" ) { // if the toPage is a string simply convert it triggerData.absUrl = $.mobile.path.makeUrlAbsolute( to, this._findBaseWithDefault() ); } else { // if the toPage is a jQuery object grab the absolute url stored // in the loadPage callback where it exists triggerData.absUrl = settings.absUrl; } // Let listeners know we're about to change the current page. this.element.trigger( pbcEvent, triggerData ); // If the default behavior is prevented, stop here! if ( pbcEvent.isDefaultPrevented() ) { return false; } return true; }, change: function( to, options ) { // If we are in the midst of a transition, queue the current request. // We'll call changePage() once we're done with the current transition // to service the request. if ( isPageTransitioning ) { pageTransitionQueue.unshift( arguments ); return; } var settings = $.extend( {}, $.mobile.changePage.defaults, options ), triggerData = {}; // Make sure we have a fromPage. settings.fromPage = settings.fromPage || this.activePage; // if the page beforechange default is prevented return early if ( !this._triggerPageBeforeChange(to, triggerData, settings) ) { return; } // We allow "pagebeforechange" observers to modify the to in // the trigger data to allow for redirects. Make sure our to is // updated. We also need to re-evaluate whether it is a string, // because an object can also be replaced by a string to = triggerData.toPage; // If the caller passed us a url, call loadPage() // to make sure it is loaded into the DOM. We'll listen // to the promise object it returns so we know when // it is done loading or if an error ocurred. if ( $.type(to) === "string" ) { // Set the isPageTransitioning flag to prevent any requests from // entering this method while we are in the midst of loading a page // or transitioning. isPageTransitioning = true; this._loadUrl( to, triggerData, settings ); } else { this.transition( to, triggerData, settings ); } }, transition: function( toPage, triggerData, settings ) { var fromPage, url, pageUrl, fileUrl, active, activeIsInitialPage, historyDir, pageTitle, isDialog, alreadyThere, newPageTitle, params, cssTransitionDeferred, beforeTransition; // If we are in the midst of a transition, queue the current request. // We'll call changePage() once we're done with the current transition // to service the request. if ( isPageTransitioning ) { // make sure to only queue the to and settings values so the arguments // work with a call to the change method pageTransitionQueue.unshift( [toPage, settings] ); return; } // DEPRECATED - this call only, in favor of the before transition // if the page beforechange default is prevented return early if ( !this._triggerPageBeforeChange(toPage, triggerData, settings) ) { return; } // if the (content|page)beforetransition default is prevented return early // Note, we have to check for both the deprecated and new events beforeTransition = this._triggerWithDeprecated( "beforetransition", triggerData ); if (beforeTransition.deprecatedEvent.isDefaultPrevented() || beforeTransition.event.isDefaultPrevented() ) { return; } // Set the isPageTransitioning flag to prevent any requests from // entering this method while we are in the midst of loading a page // or transitioning. isPageTransitioning = true; // If we are going to the first-page of the application, we need to make // sure settings.dataUrl is set to the application document url. This allows // us to avoid generating a document url with an id hash in the case where the // first-page of the document has an id attribute specified. if ( toPage[ 0 ] === $.mobile.firstPage[ 0 ] && !settings.dataUrl ) { settings.dataUrl = $.mobile.path.documentUrl.hrefNoHash; } // The caller passed us a real page DOM element. Update our // internal state and then trigger a transition to the page. fromPage = settings.fromPage; url = ( settings.dataUrl && $.mobile.path.convertUrlToDataUrl(settings.dataUrl) ) || toPage.jqmData( "url" ); // The pageUrl var is usually the same as url, except when url is obscured // as a dialog url. pageUrl always contains the file path pageUrl = url; fileUrl = $.mobile.path.getFilePath( url ); active = $.mobile.navigate.history.getActive(); activeIsInitialPage = $.mobile.navigate.history.activeIndex === 0; historyDir = 0; pageTitle = document.title; isDialog = ( settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog" ) && toPage.jqmData( "dialog" ) !== true; // By default, we prevent changePage requests when the fromPage and toPage // are the same element, but folks that generate content // manually/dynamically and reuse pages want to be able to transition to // the same page. To allow this, they will need to change the default // value of allowSamePageTransition to true, *OR*, pass it in as an // option when they manually call changePage(). It should be noted that // our default transition animations assume that the formPage and toPage // are different elements, so they may behave unexpectedly. It is up to // the developer that turns on the allowSamePageTransitiona option to // either turn off transition animations, or make sure that an appropriate // animation transition is used. if ( fromPage && fromPage[0] === toPage[0] && !settings.allowSamePageTransition ) { isPageTransitioning = false; this._triggerWithDeprecated( "transition", triggerData ); this.element.trigger( "pagechange", triggerData ); // Even if there is no page change to be done, we should keep the // urlHistory in sync with the hash changes if ( settings.fromHashChange ) { $.mobile.navigate.history.direct({ url: url }); } return; } // We need to make sure the page we are given has already been enhanced. toPage.page({ role: settings.role }); // If the changePage request was sent from a hashChange event, check to // see if the page is already within the urlHistory stack. If so, we'll // assume the user hit the forward/back button and will try to match the // transition accordingly. if ( settings.fromHashChange ) { historyDir = settings.direction === "back" ? -1 : 1; } // Kill the keyboard. // XXX_jblas: We need to stop crawling the entire document to kill focus. // Instead, we should be tracking focus with a delegate() // handler so we already have the element in hand at this // point. // Wrap this in a try/catch block since IE9 throw "Unspecified error" if // document.activeElement is undefined when we are in an IFrame. try { if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== "body" ) { $( document.activeElement ).blur(); } else { $( "input:focus, textarea:focus, select:focus" ).blur(); } } catch( e ) {} // Record whether we are at a place in history where a dialog used to be - // if so, do not add a new history entry and do not change the hash either alreadyThere = false; // If we're displaying the page as a dialog, we don't want the url // for the dialog content to be used in the hash. Instead, we want // to append the dialogHashKey to the url of the current page. if ( isDialog && active ) { // on the initial page load active.url is undefined and in that case // should be an empty string. Moving the undefined -> empty string back // into urlHistory.addNew seemed imprudent given undefined better // represents the url state // If we are at a place in history that once belonged to a dialog, reuse // this state without adding to urlHistory and without modifying the // hash. However, if a dialog is already displayed at this point, and // we're about to display another dialog, then we must add another hash // and history entry on top so that one may navigate back to the // original dialog if ( active.url && active.url.indexOf( $.mobile.dialogHashKey ) > -1 && this.activePage && !this.activePage.hasClass( "ui-dialog" ) && $.mobile.navigate.history.activeIndex > 0 ) { settings.changeHash = false; alreadyThere = true; } // Normally, we tack on a dialog hash key, but if this is the location // of a stale dialog, we reuse the URL from the entry url = ( active.url || "" ); // account for absolute urls instead of just relative urls use as hashes if ( !alreadyThere && url.indexOf("#") > -1 ) { url += $.mobile.dialogHashKey; } else { url += "#" + $.mobile.dialogHashKey; } // tack on another dialogHashKey if this is the same as the initial hash // this makes sure that a history entry is created for this dialog if ( $.mobile.navigate.history.activeIndex === 0 && url === $.mobile.navigate.history.initialDst ) { url += $.mobile.dialogHashKey; } } // if title element wasn't found, try the page div data attr too // If this is a deep-link or a reload ( active === undefined ) then just // use pageTitle newPageTitle = ( !active ) ? pageTitle : toPage.jqmData( "title" ) || toPage.children( ":jqmData(role='header')" ).find( ".ui-title" ).text(); if ( !!newPageTitle && pageTitle === document.title ) { pageTitle = newPageTitle; } if ( !toPage.jqmData( "title" ) ) { toPage.jqmData( "title", pageTitle ); } // Make sure we have a transition defined. settings.transition = settings.transition || ( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined ) || ( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition ); //add page to history stack if it's not back or forward if ( !historyDir && alreadyThere ) { $.mobile.navigate.history.getActive().pageUrl = pageUrl; } // Set the location hash. if ( url && !settings.fromHashChange ) { // rebuilding the hash here since we loose it earlier on // TODO preserve the originally passed in path if ( !$.mobile.path.isPath( url ) && url.indexOf( "#" ) < 0 ) { url = "#" + url; } // TODO the property names here are just silly params = { transition: settings.transition, title: pageTitle, pageUrl: pageUrl, role: settings.role }; if ( settings.changeHash !== false && $.mobile.hashListeningEnabled ) { $.mobile.navigate( url, params, true); } else if ( toPage[ 0 ] !== $.mobile.firstPage[ 0 ] ) { $.mobile.navigate.history.add( url, params ); } } //set page title document.title = pageTitle; //set "toPage" as activePage deprecated in 1.4 remove in 1.5 $.mobile.activePage = toPage; //new way to handle activePage this.activePage = toPage; // If we're navigating back in the URL history, set reverse accordingly. settings.reverse = settings.reverse || historyDir < 0; cssTransitionDeferred = $.Deferred(); this._cssTransition(toPage, fromPage, { transition: settings.transition, reverse: settings.reverse, deferred: cssTransitionDeferred }); cssTransitionDeferred.done($.proxy(function( name, reverse, $to, $from, alreadyFocused ) { $.mobile.removeActiveLinkClass(); //if there's a duplicateCachedPage, remove it from the DOM now that it's hidden if ( settings.duplicateCachedPage ) { settings.duplicateCachedPage.remove(); } // despite visibility: hidden addresses issue #2965 // https://github.com/jquery/jquery-mobile/issues/2965 if ( !alreadyFocused ) { $.mobile.focusPage( toPage ); } this._releaseTransitionLock(); this.element.trigger( "pagechange", triggerData ); this._triggerWithDeprecated( "transition", triggerData ); }, this)); }, // determine the current base url _findBaseWithDefault: function() { var closestBase = ( this.activePage && $.mobile.getClosestBaseUrl( this.activePage ) ); return closestBase || $.mobile.path.documentBase.hrefNoHash; } }); // The following handlers should be bound after mobileinit has been triggered // the following deferred is resolved in the init file $.mobile.navreadyDeferred = $.Deferred(); //these variables make all page containers use the same queue and only navigate one at a time // queue to hold simultanious page transitions var pageTransitionQueue = [], // indicates whether or not page is in process of transitioning isPageTransitioning = false; })( jQuery ); (function( $, undefined ) { // resolved on domready var domreadyDeferred = $.Deferred(), documentUrl = $.mobile.path.documentUrl, // used to track last vclicked element to make sure its value is added to form data $lastVClicked = null; /* Event Bindings - hashchange, submit, and click */ function findClosestLink( ele ) { while ( ele ) { // Look for the closest element with a nodeName of "a". // Note that we are checking if we have a valid nodeName // before attempting to access it. This is because the // node we get called with could have originated from within // an embedded SVG document where some symbol instance elements // don't have nodeName defined on them, or strings are of type // SVGAnimatedString. if ( ( typeof ele.nodeName === "string" ) && ele.nodeName.toLowerCase() === "a" ) { break; } ele = ele.parentNode; } return ele; } $.mobile.loadPage = function( url, opts ) { var container; opts = opts || {}; container = ( opts.pageContainer || $.mobile.pageContainer ); // create the deferred that will be supplied to loadPage callers // and resolved by the content widget's load method opts.deferred = $.Deferred(); // Preferring to allow exceptions for uninitialized opts.pageContainer // widgets so we know if we need to force init here for users container.pagecontainer( "load", url, opts ); // provide the deferred return opts.deferred.promise(); }; //define vars for interal use /* internal utility functions */ // NOTE Issue #4950 Android phonegap doesn't navigate back properly // when a full page refresh has taken place. It appears that hashchange // and replacestate history alterations work fine but we need to support // both forms of history traversal in our code that uses backward history // movement $.mobile.back = function() { var nav = window.navigator; // if the setting is on and the navigator object is // available use the phonegap navigation capability if ( this.phonegapNavigationEnabled && nav && nav.app && nav.app.backHistory ) { nav.app.backHistory(); } else { $.mobile.pageContainer.pagecontainer( "back" ); } }; // Direct focus to the page title, or otherwise first focusable element $.mobile.focusPage = function ( page ) { var autofocus = page.find( "[autofocus]" ), pageTitle = page.find( ".ui-title:eq(0)" ); if ( autofocus.length ) { autofocus.focus(); return; } if ( pageTitle.length ) { pageTitle.focus(); } else{ page.focus(); } }; // No-op implementation of transition degradation $.mobile._maybeDegradeTransition = $.mobile._maybeDegradeTransition || function( transition ) { return transition; }; // Exposed $.mobile methods $.mobile.changePage = function( to, options ) { $.mobile.pageContainer.pagecontainer( "change", to, options ); }; $.mobile.changePage.defaults = { transition: undefined, reverse: false, changeHash: true, fromHashChange: false, role: undefined, // By default we rely on the role defined by the @data-role attribute. duplicateCachedPage: undefined, pageContainer: undefined, showLoadMsg: true, //loading message shows by default when pages are being fetched during changePage dataUrl: undefined, fromPage: undefined, allowSamePageTransition: false }; $.mobile._registerInternalEvents = function() { var getAjaxFormData = function( $form, calculateOnly ) { var url, ret = true, formData, vclickedName, method; if ( !$.mobile.ajaxEnabled || // test that the form is, itself, ajax false $form.is( ":jqmData(ajax='false')" ) || // test that $.mobile.ignoreContentEnabled is set and // the form or one of it's parents is ajax=false !$form.jqmHijackable().length || $form.attr( "target" ) ) { return false; } url = ( $lastVClicked && $lastVClicked.attr( "formaction" ) ) || $form.attr( "action" ); method = ( $form.attr( "method" ) || "get" ).toLowerCase(); // If no action is specified, browsers default to using the // URL of the document containing the form. Since we dynamically // pull in pages from external documents, the form should submit // to the URL for the source document of the page containing // the form. if ( !url ) { // Get the @data-url for the page containing the form. url = $.mobile.getClosestBaseUrl( $form ); // NOTE: If the method is "get", we need to strip off the query string // because it will get replaced with the new form data. See issue #5710. if ( method === "get" ) { url = $.mobile.path.parseUrl( url ).hrefNoSearch; } if ( url === $.mobile.path.documentBase.hrefNoHash ) { // The url we got back matches the document base, // which means the page must be an internal/embedded page, // so default to using the actual document url as a browser // would. url = documentUrl.hrefNoSearch; } } url = $.mobile.path.makeUrlAbsolute( url, $.mobile.getClosestBaseUrl( $form ) ); if ( ( $.mobile.path.isExternal( url ) && !$.mobile.path.isPermittedCrossDomainRequest( documentUrl, url ) ) ) { return false; } if ( !calculateOnly ) { formData = $form.serializeArray(); if ( $lastVClicked && $lastVClicked[ 0 ].form === $form[ 0 ] ) { vclickedName = $lastVClicked.attr( "name" ); if ( vclickedName ) { // Make sure the last clicked element is included in the form $.each( formData, function( key, value ) { if ( value.name === vclickedName ) { // Unset vclickedName - we've found it in the serialized data already vclickedName = ""; return false; } }); if ( vclickedName ) { formData.push( { name: vclickedName, value: $lastVClicked.attr( "value" ) } ); } } } ret = { url: url, options: { type: method, data: $.param( formData ), transition: $form.jqmData( "transition" ), reverse: $form.jqmData( "direction" ) === "reverse", reloadPage: true } }; } return ret; }; //bind to form submit events, handle with Ajax $.mobile.document.delegate( "form", "submit", function( event ) { var formData; if ( !event.isDefaultPrevented() ) { formData = getAjaxFormData( $( this ) ); if ( formData ) { $.mobile.changePage( formData.url, formData.options ); event.preventDefault(); } } }); //add active state on vclick $.mobile.document.bind( "vclick", function( event ) { var $btn, btnEls, target = event.target, needClosest = false; // if this isn't a left click we don't care. Its important to note // that when the virtual event is generated it will create the which attr if ( event.which > 1 || !$.mobile.linkBindingEnabled ) { return; } // Record that this element was clicked, in case we need it for correct // form submission during the "submit" handler above $lastVClicked = $( target ); // Try to find a target element to which the active class will be applied if ( $.data( target, "mobile-button" ) ) { // If the form will not be submitted via AJAX, do not add active class if ( !getAjaxFormData( $( target ).closest( "form" ), true ) ) { return; } // We will apply the active state to this button widget - the parent // of the input that was clicked will have the associated data if ( target.parentNode ) { target = target.parentNode; } } else { target = findClosestLink( target ); if ( !( target && $.mobile.path.parseUrl( target.getAttribute( "href" ) || "#" ).hash !== "#" ) ) { return; } // TODO teach $.mobile.hijackable to operate on raw dom elements so the // link wrapping can be avoided if ( !$( target ).jqmHijackable().length ) { return; } } // Avoid calling .closest by using the data set during .buttonMarkup() // List items have the button data in the parent of the element clicked if ( !!~target.className.indexOf( "ui-link-inherit" ) ) { if ( target.parentNode ) { btnEls = $.data( target.parentNode, "buttonElements" ); } // Otherwise, look for the data on the target itself } else { btnEls = $.data( target, "buttonElements" ); } // If found, grab the button's outer element if ( btnEls ) { target = btnEls.outer; } else { needClosest = true; } $btn = $( target ); // If the outer element wasn't found by the our heuristics, use .closest() if ( needClosest ) { $btn = $btn.closest( ".ui-btn" ); } if ( $btn.length > 0 && !( $btn.hasClass( "ui-state-disabled" || // DEPRECATED as of 1.4.0 - remove after 1.4.0 release // only ui-state-disabled should be present thereafter $btn.hasClass( "ui-disabled" ) ) ) ) { $.mobile.removeActiveLinkClass( true ); $.mobile.activeClickedLink = $btn; $.mobile.activeClickedLink.addClass( $.mobile.activeBtnClass ); } }); // click routing - direct to HTTP or Ajax, accordingly $.mobile.document.bind( "click", function( event ) { if ( !$.mobile.linkBindingEnabled || event.isDefaultPrevented() ) { return; } var link = findClosestLink( event.target ), $link = $( link ), //remove active link class if external (then it won't be there if you come back) httpCleanup = function() { window.setTimeout(function() { $.mobile.removeActiveLinkClass( true ); }, 200 ); }, baseUrl, href, useDefaultUrlHandling, isExternal, transition, reverse, role; // If a button was clicked, clean up the active class added by vclick above if ( $.mobile.activeClickedLink && $.mobile.activeClickedLink[ 0 ] === event.target.parentNode ) { httpCleanup(); } // If there is no link associated with the click or its not a left // click we want to ignore the click // TODO teach $.mobile.hijackable to operate on raw dom elements so the link wrapping // can be avoided if ( !link || event.which > 1 || !$link.jqmHijackable().length ) { return; } //if there's a data-rel=back attr, go back in history if ( $link.is( ":jqmData(rel='back')" ) ) { $.mobile.back(); return false; } baseUrl = $.mobile.getClosestBaseUrl( $link ); //get href, if defined, otherwise default to empty hash href = $.mobile.path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl ); //if ajax is disabled, exit early if ( !$.mobile.ajaxEnabled && !$.mobile.path.isEmbeddedPage( href ) ) { httpCleanup(); //use default click handling return; } // XXX_jblas: Ideally links to application pages should be specified as // an url to the application document with a hash that is either // the site relative path or id to the page. But some of the // internal code that dynamically generates sub-pages for nested // lists and select dialogs, just write a hash in the link they // create. This means the actual URL path is based on whatever // the current value of the base tag is at the time this code // is called. For now we are just assuming that any url with a // hash in it is an application page reference. if ( href.search( "#" ) !== -1 ) { href = href.replace( /[^#]*#/, "" ); if ( !href ) { //link was an empty hash meant purely //for interaction, so we ignore it. event.preventDefault(); return; } else if ( $.mobile.path.isPath( href ) ) { //we have apath so make it the href we want to load. href = $.mobile.path.makeUrlAbsolute( href, baseUrl ); } else { //we have a simple id so use the documentUrl as its base. href = $.mobile.path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash ); } } // Should we handle this link, or let the browser deal with it? useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ); // Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR // requests if the document doing the request was loaded via the file:// protocol. // This is usually to allow the application to "phone home" and fetch app specific // data. We normally let the browser handle external/cross-domain urls, but if the // allowCrossDomainPages option is true, we will allow cross-domain http/https // requests to go through our page loading logic. //check for protocol or rel and its not an embedded page //TODO overlap in logic from isExternal, rel=external check should be // moved into more comprehensive isExternalLink isExternal = useDefaultUrlHandling || ( $.mobile.path.isExternal( href ) && !$.mobile.path.isPermittedCrossDomainRequest( documentUrl, href ) ); if ( isExternal ) { httpCleanup(); //use default click handling return; } //use ajax transition = $link.jqmData( "transition" ); reverse = $link.jqmData( "direction" ) === "reverse" || // deprecated - remove by 1.0 $link.jqmData( "back" ); //this may need to be more specific as we use data-rel more role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined; $.mobile.changePage( href, { transition: transition, reverse: reverse, role: role, link: $link } ); event.preventDefault(); }); //prefetch pages when anchors with data-prefetch are encountered $.mobile.document.delegate( ".ui-page", "pageshow.prefetch", function() { var urls = []; $( this ).find( "a:jqmData(prefetch)" ).each(function() { var $link = $( this ), url = $link.attr( "href" ); if ( url && $.inArray( url, urls ) === -1 ) { urls.push( url ); $.mobile.loadPage( url, { role: $link.attr( "data-" + $.mobile.ns + "rel" ),prefetch: true } ); } }); }); // TODO ensure that the navigate binding in the content widget happens at the right time $.mobile.pageContainer.pagecontainer(); //set page min-heights to be device specific $.mobile.document.bind( "pageshow", $.mobile.resetActivePageHeight ); $.mobile.window.bind( "throttledresize", $.mobile.resetActivePageHeight ); };//navreadyDeferred done callback $( function() { domreadyDeferred.resolve(); } ); $.when( domreadyDeferred, $.mobile.navreadyDeferred ).done( function() { $.mobile._registerInternalEvents(); } ); })( jQuery ); (function( $, window, undefined ) { // TODO remove direct references to $.mobile and properties, we should // favor injection with params to the constructor $.mobile.Transition = function() { this.init.apply( this, arguments ); }; $.extend($.mobile.Transition.prototype, { toPreClass: " ui-page-pre-in", init: function( name, reverse, $to, $from ) { $.extend(this, { name: name, reverse: reverse, $to: $to, $from: $from, deferred: new $.Deferred() }); }, cleanFrom: function() { this.$from .removeClass( $.mobile.activePageClass + " out in reverse " + this.name ) .height( "" ); }, // NOTE overridden by child object prototypes, noop'd here as defaults beforeDoneIn: function() {}, beforeDoneOut: function() {}, beforeStartOut: function() {}, doneIn: function() { this.beforeDoneIn(); this.$to.removeClass( "out in reverse " + this.name ).height( "" ); this.toggleViewportClass(); // In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition // This ensures we jump to that spot after the fact, if we aren't there already. if ( $.mobile.window.scrollTop() !== this.toScroll ) { this.scrollPage(); } if ( !this.sequential ) { this.$to.addClass( $.mobile.activePageClass ); } this.deferred.resolve( this.name, this.reverse, this.$to, this.$from, true ); }, doneOut: function( screenHeight, reverseClass, none, preventFocus ) { this.beforeDoneOut(); this.startIn( screenHeight, reverseClass, none, preventFocus ); }, hideIn: function( callback ) { // Prevent flickering in phonegap container: see comments at #4024 regarding iOS this.$to.css( "z-index", -10 ); callback.call( this ); this.$to.css( "z-index", "" ); }, scrollPage: function() { // By using scrollTo instead of silentScroll, we can keep things better in order // Just to be precautios, disable scrollstart listening like silentScroll would $.event.special.scrollstart.enabled = false; //if we are hiding the url bar or the page was previously scrolled scroll to hide or return to position if ( $.mobile.hideUrlBar || this.toScroll !== $.mobile.defaultHomeScroll ) { window.scrollTo( 0, this.toScroll ); } // reenable scrollstart listening like silentScroll would setTimeout( function() { $.event.special.scrollstart.enabled = true; }, 150 ); }, startIn: function( screenHeight, reverseClass, none, preventFocus ) { this.hideIn(function() { this.$to.addClass( $.mobile.activePageClass + this.toPreClass ); // Send focus to page as it is now display: block if ( !preventFocus ) { $.mobile.focusPage( this.$to ); } // Set to page height this.$to.height( screenHeight + this.toScroll ); if ( !none ) { this.scrollPage(); } }); this.$to .removeClass( this.toPreClass ) .addClass( this.name + " in " + reverseClass ); if ( !none ) { this.$to.animationComplete( $.proxy(function() { this.doneIn(); }, this )); } else { this.doneIn(); } }, startOut: function( screenHeight, reverseClass, none ) { this.beforeStartOut( screenHeight, reverseClass, none ); // Set the from page's height and start it transitioning out // Note: setting an explicit height helps eliminate tiling in the transitions this.$from .height( screenHeight + $.mobile.window.scrollTop() ) .addClass( this.name + " out" + reverseClass ); }, toggleViewportClass: function() { $.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + this.name ); }, transition: function() { // NOTE many of these could be calculated/recorded in the constructor, it's my // opinion that binding them as late as possible has value with regards to // better transitions with fewer bugs. Ie, it's not guaranteed that the // object will be created and transition will be run immediately after as // it is today. So we wait until transition is invoked to gather the following var reverseClass = this.reverse ? " reverse" : "", screenHeight = $.mobile.getScreenHeight(), maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $.mobile.window.width() > $.mobile.maxTransitionWidth, none = !$.support.cssTransitions || !$.support.cssAnimations || maxTransitionOverride || !this.name || this.name === "none" || Math.max( $.mobile.window.scrollTop(), this.toScroll ) > $.mobile.getMaxScrollForTransition(); this.toScroll = $.mobile.navigate.history.getActive().lastScroll || $.mobile.defaultHomeScroll; this.toggleViewportClass(); if ( this.$from && !none ) { this.startOut( screenHeight, reverseClass, none ); } else { this.doneOut( screenHeight, reverseClass, none, true ); } return this.deferred.promise(); } }); })( jQuery, this ); (function( $ ) { $.mobile.SerialTransition = function() { this.init.apply(this, arguments); }; $.extend($.mobile.SerialTransition.prototype, $.mobile.Transition.prototype, { sequential: true, beforeDoneOut: function() { if ( this.$from ) { this.cleanFrom(); } }, beforeStartOut: function( screenHeight, reverseClass, none ) { this.$from.animationComplete($.proxy(function() { this.doneOut( screenHeight, reverseClass, none ); }, this )); } }); })( jQuery ); (function( $ ) { $.mobile.ConcurrentTransition = function() { this.init.apply(this, arguments); }; $.extend($.mobile.ConcurrentTransition.prototype, $.mobile.Transition.prototype, { sequential: false, beforeDoneIn: function() { if ( this.$from ) { this.cleanFrom(); } }, beforeStartOut: function( screenHeight, reverseClass, none ) { this.doneOut( screenHeight, reverseClass, none ); } }); })( jQuery ); (function( $ ) { // generate the handlers from the above var defaultGetMaxScrollForTransition = function() { return $.mobile.getScreenHeight() * 3; }; //transition handler dictionary for 3rd party transitions $.mobile.transitionHandlers = { "sequential": $.mobile.SerialTransition, "simultaneous": $.mobile.ConcurrentTransition }; // Make our transition handler the public default. $.mobile.defaultTransitionHandler = $.mobile.transitionHandlers.sequential; $.mobile.transitionFallbacks = {}; // If transition is defined, check if css 3D transforms are supported, and if not, if a fallback is specified $.mobile._maybeDegradeTransition = function( transition ) { if ( transition && !$.support.cssTransform3d && $.mobile.transitionFallbacks[ transition ] ) { transition = $.mobile.transitionFallbacks[ transition ]; } return transition; }; // Set the getMaxScrollForTransition to default if no implementation was set by user $.mobile.getMaxScrollForTransition = $.mobile.getMaxScrollForTransition || defaultGetMaxScrollForTransition; })( jQuery ); /* * fallback transition for flip in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.flip = "fade"; })( jQuery, this ); /* * fallback transition for flow in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.flow = "fade"; })( jQuery, this ); /* * fallback transition for pop in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.pop = "fade"; })( jQuery, this ); /* * fallback transition for slide in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { // Use the simultaneous transitions handler for slide transitions $.mobile.transitionHandlers.slide = $.mobile.transitionHandlers.simultaneous; // Set the slide transitions's fallback to "fade" $.mobile.transitionFallbacks.slide = "fade"; })( jQuery, this ); /* * fallback transition for slidedown in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.slidedown = "fade"; })( jQuery, this ); /* * fallback transition for slidefade in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { // Set the slide transitions's fallback to "fade" $.mobile.transitionFallbacks.slidefade = "fade"; })( jQuery, this ); /* * fallback transition for slideup in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.slideup = "fade"; })( jQuery, this ); /* * fallback transition for turn in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.turn = "fade"; })( jQuery, this ); (function( $, undefined ) { $.mobile.degradeInputs = { color: false, date: false, datetime: false, "datetime-local": false, email: false, month: false, number: false, range: "number", search: "text", tel: false, time: false, url: false, week: false }; // Backcompat remove in 1.5 $.mobile.page.prototype.options.degradeInputs = $.mobile.degradeInputs; // Auto self-init widgets $.mobile.degradeInputsWithin = function( target ) { target = $( target ); // Degrade inputs to avoid poorly implemented native functionality target.find( "input" ).not( $.mobile.page.prototype.keepNativeSelector() ).each(function() { var element = $( this ), type = this.getAttribute( "type" ), optType = $.mobile.degradeInputs[ type ] || "text", html, hasType, findstr, repstr; if ( $.mobile.degradeInputs[ type ] ) { html = $( "<div>" ).html( element.clone() ).html(); // In IE browsers, the type sometimes doesn't exist in the cloned markup, so we replace the closing tag instead hasType = html.indexOf( " type=" ) > -1; findstr = hasType ? /\s+type=["']?\w+['"]?/ : /\/?>/; repstr = " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\"" + ( hasType ? "" : ">" ); element.replaceWith( html.replace( findstr, repstr ) ); } }); }; })( jQuery ); (function( $, window, undefined ) { $.widget( "mobile.page", $.mobile.page, { options: { // Accepts left, right and none closeBtn: "left", closeBtnText: "Close", overlayTheme: "a", corners: true, dialog: false }, _create: function() { this._super(); if ( this.options.dialog ) { $.extend( this, { _inner: this.element.children(), _headerCloseButton: null }); if ( !this.options.enhanced ) { this._setCloseBtn( this.options.closeBtn ); } } }, _enhance: function() { this._super(); // Class the markup for dialog styling and wrap interior if ( this.options.dialog ) { this.element.addClass( "ui-dialog" ) .wrapInner( $( "<div/>", { // ARIA role "role" : "dialog", "class" : "ui-dialog-contain ui-overlay-shadow" + ( this.options.corners ? " ui-corner-all" : "" ) })); } }, _setOptions: function( options ) { var closeButtonLocation, closeButtonText, currentOpts = this.options; if ( options.corners !== undefined ) { this._inner.toggleClass( "ui-corner-all", !!options.corners ); } if ( options.overlayTheme !== undefined ) { if ( $.mobile.activePage[ 0 ] === this.element[ 0 ] ) { currentOpts.overlayTheme = options.overlayTheme; this._handlePageBeforeShow(); } } if ( options.closeBtnText !== undefined ) { closeButtonLocation = currentOpts.closeBtn; closeButtonText = options.closeBtnText; } if ( options.closeBtn !== undefined ) { closeButtonLocation = options.closeBtn; } if ( closeButtonLocation ) { this._setCloseBtn( closeButtonLocation, closeButtonText ); } this._super( options ); }, _handlePageBeforeShow: function () { if ( this.options.overlayTheme && this.options.dialog ) { this.removeContainerBackground(); this.setContainerBackground( this.options.overlayTheme ); } else { this._super(); } }, _setCloseBtn: function( location, text ) { var dst, btn = this._headerCloseButton; // Sanitize value location = "left" === location ? "left" : "right" === location ? "right" : "none"; if ( "none" === location ) { if ( btn ) { btn.remove(); btn = null; } } else if ( btn ) { btn.removeClass( "ui-btn-left ui-btn-right" ).addClass( "ui-btn-" + location ); if ( text ) { btn.text( text ); } } else { dst = this._inner.find( ":jqmData(role='header')" ).first(); btn = $( "<a></a>", { "href": "#", "class": "ui-btn ui-corner-all ui-icon-delete ui-btn-icon-notext ui-btn-" + location }) .attr( "data-" + $.mobile.ns + "rel", "back" ) .text( text || this.options.closeBtnText || "" ) .prependTo( dst ); } this._headerCloseButton = btn; } }); })( jQuery, this ); (function( $, window, undefined ) { $.widget( "mobile.dialog", { options: { // Accepts left, right and none closeBtn: "left", closeBtnText: "Close", overlayTheme: "a", corners: true }, // Override the theme set by the page plugin on pageshow _handlePageBeforeShow: function() { this._isCloseable = true; if ( this.options.overlayTheme ) { this.element .page( "removeContainerBackground" ) .page( "setContainerBackground", this.options.overlayTheme ); } }, _handlePageBeforeHide: function() { this._isCloseable = false; }, // click and submit events: // - clicks and submits should use the closing transition that the dialog // opened with unless a data-transition is specified on the link/form // - if the click was on the close button, or the link has a data-rel="back" // it'll go back in history naturally _handleVClickSubmit: function( event ) { var attrs, $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ); if ( $target.length && !$target.jqmData( "transition" ) ) { attrs = {}; attrs[ "data-" + $.mobile.ns + "transition" ] = ( $.mobile.navigate.history.getActive() || {} )[ "transition" ] || $.mobile.defaultDialogTransition; attrs[ "data-" + $.mobile.ns + "direction" ] = "reverse"; $target.attr( attrs ); } }, _create: function() { var elem = this.element, opts = this.options; // Class the markup for dialog styling and wrap interior elem.addClass( "ui-dialog" ) .wrapInner( $( "<div/>", { // ARIA role "role" : "dialog", "class" : "ui-dialog-contain ui-overlay-shadow" + ( !!opts.corners ? " ui-corner-all" : "" ) })); $.extend( this, { _isCloseable: false, _inner: elem.children(), _headerCloseButton: null }); this._on( elem, { vclick: "_handleVClickSubmit", submit: "_handleVClickSubmit", pagebeforeshow: "_handlePageBeforeShow", pagebeforehide: "_handlePageBeforeHide" }); this._setCloseBtn( opts.closeBtn ); }, _setOptions: function( options ) { var closeButtonLocation, closeButtonText, currentOpts = this.options; if ( options.corners !== undefined ) { this._inner.toggleClass( "ui-corner-all", !!options.corners ); } if ( options.overlayTheme !== undefined ) { if ( $.mobile.activePage[ 0 ] === this.element[ 0 ] ) { currentOpts.overlayTheme = options.overlayTheme; this._handlePageBeforeShow(); } } if ( options.closeBtnText !== undefined ) { closeButtonLocation = currentOpts.closeBtn; closeButtonText = options.closeBtnText; } if ( options.closeBtn !== undefined ) { closeButtonLocation = options.closeBtn; } if ( closeButtonLocation ) { this._setCloseBtn( closeButtonLocation, closeButtonText ); } this._super( options ); }, _setCloseBtn: function( location, text ) { var dst, btn = this._headerCloseButton; // Sanitize value location = "left" === location ? "left" : "right" === location ? "right" : "none"; if ( "none" === location ) { if ( btn ) { btn.remove(); btn = null; } } else if ( btn ) { btn.removeClass( "ui-btn-left ui-btn-right" ).addClass( "ui-btn-" + location ); if ( text ) { btn.text( text ); } } else { dst = this._inner.find( ":jqmData(role='header')" ).first(); btn = $( "<a></a>", { "role": "button", "href": "#", "class": "ui-btn ui-corner-all ui-icon-delete ui-btn-icon-notext ui-btn-" + location }) .text( text || this.options.closeBtnText || "" ) .prependTo( dst ); this._on( btn, { click: "close" } ); } this._headerCloseButton = btn; }, // Close method goes back in history close: function() { var hist = $.mobile.navigate.history; if ( this._isCloseable ) { this._isCloseable = false; // If the hash listening is enabled and there is at least one preceding history // entry it's ok to go back. Initial pages with the dialog hash state are an example // where the stack check is necessary if ( $.mobile.hashListeningEnabled && hist.activeIndex > 0 ) { $.mobile.back(); } else { $.mobile.pageContainer.pagecontainer( "back" ); } } } }); })( jQuery, this ); (function( $, undefined ) { var rInitialLetter = /([A-Z])/g, // Construct iconpos class from iconpos value iconposClass = function( iconpos ) { return ( "ui-btn-icon-" + ( iconpos === null ? "left" : iconpos ) ); }; $.widget( "mobile.collapsible", { options: { enhanced: false, expandCueText: null, collapseCueText: null, collapsed: true, heading: "h1,h2,h3,h4,h5,h6,legend", collapsedIcon: null, expandedIcon: null, iconpos: null, theme: null, contentTheme: null, inset: null, corners: null, mini: null }, _create: function() { var elem = this.element, ui = { accordion: elem .closest( ":jqmData(role='collapsible-set')," + ":jqmData(role='collapsibleset')" + ( $.mobile.collapsibleset ? ", :mobile-collapsibleset" : "" ) ) .addClass( "ui-collapsible-set" ) }; this._ui = ui; this._renderedOptions = this._getOptions( this.options ); if ( this.options.enhanced ) { ui.heading = $( ".ui-collapsible-heading", this.element[ 0 ] ); ui.content = ui.heading.next(); ui.anchor = $( "a", ui.heading[ 0 ] ).first(); ui.status = ui.anchor.children( ".ui-collapsible-heading-status" ); } else { this._enhance( elem, ui ); } this._on( ui.heading, { "tap": function() { ui.heading.find( "a" ).first().addClass( $.mobile.activeBtnClass ); }, "click": function( event ) { this._handleExpandCollapse( !ui.heading.hasClass( "ui-collapsible-heading-collapsed" ) ); event.preventDefault(); event.stopPropagation(); } }); }, // Adjust the keys inside options for inherited values _getOptions: function( options ) { var key, accordion = this._ui.accordion, accordionWidget = this._ui.accordionWidget; // Copy options options = $.extend( {}, options ); if ( accordion.length && !accordionWidget ) { this._ui.accordionWidget = accordionWidget = accordion.data( "mobile-collapsibleset" ); } for ( key in options ) { // Retrieve the option value first from the options object passed in and, if // null, from the parent accordion or, if that's null too, or if there's no // parent accordion, then from the defaults. options[ key ] = ( options[ key ] != null ) ? options[ key ] : ( accordionWidget ) ? accordionWidget.options[ key ] : accordion.length ? $.mobile.getAttribute( accordion[ 0 ], key.replace( rInitialLetter, "-$1" ).toLowerCase() ): null; if ( null == options[ key ] ) { options[ key ] = $.mobile.collapsible.defaults[ key ]; } } return options; }, _themeClassFromOption: function( prefix, value ) { return ( value ? ( value === "none" ? "" : prefix + value ) : "" ); }, _enhance: function( elem, ui ) { var iconclass, opts = this._renderedOptions, contentThemeClass = this._themeClassFromOption( "ui-body-", opts.contentTheme ); elem.addClass( "ui-collapsible " + ( opts.inset ? "ui-collapsible-inset " : "" ) + ( opts.inset && opts.corners ? "ui-corner-all " : "" ) + ( contentThemeClass ? "ui-collapsible-themed-content " : "" ) ); ui.originalHeading = elem.children( this.options.heading ).first(), ui.content = elem .wrapInner( "<div " + "class='ui-collapsible-content " + contentThemeClass + "'></div>" ) .children( ".ui-collapsible-content" ), ui.heading = ui.originalHeading; // Replace collapsibleHeading if it's a legend if ( ui.heading.is( "legend" ) ) { ui.heading = $( "<div role='heading'>"+ ui.heading.html() +"</div>" ); ui.placeholder = $( "<div><!-- placeholder for legend --></div>" ).insertBefore( ui.originalHeading ); ui.originalHeading.remove(); } iconclass = ( opts.collapsed ? ( opts.collapsedIcon ? "ui-icon-" + opts.collapsedIcon : "" ): ( opts.expandedIcon ? "ui-icon-" + opts.expandedIcon : "" ) ); ui.status = $( "<span class='ui-collapsible-heading-status'></span>" ); ui.anchor = ui.heading .detach() //modify markup & attributes .addClass( "ui-collapsible-heading" ) .append( ui.status ) .wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" ) .find( "a" ) .first() .addClass( "ui-btn " + ( iconclass ? iconclass + " " : "" ) + ( iconclass ? iconposClass( opts.iconpos ) + " " : "" ) + this._themeClassFromOption( "ui-btn-", opts.theme ) + " " + ( opts.mini ? "ui-mini " : "" ) ); //drop heading in before content ui.heading.insertBefore( ui.content ); this._handleExpandCollapse( this.options.collapsed ); return ui; }, refresh: function() { this._applyOptions( this.options ); this._renderedOptions = this._getOptions( this.options ); }, _applyOptions: function( options ) { var isCollapsed, newTheme, oldTheme, hasCorners, elem = this.element, currentOpts = this._renderedOptions, ui = this._ui, anchor = ui.anchor, status = ui.status, opts = this._getOptions( options ); // First and foremost we need to make sure the collapsible is in the proper // state, in case somebody decided to change the collapsed option at the // same time as another option if ( options.collapsed !== undefined ) { this._handleExpandCollapse( options.collapsed ); } isCollapsed = elem.hasClass( "ui-collapsible-collapsed" ); // Only options referring to the current state need to be applied right away // It is enough to store options covering the alternate in this.options. if ( isCollapsed ) { if ( opts.expandCueText !== undefined ) { status.text( opts.expandCueText ); } if ( opts.collapsedIcon !== undefined ) { if ( currentOpts.collapsedIcon ) { anchor.removeClass( "ui-icon-" + currentOpts.collapsedIcon ); } if ( opts.collapsedIcon ) { anchor.addClass( "ui-icon-" + opts.collapsedIcon ); } } } else { if ( opts.collapseCueText !== undefined ) { status.text( opts.collapseCueText ); } if ( opts.expandedIcon !== undefined ) { if ( currentOpts.expandedIcon ) { anchor.removeClass( "ui-icon-" + currentOpts.expandedIcon ); } if ( opts.expandedIcon ) { anchor.addClass( "ui-icon-" + opts.expandedIcon ); } } } if ( opts.iconpos !== undefined ) { anchor .removeClass( iconposClass( currentOpts.iconpos ) ) .addClass( iconposClass( opts.iconpos ) ); } if ( opts.theme !== undefined ) { oldTheme = this._themeClassFromOption( "ui-btn-", currentOpts.theme ); newTheme = this._themeClassFromOption( "ui-btn-", opts.theme ); anchor.removeClass( oldTheme ).addClass( newTheme ); } if ( opts.contentTheme !== undefined ) { oldTheme = this._themeClassFromOption( "ui-body-", currentOpts.contentTheme ); newTheme = this._themeClassFromOption( "ui-body-", opts.contentTheme ); ui.content.removeClass( oldTheme ).addClass( newTheme ); } if ( opts.inset !== undefined ) { elem.toggleClass( "ui-collapsible-inset", opts.inset ); hasCorners = !!( opts.inset && ( opts.corners || currentOpts.corners ) ); } if ( opts.corners !== undefined ) { hasCorners = !!( opts.corners && ( opts.inset || currentOpts.inset ) ); } if ( hasCorners !== undefined ) { elem.toggleClass( "ui-corner-all", hasCorners ); } if ( opts.mini !== undefined ) { anchor.toggleClass( "ui-mini", opts.mini ); } }, _setOptions: function( options ) { this._applyOptions( options ); this._super( options ); this._renderedOptions = this._getOptions( this.options ); }, _handleExpandCollapse: function( isCollapse ) { var opts = this._renderedOptions, ui = this._ui; ui.status.text( isCollapse ? opts.expandCueText : opts.collapseCueText ); ui.heading .toggleClass( "ui-collapsible-heading-collapsed", isCollapse ) .find( "a" ).first() .toggleClass( "ui-icon-" + opts.expandedIcon, !isCollapse ) // logic or cause same icon for expanded/collapsed state would remove the ui-icon-class .toggleClass( "ui-icon-" + opts.collapsedIcon, ( isCollapse || opts.expandedIcon === opts.collapsedIcon ) ) .removeClass( $.mobile.activeBtnClass ); this.element.toggleClass( "ui-collapsible-collapsed", isCollapse ); ui.content .toggleClass( "ui-collapsible-content-collapsed", isCollapse ) .attr( "aria-hidden", isCollapse ) .trigger( "updatelayout" ); this.options.collapsed = isCollapse; this._trigger( isCollapse ? "collapse" : "expand" ); }, expand: function() { this._handleExpandCollapse( false ); }, collapse: function() { this._handleExpandCollapse( true ); }, _destroy: function() { var ui = this._ui, opts = this.options; if ( opts.enhanced ) { return; } if ( ui.placeholder ) { ui.originalHeading.insertBefore( ui.placeholder ); ui.placeholder.remove(); ui.heading.remove(); } else { ui.status.remove(); ui.heading .removeClass( "ui-collapsible-heading ui-collapsible-heading-collapsed" ) .children() .contents() .unwrap(); } ui.anchor.contents().unwrap(); ui.content.contents().unwrap(); this.element .removeClass( "ui-collapsible ui-collapsible-collapsed " + "ui-collapsible-themed-content ui-collapsible-inset ui-corner-all" ); } }); // Defaults to be used by all instances of collapsible if per-instance values // are unset or if nothing is specified by way of inheritance from an accordion. // Note that this hash does not contain options "collapsed" or "heading", // because those are not inheritable. $.mobile.collapsible.defaults = { expandCueText: " click to expand contents", collapseCueText: " click to collapse contents", collapsedIcon: "plus", contentTheme: "inherit", expandedIcon: "minus", iconpos: "left", inset: true, corners: true, theme: "inherit", mini: false }; })( jQuery ); (function( $, undefined ) { $.mobile.behaviors.addFirstLastClasses = { _getVisibles: function( $els, create ) { var visibles; if ( create ) { visibles = $els.not( ".ui-screen-hidden" ); } else { visibles = $els.filter( ":visible" ); if ( visibles.length === 0 ) { visibles = $els.not( ".ui-screen-hidden" ); } } return visibles; }, _addFirstLastClasses: function( $els, $visibles, create ) { $els.removeClass( "ui-first-child ui-last-child" ); $visibles.eq( 0 ).addClass( "ui-first-child" ).end().last().addClass( "ui-last-child" ); if ( !create ) { this.element.trigger( "updatelayout" ); } }, _removeFirstLastClasses: function( $els ) { $els.removeClass( "ui-first-child ui-last-child" ); } }; })( jQuery ); (function( $, undefined ) { var childCollapsiblesSelector = ":mobile-collapsible, " + $.mobile.collapsible.initSelector; $.widget( "mobile.collapsibleset", $.extend( { // The initSelector is deprecated as of 1.4.0. In 1.5.0 we will use // :jqmData(role='collapsibleset') which will allow us to get rid of the line // below altogether, because the autoinit will generate such an initSelector initSelector: ":jqmData(role='collapsible-set'),:jqmData(role='collapsibleset')", options: $.extend( { enhanced: false }, $.mobile.collapsible.defaults ), _handleCollapsibleExpand: function( event ) { var closestCollapsible = $( event.target ).closest( ".ui-collapsible" ); if ( closestCollapsible.parent().is( ":mobile-collapsibleset, :jqmData(role='collapsible-set')" ) ) { closestCollapsible .siblings( ".ui-collapsible:not(.ui-collapsible-collapsed)" ) .collapsible( "collapse" ); } }, _create: function() { var elem = this.element, opts = this.options; $.extend( this, { _classes: "" }); if ( !opts.enhanced ) { elem.addClass( "ui-collapsible-set " + this._themeClassFromOption( "ui-group-theme-", opts.theme ) + " " + ( opts.corners && opts.inset ? "ui-corner-all " : "" ) ); this.element.find( $.mobile.collapsible.initSelector ).collapsible(); } this._on( elem, { collapsibleexpand: "_handleCollapsibleExpand" } ); }, _themeClassFromOption: function( prefix, value ) { return ( value ? ( value === "none" ? "" : prefix + value ) : "" ); }, _init: function() { this._refresh( true ); // Because the corners are handled by the collapsible itself and the default state is collapsed // That was causing https://github.com/jquery/jquery-mobile/issues/4116 this.element .children( childCollapsiblesSelector ) .filter( ":jqmData(collapsed='false')" ) .collapsible( "expand" ); }, _setOptions: function( options ) { var ret, hasCorners, elem = this.element, themeClass = this._themeClassFromOption( "ui-group-theme-", options.theme ); if ( themeClass ) { elem .removeClass( this._themeClassFromOption( "ui-group-theme-", this.options.theme ) ) .addClass( themeClass ); } if ( options.inset !== undefined ) { hasCorners = !!( options.inset && ( options.corners || this.options.corners ) ); } if ( options.corners !== undefined ) { hasCorners = !!( options.corners && ( options.inset || this.options.inset ) ); } if ( hasCorners !== undefined ) { elem.toggleClass( "ui-corner-all", hasCorners ); } ret = this._super( options ); this.element.children( ":mobile-collapsible" ).collapsible( "refresh" ); return ret; }, _destroy: function() { var el = this.element; this._removeFirstLastClasses( el.children( childCollapsiblesSelector ) ); el .removeClass( "ui-collapsible-set ui-corner-all " + this._themeClassFromOption( "ui-group-theme-", this.options.theme ) ) .children( ":mobile-collapsible" ) .collapsible( "destroy" ); }, _refresh: function( create ) { var collapsiblesInSet = this.element.children( childCollapsiblesSelector ); this.element.find( $.mobile.collapsible.initSelector ).not( ".ui-collapsible" ).collapsible(); this._addFirstLastClasses( collapsiblesInSet, this._getVisibles( collapsiblesInSet, create ), create ); }, refresh: function() { this._refresh( false ); } }, $.mobile.behaviors.addFirstLastClasses ) ); })( jQuery ); (function( $, undefined ) { // Deprecated in 1.4 $.fn.fieldcontain = function(/* options */) { return this.addClass( "ui-field-contain" ); }; })( jQuery ); (function( $, undefined ) { $.fn.grid = function( options ) { return this.each(function() { var $this = $( this ), o = $.extend({ grid: null }, options ), $kids = $this.children(), gridCols = { solo:1, a:2, b:3, c:4, d:5 }, grid = o.grid, iterator, letter; if ( !grid ) { if ( $kids.length <= 5 ) { for ( letter in gridCols ) { if ( gridCols[ letter ] === $kids.length ) { grid = letter; } } } else { grid = "a"; $this.addClass( "ui-grid-duo" ); } } iterator = gridCols[grid]; $this.addClass( "ui-grid-" + grid ); $kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" ); if ( iterator > 1 ) { $kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" ); } if ( iterator > 2 ) { $kids.filter( ":nth-child(" + iterator + "n+3)" ).addClass( "ui-block-c" ); } if ( iterator > 3 ) { $kids.filter( ":nth-child(" + iterator + "n+4)" ).addClass( "ui-block-d" ); } if ( iterator > 4 ) { $kids.filter( ":nth-child(" + iterator + "n+5)" ).addClass( "ui-block-e" ); } }); }; })( jQuery ); (function( $, undefined ) { $.widget( "mobile.navbar", { options: { iconpos: "top", grid: null }, _create: function() { var $navbar = this.element, $navbtns = $navbar.find( "a" ), iconpos = $navbtns.filter( ":jqmData(icon)" ).length ? this.options.iconpos : undefined; $navbar.addClass( "ui-navbar" ) .attr( "role", "navigation" ) .find( "ul" ) .jqmEnhanceable() .grid({ grid: this.options.grid }); $navbtns .each( function() { var icon = $.mobile.getAttribute( this, "icon" ), theme = $.mobile.getAttribute( this, "theme" ), classes = "ui-btn"; if ( theme ) { classes += " ui-btn-" + theme; } if ( icon ) { classes += " ui-icon-" + icon + " ui-btn-icon-" + iconpos; } $( this ).addClass( classes ); }); $navbar.delegate( "a", "vclick", function( /* event */ ) { var activeBtn = $( this ); if ( !( activeBtn.hasClass( "ui-state-disabled" ) || // DEPRECATED as of 1.4.0 - remove after 1.4.0 release // only ui-state-disabled should be present thereafter activeBtn.hasClass( "ui-disabled" ) || activeBtn.hasClass( $.mobile.activeBtnClass ) ) ) { $navbtns.removeClass( $.mobile.activeBtnClass ); activeBtn.addClass( $.mobile.activeBtnClass ); // The code below is a workaround to fix #1181 $( document ).one( "pagehide", function() { activeBtn.removeClass( $.mobile.activeBtnClass ); }); } }); // Buttons in the navbar with ui-state-persist class should regain their active state before page show $navbar.closest( ".ui-page" ).bind( "pagebeforeshow", function() { $navbtns.filter( ".ui-state-persist" ).addClass( $.mobile.activeBtnClass ); }); } }); })( jQuery ); (function( $, undefined ) { var getAttr = $.mobile.getAttribute; $.widget( "mobile.listview", $.extend( { options: { theme: null, countTheme: null, /* Deprecated in 1.4 */ dividerTheme: null, icon: "carat-r", splitIcon: "carat-r", splitTheme: null, corners: true, shadow: true, inset: false }, _create: function() { var t = this, listviewClasses = ""; listviewClasses += t.options.inset ? " ui-listview-inset" : ""; if ( !!t.options.inset ) { listviewClasses += t.options.corners ? " ui-corner-all" : ""; listviewClasses += t.options.shadow ? " ui-shadow" : ""; } // create listview markup t.element.addClass( " ui-listview" + listviewClasses ); t.refresh( true ); }, // TODO: Remove in 1.5 _findFirstElementByTagName: function( ele, nextProp, lcName, ucName ) { var dict = {}; dict[ lcName ] = dict[ ucName ] = true; while ( ele ) { if ( dict[ ele.nodeName ] ) { return ele; } ele = ele[ nextProp ]; } return null; }, // TODO: Remove in 1.5 _addThumbClasses: function( containers ) { var i, img, len = containers.length; for ( i = 0; i < len; i++ ) { img = $( this._findFirstElementByTagName( containers[ i ].firstChild, "nextSibling", "img", "IMG" ) ); if ( img.length ) { $( this._findFirstElementByTagName( img[ 0 ].parentNode, "parentNode", "li", "LI" ) ).addClass( img.hasClass( "ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" ); } } }, _getChildrenByTagName: function( ele, lcName, ucName ) { var results = [], dict = {}; dict[ lcName ] = dict[ ucName ] = true; ele = ele.firstChild; while ( ele ) { if ( dict[ ele.nodeName ] ) { results.push( ele ); } ele = ele.nextSibling; } return $( results ); }, _beforeListviewRefresh: $.noop, _afterListviewRefresh: $.noop, refresh: function( create ) { var buttonClass, pos, numli, item, itemClass, itemTheme, itemIcon, icon, a, isDivider, startCount, newStartCount, value, last, splittheme, splitThemeClass, spliticon, altButtonClass, dividerTheme, li, o = this.options, $list = this.element, ol = !!$.nodeName( $list[ 0 ], "ol" ), start = $list.attr( "start" ), itemClassDict = {}, countBubbles = $list.find( ".ui-li-count" ), countTheme = getAttr( $list[ 0 ], "counttheme" ) || this.options.countTheme, countThemeClass = countTheme ? "ui-body-" + countTheme : "ui-body-inherit"; if ( o.theme ) { $list.addClass( "ui-group-theme-" + o.theme ); } // Check if a start attribute has been set while taking a value of 0 into account if ( ol && ( start || start === 0 ) ) { startCount = parseInt( start, 10 ) - 1; $list.css( "counter-reset", "listnumbering " + startCount ); } this._beforeListviewRefresh(); li = this._getChildrenByTagName( $list[ 0 ], "li", "LI" ); for ( pos = 0, numli = li.length; pos < numli; pos++ ) { item = li.eq( pos ); itemClass = ""; if ( create || item[ 0 ].className.search( /\bui-li-static\b|\bui-li-divider\b/ ) < 0 ) { a = this._getChildrenByTagName( item[ 0 ], "a", "A" ); isDivider = ( getAttr( item[ 0 ], "role" ) === "list-divider" ); value = item.attr( "value" ); itemTheme = getAttr( item[ 0 ], "theme" ); if ( a.length && a[ 0 ].className.search( /\bui-btn\b/ ) < 0 && !isDivider ) { itemIcon = getAttr( item[ 0 ], "icon" ); icon = ( itemIcon === false ) ? false : ( itemIcon || o.icon ); // TODO: Remove in 1.5 together with links.js (links.js / .ui-link deprecated in 1.4) a.removeClass( "ui-link" ); buttonClass = "ui-btn"; if ( itemTheme ) { buttonClass += " ui-btn-" + itemTheme; } if ( a.length > 1 ) { itemClass = "ui-li-has-alt"; last = a.last(); splittheme = getAttr( last[ 0 ], "theme" ) || o.splitTheme || getAttr( item[ 0 ], "theme", true ); splitThemeClass = splittheme ? " ui-btn-" + splittheme : ""; spliticon = getAttr( last[ 0 ], "icon" ) || getAttr( item[ 0 ], "icon" ) || o.splitIcon; altButtonClass = "ui-btn ui-btn-icon-notext ui-icon-" + spliticon + splitThemeClass; last .attr( "title", $.trim( last.getEncodedText() ) ) .addClass( altButtonClass ) .empty(); } else if ( icon ) { buttonClass += " ui-btn-icon-right ui-icon-" + icon; } a.first().addClass( buttonClass ); } else if ( isDivider ) { dividerTheme = ( getAttr( item[ 0 ], "theme" ) || o.dividerTheme || o.theme ); itemClass = "ui-li-divider ui-bar-" + ( dividerTheme ? dividerTheme : "inherit" ); item.attr( "role", "heading" ); } else if ( a.length <= 0 ) { itemClass = "ui-li-static ui-body-" + ( itemTheme ? itemTheme : "inherit" ); } if ( ol && value ) { newStartCount = parseInt( value , 10 ) - 1; item.css( "counter-reset", "listnumbering " + newStartCount ); } } // Instead of setting item class directly on the list item // at this point in time, push the item into a dictionary // that tells us what class to set on it so we can do this after this // processing loop is finished. if ( !itemClassDict[ itemClass ] ) { itemClassDict[ itemClass ] = []; } itemClassDict[ itemClass ].push( item[ 0 ] ); } // Set the appropriate listview item classes on each list item. // The main reason we didn't do this // in the for-loop above is because we can eliminate per-item function overhead // by calling addClass() and children() once or twice afterwards. This // can give us a significant boost on platforms like WP7.5. for ( itemClass in itemClassDict ) { $( itemClassDict[ itemClass ] ).addClass( itemClass ); } countBubbles.each( function() { $( this ).closest( "li" ).addClass( "ui-li-has-count" ); }); if ( countThemeClass ) { countBubbles.addClass( countThemeClass ); } // Deprecated in 1.4. From 1.5 you have to add class ui-li-has-thumb or ui-li-has-icon to the LI. this._addThumbClasses( li ); this._addThumbClasses( li.find( ".ui-btn" ) ); this._afterListviewRefresh(); this._addFirstLastClasses( li, this._getVisibles( li, create ), create ); } }, $.mobile.behaviors.addFirstLastClasses ) ); })( jQuery ); (function( $, undefined ) { function defaultAutodividersSelector( elt ) { // look for the text in the given element var text = $.trim( elt.text() ) || null; if ( !text ) { return null; } // create the text for the divider (first uppercased letter) text = text.slice( 0, 1 ).toUpperCase(); return text; } $.widget( "mobile.listview", $.mobile.listview, { options: { autodividers: false, autodividersSelector: defaultAutodividersSelector }, _beforeListviewRefresh: function() { if ( this.options.autodividers ) { this._replaceDividers(); this._superApply( arguments ); } }, _replaceDividers: function() { var i, lis, li, dividerText, lastDividerText = null, list = this.element, divider; list.children( "li:jqmData(role='list-divider')" ).remove(); lis = list.children( "li" ); for ( i = 0; i < lis.length ; i++ ) { li = lis[ i ]; dividerText = this.options.autodividersSelector( $( li ) ); if ( dividerText && lastDividerText !== dividerText ) { divider = document.createElement( "li" ); divider.appendChild( document.createTextNode( dividerText ) ); divider.setAttribute( "data-" + $.mobile.ns + "role", "list-divider" ); li.parentNode.insertBefore( divider, li ); } lastDividerText = dividerText; } } }); })( jQuery ); (function( $, undefined ) { var rdivider = /(^|\s)ui-li-divider($|\s)/, rhidden = /(^|\s)ui-screen-hidden($|\s)/; $.widget( "mobile.listview", $.mobile.listview, { options: { hideDividers: false }, _afterListviewRefresh: function() { var items, idx, item, hideDivider = true; this._superApply( arguments ); if ( this.options.hideDividers ) { items = this._getChildrenByTagName( this.element[ 0 ], "li", "LI" ); for ( idx = items.length - 1 ; idx > -1 ; idx-- ) { item = items[ idx ]; if ( item.className.match( rdivider ) ) { if ( hideDivider ) { item.className = item.className + " ui-screen-hidden"; } hideDivider = true; } else { if ( !item.className.match( rhidden ) ) { hideDivider = false; } } } } } }); })( jQuery ); (function( $, undefined ) { $.mobile.nojs = function( target ) { $( ":jqmData(role='nojs')", target ).addClass( "ui-nojs" ); }; })( jQuery ); (function( $, undefined ) { $.mobile.behaviors.formReset = { _handleFormReset: function() { this._on( this.element.closest( "form" ), { reset: function() { this._delay( "_reset" ); } }); } }; })( jQuery ); /* * "checkboxradio" plugin */ (function( $, undefined ) { $.widget( "mobile.checkboxradio", $.extend( { initSelector: "input:not( :jqmData(role='flipswitch' ) )[type='checkbox'],input[type='radio']:not( :jqmData(role='flipswitch' ))", options: { theme: "inherit", mini: false, wrapperClass: null, enhanced: false, iconpos: "left" }, _create: function() { var input = this.element, o = this.options, inheritAttr = function( input, dataAttr ) { return input.jqmData( dataAttr ) || input.closest( "form, fieldset" ).jqmData( dataAttr ); }, // NOTE: Windows Phone could not find the label through a selector // filter works though. parentLabel = input.closest( "label" ), label = parentLabel.length ? parentLabel : input .closest( "form, fieldset, :jqmData(role='page'), :jqmData(role='dialog')" ) .find( "label" ) .filter( "[for='" + $.mobile.path.hashToSelector( input[0].id ) + "']" ) .first(), inputtype = input[0].type, checkedClass = "ui-" + inputtype + "-on", uncheckedClass = "ui-" + inputtype + "-off"; if ( inputtype !== "checkbox" && inputtype !== "radio" ) { return; } if ( this.element[0].disabled ) { this.options.disabled = true; } o.iconpos = inheritAttr( input, "iconpos" ) || label.attr( "data-" + $.mobile.ns + "iconpos" ) || o.iconpos, // Establish options o.mini = inheritAttr( input, "mini" ) || o.mini; // Expose for other methods $.extend( this, { input: input, label: label, parentLabel: parentLabel, inputtype: inputtype, checkedClass: checkedClass, uncheckedClass: uncheckedClass }); if ( !this.options.enhanced ) { this._enhance(); } this._on( label, { vmouseover: "_handleLabelVMouseOver", vclick: "_handleLabelVClick" }); this._on( input, { vmousedown: "_cacheVals", vclick: "_handleInputVClick", focus: "_handleInputFocus", blur: "_handleInputBlur" }); this._handleFormReset(); this.refresh(); }, _enhance: function() { this.label.addClass( "ui-btn ui-corner-all"); if ( this.parentLabel.length > 0 ) { this.input.add( this.label ).wrapAll( this._wrapper() ); } else { //this.element.replaceWith( this.input.add( this.label ).wrapAll( this._wrapper() ) ); this.element.wrap( this._wrapper() ); this.element.parent().prepend( this.label ); } // Wrap the input + label in a div this._setOptions({ "theme": this.options.theme, "iconpos": this.options.iconpos, "mini": this.options.mini }); }, _wrapper: function() { return $( "<div class='" + ( this.options.wrapperClass ? this.options.wrapperClass : "" ) + " ui-" + this.inputtype + ( this.options.disabled ? " ui-state-disabled" : "" ) + "' ></div>" ); }, _handleInputFocus: function() { this.label.addClass( $.mobile.focusClass ); }, _handleInputBlur: function() { this.label.removeClass( $.mobile.focusClass ); }, _handleInputVClick: function() { var $this = this.element; // Adds checked attribute to checked input when keyboard is used if ( $this.is( ":checked" ) ) { $this.prop( "checked", true); this._getInputSet().not( $this ).prop( "checked", false ); } else { $this.prop( "checked", false ); } this._updateAll(); }, _handleLabelVMouseOver: function( event ) { if ( this.label.parent().hasClass( "ui-state-disabled" ) ) { event.stopPropagation(); } }, _handleLabelVClick: function( event ) { var input = this.element; if ( input.is( ":disabled" ) ) { event.preventDefault(); return; } this._cacheVals(); input.prop( "checked", this.inputtype === "radio" && true || !input.prop( "checked" ) ); // trigger click handler's bound directly to the input as a substitute for // how label clicks behave normally in the browsers // TODO: it would be nice to let the browser's handle the clicks and pass them // through to the associate input. we can swallow that click at the parent // wrapper element level input.triggerHandler( "click" ); // Input set for common radio buttons will contain all the radio // buttons, but will not for checkboxes. clearing the checked status // of other radios ensures the active button state is applied properly this._getInputSet().not( input ).prop( "checked", false ); this._updateAll(); return false; }, _cacheVals: function() { this._getInputSet().each( function() { $( this ).attr("data-" + $.mobile.ns + "cacheVal", this.checked ); }); }, //returns either a set of radios with the same name attribute, or a single checkbox _getInputSet: function() { if ( this.inputtype === "checkbox" ) { return this.element; } return this.element.closest( "form, :jqmData(role='page'), :jqmData(role='dialog')" ) .find( "input[name='" + this.element[ 0 ].name + "'][type='" + this.inputtype + "']" ); }, _updateAll: function() { var self = this; this._getInputSet().each( function() { var $this = $( this ); if ( this.checked || self.inputtype === "checkbox" ) { $this.trigger( "change" ); } }) .checkboxradio( "refresh" ); }, _reset: function() { this.refresh(); }, // Is the widget supposed to display an icon? _hasIcon: function() { var controlgroup, controlgroupWidget, controlgroupConstructor = $.mobile.controlgroup; // If the controlgroup widget is defined ... if ( controlgroupConstructor ) { controlgroup = this.element.closest( ":mobile-controlgroup," + controlgroupConstructor.prototype.initSelector ); // ... and the checkbox is in a controlgroup ... if ( controlgroup.length > 0 ) { // ... look for a controlgroup widget instance, and ... controlgroupWidget = $.data( controlgroup[ 0 ], "mobile-controlgroup" ); // ... if found, decide based on the option value, ... return ( ( controlgroupWidget ? controlgroupWidget.options.type : // ... otherwise decide based on the "type" data attribute. controlgroup.attr( "data-" + $.mobile.ns + "type" ) ) !== "horizontal" ); } } // Normally, the widget displays an icon. return true; }, refresh: function() { var hasIcon = this._hasIcon(), isChecked = this.element[ 0 ].checked, active = $.mobile.activeBtnClass, iconposClass = "ui-btn-icon-" + this.options.iconpos, addClasses = [], removeClasses = []; if ( hasIcon ) { removeClasses.push( active ); addClasses.push( iconposClass ); } else { removeClasses.push( iconposClass ); ( isChecked ? addClasses : removeClasses ).push( active ); } if ( isChecked ) { addClasses.push( this.checkedClass ); removeClasses.push( this.uncheckedClass ); } else { addClasses.push( this.uncheckedClass ); removeClasses.push( this.checkedClass ); } this.label .addClass( addClasses.join( " " ) ) .removeClass( removeClasses.join( " " ) ); }, widget: function() { return this.label.parent(); }, _setOptions: function( options ) { var label = this.label, currentOptions = this.options, outer = this.widget(), hasIcon = this._hasIcon(); if ( options.disabled !== undefined ) { this.input.prop( "disabled", !!options.disabled ); outer.toggleClass( "ui-state-disabled", !!options.disabled ); } if ( options.mini !== undefined ) { outer.toggleClass( "ui-mini", !!options.mini ); } if ( options.theme !== undefined ) { label .removeClass( "ui-btn-" + currentOptions.theme ) .addClass( "ui-btn-" + options.theme ); } if ( options.wrapperClass !== undefined ) { outer .removeClass( currentOptions.wrapperClass ) .addClass( options.wrapperClass ); } if ( options.iconpos !== undefined && hasIcon ) { label.removeClass( "ui-btn-icon-" + currentOptions.iconpos ).addClass( "ui-btn-icon-" + options.iconpos ); } else if ( !hasIcon ) { label.removeClass( "ui-btn-icon-" + currentOptions.iconpos ); } this._super( options ); } }, $.mobile.behaviors.formReset ) ); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.button", { initSelector: "input[type='button'], input[type='submit'], input[type='reset']", options: { theme: null, icon: null, iconpos: "left", iconshadow: false, /* TODO: Deprecated in 1.4, remove in 1.5. */ corners: true, shadow: true, inline: null, mini: null, wrapperClass: null, enhanced: false }, _create: function() { if ( this.element.is( ":disabled" ) ) { this.options.disabled = true; } if ( !this.options.enhanced ) { this._enhance(); } $.extend( this, { wrapper: this.element.parent() }); this._on( { focus: function() { this.widget().addClass( $.mobile.focusClass ); }, blur: function() { this.widget().removeClass( $.mobile.focusClass ); } }); this.refresh( true ); }, _enhance: function() { this.element.wrap( this._button() ); }, _button: function() { var options = this.options, iconClasses = this._getIconClasses( this.options ); return $("<div class='ui-btn ui-input-btn" + ( options.wrapperClass ? " " + options.wrapperClass : "" ) + ( options.theme ? " ui-btn-" + options.theme : "" ) + ( options.corners ? " ui-corner-all" : "" ) + ( options.shadow ? " ui-shadow" : "" ) + ( options.inline ? " ui-btn-inline" : "" ) + ( options.mini ? " ui-mini" : "" ) + ( options.disabled ? " ui-state-disabled" : "" ) + ( iconClasses ? ( " " + iconClasses ) : "" ) + "' >" + this.element.val() + "</div>" ); }, widget: function() { return this.wrapper; }, _destroy: function() { this.element.insertBefore( this.button ); this.button.remove(); }, _getIconClasses: function( options ) { return ( options.icon ? ( "ui-icon-" + options.icon + ( options.iconshadow ? " ui-shadow-icon" : "" ) + /* TODO: Deprecated in 1.4, remove in 1.5. */ " ui-btn-icon-" + options.iconpos ) : "" ); }, _setOptions: function( options ) { var outer = this.widget(); if ( options.theme !== undefined ) { outer .removeClass( this.options.theme ) .addClass( "ui-btn-" + options.theme ); } if ( options.corners !== undefined ) { outer.toggleClass( "ui-corner-all", options.corners ); } if ( options.shadow !== undefined ) { outer.toggleClass( "ui-shadow", options.shadow ); } if ( options.inline !== undefined ) { outer.toggleClass( "ui-btn-inline", options.inline ); } if ( options.mini !== undefined ) { outer.toggleClass( "ui-mini", options.mini ); } if ( options.disabled !== undefined ) { this.element.prop( "disabled", options.disabled ); outer.toggleClass( "ui-state-disabled", options.disabled ); } if ( options.icon !== undefined || options.iconshadow !== undefined || /* TODO: Deprecated in 1.4, remove in 1.5. */ options.iconpos !== undefined ) { outer .removeClass( this._getIconClasses( this.options ) ) .addClass( this._getIconClasses( $.extend( {}, this.options, options ) ) ); } this._super( options ); }, refresh: function( create ) { if ( this.options.icon && this.options.iconpos === "notext" && this.element.attr( "title" ) ) { this.element.attr( "title", this.element.val() ); } if ( !create ) { var originalElement = this.element.detach(); $( this.wrapper ).text( this.element.val() ).append( originalElement ); } } }); })( jQuery ); (function( $ ) { var meta = $( "meta[name=viewport]" ), initialContent = meta.attr( "content" ), disabledZoom = initialContent + ",maximum-scale=1, user-scalable=no", enabledZoom = initialContent + ",maximum-scale=10, user-scalable=yes", disabledInitially = /(user-scalable[\s]*=[\s]*no)|(maximum-scale[\s]*=[\s]*1)[$,\s]/.test( initialContent ); $.mobile.zoom = $.extend( {}, { enabled: !disabledInitially, locked: false, disable: function( lock ) { if ( !disabledInitially && !$.mobile.zoom.locked ) { meta.attr( "content", disabledZoom ); $.mobile.zoom.enabled = false; $.mobile.zoom.locked = lock || false; } }, enable: function( unlock ) { if ( !disabledInitially && ( !$.mobile.zoom.locked || unlock === true ) ) { meta.attr( "content", enabledZoom ); $.mobile.zoom.enabled = true; $.mobile.zoom.locked = false; } }, restore: function() { if ( !disabledInitially ) { meta.attr( "content", initialContent ); $.mobile.zoom.enabled = true; } } }); }( jQuery )); (function( $, undefined ) { $.widget( "mobile.textinput", { initSelector: "input[type='text']," + "input[type='search']," + ":jqmData(type='search')," + "input[type='number']," + ":jqmData(type='number')," + "input[type='password']," + "input[type='email']," + "input[type='url']," + "input[type='tel']," + "textarea," + "input[type='time']," + "input[type='date']," + "input[type='month']," + "input[type='week']," + "input[type='datetime']," + "input[type='datetime-local']," + "input[type='color']," + "input:not([type])," + "input[type='file']", options: { theme: null, corners: true, mini: false, // This option defaults to true on iOS devices. preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1, wrapperClass: "", enhanced: false }, _create: function() { var options = this.options, isSearch = this.element.is( "[type='search'], :jqmData(type='search')" ), isTextarea = this.element[ 0 ].tagName === "TEXTAREA", isRange = this.element.is( "[data-" + ( $.mobile.ns || "" ) + "type='range']" ), inputNeedsWrap = ( (this.element.is( "input" ) || this.element.is( "[data-" + ( $.mobile.ns || "" ) + "type='search']" ) ) && !isRange ); if ( this.element.prop( "disabled" ) ) { options.disabled = true; } $.extend( this, { classes: this._classesFromOptions(), isSearch: isSearch, isTextarea: isTextarea, isRange: isRange, inputNeedsWrap: inputNeedsWrap }); this._autoCorrect(); if ( !options.enhanced ) { this._enhance(); } this._on( { "focus": "_handleFocus", "blur": "_handleBlur" }); }, refresh: function() { this.setOptions({ "disabled" : this.element.is( ":disabled" ) }); }, _enhance: function() { var elementClasses = []; if ( this.isTextarea ) { elementClasses.push( "ui-input-text" ); } if ( this.isTextarea || this.isRange ) { elementClasses.push( "ui-shadow-inset" ); } //"search" and "text" input widgets if ( this.inputNeedsWrap ) { this.element.wrap( this._wrap() ); } else { elementClasses = elementClasses.concat( this.classes ); } this.element.addClass( elementClasses.join( " " ) ); }, widget: function() { return ( this.inputNeedsWrap ) ? this.element.parent() : this.element; }, _classesFromOptions: function() { var options = this.options, classes = []; classes.push( "ui-body-" + ( ( options.theme === null ) ? "inherit" : options.theme ) ); if ( options.corners ) { classes.push( "ui-corner-all" ); } if ( options.mini ) { classes.push( "ui-mini" ); } if ( options.disabled ) { classes.push( "ui-state-disabled" ); } if ( options.wrapperClass ) { classes.push( options.wrapperClass ); } return classes; }, _wrap: function() { return $( "<div class='" + ( this.isSearch ? "ui-input-search " : "ui-input-text " ) + this.classes.join( " " ) + " " + "ui-shadow-inset'></div>" ); }, _autoCorrect: function() { // XXX: Temporary workaround for issue 785 (Apple bug 8910589). // Turn off autocorrect and autocomplete on non-iOS 5 devices // since the popup they use can't be dismissed by the user. Note // that we test for the presence of the feature by looking for // the autocorrect property on the input element. We currently // have no test for iOS 5 or newer so we're temporarily using // the touchOverflow support flag for jQM 1.0. Yes, I feel dirty. // - jblas if ( typeof this.element[0].autocorrect !== "undefined" && !$.support.touchOverflow ) { // Set the attribute instead of the property just in case there // is code that attempts to make modifications via HTML. this.element[0].setAttribute( "autocorrect", "off" ); this.element[0].setAttribute( "autocomplete", "off" ); } }, _handleBlur: function() { this.widget().removeClass( $.mobile.focusClass ); if ( this.options.preventFocusZoom ) { $.mobile.zoom.enable( true ); } }, _handleFocus: function() { // In many situations, iOS will zoom into the input upon tap, this // prevents that from happening if ( this.options.preventFocusZoom ) { $.mobile.zoom.disable( true ); } this.widget().addClass( $.mobile.focusClass ); }, _setOptions: function ( options ) { var outer = this.widget(); this._super( options ); if ( !( options.disabled === undefined && options.mini === undefined && options.corners === undefined && options.theme === undefined && options.wrapperClass === undefined ) ) { outer.removeClass( this.classes.join( " " ) ); this.classes = this._classesFromOptions(); outer.addClass( this.classes.join( " " ) ); } if ( options.disabled !== undefined ) { this.element.prop( "disabled", !!options.disabled ); } }, _destroy: function() { if ( this.options.enhanced ) { return; } if ( this.inputNeedsWrap ) { this.element.unwrap(); } this.element.removeClass( "ui-input-text " + this.classes.join( " " ) ); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.slider", $.extend( { initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')", widgetEventPrefix: "slide", options: { theme: null, trackTheme: null, corners: true, mini: false, highlight: false }, _create: function() { // TODO: Each of these should have comments explain what they're for var self = this, control = this.element, trackTheme = this.options.trackTheme || $.mobile.getAttribute( control[ 0 ], "theme" ), trackThemeClass = trackTheme ? " ui-bar-" + trackTheme : " ui-bar-inherit", cornerClass = ( this.options.corners || control.jqmData( "corners" ) ) ? " ui-corner-all" : "", miniClass = ( this.options.mini || control.jqmData( "mini" ) ) ? " ui-mini" : "", cType = control[ 0 ].nodeName.toLowerCase(), isToggleSwitch = ( cType === "select" ), isRangeslider = control.parent().is( ":jqmData(role='rangeslider')" ), selectClass = ( isToggleSwitch ) ? "ui-slider-switch" : "", controlID = control.attr( "id" ), $label = $( "[for='" + controlID + "']" ), labelID = $label.attr( "id" ) || controlID + "-label", min = !isToggleSwitch ? parseFloat( control.attr( "min" ) ) : 0, max = !isToggleSwitch ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1, step = window.parseFloat( control.attr( "step" ) || 1 ), domHandle = document.createElement( "a" ), handle = $( domHandle ), domSlider = document.createElement( "div" ), slider = $( domSlider ), valuebg = this.options.highlight && !isToggleSwitch ? (function() { var bg = document.createElement( "div" ); bg.className = "ui-slider-bg " + $.mobile.activeBtnClass; return $( bg ).prependTo( slider ); })() : false, options, wrapper, j, length, i, optionsCount, origTabIndex, side, activeClass, sliderImg; $label.attr( "id", labelID ); this.isToggleSwitch = isToggleSwitch; domHandle.setAttribute( "href", "#" ); domSlider.setAttribute( "role", "application" ); domSlider.className = [ this.isToggleSwitch ? "ui-slider ui-slider-track ui-shadow-inset " : "ui-slider-track ui-shadow-inset ", selectClass, trackThemeClass, cornerClass, miniClass ].join( "" ); domHandle.className = "ui-slider-handle"; domSlider.appendChild( domHandle ); handle.attr({ "role": "slider", "aria-valuemin": min, "aria-valuemax": max, "aria-valuenow": this._value(), "aria-valuetext": this._value(), "title": this._value(), "aria-labelledby": labelID }); $.extend( this, { slider: slider, handle: handle, control: control, type: cType, step: step, max: max, min: min, valuebg: valuebg, isRangeslider: isRangeslider, dragging: false, beforeStart: null, userModified: false, mouseMoved: false }); if ( isToggleSwitch ) { // TODO: restore original tabindex (if any) in a destroy method origTabIndex = control.attr( "tabindex" ); if ( origTabIndex ) { handle.attr( "tabindex", origTabIndex ); } control.attr( "tabindex", "-1" ).focus(function() { $( this ).blur(); handle.focus(); }); wrapper = document.createElement( "div" ); wrapper.className = "ui-slider-inneroffset"; for ( j = 0, length = domSlider.childNodes.length; j < length; j++ ) { wrapper.appendChild( domSlider.childNodes[j] ); } domSlider.appendChild( wrapper ); // slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" ); // make the handle move with a smooth transition handle.addClass( "ui-slider-handle-snapping" ); options = control.find( "option" ); for ( i = 0, optionsCount = options.length; i < optionsCount; i++ ) { side = !i ? "b" : "a"; activeClass = !i ? "" : " " + $.mobile.activeBtnClass; sliderImg = document.createElement( "span" ); sliderImg.className = [ "ui-slider-label ui-slider-label-", side, activeClass ].join( "" ); sliderImg.setAttribute( "role", "img" ); sliderImg.appendChild( document.createTextNode( options[i].innerHTML ) ); $( sliderImg ).prependTo( slider ); } self._labels = $( ".ui-slider-label", slider ); } // monitor the input for updated values control.addClass( isToggleSwitch ? "ui-slider-switch" : "ui-slider-input" ); this._on( control, { "change": "_controlChange", "keyup": "_controlKeyup", "blur": "_controlBlur", "vmouseup": "_controlVMouseUp" }); slider.bind( "vmousedown", $.proxy( this._sliderVMouseDown, this ) ) .bind( "vclick", false ); // We have to instantiate a new function object for the unbind to work properly // since the method itself is defined in the prototype (causing it to unbind everything) this._on( document, { "vmousemove": "_preventDocumentDrag" }); this._on( slider.add( document ), { "vmouseup": "_sliderVMouseUp" }); slider.insertAfter( control ); // wrap in a div for styling purposes if ( !isToggleSwitch && !isRangeslider ) { wrapper = this.options.mini ? "<div class='ui-slider ui-mini'>" : "<div class='ui-slider'>"; control.add( slider ).wrapAll( wrapper ); } // bind the handle event callbacks and set the context to the widget instance this._on( this.handle, { "vmousedown": "_handleVMouseDown", "keydown": "_handleKeydown", "keyup": "_handleKeyup" }); this.handle.bind( "vclick", false ); this._handleFormReset(); this.refresh( undefined, undefined, true ); }, _setOptions: function( options ) { if ( options.theme !== undefined ) { this._setTheme( options.theme ); } if ( options.trackTheme !== undefined ) { this._setTrackTheme( options.trackTheme ); } if ( options.corners !== undefined ) { this._setCorners( options.corners ); } if ( options.mini !== undefined ) { this._setMini( options.mini ); } if ( options.highlight !== undefined ) { this._setHighlight( options.highlight ); } if ( options.disabled !== undefined ) { this._setDisabled( options.disabled ); } this._super( options ); }, _controlChange: function( event ) { // if the user dragged the handle, the "change" event was triggered from inside refresh(); don't call refresh() again if ( this._trigger( "controlchange", event ) === false ) { return false; } if ( !this.mouseMoved ) { this.refresh( this._value(), true ); } }, _controlKeyup: function(/* event */) { // necessary? this.refresh( this._value(), true, true ); }, _controlBlur: function(/* event */) { this.refresh( this._value(), true ); }, // it appears the clicking the up and down buttons in chrome on // range/number inputs doesn't trigger a change until the field is // blurred. Here we check thif the value has changed and refresh _controlVMouseUp: function(/* event */) { this._checkedRefresh(); }, // NOTE force focus on handle _handleVMouseDown: function(/* event */) { this.handle.focus(); }, _handleKeydown: function( event ) { var index = this._value(); if ( this.options.disabled ) { return; } // In all cases prevent the default and mark the handle as active switch ( event.keyCode ) { case $.mobile.keyCode.HOME: case $.mobile.keyCode.END: case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: event.preventDefault(); if ( !this._keySliding ) { this._keySliding = true; this.handle.addClass( "ui-state-active" ); /* TODO: We don't use this class for styling. Do we need to add it? */ } break; } // move the slider according to the keypress switch ( event.keyCode ) { case $.mobile.keyCode.HOME: this.refresh( this.min ); break; case $.mobile.keyCode.END: this.refresh( this.max ); break; case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: this.refresh( index + this.step ); break; case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: this.refresh( index - this.step ); break; } }, // remove active mark _handleKeyup: function(/* event */) { if ( this._keySliding ) { this._keySliding = false; this.handle.removeClass( "ui-state-active" ); /* See comment above. */ } }, _sliderVMouseDown: function( event ) { // NOTE: we don't do this in refresh because we still want to // support programmatic alteration of disabled inputs if ( this.options.disabled || !( event.which === 1 || event.which === 0 || event.which === undefined ) ) { return false; } if ( this._trigger( "beforestart", event ) === false ) { return false; } this.dragging = true; this.userModified = false; this.mouseMoved = false; if ( this.isToggleSwitch ) { this.beforeStart = this.element[0].selectedIndex; } this.refresh( event ); this._trigger( "start" ); return false; }, _sliderVMouseUp: function() { if ( this.dragging ) { this.dragging = false; if ( this.isToggleSwitch ) { // make the handle move with a smooth transition this.handle.addClass( "ui-slider-handle-snapping" ); if ( this.mouseMoved ) { // this is a drag, change the value only if user dragged enough if ( this.userModified ) { this.refresh( this.beforeStart === 0 ? 1 : 0 ); } else { this.refresh( this.beforeStart ); } } else { // this is just a click, change the value this.refresh( this.beforeStart === 0 ? 1 : 0 ); } } this.mouseMoved = false; this._trigger( "stop" ); return false; } }, _preventDocumentDrag: function( event ) { // NOTE: we don't do this in refresh because we still want to // support programmatic alteration of disabled inputs if ( this._trigger( "drag", event ) === false) { return false; } if ( this.dragging && !this.options.disabled ) { // this.mouseMoved must be updated before refresh() because it will be used in the control "change" event this.mouseMoved = true; if ( this.isToggleSwitch ) { // make the handle move in sync with the mouse this.handle.removeClass( "ui-slider-handle-snapping" ); } this.refresh( event ); // only after refresh() you can calculate this.userModified this.userModified = this.beforeStart !== this.element[0].selectedIndex; return false; } }, _checkedRefresh: function() { if ( this.value !== this._value() ) { this.refresh( this._value() ); } }, _value: function() { return this.isToggleSwitch ? this.element[0].selectedIndex : parseFloat( this.element.val() ) ; }, _reset: function() { this.refresh( undefined, false, true ); }, refresh: function( val, isfromControl, preventInputUpdate ) { // NOTE: we don't return here because we want to support programmatic // alteration of the input value, which should still update the slider var self = this, parentTheme = $.mobile.getAttribute( this.element[ 0 ], "theme" ), theme = this.options.theme || parentTheme, themeClass = theme ? " ui-btn-" + theme : "", trackTheme = this.options.trackTheme || parentTheme, trackThemeClass = trackTheme ? " ui-bar-" + trackTheme : " ui-bar-inherit", cornerClass = this.options.corners ? " ui-corner-all" : "", miniClass = this.options.mini ? " ui-mini" : "", left, width, data, tol, pxStep, percent, control, isInput, optionElements, min, max, step, newval, valModStep, alignValue, percentPerStep, handlePercent, aPercent, bPercent, valueChanged; self.slider[0].className = [ this.isToggleSwitch ? "ui-slider ui-slider-switch ui-slider-track ui-shadow-inset" : "ui-slider-track ui-shadow-inset", trackThemeClass, cornerClass, miniClass ].join( "" ); if ( this.options.disabled || this.element.prop( "disabled" ) ) { this.disable(); } // set the stored value for comparison later this.value = this._value(); if ( this.options.highlight && !this.isToggleSwitch && this.slider.find( ".ui-slider-bg" ).length === 0 ) { this.valuebg = (function() { var bg = document.createElement( "div" ); bg.className = "ui-slider-bg " + $.mobile.activeBtnClass; return $( bg ).prependTo( self.slider ); })(); } this.handle.addClass( "ui-btn" + themeClass + " ui-shadow" ); control = this.element; isInput = !this.isToggleSwitch; optionElements = isInput ? [] : control.find( "option" ); min = isInput ? parseFloat( control.attr( "min" ) ) : 0; max = isInput ? parseFloat( control.attr( "max" ) ) : optionElements.length - 1; step = ( isInput && parseFloat( control.attr( "step" ) ) > 0 ) ? parseFloat( control.attr( "step" ) ) : 1; if ( typeof val === "object" ) { data = val; // a slight tolerance helped get to the ends of the slider tol = 8; left = this.slider.offset().left; width = this.slider.width(); pxStep = width/((max-min)/step); if ( !this.dragging || data.pageX < left - tol || data.pageX > left + width + tol ) { return; } if ( pxStep > 1 ) { percent = ( ( data.pageX - left ) / width ) * 100; } else { percent = Math.round( ( ( data.pageX - left ) / width ) * 100 ); } } else { if ( val == null ) { val = isInput ? parseFloat( control.val() || 0 ) : control[0].selectedIndex; } percent = ( parseFloat( val ) - min ) / ( max - min ) * 100; } if ( isNaN( percent ) ) { return; } newval = ( percent / 100 ) * ( max - min ) + min; //from jQuery UI slider, the following source will round to the nearest step valModStep = ( newval - min ) % step; alignValue = newval - valModStep; if ( Math.abs( valModStep ) * 2 >= step ) { alignValue += ( valModStep > 0 ) ? step : ( -step ); } percentPerStep = 100/((max-min)/step); // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see jQueryUI: #4124) newval = parseFloat( alignValue.toFixed(5) ); if ( typeof pxStep === "undefined" ) { pxStep = width / ( (max-min) / step ); } if ( pxStep > 1 && isInput ) { percent = ( newval - min ) * percentPerStep * ( 1 / step ); } if ( percent < 0 ) { percent = 0; } if ( percent > 100 ) { percent = 100; } if ( newval < min ) { newval = min; } if ( newval > max ) { newval = max; } this.handle.css( "left", percent + "%" ); this.handle[0].setAttribute( "aria-valuenow", isInput ? newval : optionElements.eq( newval ).attr( "value" ) ); this.handle[0].setAttribute( "aria-valuetext", isInput ? newval : optionElements.eq( newval ).getEncodedText() ); this.handle[0].setAttribute( "title", isInput ? newval : optionElements.eq( newval ).getEncodedText() ); if ( this.valuebg ) { this.valuebg.css( "width", percent + "%" ); } // drag the label widths if ( this._labels ) { handlePercent = this.handle.width() / this.slider.width() * 100; aPercent = percent && handlePercent + ( 100 - handlePercent ) * percent / 100; bPercent = percent === 100 ? 0 : Math.min( handlePercent + 100 - aPercent, 100 ); this._labels.each(function() { var ab = $( this ).hasClass( "ui-slider-label-a" ); $( this ).width( ( ab ? aPercent : bPercent ) + "%" ); }); } if ( !preventInputUpdate ) { valueChanged = false; // update control"s value if ( isInput ) { valueChanged = control.val() !== newval; control.val( newval ); } else { valueChanged = control[ 0 ].selectedIndex !== newval; control[ 0 ].selectedIndex = newval; } if ( this._trigger( "beforechange", val ) === false) { return false; } if ( !isfromControl && valueChanged ) { control.trigger( "change" ); } } }, _setHighlight: function( value ) { value = !!value; if ( value ) { this.options.highlight = !!value; this.refresh(); } else if ( this.valuebg ) { this.valuebg.remove(); this.valuebg = false; } }, _setTheme: function( value ) { this.handle .removeClass( "ui-btn-" + this.options.theme ) .addClass( "ui-btn-" + value ); var currentTheme = this.options.theme ? this.options.theme : "inherit", newTheme = value ? value : "inherit"; this.control .removeClass( "ui-body-" + currentTheme ) .addClass( "ui-body-" + newTheme ); }, _setTrackTheme: function( value ) { var currentTrackTheme = this.options.trackTheme ? this.options.trackTheme : "inherit", newTrackTheme = value ? value : "inherit"; this.slider .removeClass( "ui-body-" + currentTrackTheme ) .addClass( "ui-body-" + newTrackTheme ); }, _setMini: function( value ) { value = !!value; if ( !this.isToggleSwitch && !this.isRangeslider ) { this.slider.parent().toggleClass( "ui-mini", value ); this.element.toggleClass( "ui-mini", value ); } this.slider.toggleClass( "ui-mini", value ); }, _setCorners: function( value ) { this.slider.toggleClass( "ui-corner-all", value ); if ( !this.isToggleSwitch ) { this.control.toggleClass( "ui-corner-all", value ); } }, _setDisabled: function( value ) { value = !!value; this.element.prop( "disabled", value ); this.slider .toggleClass( "ui-state-disabled", value ) .attr( "aria-disabled", value ); } }, $.mobile.behaviors.formReset ) ); })( jQuery ); (function( $, undefined ) { var popup; function getPopup() { if ( !popup ) { popup = $( "<div></div>", { "class": "ui-slider-popup ui-shadow ui-corner-all" }); } return popup.clone(); } $.widget( "mobile.slider", $.mobile.slider, { options: { popupEnabled: false, showValue: false }, _create: function() { this._super(); $.extend( this, { _currentValue: null, _popup: null, _popupVisible: false }); this._setOption( "popupEnabled", this.options.popupEnabled ); this._on( this.handle, { "vmousedown" : "_showPopup" } ); this._on( this.slider.add( this.document ), { "vmouseup" : "_hidePopup" } ); this._refresh(); }, // position the popup centered 5px above the handle _positionPopup: function() { var dstOffset = this.handle.offset(); this._popup.offset( { left: dstOffset.left + ( this.handle.width() - this._popup.width() ) / 2, top: dstOffset.top - this._popup.outerHeight() - 5 }); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "showValue" ) { this.handle.html( value && !this.options.mini ? this._value() : "" ); } else if ( key === "popupEnabled" ) { if ( value && !this._popup ) { this._popup = getPopup() .addClass( "ui-body-" + ( this.options.theme || "a" ) ) .hide() .insertBefore( this.element ); } } }, // show value on the handle and in popup refresh: function() { this._super.apply( this, arguments ); this._refresh(); }, _refresh: function() { var o = this.options, newValue; if ( o.popupEnabled ) { // remove the title attribute from the handle (which is // responsible for the annoying tooltip); NB we have // to do it here as the jqm slider sets it every time // the slider's value changes :( this.handle.removeAttr( "title" ); } newValue = this._value(); if ( newValue === this._currentValue ) { return; } this._currentValue = newValue; if ( o.popupEnabled && this._popup ) { this._positionPopup(); this._popup.html( newValue ); } else if ( o.showValue && !this.options.mini ) { this.handle.html( newValue ); } }, _showPopup: function() { if ( this.options.popupEnabled && !this._popupVisible ) { this.handle.html( "" ); this._popup.show(); this._positionPopup(); this._popupVisible = true; } }, _hidePopup: function() { var o = this.options; if ( o.popupEnabled && this._popupVisible ) { if ( o.showValue && !o.mini ) { this.handle.html( this._value() ); } this._popup.hide(); this._popupVisible = false; } } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.flipswitch", $.extend({ options: { onText: "On", offText: "Off", theme: null, enhanced: false, wrapperClass: null, corners: true, mini: false }, _create: function() { if ( !this.options.enhanced ) { this._enhance(); } else { $.extend( this, { flipswitch: this.element.parent(), on: this.element.find( ".ui-flipswitch-on" ).eq( 0 ), off: this.element.find( ".ui-flipswitch-off" ).eq(0), type: this.element.get( 0 ).tagName }); } this._handleFormReset(); // Transfer tabindex to "on" element and make input unfocusable this._originalTabIndex = this.element.attr( "tabindex" ); if ( this._originalTabIndex != null ) { this.on.attr( "tabindex", this._originalTabIndex ); } this.element.attr( "tabindex", "-1" ); this._on({ "focus" : "_handleInputFocus" }); if ( this.element.is( ":disabled" ) ) { this._setOptions({ "disabled": true }); } this._on( this.flipswitch, { "click": "_toggle", "swipeleft": "_left", "swiperight": "_right" }); this._on( this.on, { "keydown": "_keydown" }); this._on( { "change": "refresh" }); }, _handleInputFocus: function() { this.on.focus(); }, widget: function() { return this.flipswitch; }, _left: function() { this.flipswitch.removeClass( "ui-flipswitch-active" ); if ( this.type === "SELECT" ) { this.element.get( 0 ).selectedIndex = 0; } else { this.element.prop( "checked", false ); } this.element.trigger( "change" ); }, _right: function() { this.flipswitch.addClass( "ui-flipswitch-active" ); if ( this.type === "SELECT" ) { this.element.get( 0 ).selectedIndex = 1; } else { this.element.prop( "checked", true ); } this.element.trigger( "change" ); }, _enhance: function() { var flipswitch = $( "<div>" ), options = this.options, element = this.element, theme = options.theme ? options.theme : "inherit", // The "on" button is an anchor so it's focusable on = $( "<a></a>", { "href": "#" }), off = $( "<span></span>" ), type = element.get( 0 ).tagName, onText = ( type === "INPUT" ) ? options.onText : element.find( "option" ).eq( 1 ).text(), offText = ( type === "INPUT" ) ? options.offText : element.find( "option" ).eq( 0 ).text(); on .addClass( "ui-flipswitch-on ui-btn ui-shadow ui-btn-inherit" ) .text( onText ); off .addClass( "ui-flipswitch-off" ) .text( offText ); flipswitch .addClass( "ui-flipswitch ui-shadow-inset " + "ui-bar-" + theme + " " + ( options.wrapperClass ? options.wrapperClass : "" ) + " " + ( ( element.is( ":checked" ) || element .find( "option" ) .eq( 1 ) .is( ":selected" ) ) ? "ui-flipswitch-active" : "" ) + ( element.is(":disabled") ? " ui-state-disabled": "") + ( options.corners ? " ui-corner-all": "" ) + ( options.mini ? " ui-mini": "" ) ) .append( on, off ); element .addClass( "ui-flipswitch-input" ) .after( flipswitch ) .appendTo( flipswitch ); $.extend( this, { flipswitch: flipswitch, on: on, off: off, type: type }); }, _reset: function() { this.refresh(); }, refresh: function() { var direction, existingDirection = this.flipswitch.hasClass( "ui-flipswitch-active" ) ? "_right" : "_left"; if ( this.type === "SELECT" ) { direction = ( this.element.get( 0 ).selectedIndex > 0 ) ? "_right": "_left"; } else { direction = this.element.prop( "checked" ) ? "_right": "_left"; } if ( direction !== existingDirection ) { this[ direction ](); } }, _toggle: function() { var direction = this.flipswitch.hasClass( "ui-flipswitch-active" ) ? "_left" : "_right"; this[ direction ](); }, _keydown: function( e ) { if ( e.which === $.mobile.keyCode.LEFT ) { this._left(); } else if ( e.which === $.mobile.keyCode.RIGHT ) { this._right(); } else if ( e.which === $.mobile.keyCode.SPACE ) { this._toggle(); e.preventDefault(); } }, _setOptions: function( options ) { if ( options.theme !== undefined ) { var currentTheme = options.theme ? options.theme : "inherit", newTheme = options.theme ? options.theme : "inherit"; this.widget() .removeClass( "ui-bar-" + currentTheme ) .addClass( "ui-bar-" + newTheme ); } if ( options.onText !== undefined ) { this.on.text( options.onText ); } if ( options.offText !== undefined ) { this.off.text( options.offText ); } if ( options.disabled !== undefined ) { this.widget().toggleClass( "ui-state-disabled", options.disabled ); } if ( options.mini !== undefined ) { this.widget().toggleClass( "ui-mini", options.mini ); } if ( options.corners !== undefined ) { this.widget().toggleClass( "ui-corner-all", options.corners ); } this._super( options ); }, _destroy: function() { if ( this.options.enhanced ) { return; } if ( this._originalTabIndex != null ) { this.element.attr( "tabindex", this._originalTabIndex ); } else { this.element.removeAttr( "tabindex" ); } this.on.remove(); this.off.remove(); this.element.unwrap(); this.flipswitch.remove(); this.removeClass( "ui-flipswitch-input" ); } }, $.mobile.behaviors.formReset ) ); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.rangeslider", $.extend( { options: { theme: null, trackTheme: null, corners: true, mini: false, highlight: true }, _create: function() { var $el = this.element, elClass = this.options.mini ? "ui-rangeslider ui-mini" : "ui-rangeslider", _inputFirst = $el.find( "input" ).first(), _inputLast = $el.find( "input" ).last(), _label = $el.find( "label" ).first(), _sliderWidgetFirst = $.data( _inputFirst.get( 0 ), "mobile-slider" ) || $.data( _inputFirst.slider().get( 0 ), "mobile-slider" ), _sliderWidgetLast = $.data( _inputLast.get(0), "mobile-slider" ) || $.data( _inputLast.slider().get( 0 ), "mobile-slider" ), _sliderFirst = _sliderWidgetFirst.slider, _sliderLast = _sliderWidgetLast.slider, firstHandle = _sliderWidgetFirst.handle, _sliders = $( "<div class='ui-rangeslider-sliders' />" ).appendTo( $el ); _inputFirst.addClass( "ui-rangeslider-first" ); _inputLast.addClass( "ui-rangeslider-last" ); $el.addClass( elClass ); _sliderFirst.appendTo( _sliders ); _sliderLast.appendTo( _sliders ); _label.insertBefore( $el ); firstHandle.prependTo( _sliderLast ); $.extend( this, { _inputFirst: _inputFirst, _inputLast: _inputLast, _sliderFirst: _sliderFirst, _sliderLast: _sliderLast, _label: _label, _targetVal: null, _sliderTarget: false, _sliders: _sliders, _proxy: false }); this.refresh(); this._on( this.element.find( "input.ui-slider-input" ), { "slidebeforestart": "_slidebeforestart", "slidestop": "_slidestop", "slidedrag": "_slidedrag", "slidebeforechange": "_change", "blur": "_change", "keyup": "_change" }); this._on({ "mousedown":"_change" }); this._on( this.element.closest( "form" ), { "reset":"_handleReset" }); this._on( firstHandle, { "vmousedown": "_dragFirstHandle" }); }, _handleReset: function() { var self = this; //we must wait for the stack to unwind before updateing other wise sliders will not have updated yet setTimeout( function() { self._updateHighlight(); },0); }, _dragFirstHandle: function( event ) { //if the first handle is dragged send the event to the first slider $.data( this._inputFirst.get(0), "mobile-slider" ).dragging = true; $.data( this._inputFirst.get(0), "mobile-slider" ).refresh( event ); return false; }, _slidedrag: function( event ) { var first = $( event.target ).is( this._inputFirst ), otherSlider = ( first ) ? this._inputLast : this._inputFirst; this._sliderTarget = false; //if the drag was initiated on an extreme and the other handle is focused send the events to //the closest handle if ( ( this._proxy === "first" && first ) || ( this._proxy === "last" && !first ) ) { $.data( otherSlider.get(0), "mobile-slider" ).dragging = true; $.data( otherSlider.get(0), "mobile-slider" ).refresh( event ); return false; } }, _slidestop: function( event ) { var first = $( event.target ).is( this._inputFirst ); this._proxy = false; //this stops dragging of the handle and brings the active track to the front //this makes clicks on the track go the the last handle used this.element.find( "input" ).trigger( "vmouseup" ); this._sliderFirst.css( "z-index", first ? 1 : "" ); }, _slidebeforestart: function( event ) { this._sliderTarget = false; //if the track is the target remember this and the original value if ( $( event.originalEvent.target ).hasClass( "ui-slider-track" ) ) { this._sliderTarget = true; this._targetVal = $( event.target ).val(); } }, _setOptions: function( options ) { if ( options.theme !== undefined ) { this._setTheme( options.theme ); } if ( options.trackTheme !== undefined ) { this._setTrackTheme( options.trackTheme ); } if ( options.mini !== undefined ) { this._setMini( options.mini ); } if ( options.highlight !== undefined ) { this._setHighlight( options.highlight ); } this._super( options ); this.refresh(); }, refresh: function() { var $el = this.element, o = this.options; if ( this._inputFirst.is( ":disabled" ) || this._inputLast.is( ":disabled" ) ) { this.options.disabled = true; } $el.find( "input" ).slider({ theme: o.theme, trackTheme: o.trackTheme, disabled: o.disabled, corners: o.corners, mini: o.mini, highlight: o.highlight }).slider( "refresh" ); this._updateHighlight(); }, _change: function( event ) { if ( event.type === "keyup" ) { this._updateHighlight(); return false; } var self = this, min = parseFloat( this._inputFirst.val(), 10 ), max = parseFloat( this._inputLast.val(), 10 ), first = $( event.target ).hasClass( "ui-rangeslider-first" ), thisSlider = first ? this._inputFirst : this._inputLast, otherSlider = first ? this._inputLast : this._inputFirst; if ( ( this._inputFirst.val() > this._inputLast.val() && event.type === "mousedown" && !$(event.target).hasClass("ui-slider-handle")) ) { thisSlider.blur(); } else if ( event.type === "mousedown" ) { return; } if ( min > max && !this._sliderTarget ) { //this prevents min from being greater then max thisSlider.val( first ? max: min ).slider( "refresh" ); this._trigger( "normalize" ); } else if ( min > max ) { //this makes it so clicks on the target on either extreme go to the closest handle thisSlider.val( this._targetVal ).slider( "refresh" ); //You must wait for the stack to unwind so first slider is updated before updating second setTimeout( function() { otherSlider.val( first ? min: max ).slider( "refresh" ); $.data( otherSlider.get(0), "mobile-slider" ).handle.focus(); self._sliderFirst.css( "z-index", first ? "" : 1 ); self._trigger( "normalize" ); }, 0 ); this._proxy = ( first ) ? "first" : "last"; } //fixes issue where when both _sliders are at min they cannot be adjusted if ( min === max ) { $.data( thisSlider.get(0), "mobile-slider" ).handle.css( "z-index", 1 ); $.data( otherSlider.get(0), "mobile-slider" ).handle.css( "z-index", 0 ); } else { $.data( otherSlider.get(0), "mobile-slider" ).handle.css( "z-index", "" ); $.data( thisSlider.get(0), "mobile-slider" ).handle.css( "z-index", "" ); } this._updateHighlight(); if ( min >= max ) { return false; } }, _updateHighlight: function() { var min = parseInt( $.data( this._inputFirst.get(0), "mobile-slider" ).handle.get(0).style.left, 10 ), max = parseInt( $.data( this._inputLast.get(0), "mobile-slider" ).handle.get(0).style.left, 10 ), width = (max - min); this.element.find( ".ui-slider-bg" ).css({ "margin-left": min + "%", "width": width + "%" }); }, _setTheme: function( value ) { this._inputFirst.slider( "option", "theme", value ); this._inputLast.slider( "option", "theme", value ); }, _setTrackTheme: function( value ) { this._inputFirst.slider( "option", "trackTheme", value ); this._inputLast.slider( "option", "trackTheme", value ); }, _setMini: function( value ) { this._inputFirst.slider( "option", "mini", value ); this._inputLast.slider( "option", "mini", value ); this.element.toggleClass( "ui-mini", !!value ); }, _setHighlight: function( value ) { this._inputFirst.slider( "option", "highlight", value ); this._inputLast.slider( "option", "highlight", value ); }, _destroy: function() { this._label.prependTo( this.element ); this.element.removeClass( "ui-rangeslider ui-mini" ); this._inputFirst.after( this._sliderFirst ); this._inputLast.after( this._sliderLast ); this._sliders.remove(); this.element.find( "input" ).removeClass( "ui-rangeslider-first ui-rangeslider-last" ).slider( "destroy" ); } }, $.mobile.behaviors.formReset ) ); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.textinput", $.mobile.textinput, { options: { clearBtn: false, clearBtnText: "Clear text" }, _create: function() { this._super(); if ( !!this.options.clearBtn || this.isSearch ) { this._addClearBtn(); } }, clearButton: function() { return $( "<a href='#' class='ui-input-clear ui-btn ui-icon-delete ui-btn-icon-notext ui-corner-all" + "' title='" + this.options.clearBtnText + "'>" + this.options.clearBtnText + "</a>" ); }, _clearBtnClick: function( event ) { this.element.val( "" ) .focus() .trigger( "change" ); this._clearBtn.addClass( "ui-input-clear-hidden" ); event.preventDefault(); }, _addClearBtn: function() { if ( !this.options.enhanced ) { this._enhanceClear(); } $.extend( this, { _clearBtn: this.widget().find("a.ui-input-clear") }); this._bindClearEvents(); this._toggleClear(); }, _enhanceClear: function() { this.clearButton().appendTo( this.widget() ); this.widget().addClass( "ui-input-has-clear" ); }, _bindClearEvents: function() { this._on( this._clearBtn, { "click": "_clearBtnClick" }); this._on({ "keyup": "_toggleClear", "change": "_toggleClear", "input": "_toggleClear", "focus": "_toggleClear", "blur": "_toggleClear", "cut": "_toggleClear", "paste": "_toggleClear" }); }, _unbindClear: function() { this._off( this._clearBtn, "click"); this._off( this.element, "keyup change input focus blur cut paste" ); }, _setOptions: function( options ) { this._super( options ); if ( options.clearBtn !== undefined && !this.element.is( "textarea, :jqmData(type='range')" ) ) { if ( options.clearBtn ) { this._addClearBtn(); } else { this._destroyClear(); } } if ( options.clearBtnText !== undefined && this._clearBtn !== undefined ) { this._clearBtn.text( options.clearBtnText ) .attr("title", options.clearBtnText); } }, _toggleClear: function() { this._delay( "_toggleClearClass", 0 ); }, _toggleClearClass: function() { this._clearBtn.toggleClass( "ui-input-clear-hidden", !this.element.val() ); }, _destroyClear: function() { this.widget().removeClass( "ui-input-has-clear" ); this._unbindClear(); this._clearBtn.remove(); }, _destroy: function() { this._super(); this._destroyClear(); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.textinput", $.mobile.textinput, { options: { autogrow:true, keyupTimeoutBuffer: 100 }, _create: function() { this._super(); if ( this.options.autogrow && this.isTextarea ) { this._autogrow(); } }, _autogrow: function() { this.element.addClass( "ui-textinput-autogrow" ); this._on({ "keyup": "_timeout", "change": "_timeout", "input": "_timeout", "paste": "_timeout", }); // Attach to the various you-have-become-visible notifications that the // various framework elements emit. // TODO: Remove all but the updatelayout handler once #6426 is fixed. this._on( true, this.document, { // TODO: Move to non-deprecated event "pageshow": "_handleShow", "popupbeforeposition": "_handleShow", "updatelayout": "_handleShow", "panelopen": "_handleShow" }); }, // Synchronously fix the widget height if this widget's parents are such // that they show/hide content at runtime. We still need to check whether // the widget is actually visible in case it is contained inside multiple // such containers. For example: panel contains collapsible contains // autogrow textinput. The panel may emit "panelopen" indicating that its // content has become visible, but the collapsible is still collapsed, so // the autogrow textarea is still not visible. _handleShow: function( event ) { if ( $.contains( event.target, this.element[ 0 ] ) && this.element.is( ":visible" ) ) { if ( event.type !== "popupbeforeposition" ) { this.element .addClass( "ui-textinput-autogrow-resize" ) .animationComplete( $.proxy( function() { this.element.removeClass( "ui-textinput-autogrow-resize" ); }, this ), "transition" ); } this._timeout(); } }, _unbindAutogrow: function() { this.element.removeClass( "ui-textinput-autogrow" ); this._off( this.element, "keyup change input paste" ); this._off( this.document, "pageshow popupbeforeposition updatelayout panelopen" ); }, keyupTimeout: null, _prepareHeightUpdate: function( delay ) { if ( this.keyupTimeout ) { clearTimeout( this.keyupTimeout ); } if ( delay === undefined ) { this._updateHeight(); } else { this.keyupTimeout = this._delay( "_updateHeight", delay ); } }, _timeout: function() { this._prepareHeightUpdate( this.options.keyupTimeoutBuffer ); }, _updateHeight: function() { var paddingTop, paddingBottom, paddingHeight, scrollHeight, clientHeight, borderTop, borderBottom, borderHeight, height, scrollTop = this.window.scrollTop(); this.keyupTimeout = 0; // IE8 textareas have the onpage property - others do not if ( !( "onpage" in this.element[ 0 ] ) ) { this.element.css({ "height": 0, "min-height": 0, "max-height": 0 }); } scrollHeight = this.element[ 0 ].scrollHeight; clientHeight = this.element[ 0 ].clientHeight; borderTop = parseFloat( this.element.css( "border-top-width" ) ); borderBottom = parseFloat( this.element.css( "border-bottom-width" ) ); borderHeight = borderTop + borderBottom; height = scrollHeight + borderHeight + 15; // Issue 6179: Padding is not included in scrollHeight and // clientHeight by Firefox if no scrollbar is visible. Because // textareas use the border-box box-sizing model, padding should be // included in the new (assigned) height. Because the height is set // to 0, clientHeight == 0 in Firefox. Therefore, we can use this to // check if padding must be added. if ( clientHeight === 0 ) { paddingTop = parseFloat( this.element.css( "padding-top" ) ); paddingBottom = parseFloat( this.element.css( "padding-bottom" ) ); paddingHeight = paddingTop + paddingBottom; height += paddingHeight; } this.element.css({ "height": height, "min-height": "", "max-height": "" }); this.window.scrollTop( scrollTop ); }, refresh: function() { if ( this.options.autogrow && this.isTextarea ) { this._updateHeight(); } }, _setOptions: function( options ) { this._super( options ); if ( options.autogrow !== undefined && this.isTextarea ) { if ( options.autogrow ) { this._autogrow(); } else { this._unbindAutogrow(); } } } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.selectmenu", $.extend( { initSelector: "select:not( :jqmData(role='slider')):not( :jqmData(role='flipswitch') )", options: { theme: null, icon: "carat-d", iconpos: "right", inline: false, corners: true, shadow: true, iconshadow: false, /* TODO: Deprecated in 1.4, remove in 1.5. */ overlayTheme: null, dividerTheme: null, hidePlaceholderMenuItems: true, closeText: "Close", nativeMenu: true, // This option defaults to true on iOS devices. preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1, mini: false }, _button: function() { return $( "<div/>" ); }, _setDisabled: function( value ) { this.element.attr( "disabled", value ); this.button.attr( "aria-disabled", value ); return this._setOption( "disabled", value ); }, _focusButton : function() { var self = this; setTimeout( function() { self.button.focus(); }, 40); }, _selectOptions: function() { return this.select.find( "option" ); }, // setup items that are generally necessary for select menu extension _preExtension: function() { var inline = this.options.inline || this.element.jqmData( "inline" ), mini = this.options.mini || this.element.jqmData( "mini" ), classes = ""; // TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577 /* if ( $el[0].className.length ) { classes = $el[0].className; } */ if ( !!~this.element[0].className.indexOf( "ui-btn-left" ) ) { classes = " ui-btn-left"; } if ( !!~this.element[0].className.indexOf( "ui-btn-right" ) ) { classes = " ui-btn-right"; } if ( inline ) { classes += " ui-btn-inline"; } if ( mini ) { classes += " ui-mini"; } this.select = this.element.removeClass( "ui-btn-left ui-btn-right" ).wrap( "<div class='ui-select" + classes + "'>" ); this.selectId = this.select.attr( "id" ) || ( "select-" + this.uuid ); this.buttonId = this.selectId + "-button"; this.label = $( "label[for='"+ this.selectId +"']" ); this.isMultiple = this.select[ 0 ].multiple; }, _destroy: function() { var wrapper = this.element.parents( ".ui-select" ); if ( wrapper.length > 0 ) { if ( wrapper.is( ".ui-btn-left, .ui-btn-right" ) ) { this.element.addClass( wrapper.hasClass( "ui-btn-left" ) ? "ui-btn-left" : "ui-btn-right" ); } this.element.insertAfter( wrapper ); wrapper.remove(); } }, _create: function() { this._preExtension(); this.button = this._button(); var self = this, options = this.options, iconpos = options.icon ? ( options.iconpos || this.select.jqmData( "iconpos" ) ) : false, button = this.button .insertBefore( this.select ) .attr( "id", this.buttonId ) .addClass( "ui-btn" + ( options.icon ? ( " ui-icon-" + options.icon + " ui-btn-icon-" + iconpos + ( options.iconshadow ? " ui-shadow-icon" : "" ) ) : "" ) + /* TODO: Remove in 1.5. */ ( options.theme ? " ui-btn-" + options.theme : "" ) + ( options.corners ? " ui-corner-all" : "" ) + ( options.shadow ? " ui-shadow" : "" ) ); this.setButtonText(); // Opera does not properly support opacity on select elements // In Mini, it hides the element, but not its text // On the desktop,it seems to do the opposite // for these reasons, using the nativeMenu option results in a full native select in Opera if ( options.nativeMenu && window.opera && window.opera.version ) { button.addClass( "ui-select-nativeonly" ); } // Add counter for multi selects if ( this.isMultiple ) { this.buttonCount = $( "<span>" ) .addClass( "ui-li-count ui-body-inherit" ) .hide() .appendTo( button.addClass( "ui-li-has-count" ) ); } // Disable if specified if ( options.disabled || this.element.attr( "disabled" )) { this.disable(); } // Events on native select this.select.change(function() { self.refresh(); if ( !!options.nativeMenu ) { this.blur(); } }); this._handleFormReset(); this._on( this.button, { keydown: "_handleKeydown" }); this.build(); }, build: function() { var self = this; this.select .appendTo( self.button ) .bind( "vmousedown", function() { // Add active class to button self.button.addClass( $.mobile.activeBtnClass ); }) .bind( "focus", function() { self.button.addClass( $.mobile.focusClass ); }) .bind( "blur", function() { self.button.removeClass( $.mobile.focusClass ); }) .bind( "focus vmouseover", function() { self.button.trigger( "vmouseover" ); }) .bind( "vmousemove", function() { // Remove active class on scroll/touchmove self.button.removeClass( $.mobile.activeBtnClass ); }) .bind( "change blur vmouseout", function() { self.button.trigger( "vmouseout" ) .removeClass( $.mobile.activeBtnClass ); }); // In many situations, iOS will zoom into the select upon tap, this prevents that from happening self.button.bind( "vmousedown", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.disable( true ); } }); self.label.bind( "click focus", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.disable( true ); } }); self.select.bind( "focus", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.disable( true ); } }); self.button.bind( "mouseup", function() { if ( self.options.preventFocusZoom ) { setTimeout(function() { $.mobile.zoom.enable( true ); }, 0 ); } }); self.select.bind( "blur", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.enable( true ); } }); }, selected: function() { return this._selectOptions().filter( ":selected" ); }, selectedIndices: function() { var self = this; return this.selected().map(function() { return self._selectOptions().index( this ); }).get(); }, setButtonText: function() { var self = this, selected = this.selected(), text = this.placeholder, span = $( document.createElement( "span" ) ); this.button.children( "span" ).not( ".ui-li-count" ).remove().end().end().prepend( (function() { if ( selected.length ) { text = selected.map(function() { return $( this ).text(); }).get().join( ", " ); } else { text = self.placeholder; } if ( text ) { span.text( text ); } else { // Set the contents to &nbsp; which we write as &#160; to be XHTML compliant - see gh-6699 span.html( "&#160;" ); } // TODO possibly aggregate multiple select option classes return span .addClass( self.select.attr( "class" ) ) .addClass( selected.attr( "class" ) ) .removeClass( "ui-screen-hidden" ); })()); }, setButtonCount: function() { var selected = this.selected(); // multiple count inside button if ( this.isMultiple ) { this.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length ); } }, _handleKeydown: function( /* event */ ) { this._delay( "_refreshButton" ); }, _reset: function() { this.refresh(); }, _refreshButton: function() { this.setButtonText(); this.setButtonCount(); }, refresh: function() { this._refreshButton(); }, // open and close preserved in native selects // to simplify users code when looping over selects open: $.noop, close: $.noop, disable: function() { this._setDisabled( true ); this.button.addClass( "ui-state-disabled" ); }, enable: function() { this._setDisabled( false ); this.button.removeClass( "ui-state-disabled" ); } }, $.mobile.behaviors.formReset ) ); })( jQuery ); (function( $, undefined ) { $.mobile.links = function( target ) { //links within content areas, tests included with page $( target ) .find( "a" ) .jqmEnhanceable() .filter( ":jqmData(rel='popup')[href][href!='']" ) .each( function() { // Accessibility info for popups var element = this, idref = element.getAttribute( "href" ).substring( 1 ); if ( idref ) { element.setAttribute( "aria-haspopup", true ); element.setAttribute( "aria-owns", idref ); element.setAttribute( "aria-expanded", false ); } }) .end() .not( ".ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" ) .addClass( "ui-link" ); }; })( jQuery ); (function( $, undefined ) { function fitSegmentInsideSegment( windowSize, segmentSize, offset, desired ) { var returnValue = desired; if ( windowSize < segmentSize ) { // Center segment if it's bigger than the window returnValue = offset + ( windowSize - segmentSize ) / 2; } else { // Otherwise center it at the desired coordinate while keeping it completely inside the window returnValue = Math.min( Math.max( offset, desired - segmentSize / 2 ), offset + windowSize - segmentSize ); } return returnValue; } function getWindowCoordinates( theWindow ) { return { x: theWindow.scrollLeft(), y: theWindow.scrollTop(), cx: ( theWindow[ 0 ].innerWidth || theWindow.width() ), cy: ( theWindow[ 0 ].innerHeight || theWindow.height() ) }; } $.widget( "mobile.popup", { options: { wrapperClass: null, theme: null, overlayTheme: null, shadow: true, corners: true, transition: "none", positionTo: "origin", tolerance: null, closeLinkSelector: "a:jqmData(rel='back')", closeLinkEvents: "click.popup", navigateEvents: "navigate.popup", closeEvents: "navigate.popup pagebeforechange.popup", dismissible: true, enhanced: false, // NOTE Windows Phone 7 has a scroll position caching issue that // requires us to disable popup history management by default // https://github.com/jquery/jquery-mobile/issues/4784 // // NOTE this option is modified in _create! history: !$.mobile.browser.oldIE }, _create: function() { var theElement = this.element, myId = theElement.attr( "id" ), currentOptions = this.options; // We need to adjust the history option to be false if there's no AJAX nav. // We can't do it in the option declarations because those are run before // it is determined whether there shall be AJAX nav. currentOptions.history = currentOptions.history && $.mobile.ajaxEnabled && $.mobile.hashListeningEnabled; // Define instance variables $.extend( this, { _scrollTop: 0, _page: theElement.closest( ".ui-page" ), _ui: null, _fallbackTransition: "", _currentTransition: false, _prerequisites: null, _isOpen: false, _tolerance: null, _resizeData: null, _ignoreResizeTo: 0, _orientationchangeInProgress: false }); if ( this._page.length === 0 ) { this._page = $( "body" ); } if ( currentOptions.enhanced ) { this._ui = { container: theElement.parent(), screen: theElement.parent().prev(), placeholder: $( this.document[ 0 ].getElementById( myId + "-placeholder" ) ) }; } else { this._ui = this._enhance( theElement, myId ); this._applyTransition( currentOptions.transition ); } this ._setTolerance( currentOptions.tolerance ) ._ui.focusElement = this._ui.container; // Event handlers this._on( this._ui.screen, { "vclick": "_eatEventAndClose" } ); this._on( this.window, { orientationchange: $.proxy( this, "_handleWindowOrientationchange" ), resize: $.proxy( this, "_handleWindowResize" ), keyup: $.proxy( this, "_handleWindowKeyUp" ) }); this._on( this.document, { "focusin": "_handleDocumentFocusIn" } ); }, _enhance: function( theElement, myId ) { var currentOptions = this.options, wrapperClass = currentOptions.wrapperClass, ui = { screen: $( "<div class='ui-screen-hidden ui-popup-screen " + this._themeClassFromOption( "ui-overlay-", currentOptions.overlayTheme ) + "'></div>" ), placeholder: $( "<div style='display: none;'><!-- placeholder --></div>" ), container: $( "<div class='ui-popup-container ui-popup-hidden ui-popup-truncate" + ( wrapperClass ? ( " " + wrapperClass ) : "" ) + "'></div>" ) }, fragment = this.document[ 0 ].createDocumentFragment(); fragment.appendChild( ui.screen[ 0 ] ); fragment.appendChild( ui.container[ 0 ] ); if ( myId ) { ui.screen.attr( "id", myId + "-screen" ); ui.container.attr( "id", myId + "-popup" ); ui.placeholder .attr( "id", myId + "-placeholder" ) .html( "<!-- placeholder for " + myId + " -->" ); } // Apply the proto this._page[ 0 ].appendChild( fragment ); // Leave a placeholder where the element used to be ui.placeholder.insertAfter( theElement ); theElement .detach() .addClass( "ui-popup " + this._themeClassFromOption( "ui-body-", currentOptions.theme ) + " " + ( currentOptions.shadow ? "ui-overlay-shadow " : "" ) + ( currentOptions.corners ? "ui-corner-all " : "" ) ) .appendTo( ui.container ); return ui; }, _eatEventAndClose: function( theEvent ) { theEvent.preventDefault(); theEvent.stopImmediatePropagation(); if ( this.options.dismissible ) { this.close(); } return false; }, // Make sure the screen covers the entire document - CSS is sometimes not // enough to accomplish this. _resizeScreen: function() { var screen = this._ui.screen, popupHeight = this._ui.container.outerHeight( true ), screenHeight = screen.removeAttr( "style" ).height(), // Subtracting 1 here is necessary for an obscure Andrdoid 4.0 bug where // the browser hangs if the screen covers the entire document :/ documentHeight = this.document.height() - 1; if ( screenHeight < documentHeight ) { screen.height( documentHeight ); } else if ( popupHeight > screenHeight ) { screen.height( popupHeight ); } }, _handleWindowKeyUp: function( theEvent ) { if ( this._isOpen && theEvent.keyCode === $.mobile.keyCode.ESCAPE ) { return this._eatEventAndClose( theEvent ); } }, _expectResizeEvent: function() { var windowCoordinates = getWindowCoordinates( this.window ); if ( this._resizeData ) { if ( windowCoordinates.x === this._resizeData.windowCoordinates.x && windowCoordinates.y === this._resizeData.windowCoordinates.y && windowCoordinates.cx === this._resizeData.windowCoordinates.cx && windowCoordinates.cy === this._resizeData.windowCoordinates.cy ) { // timeout not refreshed return false; } else { // clear existing timeout - it will be refreshed below clearTimeout( this._resizeData.timeoutId ); } } this._resizeData = { timeoutId: this._delay( "_resizeTimeout", 200 ), windowCoordinates: windowCoordinates }; return true; }, _resizeTimeout: function() { if ( this._isOpen ) { if ( !this._expectResizeEvent() ) { if ( this._ui.container.hasClass( "ui-popup-hidden" ) ) { // effectively rapid-open the popup while leaving the screen intact this._ui.container.removeClass( "ui-popup-hidden ui-popup-truncate" ); this.reposition( { positionTo: "window" } ); this._ignoreResizeEvents(); } this._resizeScreen(); this._resizeData = null; this._orientationchangeInProgress = false; } } else { this._resizeData = null; this._orientationchangeInProgress = false; } }, _stopIgnoringResizeEvents: function() { this._ignoreResizeTo = 0; }, _ignoreResizeEvents: function() { if ( this._ignoreResizeTo ) { clearTimeout( this._ignoreResizeTo ); } this._ignoreResizeTo = this._delay( "_stopIgnoringResizeEvents", 1000 ); }, _handleWindowResize: function(/* theEvent */) { if ( this._isOpen && this._ignoreResizeTo === 0 ) { if ( ( this._expectResizeEvent() || this._orientationchangeInProgress ) && !this._ui.container.hasClass( "ui-popup-hidden" ) ) { // effectively rapid-close the popup while leaving the screen intact this._ui.container .addClass( "ui-popup-hidden ui-popup-truncate" ) .removeAttr( "style" ); } } }, _handleWindowOrientationchange: function(/* theEvent */) { if ( !this._orientationchangeInProgress && this._isOpen && this._ignoreResizeTo === 0 ) { this._expectResizeEvent(); this._orientationchangeInProgress = true; } }, // When the popup is open, attempting to focus on an element that is not a // child of the popup will redirect focus to the popup _handleDocumentFocusIn: function( theEvent ) { var target, targetElement = theEvent.target, ui = this._ui; if ( !this._isOpen ) { return; } if ( targetElement !== ui.container[ 0 ] ) { target = $( targetElement ); if ( 0 === target.parents().filter( ui.container[ 0 ] ).length ) { $( this.document[ 0 ].activeElement ).one( "focus", function(/* theEvent */) { target.blur(); }); ui.focusElement.focus(); theEvent.preventDefault(); theEvent.stopImmediatePropagation(); return false; } else if ( ui.focusElement[ 0 ] === ui.container[ 0 ] ) { ui.focusElement = target; } } this._ignoreResizeEvents(); }, _themeClassFromOption: function( prefix, value ) { return ( value ? ( value === "none" ? "" : ( prefix + value ) ) : ( prefix + "inherit" ) ); }, _applyTransition: function( value ) { if ( value ) { this._ui.container.removeClass( this._fallbackTransition ); if ( value !== "none" ) { this._fallbackTransition = $.mobile._maybeDegradeTransition( value ); if ( this._fallbackTransition === "none" ) { this._fallbackTransition = ""; } this._ui.container.addClass( this._fallbackTransition ); } } return this; }, _setOptions: function( newOptions ) { var currentOptions = this.options, theElement = this.element, screen = this._ui.screen; if ( newOptions.wrapperClass !== undefined ) { this._ui.container .removeClass( currentOptions.wrapperClass ) .addClass( newOptions.wrapperClass ); } if ( newOptions.theme !== undefined ) { theElement .removeClass( this._themeClassFromOption( "ui-body-", currentOptions.theme ) ) .addClass( this._themeClassFromOption( "ui-body-", newOptions.theme ) ); } if ( newOptions.overlayTheme !== undefined ) { screen .removeClass( this._themeClassFromOption( "ui-overlay-", currentOptions.overlayTheme ) ) .addClass( this._themeClassFromOption( "ui-overlay-", newOptions.overlayTheme ) ); if ( this._isOpen ) { screen.addClass( "in" ); } } if ( newOptions.shadow !== undefined ) { theElement.toggleClass( "ui-overlay-shadow", newOptions.shadow ); } if ( newOptions.corners !== undefined ) { theElement.toggleClass( "ui-corner-all", newOptions.corners ); } if ( newOptions.transition !== undefined ) { if ( !this._currentTransition ) { this._applyTransition( newOptions.transition ); } } if ( newOptions.tolerance !== undefined ) { this._setTolerance( newOptions.tolerance ); } if ( newOptions.disabled !== undefined ) { if ( newOptions.disabled ) { this.close(); } } return this._super( newOptions ); }, _setTolerance: function( value ) { var tol = { t: 30, r: 15, b: 30, l: 15 }, ar; if ( value !== undefined ) { ar = String( value ).split( "," ); $.each( ar, function( idx, val ) { ar[ idx ] = parseInt( val, 10 ); } ); switch( ar.length ) { // All values are to be the same case 1: if ( !isNaN( ar[ 0 ] ) ) { tol.t = tol.r = tol.b = tol.l = ar[ 0 ]; } break; // The first value denotes top/bottom tolerance, and the second value denotes left/right tolerance case 2: if ( !isNaN( ar[ 0 ] ) ) { tol.t = tol.b = ar[ 0 ]; } if ( !isNaN( ar[ 1 ] ) ) { tol.l = tol.r = ar[ 1 ]; } break; // The array contains values in the order top, right, bottom, left case 4: if ( !isNaN( ar[ 0 ] ) ) { tol.t = ar[ 0 ]; } if ( !isNaN( ar[ 1 ] ) ) { tol.r = ar[ 1 ]; } if ( !isNaN( ar[ 2 ] ) ) { tol.b = ar[ 2 ]; } if ( !isNaN( ar[ 3 ] ) ) { tol.l = ar[ 3 ]; } break; default: break; } } this._tolerance = tol; return this; }, _clampPopupWidth: function( infoOnly ) { var menuSize, windowCoordinates = getWindowCoordinates( this.window ), // rectangle within which the popup must fit rectangle = { x: this._tolerance.l, y: windowCoordinates.y + this._tolerance.t, cx: windowCoordinates.cx - this._tolerance.l - this._tolerance.r, cy: windowCoordinates.cy - this._tolerance.t - this._tolerance.b }; if ( !infoOnly ) { // Clamp the width of the menu before grabbing its size this._ui.container.css( "max-width", rectangle.cx ); } menuSize = { cx: this._ui.container.outerWidth( true ), cy: this._ui.container.outerHeight( true ) }; return { rc: rectangle, menuSize: menuSize }; }, _calculateFinalLocation: function( desired, clampInfo ) { var returnValue, rectangle = clampInfo.rc, menuSize = clampInfo.menuSize; // Center the menu over the desired coordinates, while not going outside // the window tolerances. This will center wrt. the window if the popup is // too large. returnValue = { left: fitSegmentInsideSegment( rectangle.cx, menuSize.cx, rectangle.x, desired.x ), top: fitSegmentInsideSegment( rectangle.cy, menuSize.cy, rectangle.y, desired.y ) }; // Make sure the top of the menu is visible returnValue.top = Math.max( 0, returnValue.top ); // If the height of the menu is smaller than the height of the document // align the bottom with the bottom of the document returnValue.top -= Math.min( returnValue.top, Math.max( 0, returnValue.top + menuSize.cy - this.document.height() ) ); return returnValue; }, // Try and center the overlay over the given coordinates _placementCoords: function( desired ) { return this._calculateFinalLocation( desired, this._clampPopupWidth() ); }, _createPrerequisites: function( screenPrerequisite, containerPrerequisite, whenDone ) { var prerequisites, self = this; // It is important to maintain both the local variable prerequisites and // self._prerequisites. The local variable remains in the closure of the // functions which call the callbacks passed in. The comparison between the // local variable and self._prerequisites is necessary, because once a // function has been passed to .animationComplete() it will be called next // time an animation completes, even if that's not the animation whose end // the function was supposed to catch (for example, if an abort happens // during the opening animation, the .animationComplete handler is not // called for that animation anymore, but the handler remains attached, so // it is called the next time the popup is opened - making it stale. // Comparing the local variable prerequisites to the widget-level variable // self._prerequisites ensures that callbacks triggered by a stale // .animationComplete will be ignored. prerequisites = { screen: $.Deferred(), container: $.Deferred() }; prerequisites.screen.then( function() { if ( prerequisites === self._prerequisites ) { screenPrerequisite(); } }); prerequisites.container.then( function() { if ( prerequisites === self._prerequisites ) { containerPrerequisite(); } }); $.when( prerequisites.screen, prerequisites.container ).done( function() { if ( prerequisites === self._prerequisites ) { self._prerequisites = null; whenDone(); } }); self._prerequisites = prerequisites; }, _animate: function( args ) { // NOTE before removing the default animation of the screen // this had an animate callback that would resolve the deferred // now the deferred is resolved immediately // TODO remove the dependency on the screen deferred this._ui.screen .removeClass( args.classToRemove ) .addClass( args.screenClassToAdd ); args.prerequisites.screen.resolve(); if ( args.transition && args.transition !== "none" ) { if ( args.applyTransition ) { this._applyTransition( args.transition ); } if ( this._fallbackTransition ) { this._ui.container .addClass( args.containerClassToAdd ) .removeClass( args.classToRemove ) .animationComplete( $.proxy( args.prerequisites.container, "resolve" ) ); return; } } this._ui.container.removeClass( args.classToRemove ); args.prerequisites.container.resolve(); }, // The desired coordinates passed in will be returned untouched if no reference element can be identified via // desiredPosition.positionTo. Nevertheless, this function ensures that its return value always contains valid // x and y coordinates by specifying the center middle of the window if the coordinates are absent. // options: { x: coordinate, y: coordinate, positionTo: string: "origin", "window", or jQuery selector _desiredCoords: function( openOptions ) { var offset, dst = null, windowCoordinates = getWindowCoordinates( this.window ), x = openOptions.x, y = openOptions.y, pTo = openOptions.positionTo; // Establish which element will serve as the reference if ( pTo && pTo !== "origin" ) { if ( pTo === "window" ) { x = windowCoordinates.cx / 2 + windowCoordinates.x; y = windowCoordinates.cy / 2 + windowCoordinates.y; } else { try { dst = $( pTo ); } catch( err ) { dst = null; } if ( dst ) { dst.filter( ":visible" ); if ( dst.length === 0 ) { dst = null; } } } } // If an element was found, center over it if ( dst ) { offset = dst.offset(); x = offset.left + dst.outerWidth() / 2; y = offset.top + dst.outerHeight() / 2; } // Make sure x and y are valid numbers - center over the window if ( $.type( x ) !== "number" || isNaN( x ) ) { x = windowCoordinates.cx / 2 + windowCoordinates.x; } if ( $.type( y ) !== "number" || isNaN( y ) ) { y = windowCoordinates.cy / 2 + windowCoordinates.y; } return { x: x, y: y }; }, _reposition: function( openOptions ) { // We only care about position-related parameters for repositioning openOptions = { x: openOptions.x, y: openOptions.y, positionTo: openOptions.positionTo }; this._trigger( "beforeposition", undefined, openOptions ); this._ui.container.offset( this._placementCoords( this._desiredCoords( openOptions ) ) ); }, reposition: function( openOptions ) { if ( this._isOpen ) { this._reposition( openOptions ); } }, _openPrerequisitesComplete: function() { var id = this.element.attr( "id" ); this._ui.container.addClass( "ui-popup-active" ); this._isOpen = true; this._resizeScreen(); this._ui.container.attr( "tabindex", "0" ).focus(); this._ignoreResizeEvents(); if ( id ) { this.document.find( "[aria-haspopup='true'][aria-owns='" + id + "']" ).attr( "aria-expanded", true ); } this._trigger( "afteropen" ); }, _open: function( options ) { var openOptions = $.extend( {}, this.options, options ), // TODO move blacklist to private method androidBlacklist = ( function() { var ua = navigator.userAgent, // Rendering engine is Webkit, and capture major version wkmatch = ua.match( /AppleWebKit\/([0-9\.]+)/ ), wkversion = !!wkmatch && wkmatch[ 1 ], androidmatch = ua.match( /Android (\d+(?:\.\d+))/ ), andversion = !!androidmatch && androidmatch[ 1 ], chromematch = ua.indexOf( "Chrome" ) > -1; // Platform is Android, WebKit version is greater than 534.13 ( Android 3.2.1 ) and not Chrome. if ( androidmatch !== null && andversion === "4.0" && wkversion && wkversion > 534.13 && !chromematch ) { return true; } return false; }()); // Count down to triggering "popupafteropen" - we have two prerequisites: // 1. The popup window animation completes (container()) // 2. The screen opacity animation completes (screen()) this._createPrerequisites( $.noop, $.noop, $.proxy( this, "_openPrerequisitesComplete" ) ); this._currentTransition = openOptions.transition; this._applyTransition( openOptions.transition ); this._ui.screen.removeClass( "ui-screen-hidden" ); this._ui.container.removeClass( "ui-popup-truncate" ); // Give applications a chance to modify the contents of the container before it appears this._reposition( openOptions ); this._ui.container.removeClass( "ui-popup-hidden" ); if ( this.options.overlayTheme && androidBlacklist ) { /* TODO: The native browser on Android 4.0.X ("Ice Cream Sandwich") suffers from an issue where the popup overlay appears to be z-indexed above the popup itself when certain other styles exist on the same page -- namely, any element set to `position: fixed` and certain types of input. These issues are reminiscent of previously uncovered bugs in older versions of Android's native browser: https://github.com/scottjehl/Device-Bugs/issues/3 This fix closes the following bugs ( I use "closes" with reluctance, and stress that this issue should be revisited as soon as possible ): https://github.com/jquery/jquery-mobile/issues/4816 https://github.com/jquery/jquery-mobile/issues/4844 https://github.com/jquery/jquery-mobile/issues/4874 */ // TODO sort out why this._page isn't working this.element.closest( ".ui-page" ).addClass( "ui-popup-open" ); } this._animate({ additionalCondition: true, transition: openOptions.transition, classToRemove: "", screenClassToAdd: "in", containerClassToAdd: "in", applyTransition: false, prerequisites: this._prerequisites }); }, _closePrerequisiteScreen: function() { this._ui.screen .removeClass( "out" ) .addClass( "ui-screen-hidden" ); }, _closePrerequisiteContainer: function() { this._ui.container .removeClass( "reverse out" ) .addClass( "ui-popup-hidden ui-popup-truncate" ) .removeAttr( "style" ); }, _closePrerequisitesDone: function() { var container = this._ui.container, id = this.element.attr( "id" ); container.removeAttr( "tabindex" ); // remove the global mutex for popups $.mobile.popup.active = undefined; // Blur elements inside the container, including the container $( ":focus", container[ 0 ] ).add( container[ 0 ] ).blur(); if ( id ) { this.document.find( "[aria-haspopup='true'][aria-owns='" + id + "']" ).attr( "aria-expanded", false ); } // alert users that the popup is closed this._trigger( "afterclose" ); }, _close: function( immediate ) { this._ui.container.removeClass( "ui-popup-active" ); this._page.removeClass( "ui-popup-open" ); this._isOpen = false; // Count down to triggering "popupafterclose" - we have two prerequisites: // 1. The popup window reverse animation completes (container()) // 2. The screen opacity animation completes (screen()) this._createPrerequisites( $.proxy( this, "_closePrerequisiteScreen" ), $.proxy( this, "_closePrerequisiteContainer" ), $.proxy( this, "_closePrerequisitesDone" ) ); this._animate( { additionalCondition: this._ui.screen.hasClass( "in" ), transition: ( immediate ? "none" : ( this._currentTransition ) ), classToRemove: "in", screenClassToAdd: "out", containerClassToAdd: "reverse out", applyTransition: true, prerequisites: this._prerequisites }); }, _unenhance: function() { if ( this.options.enhanced ) { return; } // Put the element back to where the placeholder was and remove the "ui-popup" class this._setOptions( { theme: $.mobile.popup.prototype.options.theme } ); this.element // Cannot directly insertAfter() - we need to detach() first, because // insertAfter() will do nothing if the payload div was not attached // to the DOM at the time the widget was created, and so the payload // will remain inside the container even after we call insertAfter(). // If that happens and we remove the container a few lines below, we // will cause an infinite recursion - #5244 .detach() .insertAfter( this._ui.placeholder ) .removeClass( "ui-popup ui-overlay-shadow ui-corner-all ui-body-inherit" ); this._ui.screen.remove(); this._ui.container.remove(); this._ui.placeholder.remove(); }, _destroy: function() { if ( $.mobile.popup.active === this ) { this.element.one( "popupafterclose", $.proxy( this, "_unenhance" ) ); this.close(); } else { this._unenhance(); } return this; }, _closePopup: function( theEvent, data ) { var parsedDst, toUrl, currentOptions = this.options, immediate = false; if ( ( theEvent && theEvent.isDefaultPrevented() ) || $.mobile.popup.active !== this ) { return; } // restore location on screen window.scrollTo( 0, this._scrollTop ); if ( theEvent && theEvent.type === "pagebeforechange" && data ) { // Determine whether we need to rapid-close the popup, or whether we can // take the time to run the closing transition if ( typeof data.toPage === "string" ) { parsedDst = data.toPage; } else { parsedDst = data.toPage.jqmData( "url" ); } parsedDst = $.mobile.path.parseUrl( parsedDst ); toUrl = parsedDst.pathname + parsedDst.search + parsedDst.hash; if ( this._myUrl !== $.mobile.path.makeUrlAbsolute( toUrl ) ) { // Going to a different page - close immediately immediate = true; } else { theEvent.preventDefault(); } } // remove nav bindings this.window.off( currentOptions.closeEvents ); // unbind click handlers added when history is disabled this.element.undelegate( currentOptions.closeLinkSelector, currentOptions.closeLinkEvents ); this._close( immediate ); }, // any navigation event after a popup is opened should close the popup // NOTE the pagebeforechange is bound to catch navigation events that don't // alter the url (eg, dialogs from popups) _bindContainerClose: function() { this.window .on( this.options.closeEvents, $.proxy( this, "_closePopup" ) ); }, widget: function() { return this._ui.container; }, // TODO no clear deliniation of what should be here and // what should be in _open. Seems to be "visual" vs "history" for now open: function( options ) { var url, hashkey, activePage, currentIsDialog, hasHash, urlHistory, self = this, currentOptions = this.options; // make sure open is idempotent if ( $.mobile.popup.active || currentOptions.disabled ) { return this; } // set the global popup mutex $.mobile.popup.active = this; this._scrollTop = this.window.scrollTop(); // if history alteration is disabled close on navigate events // and leave the url as is if ( !( currentOptions.history ) ) { self._open( options ); self._bindContainerClose(); // When histoy is disabled we have to grab the data-rel // back link clicks so we can close the popup instead of // relying on history to do it for us self.element .delegate( currentOptions.closeLinkSelector, currentOptions.closeLinkEvents, function( theEvent ) { self.close(); theEvent.preventDefault(); }); return this; } // cache some values for min/readability urlHistory = $.mobile.navigate.history; hashkey = $.mobile.dialogHashKey; activePage = $.mobile.activePage; currentIsDialog = ( activePage ? activePage.hasClass( "ui-dialog" ) : false ); this._myUrl = url = urlHistory.getActive().url; hasHash = ( url.indexOf( hashkey ) > -1 ) && !currentIsDialog && ( urlHistory.activeIndex > 0 ); if ( hasHash ) { self._open( options ); self._bindContainerClose(); return this; } // if the current url has no dialog hash key proceed as normal // otherwise, if the page is a dialog simply tack on the hash key if ( url.indexOf( hashkey ) === -1 && !currentIsDialog ) { url = url + (url.indexOf( "#" ) > -1 ? hashkey : "#" + hashkey); } else { url = $.mobile.path.parseLocation().hash + hashkey; } // Tack on an extra hashkey if this is the first page and we've just reconstructed the initial hash if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) { url += hashkey; } // swallow the the initial navigation event, and bind for the next this.window.one( "beforenavigate", function( theEvent ) { theEvent.preventDefault(); self._open( options ); self._bindContainerClose(); }); this.urlAltered = true; $.mobile.navigate( url, { role: "dialog" } ); return this; }, close: function() { // make sure close is idempotent if ( $.mobile.popup.active !== this ) { return this; } this._scrollTop = this.window.scrollTop(); if ( this.options.history && this.urlAltered ) { $.mobile.back(); this.urlAltered = false; } else { // simulate the nav bindings having fired this._closePopup(); } return this; } }); // TODO this can be moved inside the widget $.mobile.popup.handleLink = function( $link ) { var offset, path = $.mobile.path, // NOTE make sure to get only the hash from the href because ie7 (wp7) // returns the absolute href in this case ruining the element selection popup = $( path.hashToSelector( path.parseUrl( $link.attr( "href" ) ).hash ) ).first(); if ( popup.length > 0 && popup.data( "mobile-popup" ) ) { offset = $link.offset(); popup.popup( "open", { x: offset.left + $link.outerWidth() / 2, y: offset.top + $link.outerHeight() / 2, transition: $link.jqmData( "transition" ), positionTo: $link.jqmData( "position-to" ) }); } //remove after delay setTimeout( function() { $link.removeClass( $.mobile.activeBtnClass ); }, 300 ); }; // TODO move inside _create $.mobile.document.on( "pagebeforechange", function( theEvent, data ) { if ( data.options.role === "popup" ) { $.mobile.popup.handleLink( data.options.link ); theEvent.preventDefault(); } }); })( jQuery ); /* * custom "selectmenu" plugin */ (function( $, undefined ) { var unfocusableItemSelector = ".ui-disabled,.ui-state-disabled,.ui-li-divider,.ui-screen-hidden,:jqmData(role='placeholder')", goToAdjacentItem = function( item, target, direction ) { var adjacent = item[ direction + "All" ]() .not( unfocusableItemSelector ) .first(); // if there's a previous option, focus it if ( adjacent.length ) { target .blur() .attr( "tabindex", "-1" ); adjacent.find( "a" ).first().focus(); } }; $.widget( "mobile.selectmenu", $.mobile.selectmenu, { _create: function() { var o = this.options; // Custom selects cannot exist inside popups, so revert the "nativeMenu" // option to true if a parent is a popup o.nativeMenu = o.nativeMenu || ( this.element.parents( ":jqmData(role='popup'),:mobile-popup" ).length > 0 ); return this._super(); }, _handleSelectFocus: function() { this.element.blur(); this.button.focus(); }, _handleKeydown: function( event ) { this._super( event ); this._handleButtonVclickKeydown( event ); }, _handleButtonVclickKeydown: function( event ) { if ( this.options.disabled || this.isOpen ) { return; } if (event.type === "vclick" || event.keyCode && (event.keyCode === $.mobile.keyCode.ENTER || event.keyCode === $.mobile.keyCode.SPACE)) { this._decideFormat(); if ( this.menuType === "overlay" ) { this.button.attr( "href", "#" + this.popupId ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "popup" ); } else { this.button.attr( "href", "#" + this.dialogId ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "dialog" ); } this.isOpen = true; // Do not prevent default, so the navigation may have a chance to actually open the chosen format } }, _handleListFocus: function( e ) { var params = ( e.type === "focusin" ) ? { tabindex: "0", event: "vmouseover" }: { tabindex: "-1", event: "vmouseout" }; $( e.target ) .attr( "tabindex", params.tabindex ) .trigger( params.event ); }, _handleListKeydown: function( event ) { var target = $( event.target ), li = target.closest( "li" ); // switch logic based on which key was pressed switch ( event.keyCode ) { // up or left arrow keys case 38: goToAdjacentItem( li, target, "prev" ); return false; // down or right arrow keys case 40: goToAdjacentItem( li, target, "next" ); return false; // If enter or space is pressed, trigger click case 13: case 32: target.trigger( "click" ); return false; } }, _handleMenuPageHide: function() { // TODO centralize page removal binding / handling in the page plugin. // Suggestion from @jblas to do refcounting // // TODO extremely confusing dependency on the open method where the pagehide.remove // bindings are stripped to prevent the parent page from disappearing. The way // we're keeping pages in the DOM right now sucks // // rebind the page remove that was unbound in the open function // to allow for the parent page removal from actions other than the use // of a dialog sized custom select // // doing this here provides for the back button on the custom select dialog this.thisPage.page( "bindRemove" ); }, _handleHeaderCloseClick: function() { if ( this.menuType === "overlay" ) { this.close(); return false; } }, build: function() { var selectId, popupId, dialogId, label, thisPage, isMultiple, menuId, themeAttr, overlayTheme, overlayThemeAttr, dividerThemeAttr, menuPage, listbox, list, header, headerTitle, menuPageContent, menuPageClose, headerClose, self, o = this.options; if ( o.nativeMenu ) { return this._super(); } self = this; selectId = this.selectId; popupId = selectId + "-listbox"; dialogId = selectId + "-dialog"; label = this.label; thisPage = this.element.closest( ".ui-page" ); isMultiple = this.element[ 0 ].multiple; menuId = selectId + "-menu"; themeAttr = o.theme ? ( " data-" + $.mobile.ns + "theme='" + o.theme + "'" ) : ""; overlayTheme = o.overlayTheme || o.theme || null; overlayThemeAttr = overlayTheme ? ( " data-" + $.mobile.ns + "overlay-theme='" + overlayTheme + "'" ) : ""; dividerThemeAttr = ( o.dividerTheme && isMultiple ) ? ( " data-" + $.mobile.ns + "divider-theme='" + o.dividerTheme + "'" ) : ""; menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' class='ui-selectmenu' id='" + dialogId + "'" + themeAttr + overlayThemeAttr + ">" + "<div data-" + $.mobile.ns + "role='header'>" + "<div class='ui-title'>" + label.getEncodedText() + "</div>"+ "</div>"+ "<div data-" + $.mobile.ns + "role='content'></div>"+ "</div>" ); listbox = $( "<div id='" + popupId + "' class='ui-selectmenu'></div>" ).insertAfter( this.select ).popup({ theme: o.overlayTheme }); list = $( "<ul class='ui-selectmenu-list' id='" + menuId + "' role='listbox' aria-labelledby='" + this.buttonId + "'" + themeAttr + dividerThemeAttr + "></ul>" ).appendTo( listbox ); header = $( "<div class='ui-header ui-bar-" + ( o.theme ? o.theme : "inherit" ) + "'></div>" ).prependTo( listbox ); headerTitle = $( "<h1 class='ui-title'></h1>" ).appendTo( header ); if ( this.isMultiple ) { headerClose = $( "<a>", { "role": "button", "text": o.closeText, "href": "#", "class": "ui-btn ui-corner-all ui-btn-left ui-btn-icon-notext ui-icon-delete" }).appendTo( header ); } $.extend( this, { selectId: selectId, menuId: menuId, popupId: popupId, dialogId: dialogId, thisPage: thisPage, menuPage: menuPage, label: label, isMultiple: isMultiple, theme: o.theme, listbox: listbox, list: list, header: header, headerTitle: headerTitle, headerClose: headerClose, menuPageContent: menuPageContent, menuPageClose: menuPageClose, placeholder: "" }); // Create list from select, update state this.refresh(); if ( this._origTabIndex === undefined ) { // Map undefined to false, because this._origTabIndex === undefined // indicates that we have not yet checked whether the select has // originally had a tabindex attribute, whereas false indicates that // we have checked the select for such an attribute, and have found // none present. this._origTabIndex = ( this.select[ 0 ].getAttribute( "tabindex" ) === null ) ? false : this.select.attr( "tabindex" ); } this.select.attr( "tabindex", "-1" ); this._on( this.select, { focus : "_handleSelectFocus" } ); // Button events this._on( this.button, { vclick: "_handleButtonVclickKeydown" }); // Events for list items this.list.attr( "role", "listbox" ); this._on( this.list, { focusin : "_handleListFocus", focusout : "_handleListFocus", keydown: "_handleListKeydown" }); this.list .delegate( "li:not(.ui-disabled,.ui-state-disabled,.ui-li-divider)", "click", function( event ) { // index of option tag to be selected var oldIndex = self.select[ 0 ].selectedIndex, newIndex = $.mobile.getAttribute( this, "option-index" ), option = self._selectOptions().eq( newIndex )[ 0 ]; // toggle selected status on the tag for multi selects option.selected = self.isMultiple ? !option.selected : true; // toggle checkbox class for multiple selects if ( self.isMultiple ) { $( this ).find( "a" ) .toggleClass( "ui-checkbox-on", option.selected ) .toggleClass( "ui-checkbox-off", !option.selected ); } // trigger change if value changed if ( self.isMultiple || oldIndex !== newIndex ) { self.select.trigger( "change" ); } // hide custom select for single selects only - otherwise focus clicked item // We need to grab the clicked item the hard way, because the list may have been rebuilt if ( self.isMultiple ) { self.list.find( "li:not(.ui-li-divider)" ).eq( newIndex ) .find( "a" ).first().focus(); } else { self.close(); } event.preventDefault(); }); // button refocus ensures proper height calculation // by removing the inline style and ensuring page inclusion this._on( this.menuPage, { pagehide: "_handleMenuPageHide" } ); // Events on the popup this._on( this.listbox, { popupafterclose: "close" } ); // Close button on small overlays if ( this.isMultiple ) { this._on( this.headerClose, { click: "_handleHeaderCloseClick" } ); } return this; }, _isRebuildRequired: function() { var list = this.list.find( "li" ), options = this._selectOptions().not( ".ui-screen-hidden" ); // TODO exceedingly naive method to determine difference // ignores value changes etc in favor of a forcedRebuild // from the user in the refresh method return options.text() !== list.text(); }, selected: function() { return this._selectOptions().filter( ":selected:not( :jqmData(placeholder='true') )" ); }, refresh: function( force ) { var self, indices; if ( this.options.nativeMenu ) { return this._super( force ); } self = this; if ( force || this._isRebuildRequired() ) { self._buildList(); } indices = this.selectedIndices(); self.setButtonText(); self.setButtonCount(); self.list.find( "li:not(.ui-li-divider)" ) .find( "a" ).removeClass( $.mobile.activeBtnClass ).end() .attr( "aria-selected", false ) .each(function( i ) { if ( $.inArray( i, indices ) > -1 ) { var item = $( this ); // Aria selected attr item.attr( "aria-selected", true ); // Multiple selects: add the "on" checkbox state to the icon if ( self.isMultiple ) { item.find( "a" ).removeClass( "ui-checkbox-off" ).addClass( "ui-checkbox-on" ); } else { if ( item.hasClass( "ui-screen-hidden" ) ) { item.next().find( "a" ).addClass( $.mobile.activeBtnClass ); } else { item.find( "a" ).addClass( $.mobile.activeBtnClass ); } } } }); }, close: function() { if ( this.options.disabled || !this.isOpen ) { return; } var self = this; if ( self.menuType === "page" ) { self.menuPage.dialog( "close" ); self.list.appendTo( self.listbox ); } else { self.listbox.popup( "close" ); } self._focusButton(); // allow the dialog to be closed again self.isOpen = false; }, open: function() { this.button.click(); }, _focusMenuItem: function() { var selector = this.list.find( "a." + $.mobile.activeBtnClass ); if ( selector.length === 0 ) { selector = this.list.find( "li:not(" + unfocusableItemSelector + ") a.ui-btn" ); } selector.first().focus(); }, _decideFormat: function() { var self = this, $window = this.window, selfListParent = self.list.parent(), menuHeight = selfListParent.outerHeight(), scrollTop = $window.scrollTop(), btnOffset = self.button.offset().top, screenHeight = $window.height(); if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) { self.menuPage.appendTo( $.mobile.pageContainer ).page(); self.menuPageContent = self.menuPage.find( ".ui-content" ); self.menuPageClose = self.menuPage.find( ".ui-header a" ); // prevent the parent page from being removed from the DOM, // otherwise the results of selecting a list item in the dialog // fall into a black hole self.thisPage.unbind( "pagehide.remove" ); //for WebOS/Opera Mini (set lastscroll using button offset) if ( scrollTop === 0 && btnOffset > screenHeight ) { self.thisPage.one( "pagehide", function() { $( this ).jqmData( "lastScroll", btnOffset ); }); } self.menuPage.one( { pageshow: $.proxy( this, "_focusMenuItem" ), pagehide: $.proxy( this, "close" ) }); self.menuType = "page"; self.menuPageContent.append( self.list ); self.menuPage.find( "div .ui-title" ).text( self.label.text() ); } else { self.menuType = "overlay"; self.listbox.one( { popupafteropen: $.proxy( this, "_focusMenuItem" ) } ); } }, _buildList: function() { var self = this, o = this.options, placeholder = this.placeholder, needPlaceholder = true, dataIcon = "false", $options, numOptions, select, dataPrefix = "data-" + $.mobile.ns, dataIndexAttr = dataPrefix + "option-index", dataIconAttr = dataPrefix + "icon", dataRoleAttr = dataPrefix + "role", dataPlaceholderAttr = dataPrefix + "placeholder", fragment = document.createDocumentFragment(), isPlaceholderItem = false, optGroup, i, option, $option, parent, text, anchor, classes, optLabel, divider, item; self.list.empty().filter( ".ui-listview" ).listview( "destroy" ); $options = this._selectOptions(); numOptions = $options.length; select = this.select[ 0 ]; for ( i = 0; i < numOptions;i++, isPlaceholderItem = false) { option = $options[i]; $option = $( option ); // Do not create options based on ui-screen-hidden select options if ( $option.hasClass( "ui-screen-hidden" ) ) { continue; } parent = option.parentNode; text = $option.text(); anchor = document.createElement( "a" ); classes = []; anchor.setAttribute( "href", "#" ); anchor.appendChild( document.createTextNode( text ) ); // Are we inside an optgroup? if ( parent !== select && parent.nodeName.toLowerCase() === "optgroup" ) { optLabel = parent.getAttribute( "label" ); if ( optLabel !== optGroup ) { divider = document.createElement( "li" ); divider.setAttribute( dataRoleAttr, "list-divider" ); divider.setAttribute( "role", "option" ); divider.setAttribute( "tabindex", "-1" ); divider.appendChild( document.createTextNode( optLabel ) ); fragment.appendChild( divider ); optGroup = optLabel; } } if ( needPlaceholder && ( !option.getAttribute( "value" ) || text.length === 0 || $option.jqmData( "placeholder" ) ) ) { needPlaceholder = false; isPlaceholderItem = true; // If we have identified a placeholder, record the fact that it was // us who have added the placeholder to the option and mark it // retroactively in the select as well if ( null === option.getAttribute( dataPlaceholderAttr ) ) { this._removePlaceholderAttr = true; } option.setAttribute( dataPlaceholderAttr, true ); if ( o.hidePlaceholderMenuItems ) { classes.push( "ui-screen-hidden" ); } if ( placeholder !== text ) { placeholder = self.placeholder = text; } } item = document.createElement( "li" ); if ( option.disabled ) { classes.push( "ui-state-disabled" ); item.setAttribute( "aria-disabled", true ); } item.setAttribute( dataIndexAttr, i ); item.setAttribute( dataIconAttr, dataIcon ); if ( isPlaceholderItem ) { item.setAttribute( dataPlaceholderAttr, true ); } item.className = classes.join( " " ); item.setAttribute( "role", "option" ); anchor.setAttribute( "tabindex", "-1" ); if ( this.isMultiple ) { $( anchor ).addClass( "ui-btn ui-checkbox-off ui-btn-icon-right" ); } item.appendChild( anchor ); fragment.appendChild( item ); } self.list[0].appendChild( fragment ); // Hide header if it's not a multiselect and there's no placeholder if ( !this.isMultiple && !placeholder.length ) { this.header.addClass( "ui-screen-hidden" ); } else { this.headerTitle.text( this.placeholder ); } // Now populated, create listview self.list.listview(); }, _button: function() { return this.options.nativeMenu ? this._super() : $( "<a>", { "href": "#", "role": "button", // TODO value is undefined at creation "id": this.buttonId, "aria-haspopup": "true", // TODO value is undefined at creation "aria-owns": this.menuId }); }, _destroy: function() { if ( !this.options.nativeMenu ) { this.close(); // Restore the tabindex attribute to its original value if ( this._origTabIndex !== undefined ) { if ( this._origTabIndex !== false ) { this.select.attr( "tabindex", this._origTabIndex ); } else { this.select.removeAttr( "tabindex" ); } } // Remove the placeholder attribute if we were the ones to add it if ( this._removePlaceholderAttr ) { this._selectOptions().removeAttr( "data-" + $.mobile.ns + "placeholder" ); } // Remove the popup this.listbox.remove(); // Remove the dialog this.menuPage.remove(); } // Chain up this._super(); } }); })( jQuery ); // buttonMarkup is deprecated as of 1.4.0 and will be removed in 1.5.0. (function( $, undefined ) { // General policy: Do not access data-* attributes except during enhancement. // In all other cases we determine the state of the button exclusively from its // className. That's why optionsToClasses expects a full complement of options, // and the jQuery plugin completes the set of options from the default values. // Map classes to buttonMarkup boolean options - used in classNameToOptions() var reverseBoolOptionMap = { "ui-shadow" : "shadow", "ui-corner-all" : "corners", "ui-btn-inline" : "inline", "ui-shadow-icon" : "iconshadow", /* TODO: Remove in 1.5 */ "ui-mini" : "mini" }, getAttrFixed = function() { var ret = $.mobile.getAttribute.apply( this, arguments ); return ( ret == null ? undefined : ret ); }, capitalLettersRE = /[A-Z]/g; // optionsToClasses: // @options: A complete set of options to convert to class names. // @existingClasses: extra classes to add to the result // // Converts @options to buttonMarkup classes and returns the result as an array // that can be converted to an element's className with .join( " " ). All // possible options must be set inside @options. Use $.fn.buttonMarkup.defaults // to get a complete set and use $.extend to override your choice of options // from that set. function optionsToClasses( options, existingClasses ) { var classes = existingClasses ? existingClasses : []; // Add classes to the array - first ui-btn classes.push( "ui-btn" ); // If there is a theme if ( options.theme ) { classes.push( "ui-btn-" + options.theme ); } // If there's an icon, add the icon-related classes if ( options.icon ) { classes = classes.concat([ "ui-icon-" + options.icon, "ui-btn-icon-" + options.iconpos ]); if ( options.iconshadow ) { classes.push( "ui-shadow-icon" ); /* TODO: Remove in 1.5 */ } } // Add the appropriate class for each boolean option if ( options.inline ) { classes.push( "ui-btn-inline" ); } if ( options.shadow ) { classes.push( "ui-shadow" ); } if ( options.corners ) { classes.push( "ui-corner-all" ); } if ( options.mini ) { classes.push( "ui-mini" ); } // Create a string from the array and return it return classes; } // classNameToOptions: // @classes: A string containing a .className-style space-separated class list // // Loops over @classes and calculates an options object based on the // buttonMarkup-related classes it finds. It records unrecognized classes in an // array. // // Returns: An object containing the following items: // // "options": buttonMarkup options found to be present because of the // presence/absence of corresponding classes // // "unknownClasses": a string containing all the non-buttonMarkup-related // classes found in @classes // // "alreadyEnhanced": A boolean indicating whether the ui-btn class was among // those found to be present function classNameToOptions( classes ) { var idx, map, unknownClass, alreadyEnhanced = false, noIcon = true, o = { icon: "", inline: false, shadow: false, corners: false, iconshadow: false, mini: false }, unknownClasses = []; classes = classes.split( " " ); // Loop over the classes for ( idx = 0 ; idx < classes.length ; idx++ ) { // Assume it's an unrecognized class unknownClass = true; // Recognize boolean options from the presence of classes map = reverseBoolOptionMap[ classes[ idx ] ]; if ( map !== undefined ) { unknownClass = false; o[ map ] = true; // Recognize the presence of an icon and establish the icon position } else if ( classes[ idx ].indexOf( "ui-btn-icon-" ) === 0 ) { unknownClass = false; noIcon = false; o.iconpos = classes[ idx ].substring( 12 ); // Establish which icon is present } else if ( classes[ idx ].indexOf( "ui-icon-" ) === 0 ) { unknownClass = false; o.icon = classes[ idx ].substring( 8 ); // Establish the theme - this recognizes one-letter theme swatch names } else if ( classes[ idx ].indexOf( "ui-btn-" ) === 0 && classes[ idx ].length === 8 ) { unknownClass = false; o.theme = classes[ idx ].substring( 7 ); // Recognize that this element has already been buttonMarkup-enhanced } else if ( classes[ idx ] === "ui-btn" ) { unknownClass = false; alreadyEnhanced = true; } // If this class has not been recognized, add it to the list if ( unknownClass ) { unknownClasses.push( classes[ idx ] ); } } // If a "ui-btn-icon-*" icon position class is absent there cannot be an icon if ( noIcon ) { o.icon = ""; } return { options: o, unknownClasses: unknownClasses, alreadyEnhanced: alreadyEnhanced }; } function camelCase2Hyphenated( c ) { return "-" + c.toLowerCase(); } // $.fn.buttonMarkup: // DOM: gets/sets .className // // @options: options to apply to the elements in the jQuery object // @overwriteClasses: boolean indicating whether to honour existing classes // // Calculates the classes to apply to the elements in the jQuery object based on // the options passed in. If @overwriteClasses is true, it sets the className // property of each element in the jQuery object to the buttonMarkup classes // it calculates based on the options passed in. // // If you wish to preserve any classes that are already present on the elements // inside the jQuery object, including buttonMarkup-related classes that were // added by a previous call to $.fn.buttonMarkup() or during page enhancement // then you should omit @overwriteClasses or set it to false. $.fn.buttonMarkup = function( options, overwriteClasses ) { var idx, data, el, retrievedOptions, optionKey, defaults = $.fn.buttonMarkup.defaults; for ( idx = 0 ; idx < this.length ; idx++ ) { el = this[ idx ]; data = overwriteClasses ? // Assume this element is not enhanced and ignore its classes { alreadyEnhanced: false, unknownClasses: [] } : // Otherwise analyze existing classes to establish existing options and // classes classNameToOptions( el.className ); retrievedOptions = $.extend( {}, // If the element already has the class ui-btn, then we assume that // it has passed through buttonMarkup before - otherwise, the options // returned by classNameToOptions do not correctly reflect the state of // the element ( data.alreadyEnhanced ? data.options : {} ), // Finally, apply the options passed in options ); // If this is the first call on this element, retrieve remaining options // from the data-attributes if ( !data.alreadyEnhanced ) { for ( optionKey in defaults ) { if ( retrievedOptions[ optionKey ] === undefined ) { retrievedOptions[ optionKey ] = getAttrFixed( el, optionKey.replace( capitalLettersRE, camelCase2Hyphenated ) ); } } } el.className = optionsToClasses( // Merge all the options and apply them as classes $.extend( {}, // The defaults form the basis defaults, // Add the computed options retrievedOptions ), // ... and re-apply any unrecognized classes that were found data.unknownClasses ).join( " " ); if ( el.tagName.toLowerCase() !== "button" ) { el.setAttribute( "role", "button" ); } } return this; }; // buttonMarkup defaults. This must be a complete set, i.e., a value must be // given here for all recognized options $.fn.buttonMarkup.defaults = { icon: "", iconpos: "left", theme: null, inline: false, shadow: true, corners: true, iconshadow: false, /* TODO: Remove in 1.5. Option deprecated in 1.4. */ mini: false }; $.extend( $.fn.buttonMarkup, { initSelector: "a:jqmData(role='button'), .ui-bar > a, .ui-bar > :jqmData(role='controlgroup') > a, button" }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.controlgroup", $.extend( { options: { enhanced: false, theme: null, shadow: false, corners: true, excludeInvisible: true, type: "vertical", mini: false }, _create: function() { var elem = this.element, opts = this.options; // Run buttonmarkup if ( $.fn.buttonMarkup ) { this.element.find( $.fn.buttonMarkup.initSelector ).buttonMarkup(); } // Enhance child widgets $.each( this._childWidgets, $.proxy( function( number, widgetName ) { if ( $.mobile[ widgetName ] ) { this.element.find( $.mobile[ widgetName ].initSelector ).not( $.mobile.page.prototype.keepNativeSelector() )[ widgetName ](); } }, this )); $.extend( this, { _ui: null, _initialRefresh: true }); if ( opts.enhanced ) { this._ui = { groupLegend: elem.children( ".ui-controlgroup-label" ).children(), childWrapper: elem.children( ".ui-controlgroup-controls" ) }; } else { this._ui = this._enhance(); } }, _childWidgets: [ "checkboxradio", "selectmenu", "button" ], _themeClassFromOption: function( value ) { return ( value ? ( value === "none" ? "" : "ui-group-theme-" + value ) : "" ); }, _enhance: function() { var elem = this.element, opts = this.options, ui = { groupLegend: elem.children( "legend" ), childWrapper: elem .addClass( "ui-controlgroup " + "ui-controlgroup-" + ( opts.type === "horizontal" ? "horizontal" : "vertical" ) + " " + this._themeClassFromOption( opts.theme ) + " " + ( opts.corners ? "ui-corner-all " : "" ) + ( opts.mini ? "ui-mini " : "" ) ) .wrapInner( "<div " + "class='ui-controlgroup-controls " + ( opts.shadow === true ? "ui-shadow" : "" ) + "'></div>" ) .children() }; if ( ui.groupLegend.length > 0 ) { $( "<div role='heading' class='ui-controlgroup-label'></div>" ) .append( ui.groupLegend ) .prependTo( elem ); } return ui; }, _init: function() { this.refresh(); }, _setOptions: function( options ) { var callRefresh, returnValue, elem = this.element; // Must have one of horizontal or vertical if ( options.type !== undefined ) { elem .removeClass( "ui-controlgroup-horizontal ui-controlgroup-vertical" ) .addClass( "ui-controlgroup-" + ( options.type === "horizontal" ? "horizontal" : "vertical" ) ); callRefresh = true; } if ( options.theme !== undefined ) { elem .removeClass( this._themeClassFromOption( this.options.theme ) ) .addClass( this._themeClassFromOption( options.theme ) ); } if ( options.corners !== undefined ) { elem.toggleClass( "ui-corner-all", options.corners ); } if ( options.mini !== undefined ) { elem.toggleClass( "ui-mini", options.mini ); } if ( options.shadow !== undefined ) { this._ui.childWrapper.toggleClass( "ui-shadow", options.shadow ); } if ( options.excludeInvisible !== undefined ) { this.options.excludeInvisible = options.excludeInvisible; callRefresh = true; } returnValue = this._super( options ); if ( callRefresh ) { this.refresh(); } return returnValue; }, container: function() { return this._ui.childWrapper; }, refresh: function() { var $el = this.container(), els = $el.find( ".ui-btn" ).not( ".ui-slider-handle" ), create = this._initialRefresh; if ( $.mobile.checkboxradio ) { $el.find( ":mobile-checkboxradio" ).checkboxradio( "refresh" ); } this._addFirstLastClasses( els, this.options.excludeInvisible ? this._getVisibles( els, create ) : els, create ); this._initialRefresh = false; }, // Caveat: If the legend is not the first child of the controlgroup at enhance // time, it will be after _destroy(). _destroy: function() { var ui, buttons, opts = this.options; if ( opts.enhanced ) { return this; } ui = this._ui; buttons = this.element .removeClass( "ui-controlgroup " + "ui-controlgroup-horizontal ui-controlgroup-vertical ui-corner-all ui-mini " + this._themeClassFromOption( opts.theme ) ) .find( ".ui-btn" ) .not( ".ui-slider-handle" ); this._removeFirstLastClasses( buttons ); ui.groupLegend.unwrap(); ui.childWrapper.children().unwrap(); } }, $.mobile.behaviors.addFirstLastClasses ) ); })(jQuery); (function( $, undefined ) { $.widget( "mobile.toolbar", { initSelector: ":jqmData(role='footer'), :jqmData(role='header')", options: { theme: null, addBackBtn: false, backBtnTheme: null, backBtnText: "Back" }, _create: function() { var leftbtn, rightbtn, role = this.element.is( ":jqmData(role='header')" ) ? "header" : "footer", page = this.element.closest( ".ui-page" ); if ( page.length === 0 ) { page = false; this._on( this.document, { "pageshow": "refresh" }); } $.extend( this, { role: role, page: page, leftbtn: leftbtn, rightbtn: rightbtn, backBtn: null }); this.element.attr( "role", role === "header" ? "banner" : "contentinfo" ).addClass( "ui-" + role ); this.refresh(); this._setOptions( this.options ); }, _setOptions: function( o ) { if ( o.addBackBtn !== undefined ) { if ( this.options.addBackBtn && this.role === "header" && $( ".ui-page" ).length > 1 && this.page[ 0 ].getAttribute( "data-" + $.mobile.ns + "url" ) !== $.mobile.path.stripHash( location.hash ) && !this.leftbtn ) { this._addBackButton(); } else { this.element.find( ".ui-toolbar-back-btn" ).remove(); } } if ( o.backBtnTheme != null ) { this.element .find( ".ui-toolbar-back-btn" ) .addClass( "ui-btn ui-btn-" + o.backBtnTheme ); } if ( o.backBtnText !== undefined ) { this.element.find( ".ui-toolbar-back-btn .ui-btn-text" ).text( o.backBtnText ); } if ( o.theme !== undefined ) { var currentTheme = this.options.theme ? this.options.theme : "inherit", newTheme = o.theme ? o.theme : "inherit"; this.element.removeClass( "ui-bar-" + currentTheme ).addClass( "ui-bar-" + newTheme ); } this._super( o ); }, refresh: function() { if ( this.role === "header" ) { this._addHeaderButtonClasses(); } if ( !this.page ) { this._setRelative(); if ( this.role === "footer" ) { this.element.appendTo( "body" ); } } this._addHeadingClasses(); this._btnMarkup(); }, //we only want this to run on non fixed toolbars so make it easy to override _setRelative: function() { $( "[data-"+ $.mobile.ns + "role='page']" ).css({ "position": "relative" }); }, // Deprecated in 1.4. As from 1.5 button classes have to be present in the markup. _btnMarkup: function() { this.element .children( "a" ) .filter( ":not([data-" + $.mobile.ns + "role='none'])" ) .attr( "data-" + $.mobile.ns + "role", "button" ); this.element.trigger( "create" ); }, // Deprecated in 1.4. As from 1.5 ui-btn-left/right classes have to be present in the markup. _addHeaderButtonClasses: function() { var $headeranchors = this.element.children( "a, button" ); this.leftbtn = $headeranchors.hasClass( "ui-btn-left" ); this.rightbtn = $headeranchors.hasClass( "ui-btn-right" ); this.leftbtn = this.leftbtn || $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length; this.rightbtn = this.rightbtn || $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length; }, _addBackButton: function() { var theme, options = this.options; if ( !this.backBtn ) { theme = options.backBtnTheme || options.theme; this.backBtn = $( "<a role='button' href='javascript:void(0);' " + "class='ui-btn ui-corner-all ui-shadow ui-btn-left " + ( theme ? "ui-btn-" + theme + " " : "" ) + "ui-toolbar-back-btn ui-icon-carat-l ui-btn-icon-left' " + "data-" + $.mobile.ns + "rel='back'>" + options.backBtnText + "</a>" ) .prependTo( this.element ); } }, _addHeadingClasses: function() { this.element.children( "h1, h2, h3, h4, h5, h6" ) .addClass( "ui-title" ) // Regardless of h element number in src, it becomes h1 for the enhanced page .attr({ "role": "heading", "aria-level": "1" }); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.toolbar", $.mobile.toolbar, { options: { position:null, visibleOnPageShow: true, disablePageZoom: true, transition: "slide", //can be none, fade, slide (slide maps to slideup or slidedown) fullscreen: false, tapToggle: true, tapToggleBlacklist: "a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed, .ui-flipswitch, .ui-popup, .ui-panel, .ui-panel-dismiss-open", hideDuringFocus: "input, textarea, select", updatePagePadding: true, trackPersistentToolbars: true, // Browser detection! Weeee, here we go... // Unfortunately, position:fixed is costly, not to mention probably impossible, to feature-detect accurately. // Some tests exist, but they currently return false results in critical devices and browsers, which could lead to a broken experience. // Testing fixed positioning is also pretty obtrusive to page load, requiring injected elements and scrolling the window // The following function serves to rule out some popular browsers with known fixed-positioning issues // This is a plugin option like any other, so feel free to improve or overwrite it supportBlacklist: function() { return !$.support.fixedPosition; } }, _create: function() { this._super(); if ( this.options.position === "fixed" && !this.options.supportBlacklist() ) { this._makeFixed(); } }, _makeFixed: function() { this.element.addClass( "ui-"+ this.role +"-fixed" ); this.updatePagePadding(); this._addTransitionClass(); this._bindPageEvents(); this._bindToggleHandlers(); this._setOptions( this.options ); }, _setOptions: function( o ) { if ( o.position === "fixed" && this.options.position !== "fixed" ) { this._makeFixed(); } if ( this.options.position === "fixed" && !this.options.supportBlacklist() ) { var $page = ( !!this.page )? this.page: ( $(".ui-page-active").length > 0 )? $(".ui-page-active"): $(".ui-page").eq(0); if ( o.fullscreen !== undefined) { if ( o.fullscreen ) { this.element.addClass( "ui-"+ this.role +"-fullscreen" ); $page.addClass( "ui-page-" + this.role + "-fullscreen" ); } // If not fullscreen, add class to page to set top or bottom padding else { this.element.removeClass( "ui-"+ this.role +"-fullscreen" ); $page.removeClass( "ui-page-" + this.role + "-fullscreen" ).addClass( "ui-page-" + this.role+ "-fixed" ); } } } this._super(o); }, _addTransitionClass: function() { var tclass = this.options.transition; if ( tclass && tclass !== "none" ) { // use appropriate slide for header or footer if ( tclass === "slide" ) { tclass = this.element.hasClass( "ui-header" ) ? "slidedown" : "slideup"; } this.element.addClass( tclass ); } }, _bindPageEvents: function() { var page = ( !!this.page )? this.element.closest( ".ui-page" ): this.document; //page event bindings // Fixed toolbars require page zoom to be disabled, otherwise usability issues crop up // This method is meant to disable zoom while a fixed-positioned toolbar page is visible this._on( page , { "pagebeforeshow": "_handlePageBeforeShow", "webkitAnimationStart":"_handleAnimationStart", "animationstart":"_handleAnimationStart", "updatelayout": "_handleAnimationStart", "pageshow": "_handlePageShow", "pagebeforehide": "_handlePageBeforeHide" }); }, _handlePageBeforeShow: function( ) { var o = this.options; if ( o.disablePageZoom ) { $.mobile.zoom.disable( true ); } if ( !o.visibleOnPageShow ) { this.hide( true ); } }, _handleAnimationStart: function() { if ( this.options.updatePagePadding ) { this.updatePagePadding( ( !!this.page )? this.page: ".ui-page-active" ); } }, _handlePageShow: function() { this.updatePagePadding( ( !!this.page )? this.page: ".ui-page-active" ); if ( this.options.updatePagePadding ) { this._on( this.window, { "throttledresize": "updatePagePadding" } ); } }, _handlePageBeforeHide: function( e, ui ) { var o = this.options, thisFooter, thisHeader, nextFooter, nextHeader; if ( o.disablePageZoom ) { $.mobile.zoom.enable( true ); } if ( o.updatePagePadding ) { this._off( this.window, "throttledresize" ); } if ( o.trackPersistentToolbars ) { thisFooter = $( ".ui-footer-fixed:jqmData(id)", this.page ); thisHeader = $( ".ui-header-fixed:jqmData(id)", this.page ); nextFooter = thisFooter.length && ui.nextPage && $( ".ui-footer-fixed:jqmData(id='" + thisFooter.jqmData( "id" ) + "')", ui.nextPage ) || $(); nextHeader = thisHeader.length && ui.nextPage && $( ".ui-header-fixed:jqmData(id='" + thisHeader.jqmData( "id" ) + "')", ui.nextPage ) || $(); if ( nextFooter.length || nextHeader.length ) { nextFooter.add( nextHeader ).appendTo( $.mobile.pageContainer ); ui.nextPage.one( "pageshow", function() { nextHeader.prependTo( this ); nextFooter.appendTo( this ); }); } } }, _visible: true, // This will set the content element's top or bottom padding equal to the toolbar's height updatePagePadding: function( tbPage ) { var $el = this.element, header = ( this.role ==="header" ), pos = parseFloat( $el.css( header ? "top" : "bottom" ) ); // This behavior only applies to "fixed", not "fullscreen" if ( this.options.fullscreen ) { return; } // tbPage argument can be a Page object or an event, if coming from throttled resize. tbPage = ( tbPage && tbPage.type === undefined && tbPage ) || this.page || $el.closest( ".ui-page" ); tbPage = ( !!this.page )? this.page: ".ui-page-active"; $( tbPage ).css( "padding-" + ( header ? "top" : "bottom" ), $el.outerHeight() + pos ); }, _useTransition: function( notransition ) { var $win = this.window, $el = this.element, scroll = $win.scrollTop(), elHeight = $el.height(), pHeight = ( !!this.page )? $el.closest( ".ui-page" ).height():$(".ui-page-active").height(), viewportHeight = $.mobile.getScreenHeight(); return !notransition && ( this.options.transition && this.options.transition !== "none" && ( ( this.role === "header" && !this.options.fullscreen && scroll > elHeight ) || ( this.role === "footer" && !this.options.fullscreen && scroll + viewportHeight < pHeight - elHeight ) ) || this.options.fullscreen ); }, show: function( notransition ) { var hideClass = "ui-fixed-hidden", $el = this.element; if ( this._useTransition( notransition ) ) { $el .removeClass( "out " + hideClass ) .addClass( "in" ) .animationComplete(function () { $el.removeClass( "in" ); }); } else { $el.removeClass( hideClass ); } this._visible = true; }, hide: function( notransition ) { var hideClass = "ui-fixed-hidden", $el = this.element, // if it's a slide transition, our new transitions need the reverse class as well to slide outward outclass = "out" + ( this.options.transition === "slide" ? " reverse" : "" ); if ( this._useTransition( notransition ) ) { $el .addClass( outclass ) .removeClass( "in" ) .animationComplete(function() { $el.addClass( hideClass ).removeClass( outclass ); }); } else { $el.addClass( hideClass ).removeClass( outclass ); } this._visible = false; }, toggle: function() { this[ this._visible ? "hide" : "show" ](); }, _bindToggleHandlers: function() { var self = this, o = self.options, delayShow, delayHide, isVisible = true, page = ( !!this.page )? this.page: $(".ui-page"); // tap toggle page .bind( "vclick", function( e ) { if ( o.tapToggle && !$( e.target ).closest( o.tapToggleBlacklist ).length ) { self.toggle(); } }) .bind( "focusin focusout", function( e ) { //this hides the toolbars on a keyboard pop to give more screen room and prevent ios bug which //positions fixed toolbars in the middle of the screen on pop if the input is near the top or //bottom of the screen addresses issues #4410 Footer navbar moves up when clicking on a textbox in an Android environment //and issue #4113 Header and footer change their position after keyboard popup - iOS //and issue #4410 Footer navbar moves up when clicking on a textbox in an Android environment if ( screen.width < 1025 && $( e.target ).is( o.hideDuringFocus ) && !$( e.target ).closest( ".ui-header-fixed, .ui-footer-fixed" ).length ) { //Fix for issue #4724 Moving through form in Mobile Safari with "Next" and "Previous" system //controls causes fixed position, tap-toggle false Header to reveal itself // isVisible instead of self._visible because the focusin and focusout events fire twice at the same time // Also use a delay for hiding the toolbars because on Android native browser focusin is direclty followed // by a focusout when a native selects opens and the other way around when it closes. if ( e.type === "focusout" && !isVisible ) { isVisible = true; //wait for the stack to unwind and see if we have jumped to another input clearTimeout( delayHide ); delayShow = setTimeout( function() { self.show(); }, 0 ); } else if ( e.type === "focusin" && !!isVisible ) { //if we have jumped to another input clear the time out to cancel the show. clearTimeout( delayShow ); isVisible = false; delayHide = setTimeout( function() { self.hide(); }, 0 ); } } }); }, _setRelative: function() { if( this.options.position !== "fixed" ){ $( "[data-"+ $.mobile.ns + "role='page']" ).css({ "position": "relative" }); } }, _destroy: function() { var $el = this.element, header = $el.hasClass( "ui-header" ); $el.closest( ".ui-page" ).css( "padding-" + ( header ? "top" : "bottom" ), "" ); $el.removeClass( "ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden" ); $el.closest( ".ui-page" ).removeClass( "ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen" ); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.toolbar", $.mobile.toolbar, { _makeFixed: function() { this._super(); this._workarounds(); }, //check the browser and version and run needed workarounds _workarounds: function() { var ua = navigator.userAgent, platform = navigator.platform, // Rendering engine is Webkit, and capture major version wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ), wkversion = !!wkmatch && wkmatch[ 1 ], os = null, self = this; //set the os we are working in if it dosent match one with workarounds return if ( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) { os = "ios"; } else if ( ua.indexOf( "Android" ) > -1 ) { os = "android"; } else { return; } //check os version if it dosent match one with workarounds return if ( os === "ios" ) { //iOS workarounds self._bindScrollWorkaround(); } else if ( os === "android" && wkversion && wkversion < 534 ) { //Android 2.3 run all Android 2.3 workaround self._bindScrollWorkaround(); self._bindListThumbWorkaround(); } else { return; } }, //Utility class for checking header and footer positions relative to viewport _viewportOffset: function() { var $el = this.element, header = $el.hasClass( "ui-header" ), offset = Math.abs( $el.offset().top - this.window.scrollTop() ); if ( !header ) { offset = Math.round( offset - this.window.height() + $el.outerHeight() ) - 60; } return offset; }, //bind events for _triggerRedraw() function _bindScrollWorkaround: function() { var self = this; //bind to scrollstop and check if the toolbars are correctly positioned this._on( this.window, { scrollstop: function() { var viewportOffset = self._viewportOffset(); //check if the header is visible and if its in the right place if ( viewportOffset > 2 && self._visible ) { self._triggerRedraw(); } }}); }, //this addresses issue #4250 Persistent footer instability in v1.1 with long select lists in Android 2.3.3 //and issue #3748 Android 2.x: Page transitions broken when fixed toolbars used //the absolutely positioned thumbnail in a list view causes problems with fixed position buttons above in a nav bar //setting the li's to -webkit-transform:translate3d(0,0,0); solves this problem to avoide potential issues in other //platforms we scope this with the class ui-android-2x-fix _bindListThumbWorkaround: function() { this.element.closest( ".ui-page" ).addClass( "ui-android-2x-fixed" ); }, //this addresses issues #4337 Fixed header problem after scrolling content on iOS and Android //and device bugs project issue #1 Form elements can lose click hit area in position: fixed containers. //this also addresses not on fixed toolbars page in docs //adding 1px of padding to the bottom then removing it causes a "redraw" //which positions the toolbars correctly (they will always be visually correct) _triggerRedraw: function() { var paddingBottom = parseFloat( $( ".ui-page-active" ).css( "padding-bottom" ) ); //trigger page redraw to fix incorrectly positioned fixed elements $( ".ui-page-active" ).css( "padding-bottom", ( paddingBottom + 1 ) + "px" ); //if the padding is reset with out a timeout the reposition will not occure. //this is independant of JQM the browser seems to need the time to react. setTimeout( function() { $( ".ui-page-active" ).css( "padding-bottom", paddingBottom + "px" ); }, 0 ); }, destroy: function() { this._super(); //Remove the class we added to the page previously in android 2.x this.element.closest( ".ui-page-active" ).removeClass( "ui-android-2x-fix" ); } }); })( jQuery ); ( function( $, undefined ) { var ieHack = ( $.mobile.browser.oldIE && $.mobile.browser.oldIE <= 8 ), uiTemplate = $( "<div class='ui-popup-arrow-guide'></div>" + "<div class='ui-popup-arrow-container" + ( ieHack ? " ie" : "" ) + "'>" + "<div class='ui-popup-arrow'></div>" + "</div>" ); function getArrow() { var clone = uiTemplate.clone(), gd = clone.eq( 0 ), ct = clone.eq( 1 ), ar = ct.children(); return { arEls: ct.add( gd ), gd: gd, ct: ct, ar: ar }; } $.widget( "mobile.popup", $.mobile.popup, { options: { arrow: "" }, _create: function() { var ar, ret = this._super(); if ( this.options.arrow ) { this._ui.arrow = ar = this._addArrow(); } return ret; }, _addArrow: function() { var theme, opts = this.options, ar = getArrow(); theme = this._themeClassFromOption( "ui-body-", opts.theme ); ar.ar.addClass( theme + ( opts.shadow ? " ui-overlay-shadow" : "" ) ); ar.arEls.hide().appendTo( this.element ); return ar; }, _unenhance: function() { var ar = this._ui.arrow; if ( ar ) { ar.arEls.remove(); } return this._super(); }, // Pretend to show an arrow described by @p and @dir and calculate the // distance from the desired point. If a best-distance is passed in, return // the minimum of the one passed in and the one calculated. _tryAnArrow: function( p, dir, desired, s, best ) { var result, r, diff, desiredForArrow = {}, tip = {}; // If the arrow has no wiggle room along the edge of the popup, it cannot // be displayed along the requested edge without it sticking out. if ( s.arFull[ p.dimKey ] > s.guideDims[ p.dimKey ] ) { return best; } desiredForArrow[ p.fst ] = desired[ p.fst ] + ( s.arHalf[ p.oDimKey ] + s.menuHalf[ p.oDimKey ] ) * p.offsetFactor - s.contentBox[ p.fst ] + ( s.clampInfo.menuSize[ p.oDimKey ] - s.contentBox[ p.oDimKey ] ) * p.arrowOffsetFactor; desiredForArrow[ p.snd ] = desired[ p.snd ]; result = s.result || this._calculateFinalLocation( desiredForArrow, s.clampInfo ); r = { x: result.left, y: result.top }; tip[ p.fst ] = r[ p.fst ] + s.contentBox[ p.fst ] + p.tipOffset; tip[ p.snd ] = Math.max( result[ p.prop ] + s.guideOffset[ p.prop ] + s.arHalf[ p.dimKey ], Math.min( result[ p.prop ] + s.guideOffset[ p.prop ] + s.guideDims[ p.dimKey ] - s.arHalf[ p.dimKey ], desired[ p.snd ] ) ); diff = Math.abs( desired.x - tip.x ) + Math.abs( desired.y - tip.y ); if ( !best || diff < best.diff ) { // Convert tip offset to coordinates inside the popup tip[ p.snd ] -= s.arHalf[ p.dimKey ] + result[ p.prop ] + s.contentBox[ p.snd ]; best = { dir: dir, diff: diff, result: result, posProp: p.prop, posVal: tip[ p.snd ] }; } return best; }, _getPlacementState: function( clamp ) { var offset, gdOffset, ar = this._ui.arrow, state = { clampInfo: this._clampPopupWidth( !clamp ), arFull: { cx: ar.ct.width(), cy: ar.ct.height() }, guideDims: { cx: ar.gd.width(), cy: ar.gd.height() }, guideOffset: ar.gd.offset() }; offset = this.element.offset(); ar.gd.css( { left: 0, top: 0, right: 0, bottom: 0 } ); gdOffset = ar.gd.offset(); state.contentBox = { x: gdOffset.left - offset.left, y: gdOffset.top - offset.top, cx: ar.gd.width(), cy: ar.gd.height() }; ar.gd.removeAttr( "style" ); // The arrow box moves between guideOffset and guideOffset + guideDims - arFull state.guideOffset = { left: state.guideOffset.left - offset.left, top: state.guideOffset.top - offset.top }; state.arHalf = { cx: state.arFull.cx / 2, cy: state.arFull.cy / 2 }; state.menuHalf = { cx: state.clampInfo.menuSize.cx / 2, cy: state.clampInfo.menuSize.cy / 2 }; return state; }, _placementCoords: function( desired ) { var state, best, params, elOffset, bgRef, optionValue = this.options.arrow, ar = this._ui.arrow; if ( !ar ) { return this._super( desired ); } ar.arEls.show(); bgRef = {}; state = this._getPlacementState( true ); params = { "l": { fst: "x", snd: "y", prop: "top", dimKey: "cy", oDimKey: "cx", offsetFactor: 1, tipOffset: -state.arHalf.cx, arrowOffsetFactor: 0 }, "r": { fst: "x", snd: "y", prop: "top", dimKey: "cy", oDimKey: "cx", offsetFactor: -1, tipOffset: state.arHalf.cx + state.contentBox.cx, arrowOffsetFactor: 1 }, "b": { fst: "y", snd: "x", prop: "left", dimKey: "cx", oDimKey: "cy", offsetFactor: -1, tipOffset: state.arHalf.cy + state.contentBox.cy, arrowOffsetFactor: 1 }, "t": { fst: "y", snd: "x", prop: "left", dimKey: "cx", oDimKey: "cy", offsetFactor: 1, tipOffset: -state.arHalf.cy, arrowOffsetFactor: 0 } }; // Try each side specified in the options to see on which one the arrow // should be placed such that the distance between the tip of the arrow and // the desired coordinates is the shortest. $.each( ( optionValue === true ? "l,t,r,b" : optionValue ).split( "," ), $.proxy( function( key, value ) { best = this._tryAnArrow( params[ value ], value, desired, state, best ); }, this ) ); // Could not place the arrow along any of the edges - behave as if showing // the arrow was turned off. if ( !best ) { ar.arEls.hide(); return this._super( desired ); } // Move the arrow into place ar.ct .removeClass( "ui-popup-arrow-l ui-popup-arrow-t ui-popup-arrow-r ui-popup-arrow-b" ) .addClass( "ui-popup-arrow-" + best.dir ) .removeAttr( "style" ).css( best.posProp, best.posVal ) .show(); // Do not move/size the background div on IE, because we use the arrow div for background as well. if ( !ieHack ) { elOffset = this.element.offset(); bgRef[ params[ best.dir ].fst ] = ar.ct.offset(); bgRef[ params[ best.dir ].snd ] = { left: elOffset.left + state.contentBox.x, top: elOffset.top + state.contentBox.y }; } return best.result; }, _setOptions: function( opts ) { var newTheme, oldTheme = this.options.theme, ar = this._ui.arrow, ret = this._super( opts ); if ( opts.arrow !== undefined ) { if ( !ar && opts.arrow ) { this._ui.arrow = this._addArrow(); // Important to return here so we don't set the same options all over // again below. return; } else if ( ar && !opts.arrow ) { ar.arEls.remove(); this._ui.arrow = null; } } // Reassign with potentially new arrow ar = this._ui.arrow; if ( ar ) { if ( opts.theme !== undefined ) { oldTheme = this._themeClassFromOption( "ui-body-", oldTheme ); newTheme = this._themeClassFromOption( "ui-body-", opts.theme ); ar.ar.removeClass( oldTheme ).addClass( newTheme ); } if ( opts.shadow !== undefined ) { ar.ar.toggleClass( "ui-overlay-shadow", opts.shadow ); } } return ret; }, _destroy: function() { var ar = this._ui.arrow; if ( ar ) { ar.arEls.remove(); } return this._super(); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.panel", { options: { classes: { panel: "ui-panel", panelOpen: "ui-panel-open", panelClosed: "ui-panel-closed", panelFixed: "ui-panel-fixed", panelInner: "ui-panel-inner", modal: "ui-panel-dismiss", modalOpen: "ui-panel-dismiss-open", pageContainer: "ui-panel-page-container", pageWrapper: "ui-panel-wrapper", pageFixedToolbar: "ui-panel-fixed-toolbar", pageContentPrefix: "ui-panel-page-content", /* Used for wrapper and fixed toolbars position, display and open classes. */ animate: "ui-panel-animate" }, animate: true, theme: null, position: "left", dismissible: true, display: "reveal", //accepts reveal, push, overlay swipeClose: true, positionFixed: false }, _panelID: null, _closeLink: null, _parentPage: null, _page: null, _modal: null, _panelInner: null, _wrapper: null, _fixedToolbars: null, _create: function() { var el = this.element, parentPage = el.closest( ":jqmData(role='page')" ); // expose some private props to other methods $.extend( this, { _panelID: el.attr( "id" ), _closeLink: el.find( ":jqmData(rel='close')" ), _parentPage: ( parentPage.length > 0 ) ? parentPage : false, _page: this._getPage, _panelInner: this._getPanelInner(), _wrapper: this._getWrapper, _fixedToolbars: this._getFixedToolbars }); this._addPanelClasses(); // if animating, add the class to do so if ( $.support.cssTransform3d && !!this.options.animate ) { this.element.addClass( this.options.classes.animate ); } this._bindUpdateLayout(); this._bindCloseEvents(); this._bindLinkListeners(); this._bindPageEvents(); if ( !!this.options.dismissible ) { this._createModal(); } this._bindSwipeEvents(); }, _getPanelInner: function() { var panelInner = this.element.find( "." + this.options.classes.panelInner ); if ( panelInner.length === 0 ) { panelInner = this.element.children().wrapAll( "<div class='" + this.options.classes.panelInner + "' />" ).parent(); } return panelInner; }, _createModal: function() { var self = this, target = self._parentPage ? self._parentPage.parent() : self.element.parent(); self._modal = $( "<div class='" + self.options.classes.modal + "' data-panelid='" + self._panelID + "'></div>" ) .on( "mousedown", function() { self.close(); }) .appendTo( target ); }, _getPage: function() { var page = this._parentPage ? this._parentPage : $( "." + $.mobile.activePageClass ); return page; }, _getWrapper: function() { var wrapper = this._page().find( "." + this.options.classes.pageWrapper ); if ( wrapper.length === 0 ) { wrapper = this._page().children( ".ui-header:not(.ui-header-fixed), .ui-content:not(.ui-popup), .ui-footer:not(.ui-footer-fixed)" ) .wrapAll( "<div class='" + this.options.classes.pageWrapper + "'></div>" ) .parent(); } return wrapper; }, _getFixedToolbars: function() { var extFixedToolbars = $( "body" ).children( ".ui-header-fixed, .ui-footer-fixed" ), intFixedToolbars = this._page().find( ".ui-header-fixed, .ui-footer-fixed" ), fixedToolbars = extFixedToolbars.add( intFixedToolbars ).addClass( this.options.classes.pageFixedToolbar ); return fixedToolbars; }, _getPosDisplayClasses: function( prefix ) { return prefix + "-position-" + this.options.position + " " + prefix + "-display-" + this.options.display; }, _getPanelClasses: function() { var panelClasses = this.options.classes.panel + " " + this._getPosDisplayClasses( this.options.classes.panel ) + " " + this.options.classes.panelClosed + " " + "ui-body-" + ( this.options.theme ? this.options.theme : "inherit" ); if ( !!this.options.positionFixed ) { panelClasses += " " + this.options.classes.panelFixed; } return panelClasses; }, _addPanelClasses: function() { this.element.addClass( this._getPanelClasses() ); }, _handleCloseClickAndEatEvent: function( event ) { if ( !event.isDefaultPrevented() ) { event.preventDefault(); this.close(); return false; } }, _handleCloseClick: function( event ) { if ( !event.isDefaultPrevented() ) { this.close(); } }, _bindCloseEvents: function() { this._on( this._closeLink, { "click": "_handleCloseClick" }); this._on({ "click a:jqmData(ajax='false')": "_handleCloseClick" }); }, _positionPanel: function() { var self = this, panelInnerHeight = self._panelInner.outerHeight(), expand = panelInnerHeight > $.mobile.getScreenHeight(); if ( expand || !self.options.positionFixed ) { if ( expand ) { self._unfixPanel(); $.mobile.resetActivePageHeight( panelInnerHeight ); } window.scrollTo( 0, $.mobile.defaultHomeScroll ); } else { self._fixPanel(); } }, _bindFixListener: function() { this._on( $( window ), { "throttledresize": "_positionPanel" }); }, _unbindFixListener: function() { this._off( $( window ), "throttledresize" ); }, _unfixPanel: function() { if ( !!this.options.positionFixed && $.support.fixedPosition ) { this.element.removeClass( this.options.classes.panelFixed ); } }, _fixPanel: function() { if ( !!this.options.positionFixed && $.support.fixedPosition ) { this.element.addClass( this.options.classes.panelFixed ); } }, _bindUpdateLayout: function() { var self = this; self.element.on( "updatelayout", function(/* e */) { if ( self._open ) { self._positionPanel(); } }); }, _bindLinkListeners: function() { this._on( "body", { "click a": "_handleClick" }); }, _handleClick: function( e ) { if ( e.currentTarget.href.split( "#" )[ 1 ] === this._panelID && this._panelID !== undefined ) { e.preventDefault(); var link = $( e.target ); if ( link.hasClass( "ui-btn" ) ) { link.addClass( $.mobile.activeBtnClass ); this.element.one( "panelopen panelclose", function() { link.removeClass( $.mobile.activeBtnClass ); }); } this.toggle(); return false; } }, _bindSwipeEvents: function() { var self = this, area = self._modal ? self.element.add( self._modal ) : self.element; // on swipe, close the panel if ( !!self.options.swipeClose ) { if ( self.options.position === "left" ) { area.on( "swipeleft.panel", function(/* e */) { self.close(); }); } else { area.on( "swiperight.panel", function(/* e */) { self.close(); }); } } }, _bindPageEvents: function() { var self = this; this.document // Close the panel if another panel on the page opens .on( "panelbeforeopen", function( e ) { if ( self._open && e.target !== self.element[ 0 ] ) { self.close(); } }) // On escape, close? might need to have a target check too... .on( "keyup.panel", function( e ) { if ( e.keyCode === 27 && self._open ) { self.close(); } }); // Clean up open panels after page hide if ( self._parentPage ) { this.document.on( "pagehide", ":jqmData(role='page')", function() { if ( self._open ) { self.close( true ); } }); } else { this.document.on( "pagebeforehide", function() { if ( self._open ) { self.close( true ); } }); } }, // state storage of open or closed _open: false, _pageContentOpenClasses: null, _modalOpenClasses: null, open: function( immediate ) { if ( !this._open ) { var self = this, o = self.options, _openPanel = function() { self.document.off( "panelclose" ); self._page().jqmData( "panel", "open" ); if ( $.support.cssTransform3d && !!o.animate && o.display !== "overlay" ) { self._wrapper().addClass( o.classes.animate ); self._fixedToolbars().addClass( o.classes.animate ); } if ( !immediate && $.support.cssTransform3d && !!o.animate ) { self.element.animationComplete( complete, "transition" ); } else { setTimeout( complete, 0 ); } if ( o.theme && o.display !== "overlay" ) { self._page().parent() .addClass( o.classes.pageContainer + "-themed " + o.classes.pageContainer + "-" + o.theme ); } self.element .removeClass( o.classes.panelClosed ) .addClass( o.classes.panelOpen ); self._positionPanel(); self._pageContentOpenClasses = self._getPosDisplayClasses( o.classes.pageContentPrefix ); if ( o.display !== "overlay" ) { self._page().parent().addClass( o.classes.pageContainer ); self._wrapper().addClass( self._pageContentOpenClasses ); self._fixedToolbars().addClass( self._pageContentOpenClasses ); } self._modalOpenClasses = self._getPosDisplayClasses( o.classes.modal ) + " " + o.classes.modalOpen; if ( self._modal ) { self._modal .addClass( self._modalOpenClasses ) .height( Math.max( self._modal.height(), self.document.height() ) ); } }, complete = function() { if ( o.display !== "overlay" ) { self._wrapper().addClass( o.classes.pageContentPrefix + "-open" ); self._fixedToolbars().addClass( o.classes.pageContentPrefix + "-open" ); } self._bindFixListener(); self._trigger( "open" ); }; self._trigger( "beforeopen" ); if ( self._page().jqmData( "panel" ) === "open" ) { self.document.on( "panelclose", function() { _openPanel(); }); } else { _openPanel(); } self._open = true; } }, close: function( immediate ) { if ( this._open ) { var self = this, o = this.options, _closePanel = function() { self.element.removeClass( o.classes.panelOpen ); if ( o.display !== "overlay" ) { self._wrapper().removeClass( self._pageContentOpenClasses ); self._fixedToolbars().removeClass( self._pageContentOpenClasses ); } if ( !immediate && $.support.cssTransform3d && !!o.animate ) { self.element.animationComplete( complete, "transition" ); } else { setTimeout( complete, 0 ); } if ( self._modal ) { self._modal.removeClass( self._modalOpenClasses ); } }, complete = function() { if ( o.theme && o.display !== "overlay" ) { self._page().parent().removeClass( o.classes.pageContainer + "-themed " + o.classes.pageContainer + "-" + o.theme ); } self.element.addClass( o.classes.panelClosed ); if ( o.display !== "overlay" ) { self._page().parent().removeClass( o.classes.pageContainer ); self._wrapper().removeClass( o.classes.pageContentPrefix + "-open" ); self._fixedToolbars().removeClass( o.classes.pageContentPrefix + "-open" ); } if ( $.support.cssTransform3d && !!o.animate && o.display !== "overlay" ) { self._wrapper().removeClass( o.classes.animate ); self._fixedToolbars().removeClass( o.classes.animate ); } self._fixPanel(); self._unbindFixListener(); $.mobile.resetActivePageHeight(); self._page().jqmRemoveData( "panel" ); self._trigger( "close" ); }; self._trigger( "beforeclose" ); _closePanel(); self._open = false; } }, toggle: function() { this[ this._open ? "close" : "open" ](); }, _destroy: function() { var otherPanels, o = this.options, multiplePanels = ( $( "body > :mobile-panel" ).length + $.mobile.activePage.find( ":mobile-panel" ).length ) > 1; if ( o.display !== "overlay" ) { // remove the wrapper if not in use by another panel otherPanels = $( "body > :mobile-panel" ).add( $.mobile.activePage.find( ":mobile-panel" ) ); if ( otherPanels.not( ".ui-panel-display-overlay" ).not( this.element ).length === 0 ) { this._wrapper().children().unwrap(); } if ( this._open ) { this._fixedToolbars().removeClass( o.classes.pageContentPrefix + "-open" ); if ( $.support.cssTransform3d && !!o.animate ) { this._fixedToolbars().removeClass( o.classes.animate ); } this._page().parent().removeClass( o.classes.pageContainer ); if ( o.theme ) { this._page().parent().removeClass( o.classes.pageContainer + "-themed " + o.classes.pageContainer + "-" + o.theme ); } } } if ( !multiplePanels ) { this.document.off( "panelopen panelclose" ); } if ( this._open ) { this._page().jqmRemoveData( "panel" ); } this._panelInner.children().unwrap(); this.element .removeClass( [ this._getPanelClasses(), o.classes.panelOpen, o.classes.animate ].join( " " ) ) .off( "swipeleft.panel swiperight.panel" ) .off( "panelbeforeopen" ) .off( "panelhide" ) .off( "keyup.panel" ) .off( "updatelayout" ); if ( this._modal ) { this._modal.remove(); } } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.table", { options: { classes: { table: "ui-table" }, enhanced: false }, _create: function() { if ( !this.options.enhanced ) { this.element.addClass( this.options.classes.table ); } // extend here, assign on refresh > _setHeaders $.extend( this, { // Expose headers and allHeaders properties on the widget // headers references the THs within the first TR in the table headers: undefined, // allHeaders references headers, plus all THs in the thead, which may // include several rows, or not allHeaders: undefined }); this._refresh( true ); }, _setHeaders: function() { var trs = this.element.find( "thead tr" ); this.headers = this.element.find( "tr:eq(0)" ).children(); this.allHeaders = this.headers.add( trs.children() ); }, refresh: function() { this._refresh(); }, rebuild: $.noop, _refresh: function( /* create */ ) { var table = this.element, trs = table.find( "thead tr" ); // updating headers on refresh (fixes #5880) this._setHeaders(); // Iterate over the trs trs.each( function() { var columnCount = 0; // Iterate over the children of the tr $( this ).children().each( function() { var span = parseInt( this.getAttribute( "colspan" ), 10 ), selector = ":nth-child(" + ( columnCount + 1 ) + ")", j; this.setAttribute( "data-" + $.mobile.ns + "colstart", columnCount + 1 ); if ( span ) { for( j = 0; j < span - 1; j++ ) { columnCount++; selector += ", :nth-child(" + ( columnCount + 1 ) + ")"; } } // Store "cells" data on header as a reference to all cells in the // same column as this TH $( this ).jqmData( "cells", table.find( "tr" ).not( trs.eq( 0 ) ).not( this ).children( selector ) ); columnCount++; }); }); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.table", $.mobile.table, { options: { mode: "columntoggle", columnBtnTheme: null, columnPopupTheme: null, columnBtnText: "Columns...", classes: $.extend( $.mobile.table.prototype.options.classes, { popup: "ui-table-columntoggle-popup", columnBtn: "ui-table-columntoggle-btn", priorityPrefix: "ui-table-priority-", columnToggleTable: "ui-table-columntoggle" }) }, _create: function() { this._super(); if ( this.options.mode !== "columntoggle" ) { return; } $.extend( this, { _menu: null }); if ( this.options.enhanced ) { this._menu = $( this.document[ 0 ].getElementById( this._id() + "-popup" ) ).children().first(); this._addToggles( this._menu, true ); } else { this._menu = this._enhanceColToggle(); this.element.addClass( this.options.classes.columnToggleTable ); } this._setupEvents(); this._setToggleState(); }, _id: function() { return ( this.element.attr( "id" ) || ( this.widgetName + this.uuid ) ); }, _setupEvents: function() { //NOTE: inputs are bound in bindToggles, // so it can be called on refresh, too // update column toggles on resize this._on( this.window, { throttledresize: "_setToggleState" }); this._on( this._menu, { "change input": "_menuInputChange" }); }, _addToggles: function( menu, keep ) { var inputs, checkboxIndex = 0, opts = this.options, container = menu.controlgroup( "container" ); // allow update of menu on refresh (fixes #5880) if ( keep ) { inputs = menu.find( "input" ); } else { container.empty(); } // create the hide/show toggles this.headers.not( "td" ).each( function() { var header = $( this ), priority = $.mobile.getAttribute( this, "priority" ), cells = header.add( header.jqmData( "cells" ) ); if ( priority ) { cells.addClass( opts.classes.priorityPrefix + priority ); ( keep ? inputs.eq( checkboxIndex++ ) : $("<label><input type='checkbox' checked />" + ( header.children( "abbr" ).first().attr( "title" ) || header.text() ) + "</label>" ) .appendTo( container ) .children( 0 ) .checkboxradio( { theme: opts.columnPopupTheme }) ) .jqmData( "cells", cells ); } }); // set bindings here if ( !keep ) { menu.controlgroup( "refresh" ); } }, _menuInputChange: function( evt ) { var input = $( evt.target ), checked = input[ 0 ].checked; input.jqmData( "cells" ) .toggleClass( "ui-table-cell-hidden", !checked ) .toggleClass( "ui-table-cell-visible", checked ); if ( input[ 0 ].getAttribute( "locked" ) ) { input.removeAttr( "locked" ); this._unlockCells( input.jqmData( "cells" ) ); } else { input.attr( "locked", true ); } }, _unlockCells: function( cells ) { // allow hide/show via CSS only = remove all toggle-locks cells.removeClass( "ui-table-cell-hidden ui-table-cell-visible"); }, _enhanceColToggle: function() { var id , menuButton, popup, menu, table = this.element, opts = this.options, ns = $.mobile.ns, fragment = this.document[ 0 ].createDocumentFragment(); id = this._id() + "-popup"; menuButton = $( "<a href='#" + id + "' " + "class='" + opts.classes.columnBtn + " ui-btn " + "ui-btn-" + ( opts.columnBtnTheme || "a" ) + " ui-corner-all ui-shadow ui-mini' " + "data-" + ns + "rel='popup'>" + opts.columnBtnText + "</a>" ); popup = $( "<div class='" + opts.classes.popup + "' id='" + id + "'></div>" ); menu = $( "<fieldset></fieldset>" ).controlgroup(); // set extension here, send "false" to trigger build/rebuild this._addToggles( menu, false ); menu.appendTo( popup ); fragment.appendChild( popup[ 0 ] ); fragment.appendChild( menuButton[ 0 ] ); table.before( fragment ); popup.popup(); return menu; }, rebuild: function() { this._super(); if ( this.options.mode === "columntoggle" ) { // NOTE: rebuild passes "false", while refresh passes "undefined" // both refresh the table, but inside addToggles, !false will be true, // so a rebuild call can be indentified this._refresh( false ); } }, _refresh: function( create ) { this._super( create ); if ( !create && this.options.mode === "columntoggle" ) { // columns not being replaced must be cleared from input toggle-locks this._unlockCells( this.allHeaders ); // update columntoggles and cells this._addToggles( this._menu, create ); // check/uncheck this._setToggleState(); } }, _setToggleState: function() { this._menu.find( "input" ).each( function() { var checkbox = $( this ); this.checked = checkbox.jqmData( "cells" ).eq( 0 ).css( "display" ) === "table-cell"; checkbox.checkboxradio( "refresh" ); }); }, _destroy: function() { this._super(); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.table", $.mobile.table, { options: { mode: "reflow", classes: $.extend( $.mobile.table.prototype.options.classes, { reflowTable: "ui-table-reflow", cellLabels: "ui-table-cell-label" }) }, _create: function() { this._super(); // If it's not reflow mode, return here. if ( this.options.mode !== "reflow" ) { return; } if ( !this.options.enhanced ) { this.element.addClass( this.options.classes.reflowTable ); this._updateReflow(); } }, rebuild: function() { this._super(); if ( this.options.mode === "reflow" ) { this._refresh( false ); } }, _refresh: function( create ) { this._super( create ); if ( !create && this.options.mode === "reflow" ) { this._updateReflow( ); } }, _updateReflow: function() { var table = this, opts = this.options; // get headers in reverse order so that top-level headers are appended last $( table.allHeaders.get().reverse() ).each( function() { var cells = $( this ).jqmData( "cells" ), colstart = $.mobile.getAttribute( this, "colstart" ), hierarchyClass = cells.not( this ).filter( "thead th" ).length && " ui-table-cell-label-top", text = $( this ).text(), iteration, filter; if ( text !== "" ) { if ( hierarchyClass ) { iteration = parseInt( this.getAttribute( "colspan" ), 10 ); filter = ""; if ( iteration ) { filter = "td:nth-child("+ iteration +"n + " + ( colstart ) +")"; } table._addLabels( cells.filter( filter ), opts.classes.cellLabels + hierarchyClass, text ); } else { table._addLabels( cells, opts.classes.cellLabels, text ); } } }); }, _addLabels: function( cells, label, text ) { // .not fixes #6006 cells.not( ":has(b." + label + ")" ).prepend( "<b class='" + label + "'>" + text + "</b>" ); } }); })( jQuery ); (function( $, undefined ) { // TODO rename filterCallback/deprecate and default to the item itself as the first argument var defaultFilterCallback = function( index, searchValue ) { return ( ( "" + ( $.mobile.getAttribute( this, "filtertext" ) || $( this ).text() ) ) .toLowerCase().indexOf( searchValue ) === -1 ); }; $.widget( "mobile.filterable", { initSelector: ":jqmData(filter='true')", options: { filterReveal: false, filterCallback: defaultFilterCallback, enhanced: false, input: null, children: "> li, > option, > optgroup option, > tbody tr, > .ui-controlgroup-controls > .ui-btn, > .ui-controlgroup-controls > .ui-checkbox, > .ui-controlgroup-controls > .ui-radio" }, _create: function() { var opts = this.options; $.extend( this, { _search: null, _timer: 0 }); this._setInput( opts.input ); if ( !opts.enhanced ) { this._filterItems( ( ( this._search && this._search.val() ) || "" ).toLowerCase() ); } }, _onKeyUp: function() { var val, lastval, search = this._search; if ( search ) { val = search.val().toLowerCase(), lastval = $.mobile.getAttribute( search[ 0 ], "lastval" ) + ""; if ( lastval && lastval === val ) { // Execute the handler only once per value change return; } if ( this._timer ) { window.clearTimeout( this._timer ); this._timer = 0; } this._timer = this._delay( function() { this._trigger( "beforefilter", null, { input: search } ); // Change val as lastval for next execution search[ 0 ].setAttribute( "data-" + $.mobile.ns + "lastval", val ); this._filterItems( val ); this._timer = 0; }, 250 ); } }, _getFilterableItems: function() { var elem = this.element, children = this.options.children, items = !children ? { length: 0 }: $.isFunction( children ) ? children(): children.nodeName ? $( children ): children.jquery ? children: this.element.find( children ); if ( items.length === 0 ) { items = elem.children(); } return items; }, _filterItems: function( val ) { var idx, callback, length, dst, show = [], hide = [], opts = this.options, filterItems = this._getFilterableItems(); if ( val != null ) { callback = opts.filterCallback || defaultFilterCallback; length = filterItems.length; // Partition the items into those to be hidden and those to be shown for ( idx = 0 ; idx < length ; idx++ ) { dst = ( callback.call( filterItems[ idx ], idx, val ) ) ? hide : show; dst.push( filterItems[ idx ] ); } } // If nothing is hidden, then the decision whether to hide or show the items // is based on the "filterReveal" option. if ( hide.length === 0 ) { filterItems[ opts.filterReveal ? "addClass" : "removeClass" ]( "ui-screen-hidden" ); } else { $( hide ).addClass( "ui-screen-hidden" ); $( show ).removeClass( "ui-screen-hidden" ); } this._refreshChildWidget(); this._trigger( "filter", null, { items: filterItems }); }, // The Default implementation of _refreshChildWidget attempts to call // refresh on collapsibleset, controlgroup, selectmenu, or listview _refreshChildWidget: function() { var widget, idx, recognizedWidgets = [ "collapsibleset", "selectmenu", "controlgroup", "listview" ]; for ( idx = recognizedWidgets.length - 1 ; idx > -1 ; idx-- ) { widget = recognizedWidgets[ idx ]; if ( $.mobile[ widget ] ) { widget = this.element.data( "mobile-" + widget ); if ( widget && $.isFunction( widget.refresh ) ) { widget.refresh(); } } } }, // TODO: When the input is not internal, do not even store it in this._search _setInput: function ( selector ) { var search = this._search; // Stop a pending filter operation if ( this._timer ) { window.clearTimeout( this._timer ); this._timer = 0; } if ( search ) { this._off( search, "keyup change input" ); search = null; } if ( selector ) { search = selector.jquery ? selector: selector.nodeName ? $( selector ): this.document.find( selector ); this._on( search, { keyup: "_onKeyUp", change: "_onKeyUp", input: "_onKeyUp" }); } this._search = search; }, _setOptions: function( options ) { var refilter = !( ( options.filterReveal === undefined ) && ( options.filterCallback === undefined ) && ( options.children === undefined ) ); this._super( options ); if ( options.input !== undefined ) { this._setInput( options.input ); refilter = true; } if ( refilter ) { this.refresh(); } }, _destroy: function() { var opts = this.options, items = this._getFilterableItems(); if ( opts.enhanced ) { items.toggleClass( "ui-screen-hidden", opts.filterReveal ); } else { items.removeClass( "ui-screen-hidden" ); } }, refresh: function() { if ( this._timer ) { window.clearTimeout( this._timer ); this._timer = 0; } this._filterItems( ( ( this._search && this._search.val() ) || "" ).toLowerCase() ); } }); })( jQuery ); (function( $, undefined ) { // Create a function that will replace the _setOptions function of a widget, // and will pass the options on to the input of the filterable. var replaceSetOptions = function( self, orig ) { return function( options ) { orig.call( this, options ); self._syncTextInputOptions( options ); }; }, rDividerListItem = /(^|\s)ui-li-divider(\s|$)/, origDefaultFilterCallback = $.mobile.filterable.prototype.options.filterCallback; // Override the default filter callback with one that does not hide list dividers $.mobile.filterable.prototype.options.filterCallback = function( index, searchValue ) { return !this.className.match( rDividerListItem ) && origDefaultFilterCallback.call( this, index, searchValue ); }; $.widget( "mobile.filterable", $.mobile.filterable, { options: { filterPlaceholder: "Filter items...", filterTheme: null }, _create: function() { var idx, widgetName, elem = this.element, recognizedWidgets = [ "collapsibleset", "selectmenu", "controlgroup", "listview" ], createHandlers = {}; this._super(); $.extend( this, { _widget: null }); for ( idx = recognizedWidgets.length - 1 ; idx > -1 ; idx-- ) { widgetName = recognizedWidgets[ idx ]; if ( $.mobile[ widgetName ] ) { if ( this._setWidget( elem.data( "mobile-" + widgetName ) ) ) { break; } else { createHandlers[ widgetName + "create" ] = "_handleCreate"; } } } if ( !this._widget ) { this._on( elem, createHandlers ); } }, _handleCreate: function( evt ) { this._setWidget( this.element.data( "mobile-" + evt.type.substring( 0, evt.type.length - 6 ) ) ); }, _trigger: function( type, event, data ) { if ( this._widget && this._widget.widgetFullName === "mobile-listview" && type === "beforefilter" ) { // Also trigger listviewbeforefilter if this widget is also a listview this._widget._trigger( "beforefilter", event, data ); } this._super( type, event, data ); }, _setWidget: function( widget ) { if ( !this._widget && widget ) { this._widget = widget; this._widget._setOptions = replaceSetOptions( this, this._widget._setOptions ); } if ( !!this._widget ) { this._syncTextInputOptions( this._widget.options ); if ( this._widget.widgetName === "listview" ) { this._widget.options.hideDividers = true; this._widget.element.listview( "refresh" ); } } return !!this._widget; }, _isSearchInternal: function() { return ( this._search && this._search.jqmData( "ui-filterable-" + this.uuid + "-internal" ) ); }, _setInput: function( selector ) { var opts = this.options, updatePlaceholder = true, textinputOpts = {}; if ( !selector ) { if ( this._isSearchInternal() ) { // Ignore the call to set a new input if the selector goes to falsy and // the current textinput is already of the internally generated variety. return; } else { // Generating a new textinput widget. No need to set the placeholder // further down the function. updatePlaceholder = false; selector = $( "<input " + "data-" + $.mobile.ns + "type='search' " + "placeholder='" + opts.filterPlaceholder + "'></input>" ) .jqmData( "ui-filterable-" + this.uuid + "-internal", true ); $( "<form class='ui-filterable'></form>" ) .append( selector ) .submit( function( evt ) { evt.preventDefault(); selector.blur(); }) .insertBefore( this.element ); if ( $.mobile.textinput ) { if ( this.options.filterTheme != null ) { textinputOpts[ "theme" ] = opts.filterTheme; } selector.textinput( textinputOpts ); } } } this._super( selector ); if ( this._isSearchInternal() && updatePlaceholder ) { this._search.attr( "placeholder", this.options.filterPlaceholder ); } }, _setOptions: function( options ) { var ret = this._super( options ); // Need to set the filterPlaceholder after having established the search input if ( options.filterPlaceholder !== undefined ) { if ( this._isSearchInternal() ) { this._search.attr( "placeholder", options.filterPlaceholder ); } } if ( options.filterTheme !== undefined && this._search && $.mobile.textinput ) { this._search.textinput( "option", "theme", options.filterTheme ); } return ret; }, _destroy: function() { if ( this._isSearchInternal() ) { this._search.remove(); } this._super(); }, _syncTextInputOptions: function( options ) { var idx, textinputOptions = {}; // We only sync options if the filterable's textinput is of the internally // generated variety, rather than one specified by the user. if ( this._isSearchInternal() && $.mobile.textinput ) { // Apply only the options understood by textinput for ( idx in $.mobile.textinput.prototype.options ) { if ( options[ idx ] !== undefined ) { if ( idx === "theme" && this.options.filterTheme != null ) { textinputOptions[ idx ] = this.options.filterTheme; } else { textinputOptions[ idx ] = options[ idx ]; } } } this._search.textinput( "option", textinputOptions ); } } }); })( jQuery ); /*! * jQuery UI Tabs fadf2b312a05040436451c64bbfaf4814bc62c56 * http://jqueryui.com * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/tabs/ * * Depends: * jquery.ui.core.js * jquery.ui.widget.js */ (function( $, undefined ) { var tabId = 0, rhash = /#.*$/; function getNextTabId() { return ++tabId; } function isLocal( anchor ) { return anchor.hash.length > 1 && decodeURIComponent( anchor.href.replace( rhash, "" ) ) === decodeURIComponent( location.href.replace( rhash, "" ) ); } $.widget( "ui.tabs", { version: "fadf2b312a05040436451c64bbfaf4814bc62c56", delay: 300, options: { active: null, collapsible: false, event: "click", heightStyle: "content", hide: null, show: null, // callbacks activate: null, beforeActivate: null, beforeLoad: null, load: null }, _create: function() { var that = this, options = this.options; this.running = false; this.element .addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" ) .toggleClass( "ui-tabs-collapsible", options.collapsible ) // Prevent users from focusing disabled tabs via click .delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) { if ( $( this ).is( ".ui-state-disabled" ) ) { event.preventDefault(); } }) // support: IE <9 // Preventing the default action in mousedown doesn't prevent IE // from focusing the element, so if the anchor gets focused, blur. // We don't have to worry about focusing the previously focused // element since clicking on a non-focusable element should focus // the body anyway. .delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() { if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) { this.blur(); } }); this._processTabs(); options.active = this._initialActive(); // Take disabling tabs via class attribute from HTML // into account and update option properly. if ( $.isArray( options.disabled ) ) { options.disabled = $.unique( options.disabled.concat( $.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) { return that.tabs.index( li ); }) ) ).sort(); } // check for length avoids error when initializing empty list if ( this.options.active !== false && this.anchors.length ) { this.active = this._findActive( options.active ); } else { this.active = $(); } this._refresh(); if ( this.active.length ) { this.load( options.active ); } }, _initialActive: function() { var active = this.options.active, collapsible = this.options.collapsible, locationHash = location.hash.substring( 1 ); if ( active === null ) { // check the fragment identifier in the URL if ( locationHash ) { this.tabs.each(function( i, tab ) { if ( $( tab ).attr( "aria-controls" ) === locationHash ) { active = i; return false; } }); } // check for a tab marked active via a class if ( active === null ) { active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) ); } // no active tab, set to false if ( active === null || active === -1 ) { active = this.tabs.length ? 0 : false; } } // handle numbers: negative, out of range if ( active !== false ) { active = this.tabs.index( this.tabs.eq( active ) ); if ( active === -1 ) { active = collapsible ? false : 0; } } // don't allow collapsible: false and active: false if ( !collapsible && active === false && this.anchors.length ) { active = 0; } return active; }, _getCreateEventData: function() { return { tab: this.active, panel: !this.active.length ? $() : this._getPanelForTab( this.active ) }; }, _tabKeydown: function( event ) { var focusedTab = $( this.document[0].activeElement ).closest( "li" ), selectedIndex = this.tabs.index( focusedTab ), goingForward = true; if ( this._handlePageNav( event ) ) { return; } switch ( event.keyCode ) { case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: selectedIndex++; break; case $.ui.keyCode.UP: case $.ui.keyCode.LEFT: goingForward = false; selectedIndex--; break; case $.ui.keyCode.END: selectedIndex = this.anchors.length - 1; break; case $.ui.keyCode.HOME: selectedIndex = 0; break; case $.ui.keyCode.SPACE: // Activate only, no collapsing event.preventDefault(); clearTimeout( this.activating ); this._activate( selectedIndex ); return; case $.ui.keyCode.ENTER: // Toggle (cancel delayed activation, allow collapsing) event.preventDefault(); clearTimeout( this.activating ); // Determine if we should collapse or activate this._activate( selectedIndex === this.options.active ? false : selectedIndex ); return; default: return; } // Focus the appropriate tab, based on which key was pressed event.preventDefault(); clearTimeout( this.activating ); selectedIndex = this._focusNextTab( selectedIndex, goingForward ); // Navigating with control key will prevent automatic activation if ( !event.ctrlKey ) { // Update aria-selected immediately so that AT think the tab is already selected. // Otherwise AT may confuse the user by stating that they need to activate the tab, // but the tab will already be activated by the time the announcement finishes. focusedTab.attr( "aria-selected", "false" ); this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" ); this.activating = this._delay(function() { this.option( "active", selectedIndex ); }, this.delay ); } }, _panelKeydown: function( event ) { if ( this._handlePageNav( event ) ) { return; } // Ctrl+up moves focus to the current tab if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) { event.preventDefault(); this.active.focus(); } }, // Alt+page up/down moves focus to the previous/next tab (and activates) _handlePageNav: function( event ) { if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) { this._activate( this._focusNextTab( this.options.active - 1, false ) ); return true; } if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) { this._activate( this._focusNextTab( this.options.active + 1, true ) ); return true; } }, _findNextTab: function( index, goingForward ) { var lastTabIndex = this.tabs.length - 1; function constrain() { if ( index > lastTabIndex ) { index = 0; } if ( index < 0 ) { index = lastTabIndex; } return index; } while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) { index = goingForward ? index + 1 : index - 1; } return index; }, _focusNextTab: function( index, goingForward ) { index = this._findNextTab( index, goingForward ); this.tabs.eq( index ).focus(); return index; }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "disabled" ) { // don't use the widget factory's disabled handling this._setupDisabled( value ); return; } this._super( key, value); if ( key === "collapsible" ) { this.element.toggleClass( "ui-tabs-collapsible", value ); // Setting collapsible: false while collapsed; open first panel if ( !value && this.options.active === false ) { this._activate( 0 ); } } if ( key === "event" ) { this._setupEvents( value ); } if ( key === "heightStyle" ) { this._setupHeightStyle( value ); } }, _tabId: function( tab ) { return tab.attr( "aria-controls" ) || "ui-tabs-" + getNextTabId(); }, _sanitizeSelector: function( hash ) { return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : ""; }, refresh: function() { var options = this.options, lis = this.tablist.children( ":has(a[href])" ); // get disabled tabs from class attribute from HTML // this will get converted to a boolean if needed in _refresh() options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) { return lis.index( tab ); }); this._processTabs(); // was collapsed or no tabs if ( options.active === false || !this.anchors.length ) { options.active = false; this.active = $(); // was active, but active tab is gone } else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) { // all remaining tabs are disabled if ( this.tabs.length === options.disabled.length ) { options.active = false; this.active = $(); // activate previous tab } else { this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) ); } // was active, active tab still exists } else { // make sure active index is correct options.active = this.tabs.index( this.active ); } this._refresh(); }, _refresh: function() { this._setupDisabled( this.options.disabled ); this._setupEvents( this.options.event ); this._setupHeightStyle( this.options.heightStyle ); this.tabs.not( this.active ).attr({ "aria-selected": "false", tabIndex: -1 }); this.panels.not( this._getPanelForTab( this.active ) ) .hide() .attr({ "aria-expanded": "false", "aria-hidden": "true" }); // Make sure one tab is in the tab order if ( !this.active.length ) { this.tabs.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active .addClass( "ui-tabs-active ui-state-active" ) .attr({ "aria-selected": "true", tabIndex: 0 }); this._getPanelForTab( this.active ) .show() .attr({ "aria-expanded": "true", "aria-hidden": "false" }); } }, _processTabs: function() { var that = this; this.tablist = this._getList() .addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .attr( "role", "tablist" ); this.tabs = this.tablist.find( "> li:has(a[href])" ) .addClass( "ui-state-default ui-corner-top" ) .attr({ role: "tab", tabIndex: -1 }); this.anchors = this.tabs.map(function() { return $( "a", this )[ 0 ]; }) .addClass( "ui-tabs-anchor" ) .attr({ role: "presentation", tabIndex: -1 }); this.panels = $(); this.anchors.each(function( i, anchor ) { var selector, panel, panelId, anchorId = $( anchor ).uniqueId().attr( "id" ), tab = $( anchor ).closest( "li" ), originalAriaControls = tab.attr( "aria-controls" ); // inline tab if ( isLocal( anchor ) ) { selector = anchor.hash; panel = that.element.find( that._sanitizeSelector( selector ) ); // remote tab } else { panelId = that._tabId( tab ); selector = "#" + panelId; panel = that.element.find( selector ); if ( !panel.length ) { panel = that._createPanel( panelId ); panel.insertAfter( that.panels[ i - 1 ] || that.tablist ); } panel.attr( "aria-live", "polite" ); } if ( panel.length) { that.panels = that.panels.add( panel ); } if ( originalAriaControls ) { tab.data( "ui-tabs-aria-controls", originalAriaControls ); } tab.attr({ "aria-controls": selector.substring( 1 ), "aria-labelledby": anchorId }); panel.attr( "aria-labelledby", anchorId ); }); this.panels .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .attr( "role", "tabpanel" ); }, // allow overriding how to find the list for rare usage scenarios (#7715) _getList: function() { return this.element.find( "ol,ul" ).eq( 0 ); }, _createPanel: function( id ) { return $( "<div>" ) .attr( "id", id ) .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .data( "ui-tabs-destroy", true ); }, _setupDisabled: function( disabled ) { if ( $.isArray( disabled ) ) { if ( !disabled.length ) { disabled = false; } else if ( disabled.length === this.anchors.length ) { disabled = true; } } // disable tabs for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) { if ( disabled === true || $.inArray( i, disabled ) !== -1 ) { $( li ) .addClass( "ui-state-disabled" ) .attr( "aria-disabled", "true" ); } else { $( li ) .removeClass( "ui-state-disabled" ) .removeAttr( "aria-disabled" ); } } this.options.disabled = disabled; }, _setupEvents: function( event ) { var events = { click: function( event ) { event.preventDefault(); } }; if ( event ) { $.each( event.split(" "), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.anchors.add( this.tabs ).add( this.panels ) ); this._on( this.anchors, events ); this._on( this.tabs, { keydown: "_tabKeydown" } ); this._on( this.panels, { keydown: "_panelKeydown" } ); this._focusable( this.tabs ); this._hoverable( this.tabs ); }, _setupHeightStyle: function( heightStyle ) { var maxHeight, parent = this.element.parent(); if ( heightStyle === "fill" ) { maxHeight = parent.height(); maxHeight -= this.element.outerHeight() - this.element.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); this.element.children().not( this.panels ).each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.panels.each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.panels.each(function() { maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() ); }).height( maxHeight ); } }, _eventHandler: function( event ) { var options = this.options, active = this.active, anchor = $( event.currentTarget ), tab = anchor.closest( "li" ), clickedIsActive = tab[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : this._getPanelForTab( tab ), toHide = !active.length ? $() : this._getPanelForTab( active ), eventData = { oldTab: active, oldPanel: toHide, newTab: collapsing ? $() : tab, newPanel: toShow }; event.preventDefault(); if ( tab.hasClass( "ui-state-disabled" ) || // tab is already loading tab.hasClass( "ui-tabs-loading" ) || // can't switch durning an animation this.running || // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.tabs.index( tab ); this.active = clickedIsActive ? $() : tab; if ( this.xhr ) { this.xhr.abort(); } if ( !toHide.length && !toShow.length ) { $.error( "jQuery UI Tabs: Mismatching fragment identifier." ); } if ( toShow.length ) { this.load( this.tabs.index( tab ), event ); } this._toggle( event, eventData ); }, // handles show/hide for selecting tabs _toggle: function( event, eventData ) { var that = this, toShow = eventData.newPanel, toHide = eventData.oldPanel; this.running = true; function complete() { that.running = false; that._trigger( "activate", event, eventData ); } function show() { eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" ); if ( toShow.length && that.options.show ) { that._show( toShow, that.options.show, complete ); } else { toShow.show(); complete(); } } // start out by hiding, then showing, then completing if ( toHide.length && this.options.hide ) { this._hide( toHide, this.options.hide, function() { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); show(); }); } else { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); toHide.hide(); show(); } toHide.attr({ "aria-expanded": "false", "aria-hidden": "true" }); eventData.oldTab.attr( "aria-selected", "false" ); // If we're switching tabs, remove the old tab from the tab order. // If we're opening from collapsed state, remove the previous tab from the tab order. // If we're collapsing, then keep the collapsing tab in the tab order. if ( toShow.length && toHide.length ) { eventData.oldTab.attr( "tabIndex", -1 ); } else if ( toShow.length ) { this.tabs.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow.attr({ "aria-expanded": "true", "aria-hidden": "false" }); eventData.newTab.attr({ "aria-selected": "true", tabIndex: 0 }); }, _activate: function( index ) { var anchor, active = this._findActive( index ); // trying to activate the already active panel if ( active[ 0 ] === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the current active header if ( !active.length ) { active = this.active; } anchor = active.find( ".ui-tabs-anchor" )[ 0 ]; this._eventHandler({ target: anchor, currentTarget: anchor, preventDefault: $.noop }); }, _findActive: function( index ) { return index === false ? $() : this.tabs.eq( index ); }, _getIndex: function( index ) { // meta-function to give users option to provide a href string instead of a numerical index. if ( typeof index === "string" ) { index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) ); } return index; }, _destroy: function() { if ( this.xhr ) { this.xhr.abort(); } this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" ); this.tablist .removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .removeAttr( "role" ); this.anchors .removeClass( "ui-tabs-anchor" ) .removeAttr( "role" ) .removeAttr( "tabIndex" ) .removeUniqueId(); this.tabs.add( this.panels ).each(function() { if ( $.data( this, "ui-tabs-destroy" ) ) { $( this ).remove(); } else { $( this ) .removeClass( "ui-state-default ui-state-active ui-state-disabled " + "ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" ) .removeAttr( "tabIndex" ) .removeAttr( "aria-live" ) .removeAttr( "aria-busy" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-labelledby" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-expanded" ) .removeAttr( "role" ); } }); this.tabs.each(function() { var li = $( this ), prev = li.data( "ui-tabs-aria-controls" ); if ( prev ) { li .attr( "aria-controls", prev ) .removeData( "ui-tabs-aria-controls" ); } else { li.removeAttr( "aria-controls" ); } }); this.panels.show(); if ( this.options.heightStyle !== "content" ) { this.panels.css( "height", "" ); } }, enable: function( index ) { var disabled = this.options.disabled; if ( disabled === false ) { return; } if ( index === undefined ) { disabled = false; } else { index = this._getIndex( index ); if ( $.isArray( disabled ) ) { disabled = $.map( disabled, function( num ) { return num !== index ? num : null; }); } else { disabled = $.map( this.tabs, function( li, num ) { return num !== index ? num : null; }); } } this._setupDisabled( disabled ); }, disable: function( index ) { var disabled = this.options.disabled; if ( disabled === true ) { return; } if ( index === undefined ) { disabled = true; } else { index = this._getIndex( index ); if ( $.inArray( index, disabled ) !== -1 ) { return; } if ( $.isArray( disabled ) ) { disabled = $.merge( [ index ], disabled ).sort(); } else { disabled = [ index ]; } } this._setupDisabled( disabled ); }, load: function( index, event ) { index = this._getIndex( index ); var that = this, tab = this.tabs.eq( index ), anchor = tab.find( ".ui-tabs-anchor" ), panel = this._getPanelForTab( tab ), eventData = { tab: tab, panel: panel }; // not remote if ( isLocal( anchor[ 0 ] ) ) { return; } this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) ); // support: jQuery <1.8 // jQuery <1.8 returns false if the request is canceled in beforeSend, // but as of 1.8, $.ajax() always returns a jqXHR object. if ( this.xhr && this.xhr.statusText !== "canceled" ) { tab.addClass( "ui-tabs-loading" ); panel.attr( "aria-busy", "true" ); this.xhr .success(function( response ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { panel.html( response ); that._trigger( "load", event, eventData ); }, 1 ); }) .complete(function( jqXHR, status ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { if ( status === "abort" ) { that.panels.stop( false, true ); } tab.removeClass( "ui-tabs-loading" ); panel.removeAttr( "aria-busy" ); if ( jqXHR === that.xhr ) { delete that.xhr; } }, 1 ); }); } }, _ajaxSettings: function( anchor, event, eventData ) { var that = this; return { url: anchor.attr( "href" ), beforeSend: function( jqXHR, settings ) { return that._trigger( "beforeLoad", event, $.extend( { jqXHR : jqXHR, ajaxSettings: settings }, eventData ) ); } }; }, _getPanelForTab: function( tab ) { var id = $( tab ).attr( "aria-controls" ); return this.element.find( this._sanitizeSelector( "#" + id ) ); } }); })( jQuery ); (function( $, undefined ) { })( jQuery ); (function( $, window ) { $.mobile.iosorientationfixEnabled = true; // This fix addresses an iOS bug, so return early if the UA claims it's something else. var ua = navigator.userAgent, zoom, evt, x, y, z, aig; if ( !( /iPhone|iPad|iPod/.test( navigator.platform ) && /OS [1-5]_[0-9_]* like Mac OS X/i.test( ua ) && ua.indexOf( "AppleWebKit" ) > -1 ) ) { $.mobile.iosorientationfixEnabled = false; return; } zoom = $.mobile.zoom; function checkTilt( e ) { evt = e.originalEvent; aig = evt.accelerationIncludingGravity; x = Math.abs( aig.x ); y = Math.abs( aig.y ); z = Math.abs( aig.z ); // If portrait orientation and in one of the danger zones if ( !window.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ) { if ( zoom.enabled ) { zoom.disable(); } } else if ( !zoom.enabled ) { zoom.enable(); } } $.mobile.document.on( "mobileinit", function() { if ( $.mobile.iosorientationfixEnabled ) { $.mobile.window .bind( "orientationchange.iosorientationfix", zoom.enable ) .bind( "devicemotion.iosorientationfix", checkTilt ); } }); }( jQuery, this )); (function( $, window, undefined ) { var $html = $( "html" ), $window = $.mobile.window; //remove initial build class (only present on first pageshow) function hideRenderingClass() { $html.removeClass( "ui-mobile-rendering" ); } // trigger mobileinit event - useful hook for configuring $.mobile settings before they're used $( window.document ).trigger( "mobileinit" ); // support conditions // if device support condition(s) aren't met, leave things as they are -> a basic, usable experience, // otherwise, proceed with the enhancements if ( !$.mobile.gradeA() ) { return; } // override ajaxEnabled on platforms that have known conflicts with hash history updates // or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini) if ( $.mobile.ajaxBlacklist ) { $.mobile.ajaxEnabled = false; } // Add mobile, initial load "rendering" classes to docEl $html.addClass( "ui-mobile ui-mobile-rendering" ); // This is a fallback. If anything goes wrong (JS errors, etc), or events don't fire, // this ensures the rendering class is removed after 5 seconds, so content is visible and accessible setTimeout( hideRenderingClass, 5000 ); $.extend( $.mobile, { // find and enhance the pages in the dom and transition to the first page. initializePage: function() { // find present pages var path = $.mobile.path, $pages = $( ":jqmData(role='page'), :jqmData(role='dialog')" ), hash = path.stripHash( path.stripQueryParams(path.parseLocation().hash) ), hashPage = document.getElementById( hash ); // if no pages are found, create one with body's inner html if ( !$pages.length ) { $pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 ); } // add dialogs, set data-url attrs $pages.each(function() { var $this = $( this ); // unless the data url is already set set it to the pathname if ( !$this[ 0 ].getAttribute( "data-" + $.mobile.ns + "url" ) ) { $this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) || location.pathname + location.search ); } }); // define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback) $.mobile.firstPage = $pages.first(); // define page container $.mobile.pageContainer = $.mobile.firstPage .parent() .addClass( "ui-mobile-viewport" ) .pagecontainer(); // initialize navigation events now, after mobileinit has occurred and the page container // has been created but before the rest of the library is alerted to that fact $.mobile.navreadyDeferred.resolve(); // alert listeners that the pagecontainer has been determined for binding // to events triggered on it $window.trigger( "pagecontainercreate" ); // cue page loading message $.mobile.loading( "show" ); //remove initial build class (only present on first pageshow) hideRenderingClass(); // if hashchange listening is disabled, there's no hash deeplink, // the hash is not valid (contains more than one # or does not start with #) // or there is no page with that hash, change to the first page in the DOM // Remember, however, that the hash can also be a path! if ( ! ( $.mobile.hashListeningEnabled && $.mobile.path.isHashValid( location.hash ) && ( $( hashPage ).is( ":jqmData(role='page')" ) || $.mobile.path.isPath( hash ) || hash === $.mobile.dialogHashKey ) ) ) { // Store the initial destination if ( $.mobile.path.isHashValid( location.hash ) ) { $.mobile.navigate.history.initialDst = hash.replace( "#", "" ); } // make sure to set initial popstate state if it exists // so that navigation back to the initial page works properly if ( $.event.special.navigate.isPushStateEnabled() ) { $.mobile.navigate.navigator.squash( path.parseLocation().href ); } $.mobile.changePage( $.mobile.firstPage, { transition: "none", reverse: true, changeHash: false, fromHashChange: true }); } else { // trigger hashchange or navigate to squash and record the correct // history entry for an initial hash path if ( !$.event.special.navigate.isPushStateEnabled() ) { $window.trigger( "hashchange", [true] ); } else { // TODO figure out how to simplify this interaction with the initial history entry // at the bottom js/navigate/navigate.js $.mobile.navigate.history.stack = []; $.mobile.navigate( $.mobile.path.isPath( location.hash ) ? location.hash : location.href ); } } } }); $(function() { //Run inlineSVG support test $.support.inlineSVG(); // check which scrollTop value should be used by scrolling to 1 immediately at domready // then check what the scroll top is. Android will report 0... others 1 // note that this initial scroll won't hide the address bar. It's just for the check. // hide iOS browser chrome on load if hideUrlBar is true this is to try and do it as soon as possible if ( $.mobile.hideUrlBar ) { window.scrollTo( 0, 1 ); } // if defaultHomeScroll hasn't been set yet, see if scrollTop is 1 // it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar) // so if it's 1, use 0 from now on $.mobile.defaultHomeScroll = ( !$.support.scrollTop || $.mobile.window.scrollTop() === 1 ) ? 0 : 1; //dom-ready inits if ( $.mobile.autoInitializePage ) { $.mobile.initializePage(); } // window load event // hide iOS browser chrome on load if hideUrlBar is true this is as fall back incase we were too early before if ( $.mobile.hideUrlBar ) { $window.load( $.mobile.silentScroll ); } if ( !$.support.cssPointerEvents ) { // IE and Opera don't support CSS pointer-events: none that we use to disable link-based buttons // by adding the 'ui-disabled' class to them. Using a JavaScript workaround for those browser. // https://github.com/jquery/jquery-mobile/issues/3558 // DEPRECATED as of 1.4.0 - remove ui-disabled after 1.4.0 release // only ui-state-disabled should be present thereafter $.mobile.document.delegate( ".ui-state-disabled,.ui-disabled", "vclick", function( e ) { e.preventDefault(); e.stopImmediatePropagation(); } ); } }); }( jQuery, this )); }));
Intro.js
sophiatao/mhacksx
import React from 'react'; import {View, Text, StyleSheet, FlatList, TextInput, TouchableOpacity, Image} from 'react-native'; import { Col, Grid, Row } from "react-native-easy-grid"; export default class Intro extends React.Component { render() { /* Go ahead and delete ExpoConfigView and replace it with your * content, we just wanted to give you a quick view of your config */ return ( <View style={styles.container}> <Text style={styles.header}>Welcome to {"\n"}Walk in the Park.</Text> <Text style={styles.text}>Finding a place to park shouldn't be hard. Take a brake. Let us do it for you.</Text> <TouchableOpacity onPress={this.props.readIntro}><Image source={require('./assets/images/car.png')} style={{alignSelf: 'center'}}/><Text style={styles.button}>Yes, please!</Text></TouchableOpacity> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, paddingLeft: 10, paddingRight: 10, backgroundColor: '#22485e', alignItems: 'center' }, row: { marginBottom: 5, padding: 15, backgroundColor: '#22485e', borderRadius: 10, }, text: { color: 'lightblue', fontFamily: 'Helvetica', fontWeight: '100', fontSize: 18, padding: 18, paddingLeft: 30, paddingRight: 30, textAlign: 'center', }, button: { color: '#fdfdfd', fontFamily: 'Helvetica', fontWeight: '100', fontSize: 14, textAlign: 'center', }, header: { paddingTop: 15, fontSize: 24, marginLeft: 0, backgroundColor: 'transparent', marginTop: 150, color: '#fff', fontFamily: 'Helvetica', fontWeight: '100', textAlign: 'center', }, });
examples/huge-apps/routes/Course/routes/Announcements/components/Announcements.js
dashed/react-router
import React from 'react'; class Announcements extends React.Component { render () { return ( <div> <h3>Announcements</h3> {this.props.children || <p>Choose an announcement from the sidebar.</p>} </div> ); } } export default Announcements;
src/components/login/v1.js
Lokiedu/libertysoil-site
/* This file is a part of libertysoil.org website Copyright (C) 2016 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import PropTypes from 'prop-types'; import React from 'react'; import { Link } from 'react-router'; import ga from '../../external/react-google-analytics'; export default class LoginComponent extends React.Component { static displayName = 'LoginComponent'; static propTypes = { onLoginUser: PropTypes.func.isRequired }; submitHandler = (event) => { event.preventDefault(); this.props.onLoginUser(this.usernameInput.value, this.passwordInput.value).then(() => { ga('send', 'event', 'Login', 'Done'); }); }; render() { return ( <form action="" className="layout__grid layout__grid-responsive layout-align_end layout__space-double" method="post" onSubmit={this.submitHandler}> <div className="layout__grid_item layout__grid_item-identical"> <label className="label label-before_input" htmlFor="loginUsername">User name</label> <div className="input_group"> <span className="input_group__before input_group__before-outside micon micon-extra">person</span> <div className="input_group__input"> <input autoCapitalize="none" autoCorrect="off" className="input input-big input-block" id="loginUsername" name="username" placeholder="Username" ref={(input) => { return this.usernameInput = input; }} required="required" type="text" /> </div> </div> </div> <div className="layout__grid_item layout__grid_item-identical"> <label className="label label-before_input" htmlFor="loginPassword">Password</label> <div className="input_group"> <div className="input_group__input"> <input className="input input-big input-block" id="loginPassword" name="password" placeholder="Password" ref={(input) => { return this.passwordInput = input; }} required="required" type="password" /> </div> <Link className="link input_group__after input_group__after-outside_bottom" to="/resetpassword">Forgot your password?</Link> </div> </div> <div className="layout__grid_item"> <button className="button button-big button-red">Log in</button> </div> </form> ); } }
ajax/libs/Sly/1.3.0/sly.js
keicheng/cdnjs
/*! * sly 1.3.0 - 30th Nov 2014 * https://github.com/darsain/sly * * Licensed under the MIT license. * http://opensource.org/licenses/MIT */ ;(function ($, w, undefined) { 'use strict'; var pluginName = 'sly'; var className = 'Sly'; var namespace = pluginName; // Local WindowAnimationTiming interface var cAF = w.cancelAnimationFrame || w.cancelRequestAnimationFrame; var rAF = w.requestAnimationFrame; // Support indicators var transform, gpuAcceleration; // Other global values var $doc = $(document); var dragInitEvents = 'touchstart.' + namespace + ' mousedown.' + namespace; var dragMouseEvents = 'mousemove.' + namespace + ' mouseup.' + namespace; var dragTouchEvents = 'touchmove.' + namespace + ' touchend.' + namespace; var wheelEvent = (document.implementation.hasFeature('Event.wheel', '3.0') ? 'wheel.' : 'mousewheel.') + namespace; var clickEvent = 'click.' + namespace; var mouseDownEvent = 'mousedown.' + namespace; var interactiveElements = ['INPUT', 'SELECT', 'BUTTON', 'TEXTAREA']; var tmpArray = []; var time; // Math shorthands var abs = Math.abs; var sqrt = Math.sqrt; var pow = Math.pow; var round = Math.round; var max = Math.max; var min = Math.min; // Keep track of last fired global wheel event var lastGlobalWheel = 0; $doc.on(wheelEvent, function () { lastGlobalWheel = +new Date(); }); /** * Sly. * * @class * * @param {Element} frame DOM element of sly container. * @param {Object} options Object with options. * @param {Object} callbackMap Callbacks map. */ function Sly(frame, options, callbackMap) { // Extend options var o = $.extend({}, Sly.defaults, options); // Private variables var self = this; var parallax = isNumber(frame); // Frame var $frame = $(frame); var $slidee = $frame.children().eq(0); var frameSize = 0; var slideeSize = 0; var pos = { start: 0, center: 0, end: 0, cur: 0, dest: 0 }; // Scrollbar var $sb = $(o.scrollBar).eq(0); var $handle = $sb.children().eq(0); var sbSize = 0; var handleSize = 0; var hPos = { start: 0, end: 0, cur: 0 }; // Pagesbar var $pb = $(o.pagesBar); var $pages = 0; var pages = []; // Items var $items = 0; var items = []; var rel = { firstItem: 0, lastItem: 0, centerItem: 0, activeItem: -1, activePage: 0 }; // Styles var frameStyles = new StyleRestorer($frame[0]); var slideeStyles = new StyleRestorer($slidee[0]); var sbStyles = new StyleRestorer($sb[0]); var handleStyles = new StyleRestorer($handle[0]); // Navigation type booleans var basicNav = o.itemNav === 'basic'; var forceCenteredNav = o.itemNav === 'forceCentered'; var centeredNav = o.itemNav === 'centered' || forceCenteredNav; var itemNav = !parallax && (basicNav || centeredNav || forceCenteredNav); // Miscellaneous var $scrollSource = o.scrollSource ? $(o.scrollSource) : $frame; var $dragSource = o.dragSource ? $(o.dragSource) : $frame; var $forwardButton = $(o.forward); var $backwardButton = $(o.backward); var $prevButton = $(o.prev); var $nextButton = $(o.next); var $prevPageButton = $(o.prevPage); var $nextPageButton = $(o.nextPage); var callbacks = {}; var last = {}; var animation = {}; var move = {}; var dragging = { released: 1 }; var scrolling = { last: 0, delta: 0, resetTime: 200 }; var renderID = 0; var historyID = 0; var cycleID = 0; var continuousID = 0; var i, l; // Normalizing frame if (!parallax) { frame = $frame[0]; } // Expose properties self.initialized = 0; self.frame = frame; self.slidee = $slidee[0]; self.pos = pos; self.rel = rel; self.items = items; self.pages = pages; self.isPaused = 0; self.options = o; self.dragging = dragging; /** * (Re)Loading function. * * Populate arrays, set sizes, bind events, ... * * @return {Void} */ function load() { if (!self.initialized) { return; } // Local variables var lastItemsCount = 0; var lastPagesCount = pages.length; // Save old position pos.old = $.extend({}, pos); // Reset global variables frameSize = parallax ? 0 : $frame[o.horizontal ? 'width' : 'height'](); sbSize = $sb[o.horizontal ? 'width' : 'height'](); slideeSize = parallax ? frame : $slidee[o.horizontal ? 'outerWidth' : 'outerHeight'](); pages.length = 0; // Set position limits & relatives pos.start = 0; pos.end = max(slideeSize - frameSize, 0); // Sizes & offsets for item based navigations if (itemNav) { // Save the number of current items lastItemsCount = items.length; // Reset itemNav related variables $items = $slidee.children(o.itemSelector); items.length = 0; // Needed variables var paddingStart = getPx($slidee, o.horizontal ? 'paddingLeft' : 'paddingTop'); var paddingEnd = getPx($slidee, o.horizontal ? 'paddingRight' : 'paddingBottom'); var borderBox = $($items).css('boxSizing') === 'border-box'; var areFloated = $items.css('float') !== 'none'; var ignoredMargin = 0; var lastItemIndex = $items.length - 1; var lastItem; // Reset slideeSize slideeSize = 0; // Iterate through items $items.each(function (i, element) { // Item var $item = $(element); var itemSize = $item[o.horizontal ? 'outerWidth' : 'outerHeight'](); var itemMarginStart = getPx($item, o.horizontal ? 'marginLeft' : 'marginTop'); var itemMarginEnd = getPx($item, o.horizontal ? 'marginRight' : 'marginBottom'); var itemSizeFull = itemSize + itemMarginStart + itemMarginEnd; var singleSpaced = !itemMarginStart || !itemMarginEnd; var item = {}; item.el = element; item.size = singleSpaced ? itemSize : itemSizeFull; item.half = item.size / 2; item.start = slideeSize + (singleSpaced ? itemMarginStart : 0); item.center = item.start - round(frameSize / 2 - item.size / 2); item.end = item.start - frameSize + item.size; // Account for slidee padding if (!i) { slideeSize += paddingStart; } // Increment slidee size for size of the active element slideeSize += itemSizeFull; // Try to account for vertical margin collapsing in vertical mode // It's not bulletproof, but should work in 99% of cases if (!o.horizontal && !areFloated) { // Subtract smaller margin, but only when top margin is not 0, and this is not the first element if (itemMarginEnd && itemMarginStart && i > 0) { slideeSize -= min(itemMarginStart, itemMarginEnd); } } // Things to be done on last item if (i === lastItemIndex) { item.end += paddingEnd; slideeSize += paddingEnd; ignoredMargin = singleSpaced ? itemMarginEnd : 0; } // Add item object to items array items.push(item); lastItem = item; }); // Resize SLIDEE to fit all items $slidee[0].style[o.horizontal ? 'width' : 'height'] = (borderBox ? slideeSize: slideeSize - paddingStart - paddingEnd) + 'px'; // Adjust internal SLIDEE size for last margin slideeSize -= ignoredMargin; // Set limits if (items.length) { pos.start = items[0][forceCenteredNav ? 'center' : 'start']; pos.end = forceCenteredNav ? lastItem.center : frameSize < slideeSize ? lastItem.end : pos.start; } else { pos.start = pos.end = 0; } } // Calculate SLIDEE center position pos.center = round(pos.end / 2 + pos.start / 2); // Update relative positions updateRelatives(); // Scrollbar if ($handle.length && sbSize > 0) { // Stretch scrollbar handle to represent the visible area if (o.dynamicHandle) { handleSize = pos.start === pos.end ? sbSize : round(sbSize * frameSize / slideeSize); handleSize = within(handleSize, o.minHandleSize, sbSize); $handle[0].style[o.horizontal ? 'width' : 'height'] = handleSize + 'px'; } else { handleSize = $handle[o.horizontal ? 'outerWidth' : 'outerHeight'](); } hPos.end = sbSize - handleSize; if (!renderID) { syncScrollbar(); } } // Pages if (!parallax && frameSize > 0) { var tempPagePos = pos.start; var pagesHtml = ''; // Populate pages array if (itemNav) { $.each(items, function (i, item) { if (forceCenteredNav) { pages.push(item.center); } else if (item.start + item.size > tempPagePos && tempPagePos <= pos.end) { tempPagePos = item.start; pages.push(tempPagePos); tempPagePos += frameSize; if (tempPagePos > pos.end && tempPagePos < pos.end + frameSize) { pages.push(pos.end); } } }); } else { while (tempPagePos - frameSize < pos.end) { pages.push(tempPagePos); tempPagePos += frameSize; } } // Pages bar if ($pb[0] && lastPagesCount !== pages.length) { for (var i = 0; i < pages.length; i++) { pagesHtml += o.pageBuilder.call(self, i); } $pages = $pb.html(pagesHtml).children(); $pages.eq(rel.activePage).addClass(o.activeClass); } } // Extend relative variables object with some useful info rel.slideeSize = slideeSize; rel.frameSize = frameSize; rel.sbSize = sbSize; rel.handleSize = handleSize; // Activate requested position if (itemNav) { if (!self.initialized) { activate(o.startAt); self[centeredNav ? 'toCenter' : 'toStart'](o.startAt); } else if (rel.activeItem >= items.length || lastItemsCount === 0 && items.length > 0) { // Activate last item if previous active has been removed, or first item // when there were no items before, and new got appended. activate(rel.activeItem >= items.length ? items.length - 1 : 0, !lastItemsCount); } // Fix possible overflowing var activeItem = items[rel.activeItem]; slideTo(centeredNav && activeItem ? activeItem.center : within(pos.dest, pos.start, pos.end)); } else { if (!self.initialized) { slideTo(o.startAt, 1); } else { // Fix possible overflowing slideTo(within(pos.dest, pos.start, pos.end)); } } // Trigger load event trigger('load'); } self.reload = load; /** * Animate to a position. * * @param {Int} newPos New position. * @param {Bool} immediate Reposition immediately without an animation. * @param {Bool} dontAlign Do not align items, use the raw position passed in first argument. * * @return {Void} */ function slideTo(newPos, immediate, dontAlign) { // Align items if (itemNav && dragging.released && !dontAlign) { var tempRel = getRelatives(newPos); var isNotBordering = newPos > pos.start && newPos < pos.end; if (centeredNav) { if (isNotBordering) { newPos = items[tempRel.centerItem].center; } if (forceCenteredNav && o.activateMiddle) { activate(tempRel.centerItem); } } else if (isNotBordering) { newPos = items[tempRel.firstItem].start; } } // Handle overflowing position limits if (dragging.init && dragging.slidee && o.elasticBounds) { if (newPos > pos.end) { newPos = pos.end + (newPos - pos.end) / 6; } else if (newPos < pos.start) { newPos = pos.start + (newPos - pos.start) / 6; } } else { newPos = within(newPos, pos.start, pos.end); } // Update the animation object animation.start = +new Date(); animation.time = 0; animation.from = pos.cur; animation.to = newPos; animation.delta = newPos - pos.cur; animation.tweesing = dragging.tweese || dragging.init && !dragging.slidee; animation.immediate = !animation.tweesing && (immediate || dragging.init && dragging.slidee || !o.speed); // Reset dragging tweesing request dragging.tweese = 0; // Start animation rendering if (newPos !== pos.dest) { pos.dest = newPos; trigger('change'); if (!renderID) { render(); } } // Reset next cycle timeout resetCycle(); // Synchronize states updateRelatives(); updateButtonsState(); syncPagesbar(); } /** * Render animation frame. * * @return {Void} */ function render() { if (!self.initialized) { return; } // If first render call, wait for next animationFrame if (!renderID) { renderID = rAF(render); if (dragging.released) { trigger('moveStart'); } return; } // If immediate repositioning is requested, don't animate. if (animation.immediate) { pos.cur = animation.to; } // Use tweesing for animations without known end point else if (animation.tweesing) { animation.tweeseDelta = animation.to - pos.cur; // Fuck Zeno's paradox if (abs(animation.tweeseDelta) < 0.1) { pos.cur = animation.to; } else { pos.cur += animation.tweeseDelta * (dragging.released ? o.swingSpeed : o.syncSpeed); } } // Use tweening for basic animations with known end point else { animation.time = min(+new Date() - animation.start, o.speed); pos.cur = animation.from + animation.delta * jQuery.easing[o.easing](animation.time/o.speed, animation.time, 0, 1, o.speed); } // If there is nothing more to render break the rendering loop, otherwise request new animation frame. if (animation.to === pos.cur) { pos.cur = animation.to; dragging.tweese = renderID = 0; } else { renderID = rAF(render); } trigger('move'); // Update SLIDEE position if (!parallax) { if (transform) { $slidee[0].style[transform] = gpuAcceleration + (o.horizontal ? 'translateX' : 'translateY') + '(' + (-pos.cur) + 'px)'; } else { $slidee[0].style[o.horizontal ? 'left' : 'top'] = -round(pos.cur) + 'px'; } } // When animation reached the end, and dragging is not active, trigger moveEnd if (!renderID && dragging.released) { trigger('moveEnd'); } syncScrollbar(); } /** * Synchronizes scrollbar with the SLIDEE. * * @return {Void} */ function syncScrollbar() { if ($handle.length) { hPos.cur = pos.start === pos.end ? 0 : (((dragging.init && !dragging.slidee) ? pos.dest : pos.cur) - pos.start) / (pos.end - pos.start) * hPos.end; hPos.cur = within(round(hPos.cur), hPos.start, hPos.end); if (last.hPos !== hPos.cur) { last.hPos = hPos.cur; if (transform) { $handle[0].style[transform] = gpuAcceleration + (o.horizontal ? 'translateX' : 'translateY') + '(' + hPos.cur + 'px)'; } else { $handle[0].style[o.horizontal ? 'left' : 'top'] = hPos.cur + 'px'; } } } } /** * Synchronizes pagesbar with SLIDEE. * * @return {Void} */ function syncPagesbar() { if ($pages[0] && last.page !== rel.activePage) { last.page = rel.activePage; $pages.removeClass(o.activeClass).eq(rel.activePage).addClass(o.activeClass); trigger('activePage', last.page); } } /** * Returns the position object. * * @param {Mixed} item * * @return {Object} */ self.getPos = function (item) { if (itemNav) { var index = getIndex(item); return index !== -1 ? items[index] : false; } else { var $item = $slidee.find(item).eq(0); if ($item[0]) { var offset = o.horizontal ? $item.offset().left - $slidee.offset().left : $item.offset().top - $slidee.offset().top; var size = $item[o.horizontal ? 'outerWidth' : 'outerHeight'](); return { start: offset, center: offset - frameSize / 2 + size / 2, end: offset - frameSize + size, size: size }; } else { return false; } } }; /** * Continuous move in a specified direction. * * @param {Bool} forward True for forward movement, otherwise it'll go backwards. * @param {Int} speed Movement speed in pixels per frame. Overrides options.moveBy value. * * @return {Void} */ self.moveBy = function (speed) { move.speed = speed; // If already initiated, or there is nowhere to move, abort if (dragging.init || !move.speed || pos.cur === (move.speed > 0 ? pos.end : pos.start)) { return; } // Initiate move object move.lastTime = +new Date(); move.startPos = pos.cur; // Set dragging as initiated continuousInit('button'); dragging.init = 1; // Start movement trigger('moveStart'); cAF(continuousID); moveLoop(); }; /** * Continuous movement loop. * * @return {Void} */ function moveLoop() { // If there is nowhere to move anymore, stop if (!move.speed || pos.cur === (move.speed > 0 ? pos.end : pos.start)) { self.stop(); } // Request new move loop if it hasn't been stopped continuousID = dragging.init ? rAF(moveLoop) : 0; // Update move object move.now = +new Date(); move.pos = pos.cur + (move.now - move.lastTime) / 1000 * move.speed; // Slide slideTo(dragging.init ? move.pos : round(move.pos)); // Normally, this is triggered in render(), but if there // is nothing to render, we have to do it manually here. if (!dragging.init && pos.cur === pos.dest) { trigger('moveEnd'); } // Update times for future iteration move.lastTime = move.now; } /** * Stops continuous movement. * * @return {Void} */ self.stop = function () { if (dragging.source === 'button') { dragging.init = 0; dragging.released = 1; } }; /** * Activate previous item. * * @return {Void} */ self.prev = function () { self.activate(rel.activeItem - 1); }; /** * Activate next item. * * @return {Void} */ self.next = function () { self.activate(rel.activeItem + 1); }; /** * Activate previous page. * * @return {Void} */ self.prevPage = function () { self.activatePage(rel.activePage - 1); }; /** * Activate next page. * * @return {Void} */ self.nextPage = function () { self.activatePage(rel.activePage + 1); }; /** * Slide SLIDEE by amount of pixels. * * @param {Int} delta Pixels/Items. Positive means forward, negative means backward. * @param {Bool} immediate Reposition immediately without an animation. * * @return {Void} */ self.slideBy = function (delta, immediate) { if (!delta) { return; } if (itemNav) { self[centeredNav ? 'toCenter' : 'toStart']( within((centeredNav ? rel.centerItem : rel.firstItem) + o.scrollBy * delta, 0, items.length) ); } else { slideTo(pos.dest + delta, immediate); } }; /** * Animate SLIDEE to a specific position. * * @param {Int} pos New position. * @param {Bool} immediate Reposition immediately without an animation. * * @return {Void} */ self.slideTo = function (pos, immediate) { slideTo(pos, immediate); }; /** * Core method for handling `toLocation` methods. * * @param {String} location * @param {Mixed} item * @param {Bool} immediate * * @return {Void} */ function to(location, item, immediate) { // Optional arguments logic if (type(item) === 'boolean') { immediate = item; item = undefined; } if (item === undefined) { slideTo(pos[location], immediate); } else { // You can't align items to sides of the frame // when centered navigation type is enabled if (centeredNav && location !== 'center') { return; } var itemPos = self.getPos(item); if (itemPos) { slideTo(itemPos[location], immediate, !centeredNav); } } } /** * Animate element or the whole SLIDEE to the start of the frame. * * @param {Mixed} item Item DOM element, or index starting at 0. Omitting will animate SLIDEE. * @param {Bool} immediate Reposition immediately without an animation. * * @return {Void} */ self.toStart = function (item, immediate) { to('start', item, immediate); }; /** * Animate element or the whole SLIDEE to the end of the frame. * * @param {Mixed} item Item DOM element, or index starting at 0. Omitting will animate SLIDEE. * @param {Bool} immediate Reposition immediately without an animation. * * @return {Void} */ self.toEnd = function (item, immediate) { to('end', item, immediate); }; /** * Animate element or the whole SLIDEE to the center of the frame. * * @param {Mixed} item Item DOM element, or index starting at 0. Omitting will animate SLIDEE. * @param {Bool} immediate Reposition immediately without an animation. * * @return {Void} */ self.toCenter = function (item, immediate) { to('center', item, immediate); }; /** * Get the index of an item in SLIDEE. * * @param {Mixed} item Item DOM element. * * @return {Int} Item index, or -1 if not found. */ function getIndex(item) { return item != null ? isNumber(item) ? item >= 0 && item < items.length ? item : -1 : $items.index(item) : -1; } // Expose getIndex without lowering the compressibility of it, // as it is used quite often throughout Sly. self.getIndex = getIndex; /** * Get index of an item in SLIDEE based on a variety of input types. * * @param {Mixed} item DOM element, positive or negative integer. * * @return {Int} Item index, or -1 if not found. */ function getRelativeIndex(item) { return getIndex(isNumber(item) && item < 0 ? item + items.length : item); } /** * Activates an item. * * @param {Mixed} item Item DOM element, or index starting at 0. * * @return {Mixed} Activated item index or false on fail. */ function activate(item, force) { var index = getIndex(item); if (!itemNav || index < 0) { return false; } // Update classes, last active index, and trigger active event only when there // has been a change. Otherwise just return the current active index. if (last.active !== index || force) { // Update classes $items.eq(rel.activeItem).removeClass(o.activeClass); $items.eq(index).addClass(o.activeClass); last.active = rel.activeItem = index; updateButtonsState(); trigger('active', index); } return index; } /** * Activates an item and helps with further navigation when o.smart is enabled. * * @param {Mixed} item Item DOM element, or index starting at 0. * @param {Bool} immediate Whether to reposition immediately in smart navigation. * * @return {Void} */ self.activate = function (item, immediate) { var index = activate(item); // Smart navigation if (o.smart && index !== false) { // When centeredNav is enabled, center the element. // Otherwise, determine where to position the element based on its current position. // If the element is currently on the far end side of the frame, assume that user is // moving forward and animate it to the start of the visible frame, and vice versa. if (centeredNav) { self.toCenter(index, immediate); } else if (index >= rel.lastItem) { self.toStart(index, immediate); } else if (index <= rel.firstItem) { self.toEnd(index, immediate); } else { resetCycle(); } } }; /** * Activates a page. * * @param {Int} index Page index, starting from 0. * @param {Bool} immediate Whether to reposition immediately without animation. * * @return {Void} */ self.activatePage = function (index, immediate) { if (isNumber(index)) { slideTo(pages[within(index, 0, pages.length - 1)], immediate); } }; /** * Return relative positions of items based on their visibility within FRAME. * * @param {Int} slideePos Position of SLIDEE. * * @return {Void} */ function getRelatives(slideePos) { slideePos = within(isNumber(slideePos) ? slideePos : pos.dest, pos.start, pos.end); var relatives = {}; var centerOffset = forceCenteredNav ? 0 : frameSize / 2; // Determine active page if (!parallax) { for (var p = 0, pl = pages.length; p < pl; p++) { if (slideePos >= pos.end || p === pages.length - 1) { relatives.activePage = pages.length - 1; break; } if (slideePos <= pages[p] + centerOffset) { relatives.activePage = p; break; } } } // Relative item indexes if (itemNav) { var first = false; var last = false; var center = false; // From start for (var i = 0, il = items.length; i < il; i++) { // First item if (first === false && slideePos <= items[i].start + items[i].half) { first = i; } // Center item if (center === false && slideePos <= items[i].center + items[i].half) { center = i; } // Last item if (i === il - 1 || slideePos <= items[i].end + items[i].half) { last = i; break; } } // Safe assignment, just to be sure the false won't be returned relatives.firstItem = isNumber(first) ? first : 0; relatives.centerItem = isNumber(center) ? center : relatives.firstItem; relatives.lastItem = isNumber(last) ? last : relatives.centerItem; } return relatives; } /** * Update object with relative positions. * * @param {Int} newPos * * @return {Void} */ function updateRelatives(newPos) { $.extend(rel, getRelatives(newPos)); } /** * Disable navigation buttons when needed. * * Adds disabledClass, and when the button is <button> or <input>, activates :disabled state. * * @return {Void} */ function updateButtonsState() { var isStart = pos.dest <= pos.start; var isEnd = pos.dest >= pos.end; var slideePosState = isStart ? 1 : isEnd ? 2 : 3; // Update paging buttons only if there has been a change in SLIDEE position if (last.slideePosState !== slideePosState) { last.slideePosState = slideePosState; if ($prevPageButton.is('button,input')) { $prevPageButton.prop('disabled', isStart); } if ($nextPageButton.is('button,input')) { $nextPageButton.prop('disabled', isEnd); } $prevPageButton.add($backwardButton)[isStart ? 'addClass' : 'removeClass'](o.disabledClass); $nextPageButton.add($forwardButton)[isEnd ? 'addClass' : 'removeClass'](o.disabledClass); } // Forward & Backward buttons need a separate state caching because we cannot "property disable" // them while they are being used, as disabled buttons stop emitting mouse events. if (last.fwdbwdState !== slideePosState && dragging.released) { last.fwdbwdState = slideePosState; if ($backwardButton.is('button,input')) { $backwardButton.prop('disabled', isStart); } if ($forwardButton.is('button,input')) { $forwardButton.prop('disabled', isEnd); } } // Item navigation if (itemNav) { var isFirst = rel.activeItem === 0; var isLast = rel.activeItem >= items.length - 1; var itemsButtonState = isFirst ? 1 : isLast ? 2 : 3; if (last.itemsButtonState !== itemsButtonState) { last.itemsButtonState = itemsButtonState; if ($prevButton.is('button,input')) { $prevButton.prop('disabled', isFirst); } if ($nextButton.is('button,input')) { $nextButton.prop('disabled', isLast); } $prevButton[isFirst ? 'addClass' : 'removeClass'](o.disabledClass); $nextButton[isLast ? 'addClass' : 'removeClass'](o.disabledClass); } } } /** * Resume cycling. * * @param {Int} priority Resume pause with priority lower or equal than this. Used internally for pauseOnHover. * * @return {Void} */ self.resume = function (priority) { if (!o.cycleBy || !o.cycleInterval || o.cycleBy === 'items' && !items[0] || priority < self.isPaused) { return; } self.isPaused = 0; if (cycleID) { cycleID = clearTimeout(cycleID); } else { trigger('resume'); } cycleID = setTimeout(function () { trigger('cycle'); switch (o.cycleBy) { case 'items': self.activate(rel.activeItem >= items.length - 1 ? 0 : rel.activeItem + 1); break; case 'pages': self.activatePage(rel.activePage >= pages.length - 1 ? 0 : rel.activePage + 1); break; } }, o.cycleInterval); }; /** * Pause cycling. * * @param {Int} priority Pause priority. 100 is default. Used internally for pauseOnHover. * * @return {Void} */ self.pause = function (priority) { if (priority < self.isPaused) { return; } self.isPaused = priority || 100; if (cycleID) { cycleID = clearTimeout(cycleID); trigger('pause'); } }; /** * Toggle cycling. * * @return {Void} */ self.toggle = function () { self[cycleID ? 'pause' : 'resume'](); }; /** * Updates a signle or multiple option values. * * @param {Mixed} name Name of the option that should be updated, or object that will extend the options. * @param {Mixed} value New option value. * * @return {Void} */ self.set = function (name, value) { if ($.isPlainObject(name)) { $.extend(o, name); } else if (o.hasOwnProperty(name)) { o[name] = value; } }; /** * Add one or multiple items to the SLIDEE end, or a specified position index. * * @param {Mixed} element Node element, or HTML string. * @param {Int} index Index of a new item position. By default item is appended at the end. * * @return {Void} */ self.add = function (element, index) { var $element = $(element); if (itemNav) { // Insert the element(s) if (index == null || !items[0] || index >= items.length) { $element.appendTo($slidee); } else if (items.length) { $element.insertBefore(items[index].el); } // Adjust the activeItem index if (index <= rel.activeItem) { last.active = rel.activeItem += $element.length; } } else { $slidee.append($element); } // Reload load(); }; /** * Remove an item from SLIDEE. * * @param {Mixed} element Item index, or DOM element. * @param {Int} index Index of a new item position. By default item is appended at the end. * * @return {Void} */ self.remove = function (element) { if (itemNav) { var index = getRelativeIndex(element); if (index > -1) { // Remove the element $items.eq(index).remove(); // If the current item is being removed, activate new one after reload var reactivate = index === rel.activeItem; // Adjust the activeItem index if (index < rel.activeItem) { last.active = --rel.activeItem; } // Reload load(); // Activate new item at the removed position if (reactivate) { last.active = null; self.activate(rel.activeItem); } } } else { $(element).remove(); load(); } }; /** * Helps re-arranging items. * * @param {Mixed} item Item DOM element, or index starting at 0. Use negative numbers to select items from the end. * @param {Mixed} position Item insertion anchor. Accepts same input types as item argument. * @param {Bool} after Insert after instead of before the anchor. * * @return {Void} */ function moveItem(item, position, after) { item = getRelativeIndex(item); position = getRelativeIndex(position); // Move only if there is an actual change requested if (item > -1 && position > -1 && item !== position && (!after || position !== item - 1) && (after || position !== item + 1)) { $items.eq(item)[after ? 'insertAfter' : 'insertBefore'](items[position].el); var shiftStart = item < position ? item : (after ? position : position - 1); var shiftEnd = item > position ? item : (after ? position + 1 : position); var shiftsUp = item > position; // Update activeItem index if (item === rel.activeItem) { last.active = rel.activeItem = after ? (shiftsUp ? position + 1 : position) : (shiftsUp ? position : position - 1); } else if (rel.activeItem > shiftStart && rel.activeItem < shiftEnd) { last.active = rel.activeItem += shiftsUp ? 1 : -1; } // Reload load(); } } /** * Move item after the target anchor. * * @param {Mixed} item Item to be moved. Can be DOM element or item index. * @param {Mixed} position Target position anchor. Can be DOM element or item index. * * @return {Void} */ self.moveAfter = function (item, position) { moveItem(item, position, 1); }; /** * Move item before the target anchor. * * @param {Mixed} item Item to be moved. Can be DOM element or item index. * @param {Mixed} position Target position anchor. Can be DOM element or item index. * * @return {Void} */ self.moveBefore = function (item, position) { moveItem(item, position); }; /** * Registers callbacks. * * @param {Mixed} name Event name, or callbacks map. * @param {Mixed} fn Callback, or an array of callback functions. * * @return {Void} */ self.on = function (name, fn) { // Callbacks map if (type(name) === 'object') { for (var key in name) { if (name.hasOwnProperty(key)) { self.on(key, name[key]); } } // Callback } else if (type(fn) === 'function') { var names = name.split(' '); for (var n = 0, nl = names.length; n < nl; n++) { callbacks[names[n]] = callbacks[names[n]] || []; if (callbackIndex(names[n], fn) === -1) { callbacks[names[n]].push(fn); } } // Callbacks array } else if (type(fn) === 'array') { for (var f = 0, fl = fn.length; f < fl; f++) { self.on(name, fn[f]); } } }; /** * Registers callbacks to be executed only once. * * @param {Mixed} name Event name, or callbacks map. * @param {Mixed} fn Callback, or an array of callback functions. * * @return {Void} */ self.one = function (name, fn) { function proxy() { fn.apply(self, arguments); self.off(name, proxy); } self.on(name, proxy); }; /** * Remove one or all callbacks. * * @param {String} name Event name. * @param {Mixed} fn Callback, or an array of callback functions. Omit to remove all callbacks. * * @return {Void} */ self.off = function (name, fn) { if (fn instanceof Array) { for (var f = 0, fl = fn.length; f < fl; f++) { self.off(name, fn[f]); } } else { var names = name.split(' '); for (var n = 0, nl = names.length; n < nl; n++) { callbacks[names[n]] = callbacks[names[n]] || []; if (fn == null) { callbacks[names[n]].length = 0; } else { var index = callbackIndex(names[n], fn); if (index !== -1) { callbacks[names[n]].splice(index, 1); } } } } }; /** * Returns callback array index. * * @param {String} name Event name. * @param {Function} fn Function * * @return {Int} Callback array index, or -1 if isn't registered. */ function callbackIndex(name, fn) { for (var i = 0, l = callbacks[name].length; i < l; i++) { if (callbacks[name][i] === fn) { return i; } } return -1; } /** * Reset next cycle timeout. * * @return {Void} */ function resetCycle() { if (dragging.released && !self.isPaused) { self.resume(); } } /** * Calculate SLIDEE representation of handle position. * * @param {Int} handlePos * * @return {Int} */ function handleToSlidee(handlePos) { return round(within(handlePos, hPos.start, hPos.end) / hPos.end * (pos.end - pos.start)) + pos.start; } /** * Keeps track of a dragging delta history. * * @return {Void} */ function draggingHistoryTick() { // Looking at this, I know what you're thinking :) But as we need only 4 history states, doing it this way // as opposed to a proper loop is ~25 bytes smaller (when minified with GCC), a lot faster, and doesn't // generate garbage. The loop version would create 2 new variables on every tick. Unexaptable! dragging.history[0] = dragging.history[1]; dragging.history[1] = dragging.history[2]; dragging.history[2] = dragging.history[3]; dragging.history[3] = dragging.delta; } /** * Initialize continuous movement. * * @return {Void} */ function continuousInit(source) { dragging.released = 0; dragging.source = source; dragging.slidee = source === 'slidee'; } /** * Dragging initiator. * * @param {Event} event * * @return {Void} */ function dragInit(event) { var isTouch = event.type === 'touchstart'; var source = event.data.source; var isSlidee = source === 'slidee'; // Ignore when already in progress, or interactive element in non-touch navivagion if (dragging.init || !isTouch && isInteractive(event.target)) { return; } // Handle dragging conditions if (source === 'handle' && (!o.dragHandle || hPos.start === hPos.end)) { return; } // SLIDEE dragging conditions if (isSlidee && !(isTouch ? o.touchDragging : o.mouseDragging && event.which < 2)) { return; } if (!isTouch) { // prevents native image dragging in Firefox stopDefault(event); } // Reset dragging object continuousInit(source); // Properties used in dragHandler dragging.init = 0; dragging.$source = $(event.target); dragging.touch = isTouch; dragging.pointer = isTouch ? event.originalEvent.touches[0] : event; dragging.initX = dragging.pointer.pageX; dragging.initY = dragging.pointer.pageY; dragging.initPos = isSlidee ? pos.cur : hPos.cur; dragging.start = +new Date(); dragging.time = 0; dragging.path = 0; dragging.delta = 0; dragging.locked = 0; dragging.history = [0, 0, 0, 0]; dragging.pathToLock = isSlidee ? isTouch ? 30 : 10 : 0; // Bind dragging events $doc.on(isTouch ? dragTouchEvents : dragMouseEvents, dragHandler); // Pause ongoing cycle self.pause(1); // Add dragging class (isSlidee ? $slidee : $handle).addClass(o.draggedClass); // Trigger moveStart event trigger('moveStart'); // Keep track of a dragging path history. This is later used in the // dragging release swing calculation when dragging SLIDEE. if (isSlidee) { historyID = setInterval(draggingHistoryTick, 10); } } /** * Handler for dragging scrollbar handle or SLIDEE. * * @param {Event} event * * @return {Void} */ function dragHandler(event) { dragging.released = event.type === 'mouseup' || event.type === 'touchend'; dragging.pointer = dragging.touch ? event.originalEvent[dragging.released ? 'changedTouches' : 'touches'][0] : event; dragging.pathX = dragging.pointer.pageX - dragging.initX; dragging.pathY = dragging.pointer.pageY - dragging.initY; dragging.path = sqrt(pow(dragging.pathX, 2) + pow(dragging.pathY, 2)); dragging.delta = o.horizontal ? dragging.pathX : dragging.pathY; if (!dragging.init) { if (o.horizontal ? abs(dragging.pathX) > abs(dragging.pathY) : abs(dragging.pathX) < abs(dragging.pathY)) { dragging.init = 1; } else { return dragEnd(); } } stopDefault(event); // Disable click on a source element, as it is unwelcome when dragging if (!dragging.locked && dragging.path > dragging.pathToLock && dragging.slidee) { dragging.locked = 1; dragging.$source.on(clickEvent, disableOneEvent); } // Cancel dragging on release if (dragging.released) { dragEnd(); // Adjust path with a swing on mouse release if (o.releaseSwing && dragging.slidee) { dragging.swing = (dragging.delta - dragging.history[0]) / 40 * 300; dragging.delta += dragging.swing; dragging.tweese = abs(dragging.swing) > 10; } } slideTo(dragging.slidee ? round(dragging.initPos - dragging.delta) : handleToSlidee(dragging.initPos + dragging.delta)); } /** * Stops dragging and cleans up after it. * * @return {Void} */ function dragEnd() { clearInterval(historyID); $doc.off(dragging.touch ? dragTouchEvents : dragMouseEvents, dragHandler); (dragging.slidee ? $slidee : $handle).removeClass(o.draggedClass); // Make sure that disableOneEvent is not active in next tick. setTimeout(function () { dragging.$source.off(clickEvent, disableOneEvent); }); // Resume ongoing cycle self.resume(1); // Normally, this is triggered in render(), but if there // is nothing to render, we have to do it manually here. if (pos.cur === pos.dest && dragging.init) { trigger('moveEnd'); } dragging.init = 0; } /** * Check whether element is interactive. * * @return {Boolean} */ function isInteractive(element) { return ~$.inArray(element.nodeName, interactiveElements) || $(element).is(o.interactive); } /** * Continuous movement cleanup on mouseup. * * @return {Void} */ function movementReleaseHandler() { self.stop(); $doc.off('mouseup', movementReleaseHandler); } /** * Buttons navigation handler. * * @param {Event} event * * @return {Void} */ function buttonsHandler(event) { /*jshint validthis:true */ stopDefault(event); switch (this) { case $forwardButton[0]: case $backwardButton[0]: self.moveBy($forwardButton.is(this) ? o.moveBy : -o.moveBy); $doc.on('mouseup', movementReleaseHandler); break; case $prevButton[0]: self.prev(); break; case $nextButton[0]: self.next(); break; case $prevPageButton[0]: self.prevPage(); break; case $nextPageButton[0]: self.nextPage(); break; } } /** * Mouse wheel delta normalization. * * @param {Event} event * * @return {Int} */ function normalizeWheelDelta(event) { // wheelDelta needed only for IE8- scrolling.curDelta = ((o.horizontal ? event.deltaY || event.deltaX : event.deltaY) || -event.wheelDelta); scrolling.curDelta /= event.deltaMode === 1 ? 3 : 100; if (!itemNav) { return scrolling.curDelta; } time = +new Date(); if (scrolling.last < time - scrolling.resetTime) { scrolling.delta = 0; } scrolling.last = time; scrolling.delta += scrolling.curDelta; if (abs(scrolling.delta) < 1) { scrolling.finalDelta = 0; } else { scrolling.finalDelta = round(scrolling.delta / 1); scrolling.delta %= 1; } return scrolling.finalDelta; } /** * Mouse scrolling handler. * * @param {Event} event * * @return {Void} */ function scrollHandler(event) { // Don't hijack global scrolling var time = +new Date(); if (lastGlobalWheel + 300 > time) { lastGlobalWheel = time; return; } // Ignore if there is no scrolling to be done if (!o.scrollBy || pos.start === pos.end) { return; } var delta = normalizeWheelDelta(event.originalEvent); // Trap scrolling only when necessary and/or requested if (o.scrollTrap || delta > 0 && pos.dest < pos.end || delta < 0 && pos.dest > pos.start) { stopDefault(event, 1); } self.slideBy(o.scrollBy * delta); } /** * Scrollbar click handler. * * @param {Event} event * * @return {Void} */ function scrollbarHandler(event) { // Only clicks on scroll bar. Ignore the handle. if (o.clickBar && event.target === $sb[0]) { stopDefault(event); // Calculate new handle position and sync SLIDEE to it slideTo(handleToSlidee((o.horizontal ? event.pageX - $sb.offset().left : event.pageY - $sb.offset().top) - handleSize / 2)); } } /** * Keyboard input handler. * * @param {Event} event * * @return {Void} */ function keyboardHandler(event) { if (!o.keyboardNavBy) { return; } switch (event.which) { // Left or Up case o.horizontal ? 37 : 38: stopDefault(event); self[o.keyboardNavBy === 'pages' ? 'prevPage' : 'prev'](); break; // Right or Down case o.horizontal ? 39 : 40: stopDefault(event); self[o.keyboardNavBy === 'pages' ? 'nextPage' : 'next'](); break; } } /** * Click on item activation handler. * * @param {Event} event * * @return {Void} */ function activateHandler(event) { /*jshint validthis:true */ // Ignore clicks on interactive elements. if (isInteractive(this)) { event.stopPropagation(); return; } // Accept only events from direct SLIDEE children. if (this.parentNode === $slidee[0]) { self.activate(this); } } /** * Click on page button handler. * * @param {Event} event * * @return {Void} */ function activatePageHandler() { /*jshint validthis:true */ // Accept only events from direct pages bar children. if (this.parentNode === $pb[0]) { self.activatePage($pages.index(this)); } } /** * Pause on hover handler. * * @param {Event} event * * @return {Void} */ function pauseOnHoverHandler(event) { if (o.pauseOnHover) { self[event.type === 'mouseenter' ? 'pause' : 'resume'](2); } } /** * Trigger callbacks for event. * * @param {String} name Event name. * @param {Mixed} argX Arguments passed to callbacks. * * @return {Void} */ function trigger(name, arg1) { if (callbacks[name]) { l = callbacks[name].length; // Callbacks will be stored and executed from a temporary array to not // break the execution queue when one of the callbacks unbinds itself. tmpArray.length = 0; for (i = 0; i < l; i++) { tmpArray.push(callbacks[name][i]); } // Execute the callbacks for (i = 0; i < l; i++) { tmpArray[i].call(self, name, arg1); } } } /** * Destroys instance and everything it created. * * @return {Void} */ self.destroy = function () { // Unbind all events $doc .add($scrollSource) .add($handle) .add($sb) .add($pb) .add($forwardButton) .add($backwardButton) .add($prevButton) .add($nextButton) .add($prevPageButton) .add($nextPageButton) .unbind('.' + namespace); // Remove classes $prevButton .add($nextButton) .add($prevPageButton) .add($nextPageButton) .removeClass(o.disabledClass); if ($items) { $items.eq(rel.activeItem).removeClass(o.activeClass); } // Remove page items $pb.empty(); if (!parallax) { // Unbind events from frame $frame.unbind('.' + namespace); // Restore original styles frameStyles.restore(); slideeStyles.restore(); sbStyles.restore(); handleStyles.restore(); // Remove the instance from element data storage $.removeData(frame, namespace); } // Clean up collections items.length = pages.length = 0; last = {}; // Reset initialized status and return the instance self.initialized = 0; return self; }; /** * Initialize. * * @return {Object} */ self.init = function () { if (self.initialized) { return; } // Register callbacks map self.on(callbackMap); // Save styles var holderProps = ['overflow', 'position']; var movableProps = ['position', 'webkitTransform', 'msTransform', 'transform', 'left', 'top', 'width', 'height']; frameStyles.save.apply(frameStyles, holderProps); sbStyles.save.apply(sbStyles, holderProps); slideeStyles.save.apply(slideeStyles, movableProps); handleStyles.save.apply(handleStyles, movableProps); // Set required styles var $movables = $handle; if (!parallax) { $movables = $movables.add($slidee); $frame.css('overflow', 'hidden'); if (!transform && $frame.css('position') === 'static') { $frame.css('position', 'relative'); } } if (transform) { if (gpuAcceleration) { $movables.css(transform, gpuAcceleration); } } else { if ($sb.css('position') === 'static') { $sb.css('position', 'relative'); } $movables.css({ position: 'absolute' }); } // Navigation buttons if (o.forward) { $forwardButton.on(mouseDownEvent, buttonsHandler); } if (o.backward) { $backwardButton.on(mouseDownEvent, buttonsHandler); } if (o.prev) { $prevButton.on(clickEvent, buttonsHandler); } if (o.next) { $nextButton.on(clickEvent, buttonsHandler); } if (o.prevPage) { $prevPageButton.on(clickEvent, buttonsHandler); } if (o.nextPage) { $nextPageButton.on(clickEvent, buttonsHandler); } // Scrolling navigation $scrollSource.on(wheelEvent, scrollHandler); // Clicking on scrollbar navigation if ($sb[0]) { $sb.on(clickEvent, scrollbarHandler); } // Click on items navigation if (itemNav && o.activateOn) { $frame.on(o.activateOn + '.' + namespace, '*', activateHandler); } // Pages navigation if ($pb[0] && o.activatePageOn) { $pb.on(o.activatePageOn + '.' + namespace, '*', activatePageHandler); } // Dragging navigation $dragSource.on(dragInitEvents, { source: 'slidee' }, dragInit); // Scrollbar dragging navigation if ($handle) { $handle.on(dragInitEvents, { source: 'handle' }, dragInit); } // Keyboard navigation $doc.bind('keydown.' + namespace, keyboardHandler); if (!parallax) { // Pause on hover $frame.on('mouseenter.' + namespace + ' mouseleave.' + namespace, pauseOnHoverHandler); // Reset native FRAME element scroll $frame.on('scroll.' + namespace, resetScroll); } // Mark instance as initialized self.initialized = 1; // Load load(); // Initiate automatic cycling if (o.cycleBy && !parallax) { self[o.startPaused ? 'pause' : 'resume'](); } // Return instance return self; }; } /** * Return type of the value. * * @param {Mixed} value * * @return {String} */ function type(value) { if (value == null) { return String(value); } if (typeof value === 'object' || typeof value === 'function') { return Object.prototype.toString.call(value).match(/\s([a-z]+)/i)[1].toLowerCase() || 'object'; } return typeof value; } /** * Event preventDefault & stopPropagation helper. * * @param {Event} event Event object. * @param {Bool} noBubbles Cancel event bubbling. * * @return {Void} */ function stopDefault(event, noBubbles) { event.preventDefault(); if (noBubbles) { event.stopPropagation(); } } /** * Disables an event it was triggered on and unbinds itself. * * @param {Event} event * * @return {Void} */ function disableOneEvent(event) { /*jshint validthis:true */ stopDefault(event, 1); $(this).off(event.type, disableOneEvent); } /** * Resets native element scroll values to 0. * * @return {Void} */ function resetScroll() { /*jshint validthis:true */ this.scrollLeft = 0; this.scrollTop = 0; } /** * Check if variable is a number. * * @param {Mixed} value * * @return {Boolean} */ function isNumber(value) { return !isNaN(parseFloat(value)) && isFinite(value); } /** * Parse style to pixels. * * @param {Object} $item jQuery object with element. * @param {Property} property CSS property to get the pixels from. * * @return {Int} */ function getPx($item, property) { return 0 | round(String($item.css(property)).replace(/[^\-0-9.]/g, '')); } /** * Make sure that number is within the limits. * * @param {Number} number * @param {Number} min * @param {Number} max * * @return {Number} */ function within(number, min, max) { return number < min ? min : number > max ? max : number; } /** * Saves element styles for later restoration. * * Example: * var styles = new StyleRestorer(frame); * styles.save('position'); * element.style.position = 'absolute'; * styles.restore(); // restores to state before the assignment above * * @param {Element} element */ function StyleRestorer(element) { var self = {}; self.style = {}; self.save = function () { if (!element) return; for (var i = 0; i < arguments.length; i++) { self.style[arguments[i]] = element.style[arguments[i]]; } return self; }; self.restore = function () { if (!element) return; for (var prop in self.style) { if (self.style.hasOwnProperty(prop)) element.style[prop] = self.style[prop]; } return self; }; return self; } // Local WindowAnimationTiming interface polyfill (function (w) { rAF = w.requestAnimationFrame || w.webkitRequestAnimationFrame || fallback; /** * Fallback implementation. */ var prev = new Date().getTime(); function fallback(fn) { var curr = new Date().getTime(); var ms = Math.max(0, 16 - (curr - prev)); var req = setTimeout(fn, ms); prev = curr; return req; } /** * Cancel. */ var cancel = w.cancelAnimationFrame || w.webkitCancelAnimationFrame || w.clearTimeout; cAF = function(id){ cancel.call(w, id); }; }(window)); // Feature detects (function () { var prefixes = ['', 'webkit', 'moz', 'ms', 'o']; var el = document.createElement('div'); function testProp(prop) { for (var p = 0, pl = prefixes.length; p < pl; p++) { var prefixedProp = prefixes[p] ? prefixes[p] + prop.charAt(0).toUpperCase() + prop.slice(1) : prop; if (el.style[prefixedProp] != null) { return prefixedProp; } } } // Global support indicators transform = testProp('transform'); gpuAcceleration = testProp('perspective') ? 'translateZ(0) ' : ''; }()); // Expose class globally w[className] = Sly; // jQuery proxy $.fn[pluginName] = function (options, callbackMap) { var method, methodArgs; // Attributes logic if (!$.isPlainObject(options)) { if (type(options) === 'string' || options === false) { method = options === false ? 'destroy' : options; methodArgs = Array.prototype.slice.call(arguments, 1); } options = {}; } // Apply to all elements return this.each(function (i, element) { // Call with prevention against multiple instantiations var plugin = $.data(element, namespace); if (!plugin && !method) { // Create a new object if it doesn't exist yet plugin = $.data(element, namespace, new Sly(element, options, callbackMap).init()); } else if (plugin && method) { // Call method if (plugin[method]) { plugin[method].apply(plugin, methodArgs); } } }); }; // Default options Sly.defaults = { horizontal: false, // Switch to horizontal mode. // Item based navigation itemNav: null, // Item navigation type. Can be: 'basic', 'centered', 'forceCentered'. itemSelector: null, // Select only items that match this selector. smart: false, // Repositions the activated item to help with further navigation. activateOn: null, // Activate an item on this event. Can be: 'click', 'mouseenter', ... activateMiddle: false, // Always activate the item in the middle of the FRAME. forceCentered only. // Scrolling scrollSource: null, // Element for catching the mouse wheel scrolling. Default is FRAME. scrollBy: 0, // Pixels or items to move per one mouse scroll. 0 to disable scrolling. scrollHijack: 300, // Milliseconds since last wheel event after which it is acceptable to hijack global scroll. scrollTrap: false, // Don't bubble scrolling when hitting scrolling limits. // Dragging dragSource: null, // Selector or DOM element for catching dragging events. Default is FRAME. mouseDragging: false, // Enable navigation by dragging the SLIDEE with mouse cursor. touchDragging: false, // Enable navigation by dragging the SLIDEE with touch events. releaseSwing: false, // Ease out on dragging swing release. swingSpeed: 0.2, // Swing synchronization speed, where: 1 = instant, 0 = infinite. elasticBounds: false, // Stretch SLIDEE position limits when dragging past FRAME boundaries. interactive: null, // Selector for special interactive elements. // Scrollbar scrollBar: null, // Selector or DOM element for scrollbar container. dragHandle: false, // Whether the scrollbar handle should be draggable. dynamicHandle: false, // Scrollbar handle represents the ratio between hidden and visible content. minHandleSize: 50, // Minimal height or width (depends on sly direction) of a handle in pixels. clickBar: false, // Enable navigation by clicking on scrollbar. syncSpeed: 0.5, // Handle => SLIDEE synchronization speed, where: 1 = instant, 0 = infinite. // Pagesbar pagesBar: null, // Selector or DOM element for pages bar container. activatePageOn: null, // Event used to activate page. Can be: click, mouseenter, ... pageBuilder: // Page item generator. function (index) { return '<li>' + (index + 1) + '</li>'; }, // Navigation buttons forward: null, // Selector or DOM element for "forward movement" button. backward: null, // Selector or DOM element for "backward movement" button. prev: null, // Selector or DOM element for "previous item" button. next: null, // Selector or DOM element for "next item" button. prevPage: null, // Selector or DOM element for "previous page" button. nextPage: null, // Selector or DOM element for "next page" button. // Automated cycling cycleBy: null, // Enable automatic cycling by 'items' or 'pages'. cycleInterval: 5000, // Delay between cycles in milliseconds. pauseOnHover: false, // Pause cycling when mouse hovers over the FRAME. startPaused: false, // Whether to start in paused sate. // Mixed options moveBy: 300, // Speed in pixels per second used by forward and backward buttons. speed: 0, // Animations speed in milliseconds. 0 to disable animations. easing: 'swing', // Easing for duration based (tweening) animations. startAt: 0, // Starting offset in pixels or items. keyboardNavBy: null, // Enable keyboard navigation by 'items' or 'pages'. // Classes draggedClass: 'dragged', // Class for dragged elements (like SLIDEE or scrollbar handle). activeClass: 'active', // Class for active items and pages. disabledClass: 'disabled' // Class for disabled navigation elements. }; }(jQuery, window));
ajax/libs/golden-layout/1.5.0/goldenlayout.js
wout/cdnjs
(function($){var lm={"config":{},"container":{},"errors":{},"controls":{},"items":{},"utils":{}}; lm.utils.F = function () {}; lm.utils.extend = function( subClass, superClass ) { subClass.prototype = lm.utils.createObject( superClass.prototype ); subClass.prototype.contructor = subClass; }; lm.utils.createObject = function( prototype ) { if( typeof Object.create === 'function' ) { return Object.create( prototype ); } else { lm.utils.F.prototype = prototype; return new lm.utils.F(); } }; lm.utils.objectKeys = function( object ) { var keys, key; if( typeof Object.keys === 'function' ) { return Object.keys( object ); } else { keys = []; for( key in object ) { keys.push( key ); } return keys; } }; lm.utils.getQueryStringParam = function( param ) { if( !window.location.search ) { return null; } var keyValuePairs = window.location.search.substr( 1 ).split( '&' ), params = {}, pair, i; for( i = 0; i < keyValuePairs.length; i++ ) { pair = keyValuePairs[ i ].split( '=' ); params[ pair[ 0 ] ] = pair[ 1 ]; } return params[ param ] || null; }; lm.utils.copy = function( target, source ) { for( var key in source ) { target[ key ] = source[ key ]; } return target; }; /** * This is based on Paul Irish's shim, but looks quite odd in comparison. Why? * Because * a) it shouldn't affect the global requestAnimationFrame function * b) it shouldn't pass on the time that has passed * * @param {Function} fn * * @returns {void} */ lm.utils.animFrame = function( fn ){ return ( window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); })(function(){ fn(); }); }; lm.utils.indexOf = function( needle, haystack ) { if( !( haystack instanceof Array ) ) { throw new Error( 'Haystack is not an Array' ); } if( haystack.indexOf ) { return haystack.indexOf( needle ); } else { for( var i = 0; i < haystack.length; i++ ) { if( haystack[ i ] === needle ) { return i; } } return -1; } }; lm.utils.fnBind = function( fn, context, boundArgs ) { if( Function.prototype.bind !== undefined ) { return Function.prototype.bind.apply( fn, [ context ].concat( boundArgs || [] ) ); } var bound = function () { // Join the already applied arguments to the now called ones (after converting to an array again). var args = ( boundArgs || [] ).concat(Array.prototype.slice.call(arguments, 0)); // If not being called as a constructor if (!(this instanceof bound)){ // return the result of the function called bound to target and partially applied. return fn.apply(context, args); } // If being called as a constructor, apply the function bound to self. fn.apply(this, args); }; // Attach the prototype of the function to our newly created function. bound.prototype = fn.prototype; return bound; }; lm.utils.removeFromArray = function( item, array ) { var index = lm.utils.indexOf( item, array ); if( index === -1 ) { throw new Error( 'Can\'t remove item from array. Item is not in the array' ); } array.splice( index, 1 ); }; lm.utils.now = function() { if( typeof Date.now === 'function' ) { return Date.now(); } else { return ( new Date() ).getTime(); } }; lm.utils.getUniqueId = function() { return ( Math.random() * 1000000000000000 ) .toString(36) .replace( '.', '' ); }; /** * A basic XSS filter. It is ultimately up to the * implementing developer to make sure their particular * applications and usecases are save from cross site scripting attacks * * @param {String} input * @param {Boolean} keepTags * * @returns {String} filtered input */ lm.utils.filterXss = function( input, keepTags ) { var output = input .replace( /javascript/gi, 'j&#97;vascript' ) .replace( /expression/gi, 'expr&#101;ssion' ) .replace( /onload/gi, 'onlo&#97;d' ) .replace( /script/gi, '&#115;cript' ) .replace( /onerror/gi, 'on&#101;rror' ); if( keepTags === true ) { return output; } else { return output .replace( />/g, '&gt;' ) .replace( /</g, '&lt;' ); } }; /** * Removes html tags from a string * * @param {String} input * * @returns {String} input without tags */ lm.utils.stripTags = function( input ) { return $.trim( input.replace( /(<([^>]+)>)/ig, '' ) ); }; /** * A generic and very fast EventEmitter * implementation. On top of emitting the * actual event it emits an * * lm.utils.EventEmitter.ALL_EVENT * * event for every event triggered. This allows * to hook into it and proxy events forwards * * @constructor */ lm.utils.EventEmitter = function() { this._mSubscriptions = { }; this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ] = []; /** * Listen for events * * @param {String} sEvent The name of the event to listen to * @param {Function} fCallback The callback to execute when the event occurs * @param {[Object]} oContext The value of the this pointer within the callback function * * @returns {void} */ this.on = function( sEvent, fCallback, oContext ) { if( !this._mSubscriptions[ sEvent ] ) { this._mSubscriptions[ sEvent ] = []; } this._mSubscriptions[ sEvent ].push({ fn: fCallback, ctx: oContext }); }; /** * Emit an event and notify listeners * * @param {String} sEvent The name of the event * @param {Mixed} various additional arguments that will be passed to the listener * * @returns {void} */ this.emit = function( sEvent ) { var i, ctx, args; args = Array.prototype.slice.call( arguments, 1 ); if( this._mSubscriptions[ sEvent ] ) { for( i = 0; i < this._mSubscriptions[ sEvent ].length; i++ ) { ctx = this._mSubscriptions[ sEvent ][ i ].ctx || {}; this._mSubscriptions[ sEvent ][ i ].fn.apply( ctx, args ); } } args.unshift( sEvent ); for( i = 0; i < this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ].length; i++ ) { ctx = this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ][ i ].ctx || {}; this._mSubscriptions[ lm.utils.EventEmitter.ALL_EVENT ][ i ].fn.apply( ctx, args ); } }; /** * Removes a listener for an event * * @param {String} sEvent The name of the event * @param {Function} fCallback The previously registered callback method * @param {Object} oContext The previously registered context * * @returns {void} */ this.unbind = function( sEvent, fCallback, oContext ) { if( !this._mSubscriptions[ sEvent ] ) { throw new Error( 'No subscribtions to unsubscribe for event ' + sEvent ); } var i, bUnbound = false; for( i = 0; i < this._mSubscriptions[ sEvent ].length; i++ ) { if ( this._mSubscriptions[ sEvent ][ i ].fn === fCallback && ( !oContext || oContext === this._mSubscriptions[ sEvent ][ i ].ctx ) ) { this._mSubscriptions[ sEvent ].splice( i, 1 ); bUnbound = true; } } if( bUnbound === false ) { throw new Error( 'Nothing to unbind for ' + sEvent ); } }; /** * Alias for unbind */ this.off = this.unbind; /** * Alias for emit */ this.trigger = this.emit; }; /** * The name of the event that's triggered for every other event * * usage * * myEmitter.on( lm.utils.EventEmitter.ALL_EVENT, function( eventName, argsArray ){ * //do stuff * }); * * @type {String} */ lm.utils.EventEmitter.ALL_EVENT = '__all'; lm.utils.DragListener = function(eElement, nButtonCode) { lm.utils.EventEmitter.call(this); this._eElement = $(eElement); this._oDocument = $(document); this._eBody = $(document.body); this._nButtonCode = nButtonCode || 0; /** * The delay after which to start the drag in milliseconds */ this._nDelay = 200; /** * The distance the mouse needs to be moved to qualify as a drag */ this._nDistance = 10;//TODO - works better with delay only this._nX = 0; this._nY = 0; this._nOriginalX = 0; this._nOriginalY = 0; this._bDragging = false; this._fMove = lm.utils.fnBind( this.onMouseMove, this ); this._fUp = lm.utils.fnBind( this.onMouseUp, this ); this._fDown = lm.utils.fnBind( this.onMouseDown, this ); this._eElement.on( 'mousedown touchstart', this._fDown ); }; lm.utils.DragListener.timeout = null; lm.utils.copy( lm.utils.DragListener.prototype, { destroy: function() { this._eElement.unbind( 'mousedown touchstart', this._fDown ); }, onMouseDown: function(oEvent) { oEvent.preventDefault(); var coordinates = this._getCoordinates( oEvent ); this._nOriginalX = coordinates.x; this._nOriginalY = coordinates.y; this._oDocument.on('mousemove touchmove', this._fMove); this._oDocument.one('mouseup touchend', this._fUp); this._timeout = setTimeout( lm.utils.fnBind( this._startDrag, this ), this._nDelay ); }, onMouseMove: function(oEvent) { oEvent.preventDefault(); var coordinates = this._getCoordinates( oEvent ); this._nX = coordinates.x - this._nOriginalX; this._nY = coordinates.y - this._nOriginalY; if( this._bDragging === false ) { if( Math.abs( this._nX ) > this._nDistance || Math.abs( this._nY ) > this._nDistance ){ clearTimeout( this._timeout ); this._startDrag(); } } if( this._bDragging ) { this.emit('drag', this._nX, this._nY, oEvent ); } }, onMouseUp: function(oEvent) { clearTimeout( this._timeout ); this._eBody.removeClass( 'lm_dragging' ); this._oDocument.unbind( 'mousemove touchmove', this._fMove); if( this._bDragging === true ) { this._bDragging = false; this.emit('dragStop', oEvent, this._nOriginalX + this._nX); } }, _startDrag: function() { this._bDragging = true; this._eBody.addClass( 'lm_dragging' ); this.emit('dragStart', this._nOriginalX, this._nOriginalY); }, _getCoordinates: function( event ) { var coordinates = {}; if( event.type.substr( 0, 5 ) === 'touch' ) { coordinates.x = event.originalEvent.targetTouches[ 0 ].pageX; coordinates.y = event.originalEvent.targetTouches[ 0 ].pageY; } else { coordinates.x = event.pageX; coordinates.y = event.pageY; } return coordinates; } }); /** * The main class that will be exposed as GoldenLayout. * * @public * @constructor * @param {GoldenLayout config} config * @param {[DOM element container]} container Can be a jQuery selector string or a Dom element. Defaults to body * * @returns {VOID} */ lm.LayoutManager = function( config, container ) { if( !$ || typeof $.noConflict !== 'function' ) { var errorMsg = 'jQuery is missing as dependency for GoldenLayout. '; errorMsg += 'Please either expose $ on GoldenLayout\'s scope (e.g. window) or add "jquery" to '; errorMsg += 'your paths when using RequireJS/AMD'; throw new Error( errorMsg ); } lm.utils.EventEmitter.call( this ); this.isInitialised = false; this._isFullPage = false; this._resizeTimeoutId = null; this._components = { 'lm-react-component': lm.utils.ReactComponentHandler }; this._itemAreas = []; this._resizeFunction = lm.utils.fnBind( this._onResize, this ); this._maximisedItem = null; this._maximisePlaceholder = $( '<div class="lm_maximise_place"></div>' ); this._creationTimeoutPassed = false; this._subWindowsCreated = false; this.width = null; this.height = null; this.root = null; this.openPopouts = []; this.selectedItem = null; this.isSubWindow = false; this.eventHub = new lm.utils.EventHub( this ); this.config = this._createConfig( config ); this.container = container; this.dropTargetIndicator = null; this.transitionIndicator = null; this.tabDropPlaceholder = $( '<div class="lm_drop_tab_placeholder"></div>' ); if( this.isSubWindow === true ) { $( 'body' ).css( 'visibility', 'hidden' ); } $( window ).on( 'unload beforeunload', lm.utils.fnBind( this._onUnload, this) ); this._typeToItem = { 'column': lm.utils.fnBind( lm.items.RowOrColumn, this, [ true ] ), 'row': lm.utils.fnBind( lm.items.RowOrColumn, this, [ false ] ), 'stack': lm.items.Stack, 'component': lm.items.Component }; }; /** * Hook that allows to access private classes */ lm.LayoutManager.__lm = lm; /** * Takes a GoldenLayout configuration object and * replaces its keys and values recoursively with * one letter codes * * @static * @public * @param {Object} config A GoldenLayout config object * * @returns {Object} minified config */ lm.LayoutManager.minifyConfig = function( config ) { return ( new lm.utils.ConfigMinifier() ).minifyConfig( config ); }; /** * Takes a configuration Object that was previously minified * using minifyConfig and returns its original version * * @static * @public * @param {Object} minifiedConfig * * @returns {Object} the original configuration */ lm.LayoutManager.unminifyConfig = function( config ) { return ( new lm.utils.ConfigMinifier() ).unminifyConfig( config ); }; lm.utils.copy( lm.LayoutManager.prototype, { /** * Register a component with the layout manager. If a configuration node * of type component is reached it will look up componentName and create the * associated component * * { * type: "component", * componentName: "EquityNewsFeed", * componentState: { "feedTopic": "us-bluechips" } * } * * @public * @param {String} name * @param {Function} constructor * * @returns {void} */ registerComponent: function( name, constructor ) { if( typeof constructor !== 'function' ) { throw new Error( 'Please register a constructor function' ); } if( this._components[ name ] !== undefined ) { throw new Error( 'Component ' + name + ' is already registered' ); } this._components[ name ] = constructor; }, /** * Creates a layout configuration object based on the the current state * * @public * @returns {Object} GoldenLayout configuration */ toConfig: function( root ) { var config, next, i; if( this.isInitialised === false ) { throw new Error( 'Can\'t create config, layout not yet initialised' ); } if( root && !( root instanceof lm.items.AbstractContentItem ) ){ throw new Error( 'Root must be a ContentItem' ); } /* * settings & labels */ config = { settings: lm.utils.copy( {}, this.config.settings ), dimensions: lm.utils.copy( {}, this.config.dimensions ), labels: lm.utils.copy( {}, this.config.labels ) }; /* * Content */ config.content = []; next = function( configNode, item ) { var key, i; for( key in item.config ) { if( key !== 'content' ) { configNode[ key ] = item.config[ key ]; } } if( item.contentItems.length ) { configNode.content = []; for( i = 0; i < item.contentItems.length; i++ ) { configNode.content[ i ] = {}; next( configNode.content[ i ], item.contentItems[ i ] ); } } }; if( root ) { next( config, { contentItems: [ root ] } ); } else { next( config, this.root ); } /* * Retrieve config for subwindows */ this._$reconcilePopoutWindows(); config.openPopouts = []; for( i = 0; i < this.openPopouts.length; i++ ) { config.openPopouts.push( this.openPopouts[ i ].toConfig() ); } /* * Add maximised item */ config.maximisedItemId = this._maximisedItem ? '__glMaximised' : null; return config; }, /** * Returns a previously registered component * * @public * @param {String} name The name used * * @returns {Function} */ getComponent: function( name ) { if( this._components[ name ] === undefined ) { throw new lm.errors.ConfigurationError( 'Unknown component "' + name + '"' ); } return this._components[ name ]; }, /** * Creates the actual layout. Must be called after all initial components * are registered. Recourses through the configuration and sets up * the item tree. * * If called before the document is ready it adds itself as a listener * to the document.ready event * * @public * * @returns {void} */ init: function() { /** * Create the popout windows straight away. If popouts are blocked * an error is thrown on the same 'thread' rather than a timeout and can * be caught. This also prevents any further initilisation from taking place. */ if( this._subWindowsCreated === false ) { this._createSubWindows(); this._subWindowsCreated = true; } /** * If the document isn't ready yet, wait for it. */ if( document.readyState === 'loading' || document.body === null ) { $(document).ready( lm.utils.fnBind( this.init, this )); return; } /** * If this is a subwindow, wait a few milliseconds for the original * page's js calls to be executed, then replace the bodies content * with GoldenLayout */ if( this.isSubWindow === true && this._creationTimeoutPassed === false ) { setTimeout( lm.utils.fnBind( this.init, this ), 7 ); this._creationTimeoutPassed = true; return; } if( this.isSubWindow === true ) { this._adjustToWindowMode(); } this._setContainer(); this.dropTargetIndicator = new lm.controls.DropTargetIndicator( this.container ); this.transitionIndicator = new lm.controls.TransitionIndicator(); this.updateSize(); this._create( this.config ); this._bindEvents(); this.isInitialised = true; this.emit( 'initialised' ); }, /** * Updates the layout managers size * * @public * @param {[int]} width height in pixels * @param {[int]} height width in pixels * * @returns {void} */ updateSize: function( width, height ) { if( arguments.length === 2 ) { this.width = width; this.height = height; } else { this.width = this.container.width(); this.height = this.container.height(); } if( this.isInitialised === true ) { this.root.callDownwards( 'setSize' ); if( this._maximisedItem ) { this._maximisedItem.element.width( this.container.width() ); this._maximisedItem.element.height( this.container.height() ); this._maximisedItem.callDownwards( 'setSize' ); } } }, /** * Destroys the LayoutManager instance itself as well as every ContentItem * within it. After this is called nothing should be left of the LayoutManager. * * @public * @returns {void} */ destroy: function() { if( this.isInitialised === false ) { return; } this._onUnload(); $( window ).off( 'resize', this._resizeFunction ); this.root.callDownwards( '_$destroy', [], true ); this.root.contentItems = []; this.tabDropPlaceholder.remove(); this.dropTargetIndicator.destroy(); this.transitionIndicator.destroy(); }, /** * Recoursively creates new item tree structures based on a provided * ItemConfiguration object * * @public * @param {Object} config ItemConfig * @param {[ContentItem]} parent The item the newly created item should be a child of * * @returns {lm.items.ContentItem} */ createContentItem: function( config, parent ) { var typeErrorMsg, contentItem; if( typeof config.type !== 'string' ) { throw new lm.errors.ConfigurationError( 'Missing parameter \'type\'', config ); } if( !this._typeToItem[ config.type ] ) { typeErrorMsg = 'Unknown type \'' + config.type + '\'. ' + 'Valid types are ' + lm.utils.objectKeys( this._typeToItem ).join( ',' ); throw new lm.errors.ConfigurationError( typeErrorMsg ); } /** * We add an additional stack around every component that's not within a stack anyways */ if( // If this is a component config.type === 'component' && // and it's not already within a stack !( parent instanceof lm.items.Stack ) && // and we have a parent !!parent && // and it's not the topmost item in a new window !( this.isSubWindow === true && parent instanceof lm.items.Root ) ) { config = { type: 'stack', isClosable: config.isClosable, width: config.width, height: config.height, content: [ config ] }; } contentItem = new this._typeToItem[ config.type ]( this, config, parent ); return contentItem; }, /** * Creates a popout window with the specified content and dimensions * * @param {Object|lm.itemsAbstractContentItem} configOrContentItem * @param {[Object]} dimensions A map with width, height, left and top * @param {[String]} parentId the id of the element this item will be appended to * when popIn is called * @param {[Number]} indexInParent The position of this item within its parent element * @returns {lm.controls.BrowserPopout} */ createPopout: function( configOrContentItem, dimensions, parentId, indexInParent ) { var config = configOrContentItem, isItem = configOrContentItem instanceof lm.items.AbstractContentItem, self = this, windowLeft, windowTop, offset, parent, child, browserPopout; parentId = parentId || null; if( isItem ) { config = this.toConfig( configOrContentItem ).content; parentId = lm.utils.getUniqueId(); /** * If the item is the only component within a stack or for some * other reason the only child of its parent the parent will be destroyed * when the child is removed. * * In order to support this we move up the tree until we find something * that will remain after the item is being popped out */ parent = configOrContentItem.parent; child = configOrContentItem; while( parent.contentItems.length === 1 && !parent.isRoot ) { parent = parent.parent; child = child.parent; } parent.addId( parentId ); if( isNaN( indexInParent ) ) { indexInParent = lm.utils.indexOf( child, parent.contentItems ); } } else { if( !( config instanceof Array ) ) { config = [ config ]; } } if( !dimensions && isItem ) { windowLeft = window.screenX || window.screenLeft; windowTop = window.screenY || window.screenTop; offset = configOrContentItem.element.offset(); dimensions = { left: windowLeft + offset.left, top: windowTop + offset.top, width: configOrContentItem.element.width(), height: configOrContentItem.element.height() }; } if( !dimensions && !isItem ) { dimensions = { left: window.screenX || window.screenLeft + 20, top: window.screenY || window.screenTop + 20, width: 500, height: 309 }; } if( isItem ) { configOrContentItem.remove(); } browserPopout = new lm.controls.BrowserPopout( config, dimensions, parentId, indexInParent, this ); browserPopout.on( 'initialised', function(){ self.emit( 'windowOpened', browserPopout ); }); browserPopout.on( 'closed', function(){ self._$reconcilePopoutWindows(); }); this.openPopouts.push( browserPopout ); return browserPopout; }, /** * Attaches DragListener to any given DOM element * and turns it into a way of creating new ContentItems * by 'dragging' the DOM element into the layout * * @param {jQuery DOM element} element * @param {Object} itemConfig for the new item to be created * * @returns {void} */ createDragSource: function( element, itemConfig ) { this.config.settings.constrainDragToContainer = false; new lm.controls.DragSource( $( element ), itemConfig, this ); }, /** * Programmatically selects an item. This deselects * the currently selected item, selects the specified item * and emits a selectionChanged event * * @param {lm.item.AbstractContentItem} item# * @param {[Boolean]} _$silent Wheather to notify the item of its selection * @event selectionChanged * * @returns {VOID} */ selectItem: function( item, _$silent ) { if( this.config.settings.selectionEnabled !== true ) { throw new Error( 'Please set selectionEnabled to true to use this feature' ); } if( item === this.selectedItem ) { return; } if( this.selectedItem !== null ) { this.selectedItem.deselect(); } if( item && _$silent !== true ) { item.select(); } this.selectedItem = item; this.emit( 'selectionChanged', item ); }, /************************* * PACKAGE PRIVATE *************************/ _$maximiseItem: function( contentItem ) { if( this._maximisedItem !== null ) { this._$minimiseItem( this._maximisedItem ); } this._maximisedItem = contentItem; this._maximisedItem.addId( '__glMaximised' ); contentItem.element.addClass( 'lm_maximised' ); contentItem.element.after( this._maximisePlaceholder ); this.root.element.prepend( contentItem.element ); contentItem.element.width( this.container.width() ); contentItem.element.height( this.container.height() ); contentItem.callDownwards( 'setSize' ); this._maximisedItem.emit( 'maximised' ); this.emit( 'stateChanged' ); }, _$minimiseItem: function( contentItem ) { contentItem.element.removeClass( 'lm_maximised' ); contentItem.removeId( '__glMaximised' ); this._maximisePlaceholder.after( contentItem.element ); this._maximisePlaceholder.remove(); contentItem.parent.callDownwards( 'setSize' ); this._maximisedItem = null; contentItem.emit( 'minimised' ); this.emit( 'stateChanged' ); }, /** * This method is used to get around sandboxed iframe restrictions. * If 'allow-top-navigation' is not specified in the iframe's 'sandbox' attribute * (as is the case with codepens) the parent window is forbidden from calling certain * methods on the child, such as window.close() or setting document.location.href. * * This prevented GoldenLayout popouts from popping in in codepens. The fix is to call * _$closeWindow on the child window's gl instance which (after a timeout to disconnect * the invoking method from the close call) closes itself. * * @packagePrivate * * @returns {void} */ _$closeWindow: function() { window.setTimeout(function(){ window.close(); }, 1); }, _$getArea: function( x, y ) { var i, area, smallestSurface = Infinity, mathingArea = null; for( i = 0; i < this._itemAreas.length; i++ ) { area = this._itemAreas[ i ]; if( x > area.x1 && x < area.x2 && y > area.y1 && y < area.y2 && smallestSurface > area.surface ){ smallestSurface = area.surface; mathingArea = area; } } return mathingArea; }, _$calculateItemAreas: function() { var i, area, allContentItems = this._getAllContentItems(); this._itemAreas = []; /** * If the last item is dragged out, highlight the entire container size to * allow to re-drop it. allContentItems[ 0 ] === this.root at this point * * Don't include root into the possible drop areas though otherwise since it * will used for every gap in the layout, e.g. splitters */ if( allContentItems.length === 1 ) { this._itemAreas.push( this.root._$getArea() ); return; } for( i = 0; i < allContentItems.length; i++ ) { if( !( allContentItems[ i ].isStack ) ) { continue; } area = allContentItems[ i ]._$getArea(); if( area === null ) { continue; } else if( area instanceof Array ) { this._itemAreas = this._itemAreas.concat( area ); } else { this._itemAreas.push( area ); } } }, /** * Takes a contentItem or a configuration and optionally a parent * item and returns an initialised instance of the contentItem * * @packagePrivate * * @param {lm.items.AbtractContentItem|Object} contentItemOrConfig * @param {lm.items.AbtractContentItem} parent Only necessary when passing in config * * @returns {lm.items.AbtractContentItem} */ _$normalizeContentItem: function( contentItemOrConfig, parent ) { if( !contentItemOrConfig ) { throw new Error( 'No content item defined' ); } if( contentItemOrConfig instanceof lm.items.AbstractContentItem ) { return contentItemOrConfig; } if( $.isPlainObject( contentItemOrConfig ) && contentItemOrConfig.type ) { var newContentItem = this.createContentItem( contentItemOrConfig, parent ); newContentItem.callDownwards( '_$init' ); return newContentItem; } else { throw new Error( 'Invalid contentItem' ); } }, /** * Iterates through the array of open popout windows and removes the ones * that are effectively closed. This is necessary due to the lack of reliably * listening for window.close / unload events in a cross browser compatible fashion. * * @packagePrivate * * @returns {void} */ _$reconcilePopoutWindows: function() { var openPopouts = [], i; for( i = 0; i < this.openPopouts.length; i++ ) { if( this.openPopouts[ i ].getWindow().closed === false ) { openPopouts.push( this.openPopouts[ i ] ); } else { this.emit( 'windowClosed', this.openPopouts[ i ] ); } } if( this.openPopouts.length !== openPopouts.length ) { this.emit( 'stateChanged' ); this.openPopouts = openPopouts; } }, /*************************** * PRIVATE ***************************/ /** * Returns a flattened array of all content items, * regardles of level or type * * @private * * @returns {void} */ _getAllContentItems: function() { var allContentItems = []; var addChildren = function( contentItem ) { allContentItems.push( contentItem ); if( contentItem.contentItems instanceof Array ) { for( var i = 0; i < contentItem.contentItems.length; i++ ) { addChildren( contentItem.contentItems[ i ] ); } } }; addChildren( this.root ); return allContentItems; }, /** * Binds to DOM/BOM events on init * * @private * * @returns {void} */ _bindEvents: function() { if( this._isFullPage ) { $(window).resize( this._resizeFunction ); } }, /** * Debounces resize events * * @private * * @returns {void} */ _onResize: function() { clearTimeout( this._resizeTimeoutId ); this._resizeTimeoutId = setTimeout(lm.utils.fnBind( this.updateSize, this ), 100 ); }, /** * Extends the default config with the user specific settings and applies * derivations. Please note that there's a seperate method (AbstractContentItem._extendItemNode) * that deals with the extension of item configs * * @param {Object} config * @static * @returns {Object} config */ _createConfig: function( config ) { var windowConfigKey = lm.utils.getQueryStringParam( 'gl-window' ); if( windowConfigKey ) { this.isSubWindow = true; config = localStorage.getItem( windowConfigKey ); config = JSON.parse( config ); config = ( new lm.utils.ConfigMinifier() ).unminifyConfig( config ); localStorage.removeItem( windowConfigKey ); } config = $.extend( true, {}, lm.config.defaultConfig, config ); var nextNode = function( node ) { for( var key in node ) { if( typeof node[ key ] === 'object' ) { nextNode( node[ key ] ); } else if( key === 'type' && node[ key ] === 'react-component' ) { node.type = 'component'; node.componentName = 'lm-react-component'; } } } nextNode( config ); if( config.settings.hasHeaders === false ) { config.dimensions.headerHeight = 0; } return config; }, /** * This is executed when GoldenLayout detects that it is run * within a previously opened popout window. * * @private * * @returns {void} */ _adjustToWindowMode: function() { var popInButton = $( '<div class="lm_popin" title="' + this.config.labels.popin + '">' + '<div class="lm_icon"></div>' + '<div class="lm_bg"></div>' + '</div>'); popInButton.click(lm.utils.fnBind(function(){ this.emit( 'popIn' ); }, this)); document.title = lm.utils.stripTags( this.config.content[ 0 ].title ); $( 'head' ).append( $( 'body link, body style, template, .gl_keep' ) ); this.container = $( 'body' ) .html( '' ) .css( 'visibility', 'visible' ) .append( popInButton ); /* * This seems a bit pointless, but actually causes a reflow/re-evaluation getting around * slickgrid's "Cannot find stylesheet." bug in chrome */ var x = document.body.offsetHeight; // jshint ignore:line /* * Expose this instance on the window object * to allow the opening window to interact with * it */ window.__glInstance = this; }, /** * Creates Subwindows (if there are any). Throws an error * if popouts are blocked. * * @returns {void} */ _createSubWindows: function() { var i, popout; for( i = 0; i < this.config.openPopouts.length; i++ ) { popout = this.config.openPopouts[ i ]; this.createPopout( popout.content, popout.dimensions, popout.parentId, popout.indexInParent ); } }, /** * Determines what element the layout will be created in * * @private * * @returns {void} */ _setContainer: function() { var container = $( this.container || 'body' ); if( container.length === 0 ) { throw new Error( 'GoldenLayout container not found' ); } if( container.length > 1 ) { throw new Error( 'GoldenLayout more than one container element specified' ); } if( container[ 0 ] === document.body ) { this._isFullPage = true; $( 'html, body' ).css({ height: '100%', margin:0, padding: 0, overflow: 'hidden' }); } this.container = container; }, /** * Kicks of the initial, recoursive creation chain * * @param {Object} config GoldenLayout Config * * @returns {void} */ _create: function( config ) { var errorMsg; if( !( config.content instanceof Array ) ) { if( config.content === undefined ) { errorMsg = 'Missing setting \'content\' on top level of configuration'; } else { errorMsg = 'Configuration parameter \'content\' must be an array'; } throw new lm.errors.ConfigurationError( errorMsg, config ); } if( config.content.length > 1 ) { errorMsg = 'Top level content can\'t contain more then one element.'; throw new lm.errors.ConfigurationError( errorMsg, config ); } this.root = new lm.items.Root( this, { content: config.content }, this.container ); this.root.callDownwards( '_$init' ); if( config.maximisedItemId === '__glMaximised' ) { this.root.getItemsById( config.maximisedItemId )[ 0 ].toggleMaximise(); } }, /** * Called when the window is closed or the user navigates away * from the page * * @returns {void} */ _onUnload: function() { if( this.config.settings.closePopoutsOnUnload === true ) { for( var i = 0; i < this.openPopouts.length; i++ ) { this.openPopouts[ i ].close(); } } } }); /** * Expose the Layoutmanager as the single entrypoint using UMD */ (function () { /* global define */ if ( typeof define === 'function' && define.amd) { define([ 'jquery' ], function( jquery ){ $ = jquery; return lm.LayoutManager; }); // jshint ignore:line } else if (typeof exports === 'object') { module.exports = lm.LayoutManager; } else { window.GoldenLayout = lm.LayoutManager; } })(); lm.config.defaultConfig = { openPopouts:[], settings:{ hasHeaders: true, constrainDragToContainer: true, reorderEnabled: true, selectionEnabled: false, popoutWholeStack: false, blockedPopoutsThrowError: true, closePopoutsOnUnload: true, showPopoutIcon: true, showMaximiseIcon: true, showCloseIcon: true }, dimensions: { borderWidth: 5, minItemHeight: 10, minItemWidth: 10, headerHeight: 20, dragProxyWidth: 300, dragProxyHeight: 200 }, labels: { close: 'close', maximise: 'maximise', minimise: 'minimise', popout: 'open in new window', popin: 'pop in' } }; lm.config.itemDefaultConfig = { isClosable: true, reorderEnabled: true, title: '' }; lm.container.ItemContainer = function( config, parent, layoutManager ) { lm.utils.EventEmitter.call( this ); this.width = null; this.height = null; this.title = config.componentName; this.parent = parent; this.layoutManager = layoutManager; this.isHidden = false; this._config = config; this._element = $([ '<div class="lm_item_container">', '<div class="lm_content"></div>', '</div>' ].join( '' )); this._contentElement = this._element.find( '.lm_content' ); }; lm.utils.copy( lm.container.ItemContainer.prototype, { /** * Get the inner DOM element the container's content * is intended to live in * * @returns {DOM element} */ getElement: function() { return this._contentElement; }, /** * Hide the container. Notifies the containers content first * and then hides the DOM node. If the container is already hidden * this should have no effect * * @returns {void} */ hide: function() { this.emit( 'hide' ); this.isHidden = true; this._element.hide(); }, /** * Shows a previously hidden container. Notifies the * containers content first and then shows the DOM element. * If the container is already visible this has no effect. * * @returns {void} */ show: function() { this.emit( 'show' ); this.isHidden = false; this._element.show(); }, /** * Set the size from within the container. Traverses up * the item tree until it finds a row or column element * and resizes its items accordingly. * * If this container isn't a descendant of a row or column * it returns false * @todo Rework!!! * @param {Number} width The new width in pixel * @param {Number} height The new height in pixel * * @returns {Boolean} resizeSuccesful */ setSize: function( width, height ) { var rowOrColumn = this.parent, rowOrColumnChild = this, totalPixel, percentage, direction, newSize, delta, i; while( !rowOrColumn.isColumn && !rowOrColumn.isRow ) { rowOrColumnChild = rowOrColumn; rowOrColumn = rowOrColumn.parent; /** * No row or column has been found */ if( rowOrColumn.isRoot ) { return false; } } direction = rowOrColumn.isColumn ? "height" : "width"; newSize = direction === "height" ? height : width; totalPixel = this[direction] * ( 1 / ( rowOrColumnChild.config[direction] / 100 ) ); percentage = ( newSize / totalPixel ) * 100; delta = ( rowOrColumnChild.config[direction] - percentage ) / rowOrColumn.contentItems.length; for( i = 0; i < rowOrColumn.contentItems.length; i++ ) { if( rowOrColumn.contentItems[ i ] === rowOrColumnChild ) { rowOrColumn.contentItems[ i ].config[direction] = percentage; } else { rowOrColumn.contentItems[ i ].config[direction] += delta; } } rowOrColumn.callDownwards( 'setSize' ); return true; }, /** * Closes the container if it is closable. Can be called by * both the component within at as well as the contentItem containing * it. Emits a close event before the container itself is closed. * * @returns {void} */ close: function() { if( this._config.isClosable ) { this.emit( 'close' ); this.parent.close(); } }, /** * Returns the current state object * * @returns {Object} state */ getState: function() { return this._config.componentState; }, /** * Merges the provided state into the current one * * @param {Object} state * * @returns {void} */ extendState: function( state ) { this.setState( $.extend( true, this.getState(), state ) ); }, /** * Notifies the layout manager of a stateupdate * * @param {serialisable} state */ setState: function( state ) { this._config.componentState = state; this.parent.emitBubblingEvent( 'stateChanged' ); }, /** * Set's the components title * * @param {String} title */ setTitle: function( title ) { this.parent.setTitle( title ); }, /** * Set's the containers size. Called by the container's component. * To set the size programmatically from within the container please * use the public setSize method * * @param {[Int]} width in px * @param {[Int]} height in px * * @returns {void} */ _$setSize: function( width, height ) { if( width !== this.width || height !== this.height ) { this.width = width; this.height = height; this._contentElement.width( this.width ).height( this.height ); this.emit( 'resize' ); } } }); /** * Pops a content item out into a new browser window. * This is achieved by * * - Creating a new configuration with the content item as root element * - Serializing and minifying the configuration * - Opening the current window's URL with the configuration as a GET parameter * - GoldenLayout when opened in the new window will look for the GET parameter * and use it instead of the provided configuration * * @param {Object} config GoldenLayout item config * @param {Object} dimensions A map with width, height, top and left * @param {String} parentId The id of the element the item will be appended to on popIn * @param {Number} indexInParent The position of this element within its parent * @param {lm.LayoutManager} layoutManager */ lm.controls.BrowserPopout = function( config, dimensions, parentId, indexInParent, layoutManager ) { lm.utils.EventEmitter.call( this ); this.isInitialised = false; this._config = config; this._dimensions = dimensions; this._parentId = parentId; this._indexInParent = indexInParent; this._layoutManager = layoutManager; this._popoutWindow = null; this._id = null; this._createWindow(); }; lm.utils.copy( lm.controls.BrowserPopout.prototype, { toConfig: function() { return { dimensions:{ width: this.getGlInstance().width, height: this.getGlInstance().height, left: this._popoutWindow.screenX || this._popoutWindow.screenLeft, top: this._popoutWindow.screenY || this._popoutWindow.screenTop }, content: this.getGlInstance().toConfig().content, parentId: this._parentId, indexInParent: this._indexInParent }; }, getGlInstance: function() { return this._popoutWindow.__glInstance; }, getWindow: function() { return this._popoutWindow; }, close: function() { if( this.getGlInstance() ) { this.getGlInstance()._$closeWindow(); } else { try{ this.getWindow().close(); } catch( e ){} } }, /** * Returns the popped out item to its original position. If the original * parent isn't available anymore it falls back to the layout's topmost element */ popIn: function() { var childConfig, parentItem, index = this._indexInParent; if( this._parentId ) { /* * The $.extend call seems a bit pointless, but it's crucial to * copy the config returned by this.getGlInstance().toConfig() * onto a new object. Internet Explorer keeps the references * to objects on the child window, resulting in the following error * once the child window is closed: * * The callee (server [not server application]) is not available and disappeared */ childConfig = $.extend( true, {}, this.getGlInstance().toConfig() ).content[ 0 ]; parentItem = this._layoutManager.root.getItemsById( this._parentId )[ 0 ]; /* * Fallback if parentItem is not available. Either add it to the topmost * item or make it the topmost item if the layout is empty */ if( !parentItem ) { if( this._layoutManager.root.contentItems.length > 0 ) { parentItem = this._layoutManager.root.contentItems[ 0 ]; } else { parentItem = this._layoutManager.root; } index = 0; } } parentItem.addChild( childConfig, this._indexInParent ); this.close(); }, /** * Creates the URL and window parameter * and opens a new window * * @private * * @returns {void} */ _createWindow: function() { var checkReadyInterval, url = this._createUrl(), /** * Bogus title to prevent re-usage of existing window with the * same title. The actual title will be set by the new window's * GoldenLayout instance if it detects that it is in subWindowMode */ title = Math.floor( Math.random() * 1000000 ).toString( 36 ), /** * The options as used in the window.open string */ options = this._serializeWindowOptions({ width: this._dimensions.width, height: this._dimensions.height, innerWidth: this._dimensions.width, innerHeight: this._dimensions.height, menubar: 'no', toolbar: 'no', location: 'no', personalbar: 'no', resizable: 'yes', scrollbars: 'no', status: 'no' }); this._popoutWindow = window.open( url, title, options ); if( !this._popoutWindow ) { if( this._layoutManager.config.settings.blockedPopoutsThrowError === true ) { var error = new Error( 'Popout blocked' ); error.type = 'popoutBlocked'; throw error; } else { return; } } $( this._popoutWindow ) .on( 'load', lm.utils.fnBind( this._positionWindow, this ) ) .on( 'unload beforeunload', lm.utils.fnBind( this._onClose, this ) ); /** * Polling the childwindow to find out if GoldenLayout has been initialised * doesn't seem optimal, but the alternatives - adding a callback to the parent * window or raising an event on the window object - both would introduce knowledge * about the parent to the child window which we'd rather avoid */ checkReadyInterval = setInterval(lm.utils.fnBind(function(){ if( this._popoutWindow.__glInstance && this._popoutWindow.__glInstance.isInitialised ) { this._onInitialised(); clearInterval( checkReadyInterval ); } }, this ), 10 ); }, /** * Serialises a map of key:values to a window options string * * @param {Object} windowOptions * * @returns {String} serialised window options */ _serializeWindowOptions: function( windowOptions ) { var windowOptionsString = [], key; for( key in windowOptions ) { windowOptionsString.push( key + '=' + windowOptions[ key ] ); } return windowOptionsString.join( ',' ); }, /** * Creates the URL for the new window, including the * config GET parameter * * @returns {String} URL */ _createUrl: function() { var config = { content: this._config }, storageKey = 'gl-window-config-' + lm.utils.getUniqueId(), urlParts; config = ( new lm.utils.ConfigMinifier() ).minifyConfig( config ); try{ localStorage.setItem( storageKey, JSON.stringify( config ) ); } catch( e ) { throw new Error( 'Error while writing to localStorage ' + e.toString() ); } urlParts = document.location.href.split( '?' ); // URL doesn't contain GET-parameters if( urlParts.length === 1 ) { return urlParts[ 0 ] + '?gl-window=' + storageKey; // URL contains GET-parameters } else { return document.location.href + '&gl-window=' + storageKey; } }, /** * Move the newly created window roughly to * where the component used to be. * * @private * * @returns {void} */ _positionWindow: function() { this._popoutWindow.moveTo( this._dimensions.left, this._dimensions.top ); this._popoutWindow.focus(); }, /** * Callback when the new window is opened and the GoldenLayout instance * within it is initialised * * @returns {void} */ _onInitialised: function() { this.isInitialised = true; this.getGlInstance().on( 'popIn', this.popIn, this ); this.emit( 'initialised' ); }, /** * Invoked 50ms after the window unload event * * @private * * @returns {void} */ _onClose: function() { setTimeout( lm.utils.fnBind( this.emit, this, [ 'closed' ] ), 50 ); } }); /** * This class creates a temporary container * for the component whilst it is being dragged * and handles drag events * * @constructor * @private * * @param {Number} x The initial x position * @param {Number} y The initial y position * @param {lm.utils.DragListener} dragListener * @param {lm.LayoutManager} layoutManager * @param {lm.item.AbstractContentItem} contentItem * @param {lm.item.AbstractContentItem} originalParent */ lm.controls.DragProxy = function( x, y, dragListener, layoutManager, contentItem, originalParent ) { lm.utils.EventEmitter.call( this ); this._dragListener = dragListener; this._layoutManager = layoutManager; this._contentItem = contentItem; this._originalParent = originalParent; this._area = null; this._lastValidArea = null; this._dragListener.on( 'drag', this._onDrag, this ); this._dragListener.on( 'dragStop', this._onDrop, this ); this.element = $( lm.controls.DragProxy._template ); this.element.css({ left: x, top: y }); this.element.find( '.lm_title' ).html( this._contentItem.config.title ); this.childElementContainer = this.element.find( '.lm_content' ); this.childElementContainer.append( contentItem.element ); this._updateTree(); this._layoutManager._$calculateItemAreas(); this._setDimensions(); $( document.body ).append( this.element ); var offset = this._layoutManager.container.offset(); this._minX = offset.left; this._minY = offset.top; this._maxX = this._layoutManager.container.width() + this._minX; this._maxY = this._layoutManager.container.height() + this._minY; this._width = this.element.width(); this._height = this.element.height(); }; lm.controls.DragProxy._template = '<div class="lm_dragProxy">' + '<div class="lm_header">' + '<ul class="lm_tabs">' + '<li class="lm_tab lm_active"><i class="lm_left"></i>' + '<span class="lm_title"></span>' + '<i class="lm_right"></i></li>' + '</ul>' + '</div>' + '<div class="lm_content"></div>' + '</div>'; lm.utils.copy( lm.controls.DragProxy.prototype, { /** * Callback on every mouseMove event during a drag. Determines if the drag is * still within the valid drag area and calls the layoutManager to highlight the * current drop area * * @param {Number} offsetX The difference from the original x position in px * @param {Number} offsetY The difference from the original y position in px * @param {jQuery DOM event} event * * @private * * @returns {void} */ _onDrag: function( offsetX, offsetY, event ) { var x = event.pageX, y = event.pageY, isWithinContainer = x > this._minX && x < this._maxX && y > this._minY && y < this._maxY; if( !isWithinContainer && this._layoutManager.config.settings.constrainDragToContainer === true ) { return; } this.element.css({ left: x, top: y }); this._area = this._layoutManager._$getArea( x, y ); if( this._area !== null ) { this._lastValidArea = this._area; this._area.contentItem._$highlightDropZone( x, y, this._area ); } }, /** * Callback when the drag has finished. Determines the drop area * and adds the child to it * * @private * * @returns {void} */ _onDrop: function() { this._layoutManager.dropTargetIndicator.hide(); /* * Valid drop area found */ if( this._area !== null ) { this._area.contentItem._$onDrop( this._contentItem ); /** * No valid drop area available at present, but one has been found before. * Use it */ } else if( this._lastValidArea !== null ) { this._lastValidArea.contentItem._$onDrop( this._contentItem ); /** * No valid drop area found during the duration of the drag. Return * content item to its original position if a original parent is provided. * (Which is not the case if the drag had been initiated by createDragSource) */ } else if ( this._originalParent ){ this._originalParent.addChild( this._contentItem ); } this.element.remove(); }, /** * Removes the item from it's original position within the tree * * @private * * @returns {void} */ _updateTree: function() { /** * parent is null if the drag had been initiated by a external drag source */ if( this._contentItem.parent ) { this._contentItem.parent.removeChild( this._contentItem, true ); } this._contentItem._$setParent( this ); }, /** * Updates the Drag Proxie's dimensions * * @private * * @returns {void} */ _setDimensions: function() { var dimensions = this._layoutManager.config.dimensions, width = dimensions.dragProxyWidth, height = dimensions.dragProxyHeight - dimensions.headerHeight; this.childElementContainer.width( width ); this.childElementContainer.height( height ); this._contentItem.element.width( width ); this._contentItem.element.height( height ); this._contentItem.callDownwards( '_$show' ); this._contentItem.callDownwards( 'setSize' ); } }); /** * Allows for any DOM item to create a component on drag * start tobe dragged into the Layout * * @param {jQuery element} element * @param {Object} itemConfig the configuration for the contentItem that will be created * @param {LayoutManager} layoutManager * * @constructor */ lm.controls.DragSource = function( element, itemConfig, layoutManager ) { this._element = element; this._itemConfig = itemConfig; this._layoutManager = layoutManager; this._dragListener = null; this._createDragListener(); }; lm.utils.copy( lm.controls.DragSource.prototype, { /** * Called initially and after every drag * * @returns {void} */ _createDragListener: function() { if( this._dragListener !== null ) { this._dragListener.destroy(); } this._dragListener = new lm.utils.DragListener( this._element ); this._dragListener.on( 'dragStart', this._onDragStart, this ); this._dragListener.on( 'dragStop', this._createDragListener, this ); }, /** * Callback for the DragListener's dragStart event * * @param {int} x the x position of the mouse on dragStart * @param {int} y the x position of the mouse on dragStart * * @returns {void} */ _onDragStart: function( x, y ) { var contentItem = this._layoutManager._$normalizeContentItem( this._itemConfig ), dragProxy = new lm.controls.DragProxy( x, y, this._dragListener, this._layoutManager, contentItem, null ); this._layoutManager.transitionIndicator.transitionElements( this._element, dragProxy.element ); } }); lm.controls.DropTargetIndicator = function() { this.element = $( lm.controls.DropTargetIndicator._template ); $(document.body).append( this.element ); }; lm.controls.DropTargetIndicator._template = '<div class="lm_dropTargetIndicator"><div class="lm_inner"></div></div>'; lm.utils.copy( lm.controls.DropTargetIndicator.prototype, { destroy: function() { this.element.remove(); }, highlight: function( x1, y1, x2, y2 ) { this.highlightArea({ x1:x1, y1:y1, x2:x2, y2:y2 }); }, highlightArea: function( area ) { this.element.css({ left: area.x1, top: area.y1, width: area.x2 - area.x1, height: area.y2 - area.y1 }).show(); }, hide: function() { this.element.hide(); } }); /** * This class represents a header above a Stack ContentItem. * * @param {lm.LayoutManager} layoutManager * @param {lm.item.AbstractContentItem} parent */ lm.controls.Header = function( layoutManager, parent ) { lm.utils.EventEmitter.call( this ); this.layoutManager = layoutManager; this.element = $( lm.controls.Header._template ); if( this.layoutManager.config.settings.selectionEnabled === true ) { this.element.addClass( 'lm_selectable' ); this.element.click( lm.utils.fnBind( this._onHeaderClick, this ) ); } this.element.height( layoutManager.config.dimensions.headerHeight ); this.tabsContainer = this.element.find( '.lm_tabs' ); this.controlsContainer = this.element.find( '.lm_controls' ); this.parent = parent; this.parent.on( 'resize', this._updateTabSizes, this ); this.tabs = []; this.activeContentItem = null; this._createControls(); }; lm.controls.Header._template = [ '<div class="lm_header">', '<ul class="lm_tabs"></ul>', '<ul class="lm_controls"></ul>', '</div>' ].join( '' ); lm.utils.copy( lm.controls.Header.prototype, { /** * Creates a new tab and associates it with a contentItem * * @param {lm.item.AbstractContentItem} contentItem * @param {Integer} index The position of the tab * * @returns {void} */ createTab: function( contentItem, index ) { var tab, i; //If there's already a tab relating to the //content item, don't do anything for( i = 0; i < this.tabs.length; i++ ) { if( this.tabs[ i ].contentItem === contentItem ) { return; } } tab = new lm.controls.Tab( this, contentItem ); if( this.tabs.length === 0 ) { this.tabs.push( tab ); this.tabsContainer.append( tab.element ); return; } if( index === undefined ) { index = this.tabs.length; } if( index > 0 ) { this.tabs[ index - 1 ].element.after( tab.element ); } else { this.tabs[ 0 ].element.before( tab.element ); } this.tabs.splice( index, 0, tab ); this._updateTabSizes(); }, /** * Finds a tab based on the contentItem its associated with and removes it. * * @param {lm.item.AbstractContentItem} contentItem * * @returns {void} */ removeTab: function( contentItem ) { for( var i = 0; i < this.tabs.length; i++ ) { if( this.tabs[ i ].contentItem === contentItem ) { this.tabs[ i ]._$destroy(); this.tabs.splice( i, 1 ); return; } } throw new Error( 'contentItem is not controlled by this header' ); }, /** * The programmatical equivalent of clicking a Tab. * * @param {lm.item.AbstractContentItem} contentItem */ setActiveContentItem: function( contentItem ) { var i, isActive; for( i = 0; i < this.tabs.length; i++ ) { isActive = this.tabs[ i ].contentItem === contentItem; this.tabs[ i ].setActive( isActive ); if( isActive === true ) { this.activeContentItem = contentItem; this.parent.config.activeItemIndex = i; } } this._updateTabSizes(); this.parent.emitBubblingEvent( 'stateChanged' ); }, /** * Destroys the entire header * * @package private * * @returns {void} */ _$destroy: function() { this.emit( 'destroy' ); for( var i = 0; i < this.tabs.length; i++ ) { this.tabs[ i ]._$destroy(); } this.element.remove(); }, /** * Creates the popout, maximise and close buttons in the header's top right corner * * @returns {void} */ _createControls: function() { var closeStack, popout, label, maximiseLabel, minimiseLabel, maximise, maximiseButton; /** * Popout control to launch component in new window. */ if( this.layoutManager.config.settings.showPopoutIcon ) { popout = lm.utils.fnBind( this._onPopoutClick, this ); label = this.layoutManager.config.labels.popout; new lm.controls.HeaderButton( this, label, 'lm_popout', popout ); } /** * Maximise control - set the component to the full size of the layout */ if( this.layoutManager.config.settings.showMaximiseIcon ) { maximise = lm.utils.fnBind( this.parent.toggleMaximise, this.parent ); maximiseLabel = this.layoutManager.config.labels.maximise; minimiseLabel = this.layoutManager.config.labels.minimise; maximiseButton = new lm.controls.HeaderButton( this, maximiseLabel, 'lm_maximise', maximise ); this.parent.on( 'maximised', function(){ maximiseButton.element.attr( 'title', minimiseLabel ); }); this.parent.on( 'minimised', function(){ maximiseButton.element.attr( 'title', maximiseLabel ); }); } /** * Close button */ if( this.parent.config.isClosable && this.layoutManager.config.settings.showCloseIcon ) { closeStack = lm.utils.fnBind( this.parent.remove, this.parent ); label = this.layoutManager.config.labels.close; new lm.controls.HeaderButton( this, label, 'lm_close', closeStack ); } }, _onPopoutClick: function() { if( this.layoutManager.config.settings.popoutWholeStack === true ) { this.parent.popout(); } else { this.activeContentItem.popout(); } }, /** * Invoked when the header's background is clicked (not it's tabs or controls) * * @param {jQuery DOM event} event * * @returns {void} */ _onHeaderClick: function( event ) { if( event.target === this.element[ 0 ] ) { this.parent.select(); } }, /** * Shrinks the tabs if the available space is not sufficient * * @returns {void} */ _updateTabSizes: function() { if( this.tabs.length === 0 ) { return; } var availableWidth = this.element.outerWidth() - this.controlsContainer.outerWidth(), totalTabWidth = 0, tabElement, i, marginLeft, gap; for( i = 0; i < this.tabs.length; i++ ) { tabElement = this.tabs[ i ].element; /* * In order to show every tab's close icon, decrement the z-index from left to right */ tabElement.css( 'z-index', this.tabs.length - i ); totalTabWidth += tabElement.outerWidth() + parseInt( tabElement.css( 'margin-right' ), 10 ); } gap = ( totalTabWidth - availableWidth ) / ( this.tabs.length - 1 ); for( i = 0; i < this.tabs.length; i++ ) { /* * The active tab keeps it's original width */ if( !this.tabs[ i ].isActive && gap > 0 ) { marginLeft = '-' + Math.floor( gap )+ 'px'; } else { marginLeft = ''; } this.tabs[ i ].element.css( 'margin-left', marginLeft ); } if( availableWidth < totalTabWidth ) { this.element.css( 'overflow', 'hidden' ); } else { this.element.css( 'overflow', 'visible' ); } } }); lm.controls.HeaderButton = function( header, label, cssClass, action ) { this._header = header; this.element = $( '<li class="' + cssClass + '" title="' + label + '"></li>' ); this._header.on( 'destroy', this._$destroy, this ); this._action = action; this.element.click( this._action ); this._header.controlsContainer.append( this.element ); }; lm.utils.copy( lm.controls.HeaderButton.prototype, { _$destroy: function() { this.element.off(); this.element.remove(); } }); lm.controls.Splitter = function( isVertical, size ) { this._isVertical = isVertical; this._size = size; this.element = this._createElement(); this._dragListener = new lm.utils.DragListener( this.element ); }; lm.utils.copy( lm.controls.Splitter.prototype, { on: function( event, callback, context ) { this._dragListener.on( event, callback, context ); }, _$destroy: function() { this.element.remove(); }, _createElement: function() { var element = $( '<div class="lm_splitter"><div class="lm_drag_handle"></div></div>' ); element.addClass( 'lm_' + ( this._isVertical ? 'vertical' : 'horizontal' ) ); element[ this._isVertical ? 'height' : 'width' ]( this._size ); return element; } }); /** * Represents an individual tab within a Stack's header * * @param {lm.controls.Header} header * @param {lm.items.AbstractContentItem} contentItem * * @constructor */ lm.controls.Tab = function( header, contentItem ) { this.header = header; this.contentItem = contentItem; this.element = $( lm.controls.Tab._template ); this.titleElement = this.element.find( '.lm_title' ); this.closeElement = this.element.find( '.lm_close_tab' ); this.closeElement[ contentItem.config.isClosable ? 'show' : 'hide' ](); this.isActive = false; this.setTitle( contentItem.config.title ); this.contentItem.on( 'titleChanged', this.setTitle, this ); this._layoutManager = this.contentItem.layoutManager; if( this._layoutManager.config.settings.reorderEnabled === true && contentItem.config.reorderEnabled === true ) { this._dragListener = new lm.utils.DragListener( this.element ); this._dragListener.on( 'dragStart', this._onDragStart, this ); } this._onTabClickFn = lm.utils.fnBind( this._onTabClick, this ); this._onCloseClickFn = lm.utils.fnBind( this._onCloseClick, this ); this.element.click( this._onTabClickFn ); if( this._layoutManager.config.settings.showCloseIcon === true ) { this.closeElement.click( this._onCloseClickFn ); } else { this.closeElement.remove(); } this.contentItem.tab = this; this.contentItem.emit( 'tab', this ); this.contentItem.layoutManager.emit( 'tabCreated', this ); if( this.contentItem.isComponent ) { this.contentItem.container.tab = this; this.contentItem.container.emit( 'tab', this ); } }; /** * The tab's html template * * @type {String} */ lm.controls.Tab._template = '<li class="lm_tab"><i class="lm_left"></i>' + '<span class="lm_title"></span><div class="lm_close_tab"></div>' + '<i class="lm_right"></i></li>'; lm.utils.copy( lm.controls.Tab.prototype,{ /** * Sets the tab's title to the provided string and sets * its title attribute to a pure text representation (without * html tags) of the same string. * * @public * @param {String} title can contain html */ setTitle: function( title ) { this.element.attr( 'title', lm.utils.stripTags( title ) ); this.titleElement.html( title ); }, /** * Sets this tab's active state. To programmatically * switch tabs, use header.setActiveContentItem( item ) instead. * * @public * @param {Boolean} isActive */ setActive: function( isActive ) { if( isActive === this.isActive ) { return; } this.isActive = isActive; if( isActive ) { this.element.addClass( 'lm_active' ); } else { this.element.removeClass( 'lm_active'); } }, /** * Destroys the tab * * @private * @returns {void} */ _$destroy: function() { this.element.off( 'click', this._onTabClickFn ); this.closeElement.off( 'click', this._onCloseClickFn ); this.element.remove(); }, /** * Callback for the DragListener * * @param {Number} x The tabs absolute x position * @param {Number} y The tabs absolute y position * * @private * @returns {void} */ _onDragStart: function( x, y ) { if( this.contentItem.parent.isMaximised === true ) { this.contentItem.parent.toggleMaximise(); } new lm.controls.DragProxy( x, y, this._dragListener, this._layoutManager, this.contentItem, this.header.parent ); }, /** * Callback when the tab is clicked * * @param {jQuery DOM event} event * * @private * @returns {void} */ _onTabClick: function( event ) { // left mouse button if( event.button === 0 ) { this.header.parent.setActiveContentItem( this.contentItem ); // middle mouse button } else if( event.button === 1 && this.contentItem.config.isClosable ) { this._onCloseClick( event ); } }, /** * Callback when the tab's close button is * clicked * * @param {jQuery DOM event} event * * @private * @returns {void} */ _onCloseClick: function( event ) { event.stopPropagation(); this.header.parent.removeChild( this.contentItem ); } }); lm.controls.TransitionIndicator = function() { this._element = $( '<div class="lm_transition_indicator"></div>' ); $( document.body ).append( this._element ); this._toElement = null; this._fromDimensions = null; this._totalAnimationDuration = 200; this._animationStartTime = null; }; lm.utils.copy( lm.controls.TransitionIndicator.prototype, { destroy: function() { this._element.remove(); }, transitionElements: function( fromElement, toElement ) { /** * TODO - This is not quite as cool as expected. Review. */ return; this._toElement = toElement; this._animationStartTime = lm.utils.now(); this._fromDimensions = this._measure( fromElement ); this._fromDimensions.opacity = 0.8; this._element.show().css( this._fromDimensions ); lm.utils.animFrame( lm.utils.fnBind( this._nextAnimationFrame, this ) ); }, _nextAnimationFrame: function() { var toDimensions = this._measure( this._toElement ), animationProgress = ( lm.utils.now() - this._animationStartTime ) / this._totalAnimationDuration, currentFrameStyles = {}, cssProperty; if( animationProgress >= 1 ) { this._element.hide(); return; } toDimensions.opacity = 0; for( cssProperty in this._fromDimensions ) { currentFrameStyles[ cssProperty ] = this._fromDimensions[ cssProperty ] + ( toDimensions[ cssProperty] - this._fromDimensions[ cssProperty ] ) * animationProgress; } this._element.css( currentFrameStyles ); lm.utils.animFrame( lm.utils.fnBind( this._nextAnimationFrame, this ) ); }, _measure: function( element ) { var offset = element.offset(); return { left: offset.left, top: offset.top, width: element.outerWidth(), height: element.outerHeight() }; } }); lm.errors.ConfigurationError = function( message, node ) { Error.call( this ); this.name = 'Configuration Error'; this.message = message; this.node = node; }; lm.errors.ConfigurationError.prototype = new Error(); /** * This is the baseclass that all content items inherit from. * Most methods provide a subset of what the sub-classes do. * * It also provides a number of functions for tree traversal * * @param {lm.LayoutManager} layoutManager * @param {item node configuration} config * @param {lm.item} parent * * @event stateChanged * @event beforeItemDestroyed * @event itemDestroyed * @event itemCreated * @event componentCreated * @event rowCreated * @event columnCreated * @event stackCreated * * @constructor */ lm.items.AbstractContentItem = function( layoutManager, config, parent ) { lm.utils.EventEmitter.call( this ); this.config = this._extendItemNode( config ); this.type = config.type; this.contentItems = []; this.parent = parent; this.isInitialised = false; this.isMaximised = false; this.isRoot = false; this.isRow = false; this.isColumn = false; this.isStack = false; this.isComponent = false; this.layoutManager = layoutManager; this._pendingEventPropagations = {}; this._throttledEvents = [ 'stateChanged' ]; this.on( lm.utils.EventEmitter.ALL_EVENT, this._propagateEvent, this ); if( config.content ) { this._createContentItems( config ); } }; lm.utils.copy( lm.items.AbstractContentItem.prototype, { /** * Set the size of the component and its children, called recoursively * * @abstract * @returns void */ setSize: function() { throw new Error( 'Abstract Method' ); }, /** * Calls a method recoursively downwards on the tree * * @param {String} functionName the name of the function to be called * @param {[Array]}functionArguments optional arguments that are passed to every function * @param {[bool]} bottomUp Call methods from bottom to top, defaults to false * @param {[bool]} skipSelf Don't invoke the method on the class that calls it, defaults to false * * @returns {void} */ callDownwards: function( functionName, functionArguments, bottomUp, skipSelf ) { var i; if( bottomUp !== true && skipSelf !== true ) { this[ functionName ].apply( this, functionArguments || [] ); } for( i = 0; i < this.contentItems.length; i++ ) { this.contentItems[ i ].callDownwards( functionName, functionArguments, bottomUp ); } if( bottomUp === true && skipSelf !== true ) { this[ functionName ].apply( this, functionArguments || [] ); } }, /** * Removes a child node (and its children) from the tree * * @param {lm.items.ContentItem} contentItem * * @returns {void} */ removeChild: function( contentItem, keepChild ) { /* * Get the position of the item that's to be removed within all content items this node contains */ var index = lm.utils.indexOf( contentItem, this.contentItems ); /* * Make sure the content item to be removed is actually a child of this item */ if( index === -1 ) { throw new Error( 'Can\'t remove child item. Unknown content item' ); } /** * Call ._$destroy on the content item. This also calls ._$destroy on all its children */ if( keepChild !== true ) { this.contentItems[ index ]._$destroy(); } /** * Remove the content item from this nodes array of children */ this.contentItems.splice( index, 1 ); /** * Remove the item from the configuration */ this.config.content.splice( index, 1 ); /** * If this node still contains other content items, adjust their size */ if( this.contentItems.length > 0 ) { this.callDownwards( 'setSize' ); /** * If this was the last content item, remove this node as well */ } else if( !(this instanceof lm.items.Root) && this.config.isClosable === true ) { this.parent.removeChild( this ); } }, /** * Sets up the tree structure for the newly added child * The responsibility for the actual DOM manipulations lies * with the concrete item * * @param {lm.items.AbstractContentItem} contentItem * @param {[Int]} index If omitted item will be appended */ addChild: function( contentItem, index ) { if ( index === undefined ) { index = this.contentItems.length; } this.contentItems.splice( index, 0, contentItem ); if( this.config.content === undefined ) { this.config.content = []; } this.config.content.splice( index, 0, contentItem.config ); contentItem.parent = this; if( contentItem.parent.isInitialised === true && contentItem.isInitialised === false ) { contentItem._$init(); } }, /** * Replaces oldChild with newChild. This used to use jQuery.replaceWith... which for * some reason removes all event listeners, so isn't really an option. * * @param {lm.item.AbstractContentItem} oldChild * @param {lm.item.AbstractContentItem} newChild * * @returns {void} */ replaceChild: function( oldChild, newChild, _$destroyOldChild ) { newChild = this.layoutManager._$normalizeContentItem( newChild ); var index = lm.utils.indexOf( oldChild, this.contentItems ), parentNode = oldChild.element[ 0 ].parentNode; if( index === -1 ) { throw new Error( 'Can\'t replace child. oldChild is not child of this' ); } parentNode.replaceChild( newChild.element[ 0 ], oldChild.element[ 0 ] ); /* * Optionally destroy the old content item */ if( _$destroyOldChild === true ) { oldChild.parent = null; oldChild._$destroy(); } /* * Wire the new contentItem into the tree */ this.contentItems[ index ] = newChild; newChild.parent = this; //TODO This doesn't update the config... refactor to leave item nodes untouched after creation if( newChild.parent.isInitialised === true && newChild.isInitialised === false ) { newChild._$init(); } this.callDownwards( 'setSize' ); }, /** * Convenience method. * Shorthand for this.parent.removeChild( this ) * * @returns {void} */ remove: function() { this.parent.removeChild( this ); }, /** * Removes the component from the layout and creates a new * browser window with the component and its children inside * * @returns {lm.controls.BrowserPopout} */ popout: function() { var browserPopout = this.layoutManager.createPopout( this ); this.emitBubblingEvent( 'stateChanged' ); return browserPopout; }, /** * Maximises the Item or minimises it if it is already maximised * * @returns {void} */ toggleMaximise: function() { if( this.isMaximised === true ) { this.layoutManager._$minimiseItem( this ); } else { this.layoutManager._$maximiseItem( this ); } this.isMaximised = !this.isMaximised; this.emitBubblingEvent( 'stateChanged' ); }, /** * Selects the item if it is not already selected * * @returns {void} */ select: function() { if( this.layoutManager.selectedItem !== this ) { this.layoutManager.selectItem( this, true ); this.element.addClass( 'lm_selected' ); } }, /** * De-selects the item if it is selected * * @returns {void} */ deselect: function() { if( this.layoutManager.selectedItem === this ) { this.layoutManager.selectedItem = null; this.element.removeClass( 'lm_selected' ); } }, /** * Set this component's title * * @public * @param {String} title * * @returns {void} */ setTitle: function( title ) { this.config.title = title; this.emit( 'titleChanged', title ); this.emit( 'stateChanged' ); }, /** * Checks whether a provided id is present * * @public * @param {String} id * * @returns {Boolean} isPresent */ hasId: function( id ) { if( !this.config.id ) { return false; } else if( typeof this.config.id === 'string' ) { return this.config.id === id; } else if( this.config.id instanceof Array ) { return lm.utils.indexOf( id, this.config.id ) !== -1; } }, /** * Adds an id. Adds it as a string if the component doesn't * have an id yet or creates/uses an array * * @public * @param {String} id * * @returns {void} */ addId: function( id ) { if( this.hasId( id ) ) { return; } if( !this.config.id ) { this.config.id = id; } else if( typeof this.config.id === 'string' ) { this.config.id = [ this.config.id, id ]; } else if( this.config.id instanceof Array ) { this.config.id.push( id ); } }, /** * Removes an existing id. Throws an error * if the id is not present * * @public * @param {String} id * * @returns {void} */ removeId: function( id ) { if( !this.hasId( id ) ) { throw new Error( 'Id not found' ); } if( typeof this.config.id === 'string' ) { delete this.config.id; } else if( this.config.id instanceof Array ) { var index = lm.utils.indexOf( id, this.config.id ); this.config.id.splice( index, 1 ); } }, /**************************************** * SELECTOR ****************************************/ getItemsByFilter: function( filter ) { var result = [], next = function( contentItem ) { for( var i = 0; i < contentItem.contentItems.length; i++ ) { if( filter( contentItem.contentItems[ i ] ) === true ) { result.push( contentItem.contentItems[ i ] ); } next( contentItem.contentItems[ i ] ); } }; next( this ); return result; }, getItemsById: function( id ) { return this.getItemsByFilter( function( item ){ if( item.config.id instanceof Array ) { return lm.utils.indexOf( id, item.config.id ) !== -1; } else { return item.config.id === id; } }); }, getItemsByType: function( type ) { return this._$getItemsByProperty( 'type', type ); }, getComponentsByName: function( componentName ) { var components = this._$getItemsByProperty( 'componentName', componentName ), instances = [], i; for( i = 0; i < components.length; i++ ) { instances.push( components[ i ].instance ); } return instances; }, /**************************************** * PACKAGE PRIVATE ****************************************/ _$getItemsByProperty: function( key, value ) { return this.getItemsByFilter( function( item ){ return item[ key ] === value; }); }, _$setParent: function( parent ) { this.parent = parent; }, _$highlightDropZone: function( x, y, area ) { this.layoutManager.dropTargetIndicator.highlightArea( area ); }, _$onDrop: function( contentItem ) { this.addChild( contentItem ); }, _$hide: function() { this._callOnActiveComponents( 'hide' ); this.element.hide(); this.layoutManager.updateSize(); }, _$show: function() { this._callOnActiveComponents( 'show' ); this.element.show(); this.layoutManager.updateSize(); }, _callOnActiveComponents: function( methodName ) { var stacks = this.getItemsByType( 'stack' ), activeContentItem, i; for( i = 0; i < stacks.length; i++ ) { activeContentItem = stacks[ i ].getActiveContentItem(); if( activeContentItem && activeContentItem.isComponent ) { activeContentItem.container[ methodName ](); } } }, /** * Destroys this item ands its children * * @returns {void} */ _$destroy: function() { this.emitBubblingEvent( 'beforeItemDestroyed' ); this.callDownwards( '_$destroy', [], true, true ); this.element.remove(); this.emitBubblingEvent( 'itemDestroyed' ); }, /** * Returns the area the component currently occupies in the format * * { * x1: int * xy: int * y1: int * y2: int * contentItem: contentItem * } */ _$getArea: function( element ) { element = element || this.element; var offset = element.offset(), width = element.width(), height = element.height(); return { x1: offset.left, y1: offset.top, x2: offset.left + width, y2: offset.top + height, surface: width * height, contentItem: this }; }, /** * The tree of content items is created in two steps: First all content items are instantiated, * then init is called recoursively from top to bottem. This is the basic init function, * it can be used, extended or overwritten by the content items * * Its behaviour depends on the content item * * @package private * * @returns {void} */ _$init: function() { var i; this.setSize(); for( i = 0; i < this.contentItems.length; i++ ) { this.childElementContainer.append( this.contentItems[ i ].element ); } this.isInitialised = true; this.emitBubblingEvent( 'itemCreated' ); this.emitBubblingEvent( this.type + 'Created' ); }, /** * Emit an event that bubbles up the item tree. * * @param {String} name The name of the event * * @returns {void} */ emitBubblingEvent: function( name ) { var event = new lm.utils.BubblingEvent( name, this ); this.emit( name, event ); }, /** * Private method, creates all content items for this node at initialisation time * PLEASE NOTE, please see addChild for adding contentItems add runtime * @private * @param {configuration item node} config * * @returns {void} */ _createContentItems: function( config ) { var oContentItem, i; if( !( config.content instanceof Array ) ) { throw new lm.errors.ConfigurationError( 'content must be an Array', config ); } for( i = 0; i < config.content.length; i++ ) { oContentItem = this.layoutManager.createContentItem( config.content[ i ], this ); this.contentItems.push( oContentItem ); } }, /** * Extends an item configuration node with default settings * @private * @param {configuration item node} config * * @returns {configuration item node} extended config */ _extendItemNode: function( config ) { for( var key in lm.config.itemDefaultConfig ) { if( config[ key ] === undefined ) { config[ key ] = lm.config.itemDefaultConfig[ key ]; } } return config; }, /** * Called for every event on the item tree. Decides whether the event is a bubbling * event and propagates it to its parent * * @param {String} name the name of the event * @param {lm.utils.BubblingEvent} event * * @returns {void} */ _propagateEvent: function( name, event ) { if( event instanceof lm.utils.BubblingEvent && event.isPropagationStopped === false && this.isInitialised === true ) { /** * In some cases (e.g. if an element is created from a DragSource) it * doesn't have a parent and is not below root. If that's the case * propagate the bubbling event from the top level of the substree directly * to the layoutManager */ if( this.isRoot === false && this.parent ) { this.parent.emit.apply( this.parent, Array.prototype.slice.call( arguments, 0 ) ); } else { this._scheduleEventPropagationToLayoutManager( name, event ); } } }, /** * All raw events bubble up to the root element. Some events that * are propagated to - and emitted by - the layoutManager however are * only string-based, batched and sanitized to make them more usable * * @param {String} name the name of the event * * @private * @returns {void} */ _scheduleEventPropagationToLayoutManager: function( name, event ) { if( lm.utils.indexOf( name, this._throttledEvents ) === -1 ) { this.layoutManager.emit( name, event.origin ); } else { if( this._pendingEventPropagations[ name ] !== true ) { this._pendingEventPropagations[ name ] = true; lm.utils.animFrame( lm.utils.fnBind( this._propagateEventToLayoutManager, this, [ name, event ] ) ); } } }, /** * Callback for events scheduled by _scheduleEventPropagationToLayoutManager * * @param {String} name the name of the event * * @private * @returns {void} */ _propagateEventToLayoutManager: function( name, event ) { this._pendingEventPropagations[ name ] = false; this.layoutManager.emit( name, event ); } }); /** * @param {[type]} layoutManager [description] * @param {[type]} config [description] * @param {[type]} parent [description] */ lm.items.Component = function( layoutManager, config, parent ) { lm.items.AbstractContentItem.call( this, layoutManager, config, parent ); var ComponentConstructor = layoutManager.getComponent( this.config.componentName ), componentConfig = $.extend( true, {}, this.config.componentState || {} ); componentConfig.componentName = this.config.componentName; this.componentName = this.config.componentName; if( this.config.title === '' ) { this.config.title = this.config.componentName; } this.isComponent = true; this.container = new lm.container.ItemContainer( this.config, this, layoutManager ); this.instance = new ComponentConstructor( this.container, componentConfig ); this.element = this.container._element; }; lm.utils.extend( lm.items.Component, lm.items.AbstractContentItem ); lm.utils.copy( lm.items.Component.prototype, { close: function() { this.parent.removeChild( this ); }, setSize: function() { this.container._$setSize( this.element.width(), this.element.height() ); }, _$init: function() { lm.items.AbstractContentItem.prototype._$init.call( this ); this.container.emit( 'open' ); }, _$hide: function() { this.container.hide(); lm.items.AbstractContentItem.prototype._$hide.call( this ); }, _$show: function() { this.container.show(); lm.items.AbstractContentItem.prototype._$show.call( this ); }, _$destroy: function() { this.container.emit( 'destroy' ); lm.items.AbstractContentItem.prototype._$destroy.call( this ); }, /** * Dragging onto a component directly is not an option * * @returns null */ _$getArea: function() { return null; } }); lm.items.Root = function( layoutManager, config, containerElement ) { lm.items.AbstractContentItem.call( this, layoutManager, config, null ); this.isRoot = true; this.type = 'root'; this.element = $( '<div class="lm_goldenlayout lm_item lm_root"></div>' ); this.childElementContainer = this.element; this._containerElement = containerElement; this._containerElement.append( this.element ); }; lm.utils.extend( lm.items.Root, lm.items.AbstractContentItem ); lm.utils.copy( lm.items.Root.prototype, { addChild: function( contentItem ) { if( this.contentItems.length > 0 ) { throw new Error( 'Root node can only have a single child' ); } contentItem = this.layoutManager._$normalizeContentItem( contentItem, this ); this.childElementContainer.append( contentItem.element ); lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem ); this.callDownwards( 'setSize' ); this.emitBubblingEvent( 'stateChanged' ); }, setSize: function() { var width = this._containerElement.width(), height = this._containerElement.height(); this.element.width( width ); this.element.height( height ); /* * Root can be empty */ if( this.contentItems[ 0 ] ) { this.contentItems[ 0 ].element.width( width ); this.contentItems[ 0 ].element.height( height ); } }, _$onDrop: function( contentItem ) { var stack; if( contentItem.isComponent === true ) { stack = this.layoutManager.createContentItem( {type: 'stack' }, this ); stack.addChild( contentItem ); this.addChild( stack ); } else { this.addChild( contentItem ); } } }); lm.items.RowOrColumn = function( isColumn, layoutManager, config, parent ) { lm.items.AbstractContentItem.call( this, layoutManager, config, parent ); this.isRow = !isColumn; this.isColumn = isColumn; this.element = $( '<div class="lm_item lm_' + ( isColumn ? 'column' : 'row' ) + '"></div>' ); this.childElementContainer = this.element; this._splitterSize = layoutManager.config.dimensions.borderWidth; this._isColumn = isColumn; this._dimension = isColumn ? 'height' : 'width'; this._splitter = []; this._splitterPosition = null; this._splitterMinPosition = null; this._splitterMaxPosition = null; }; lm.utils.extend( lm.items.RowOrColumn, lm.items.AbstractContentItem ); lm.utils.copy( lm.items.RowOrColumn.prototype, { /** * Add a new contentItem to the Row or Column * * @param {lm.item.AbstractContentItem} contentItem * @param {[int]} index The position of the new item within the Row or Column. * If no index is provided the item will be added to the end * @param {[bool]} _$suspendResize If true the items won't be resized. This will leave the item in * an inconsistent state and is only intended to be used if multiple * children need to be added in one go and resize is called afterwards * * @returns {void} */ addChild: function( contentItem, index, _$suspendResize ) { var newItemSize, itemSize, i, splitterElement; contentItem = this.layoutManager._$normalizeContentItem( contentItem, this ); if( index === undefined ) { index = this.contentItems.length; } if( this.contentItems.length > 0 ) { splitterElement = this._createSplitter( Math.max( 0, index - 1 ) ).element; if( index > 0 ) { this.contentItems[ index - 1 ].element.after( splitterElement ); splitterElement.after( contentItem.element ); } else { this.contentItems[ 0 ].element.before( splitterElement ); splitterElement.before( contentItem.element ); } } else { this.childElementContainer.append( contentItem.element ); } lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem, index ); newItemSize = ( 1 / this.contentItems.length ) * 100; if( _$suspendResize === true ) { this.emitBubblingEvent( 'stateChanged' ); return; } for( i = 0; i < this.contentItems.length; i++ ) { if( this.contentItems[ i ] === contentItem ) { contentItem.config[ this._dimension ] = newItemSize; } else { itemSize = this.contentItems[ i ].config[ this._dimension ] *= ( 100 - newItemSize ) / 100; this.contentItems[ i ].config[ this._dimension ] = itemSize; } } this.callDownwards( 'setSize' ); this.emitBubblingEvent( 'stateChanged' ); }, /** * Removes a child of this element * * @param {lm.items.AbstractContentItem} contentItem * @param {boolean} keepChild If true the child will be removed, but not destroyed * * @returns {void} */ removeChild: function( contentItem, keepChild ) { var removedItemSize = contentItem.config[ this._dimension ], index = lm.utils.indexOf( contentItem, this.contentItems ), splitterIndex = Math.max( index - 1, 0 ), i, childItem; if( index === -1 ) { throw new Error( 'Can\'t remove child. ContentItem is not child of this Row or Column' ); } /** * Remove the splitter before the item or after if the item happens * to be the first in the row/column */ if( this._splitter[ splitterIndex ] ) { this._splitter[ splitterIndex ]._$destroy(); this._splitter.splice( splitterIndex, 1 ); } /** * Allocate the space that the removed item occupied to the remaining items */ for( i = 0; i < this.contentItems.length; i++ ) { if( this.contentItems[ i ] !== contentItem ) { this.contentItems[ i ].config[ this._dimension ] += removedItemSize / ( this.contentItems.length - 1 ); } } lm.items.AbstractContentItem.prototype.removeChild.call( this, contentItem, keepChild ); if( this.contentItems.length === 1 && this.config.isClosable === true ) { childItem = this.contentItems[ 0 ]; this.contentItems = []; this.parent.replaceChild( this, childItem, true ); } else { this.callDownwards( 'setSize' ); this.emitBubblingEvent( 'stateChanged' ); } }, /** * Replaces a child of this Row or Column with another contentItem * * @param {lm.items.AbstractContentItem} oldChild * @param {lm.items.AbstractContentItem} newChild * * @returns {void} */ replaceChild: function( oldChild, newChild ) { var size = oldChild.config[ this._dimension ]; lm.items.AbstractContentItem.prototype.replaceChild.call( this, oldChild, newChild ); newChild.config[ this._dimension ] = size; this.callDownwards( 'setSize' ); this.emitBubblingEvent( 'stateChanged' ); }, /** * Called whenever the dimensions of this item or one of its parents change * * @returns {void} */ setSize: function() { if( this.contentItems.length > 0 ) { this._calculateRelativeSizes(); this._setAbsoluteSizes(); } this.emitBubblingEvent( 'stateChanged' ); this.emit( 'resize' ); }, /** * Invoked recoursively by the layout manager. AbstractContentItem.init appends * the contentItem's DOM elements to the container, RowOrColumn init adds splitters * in between them * * @package private * @override AbstractContentItem._$init * @returns {void} */ _$init: function() { if( this.isInitialised === true ) return; var i; lm.items.AbstractContentItem.prototype._$init.call( this ); for( i = 0; i < this.contentItems.length - 1; i++ ) { this.contentItems[ i ].element.after( this._createSplitter( i ).element ); } }, /** * Turns the relative sizes calculated by _calculateRelativeSizes into * absolute pixel values and applies them to the children's DOM elements * * Assigns additional pixels to counteract Math.floor * * @private * @returns {void} */ _setAbsoluteSizes: function() { var i, totalSplitterSize = ( this.contentItems.length - 1 ) * this._splitterSize, totalWidth = this.element.width(), totalHeight = this.element.height(), totalAssigned = 0, additionalPixel, itemSize, itemSizes = []; if( this._isColumn ) { totalHeight -= totalSplitterSize; } else { totalWidth -= totalSplitterSize; } for( i = 0; i < this.contentItems.length; i++ ) { if( this._isColumn ) { itemSize = Math.floor( totalHeight * ( this.contentItems[ i ].config.height / 100 ) ); } else { itemSize = Math.floor( totalWidth * ( this.contentItems[ i ].config.width / 100 ) ); } totalAssigned += itemSize; itemSizes.push( itemSize ); } additionalPixel = ( this._isColumn ? totalHeight : totalWidth ) - totalAssigned; for( i = 0; i < this.contentItems.length; i++ ) { if( additionalPixel - i > 0 ) { itemSizes[ i ]++; } if( this._isColumn ) { this.contentItems[ i ].element.width( totalWidth ); this.contentItems[ i ].element.height( itemSizes[ i ] ); } else { this.contentItems[ i ].element.width( itemSizes[ i ] ); this.contentItems[ i ].element.height( totalHeight ); } } }, /** * Calculates the relative sizes of all children of this Item. The logic * is as follows: * * - Add up the total size of all items that have a configured size * * - If the total == 100 (check for floating point errors) * Excellent, job done * * - If the total is > 100, * set the size of items without set dimensions to 1/3 and add this to the total * set the size off all items so that the total is hundred relative to their original size * * - If the total is < 100 * If there are items without set dimensions, distribute the remainder to 100 evenly between them * If there are no items without set dimensions, increase all items sizes relative to * their original size so that they add up to 100 * * @private * @returns {void} */ _calculateRelativeSizes: function() { var i, total = 0, itemsWithoutSetDimension = [], dimension = this._isColumn ? 'height' : 'width'; for( i = 0; i < this.contentItems.length; i++ ) { if( this.contentItems[ i ].config[ dimension ] !== undefined ) { total += this.contentItems[ i ].config[ dimension ]; } else { itemsWithoutSetDimension.push( this.contentItems[ i ] ); } } /** * Everything adds up to hundred, all good :-) */ if( Math.round( total ) === 100 ) { return; } /** * Allocate the remaining size to the items without a set dimension */ if( Math.round( total ) < 100 && itemsWithoutSetDimension.length > 0 ) { for( i = 0; i < itemsWithoutSetDimension.length; i++ ) { itemsWithoutSetDimension[ i ].config[ dimension ] = ( 100 - total ) / itemsWithoutSetDimension.length; } return; } /** * If the total is > 100, but there are also items without a set dimension left, assing 50 * as their dimension and add it to the total * * This will be reset in the next step */ if( Math.round( total ) > 100 ) { for( i = 0; i < itemsWithoutSetDimension.length; i++ ) { itemsWithoutSetDimension[ i ].config[ dimension ] = 50; total += 50; } } /** * Set every items size relative to 100 relative to its size to total */ for( i = 0; i < this.contentItems.length; i++ ) { this.contentItems[ i ].config[ dimension ] = ( this.contentItems[ i ].config[ dimension ] / total ) * 100; } }, /** * Instantiates a new lm.controls.Splitter, binds events to it and adds * it to the array of splitters at the position specified as the index argument * * What it doesn't do though is append the splitter to the DOM * * @param {Int} index The position of the splitter * * @returns {lm.controls.Splitter} */ _createSplitter: function( index ) { var splitter; splitter = new lm.controls.Splitter( this._isColumn, this._splitterSize ); splitter.on( 'drag', lm.utils.fnBind( this._onSplitterDrag, this, [ splitter ] ), this ); splitter.on( 'dragStop', lm.utils.fnBind( this._onSplitterDragStop, this, [ splitter ] ), this ); splitter.on( 'dragStart', lm.utils.fnBind( this._onSplitterDragStart, this, [ splitter ] ), this ); this._splitter.splice( index, 0, splitter ); return splitter; }, /** * Locates the instance of lm.controls.Splitter in the array of * registered splitters and returns a map containing the contentItem * before and after the splitters, both of which are affected if the * splitter is moved * * @param {lm.controls.Splitter} splitter * * @returns {Object} A map of contentItems that the splitter affects */ _getItemsForSplitter: function( splitter ) { var index = lm.utils.indexOf( splitter, this._splitter ); return { before: this.contentItems[ index ], after: this.contentItems[ index + 1 ] }; }, /** * Invoked when a splitter's dragListener fires dragStart. Calculates the splitters * movement area once (so that it doesn't need calculating on every mousemove event) * * @param {lm.controls.Splitter} splitter * * @returns {void} */ _onSplitterDragStart: function( splitter ) { var items = this._getItemsForSplitter( splitter ), minSize = this.layoutManager.config.dimensions[ this._isColumn ? 'minItemHeight' : 'minItemWidth' ]; this._splitterPosition = 0; this._splitterMinPosition = -1 * ( items.before.element[ this._dimension ]() - minSize ); this._splitterMaxPosition = items.after.element[ this._dimension ]() - minSize; }, /** * Invoked when a splitter's DragListener fires drag. Updates the splitters DOM position, * but not the sizes of the elements the splitter controls in order to minimize resize events * * @param {lm.controls.Splitter} splitter * @param {Int} offsetX Relative pixel values to the splitters original position. Can be negative * @param {Int} offsetY Relative pixel values to the splitters original position. Can be negative * * @returns {void} */ _onSplitterDrag: function( splitter, offsetX, offsetY ) { var offset = this._isColumn ? offsetY : offsetX; if( offset > this._splitterMinPosition && offset < this._splitterMaxPosition ) { this._splitterPosition = offset; splitter.element.css( this._isColumn ? 'top' : 'left', offset ); } }, /** * Invoked when a splitter's DragListener fires dragStop. Resets the splitters DOM position, * and applies the new sizes to the elements before and after the splitter and their children * on the next animation frame * * @param {lm.controls.Splitter} splitter * * @returns {void} */ _onSplitterDragStop: function( splitter ) { var items = this._getItemsForSplitter( splitter ), sizeBefore = items.before.element[ this._dimension ](), sizeAfter = items.after.element[ this._dimension ](), splitterPositionInRange = ( this._splitterPosition + sizeBefore ) / ( sizeBefore + sizeAfter ), totalRelativeSize = items.before.config[ this._dimension ] + items.after.config[ this._dimension ]; items.before.config[ this._dimension ] = splitterPositionInRange * totalRelativeSize; items.after.config[ this._dimension ] = ( 1 - splitterPositionInRange ) * totalRelativeSize; splitter.element.css({ 'top': 0, 'left': 0 }); lm.utils.animFrame( lm.utils.fnBind( this.callDownwards, this, [ 'setSize' ] ) ); } }); lm.items.Stack = function( layoutManager, config, parent ) { lm.items.AbstractContentItem.call( this, layoutManager, config, parent ); this.element = $( '<div class="lm_item lm_stack"></div>' ); this._activeContentItem = null; this._dropZones = {}; this._dropSegment = null; this._contentAreaDimensions = null; this._dropIndex = null; this.isStack = true; this.childElementContainer = $( '<div class="lm_items"></div>' ); this.header = new lm.controls.Header( layoutManager, this ); if( layoutManager.config.settings.hasHeaders === true ) { this.element.append( this.header.element ); } this.element.append( this.childElementContainer ); }; lm.utils.extend( lm.items.Stack, lm.items.AbstractContentItem ); lm.utils.copy( lm.items.Stack.prototype, { setSize: function() { var i, contentWidth = this.element.width(), contentHeight = this.element.height() - this.layoutManager.config.dimensions.headerHeight; this.childElementContainer.width( contentWidth ); this.childElementContainer.height( contentHeight ); for( i = 0; i < this.contentItems.length; i++ ) { this.contentItems[ i ].element.width( contentWidth ).height( contentHeight ); } this.emit( 'resize' ); this.emitBubblingEvent( 'stateChanged' ); }, _$init: function() { var i, initialItem; if( this.isInitialised === true ) return; lm.items.AbstractContentItem.prototype._$init.call( this ); for( i = 0; i < this.contentItems.length; i++ ) { this.header.createTab( this.contentItems[ i ] ); this.contentItems[ i ]._$hide(); } if( this.contentItems.length > 0 ) { initialItem = this.contentItems[ this.config.activeItemIndex || 0 ]; if( !initialItem ) { throw new Error( 'Configured activeItemIndex out of bounds' ); } this.setActiveContentItem( initialItem ); } }, setActiveContentItem: function( contentItem ) { if( lm.utils.indexOf( contentItem, this.contentItems ) === -1 ) { throw new Error( 'contentItem is not a child of this stack' ); } if( this._activeContentItem !== null ) { this._activeContentItem._$hide(); } this._activeContentItem = contentItem; this.header.setActiveContentItem( contentItem ); contentItem._$show(); this.emit( 'activeContentItemChanged', contentItem ); this.emitBubblingEvent( 'stateChanged' ); }, getActiveContentItem: function() { return this.header.activeContentItem; }, addChild: function( contentItem, index ) { contentItem = this.layoutManager._$normalizeContentItem( contentItem, this ); lm.items.AbstractContentItem.prototype.addChild.call( this, contentItem, index ); this.childElementContainer.append( contentItem.element ); this.header.createTab( contentItem, index ); this.setActiveContentItem( contentItem ); this.callDownwards( 'setSize' ); this.emitBubblingEvent( 'stateChanged' ); }, removeChild: function( contentItem, keepChild ) { var index = lm.utils.indexOf( contentItem, this.contentItems ); lm.items.AbstractContentItem.prototype.removeChild.call( this, contentItem, keepChild ); this.header.removeTab( contentItem ); if( this.contentItems.length > 0 ) { this.setActiveContentItem( this.contentItems[ Math.max( index -1 , 0 ) ] ); } else { this._activeContentItem = null; } this.emitBubblingEvent( 'stateChanged' ); }, _$destroy: function() { lm.items.AbstractContentItem.prototype._$destroy.call( this ); this.header._$destroy(); }, /** * Ok, this one is going to be the tricky one: The user has dropped {contentItem} onto this stack. * * It was dropped on either the stacks header or the top, right, bottom or left bit of the content area * (which one of those is stored in this._dropSegment). Now, if the user has dropped on the header the case * is relatively clear: We add the item to the existing stack... job done (might be good to have * tab reordering at some point, but lets not sweat it right now) * * If the item was dropped on the content part things are a bit more complicated. If it was dropped on either the * top or bottom region we need to create a new column and place the items accordingly. * Unless, of course if the stack is already within a column... in which case we want * to add the newly created item to the existing column... * either prepend or append it, depending on wether its top or bottom. * * Same thing for rows and left / right drop segments... so in total there are 9 things that can potentially happen * (left, top, right, bottom) * is child of the right parent (row, column) + header drop * * @param {lm.item} contentItem * * @returns {void} */ _$onDrop: function( contentItem ) { /* * The item was dropped on the header area. Just add it as a child of this stack and * get the hell out of this logic */ if( this._dropSegment === 'header' ) { this._resetHeaderDropZone(); this.addChild( contentItem, this._dropIndex ); return; } /* * The stack is empty. Let's just add the element. */ if( this._dropSegment === 'body' ) { this.addChild( contentItem ); return; } /* * The item was dropped on the top-, left-, bottom- or right- part of the content. Let's * aggregate some conditions to make the if statements later on more readable */ var isVertical = this._dropSegment === 'top' || this._dropSegment === 'bottom', isHorizontal = this._dropSegment === 'left' || this._dropSegment === 'right', insertBefore = this._dropSegment === 'top' || this._dropSegment === 'left', hasCorrectParent = ( isVertical && this.parent.isColumn ) || ( isHorizontal && this.parent.isRow ), type = isVertical ? 'column' : 'row', dimension = isVertical ? 'height' : 'width', index, stack, rowOrColumn; /* * The content item can be either a component or a stack. If it is a component, wrap it into a stack */ if( contentItem.isComponent ) { stack = this.layoutManager.createContentItem({ type: 'stack' }, this ); stack._$init(); stack.addChild( contentItem ); contentItem = stack; } /* * If the item is dropped on top or bottom of a column or left and right of a row, it's already * layd out in the correct way. Just add it as a child */ if( hasCorrectParent ) { index = lm.utils.indexOf( this, this.parent.contentItems ); this.parent.addChild( contentItem, insertBefore ? index : index + 1, true ); this.config[ dimension ] *= 0.5; contentItem.config[ dimension ] = this.config[ dimension ]; this.parent.callDownwards( 'setSize' ); /* * This handles items that are dropped on top or bottom of a row or left / right of a column. We need * to create the appropriate contentItem for them to life in */ } else { type = isVertical ? 'column' : 'row'; rowOrColumn = this.layoutManager.createContentItem({ type: type }, this ); this.parent.replaceChild( this, rowOrColumn ); rowOrColumn.addChild( contentItem, insertBefore ? 0 : undefined, true ); rowOrColumn.addChild( this, insertBefore ? undefined : 0, true ); this.config[ dimension ] = 50; contentItem.config[ dimension ] = 50; rowOrColumn.callDownwards( 'setSize' ); } }, /** * If the user hovers above the header part of the stack, indicate drop positions for tabs. * otherwise indicate which segment of the body the dragged item would be dropped on * * @param {Int} x Absolute Screen X * @param {Int} y Absolute Screen Y * * @returns {void} */ _$highlightDropZone: function( x, y ) { var segment, area; for( segment in this._contentAreaDimensions ) { area = this._contentAreaDimensions[ segment ].hoverArea; if( area.x1 < x && area.x2 > x && area.y1 < y && area.y2 > y ) { if( segment === 'header' ) { this._dropSegment = 'header'; this._highlightHeaderDropZone( x ); } else { this._resetHeaderDropZone(); this._highlightBodyDropZone( segment ); } return; } } }, _$getArea: function() { if( this.element.is( ':visible' ) === false ) { return null; } var getArea = lm.items.AbstractContentItem.prototype._$getArea, headerArea = getArea.call( this, this.header.element ), contentArea = getArea.call( this, this.childElementContainer ), contentWidth = contentArea.x2 - contentArea.x1, contentHeight = contentArea.y2 - contentArea.y1; this._contentAreaDimensions = { header: { hoverArea: { x1: headerArea.x1, y1: headerArea.y1, x2: headerArea.x2, y2: headerArea.y2 }, highlightArea: { x1: headerArea.x1, y1: headerArea.y1, x2: headerArea.x2, y2: headerArea.y2 } } }; /** * If this Stack is a parent to rows, columns or other stacks only its * header is a valid dropzone. */ if( this._activeContentItem && this._activeContentItem.isComponent === false ) { return headerArea; } /** * Highlight the entire body if the stack is empty */ if( this.contentItems.length === 0 ) { this._contentAreaDimensions.body = { hoverArea: { x1: contentArea.x1, y1: contentArea.y1, x2: contentArea.x2, y2: contentArea.y2 }, highlightArea: { x1: contentArea.x1, y1: contentArea.y1, x2: contentArea.x2, y2: contentArea.y2 } }; return getArea.call( this, this.element ); } this._contentAreaDimensions.left = { hoverArea: { x1: contentArea.x1, y1: contentArea.y1, x2: contentArea.x1 + contentWidth * 0.25, y2: contentArea.y2 }, highlightArea: { x1: contentArea.x1, y1: contentArea.y1, x2: contentArea.x1 + contentWidth * 0.5, y2: contentArea.y2 } }; this._contentAreaDimensions.top = { hoverArea: { x1: contentArea.x1 + contentWidth * 0.25, y1: contentArea.y1, x2: contentArea.x1 + contentWidth * 0.75, y2: contentArea.y1 + contentHeight * 0.5 }, highlightArea: { x1: contentArea.x1, y1: contentArea.y1, x2: contentArea.x2, y2: contentArea.y1 + contentHeight * 0.5 } }; this._contentAreaDimensions.right = { hoverArea: { x1: contentArea.x1 + contentWidth * 0.75, y1: contentArea.y1, x2: contentArea.x2, y2: contentArea.y2 }, highlightArea: { x1: contentArea.x1 + contentWidth * 0.5, y1: contentArea.y1, x2: contentArea.x2, y2: contentArea.y2 } }; this._contentAreaDimensions.bottom = { hoverArea: { x1: contentArea.x1 + contentWidth * 0.25, y1: contentArea.y1 + contentHeight * 0.5, x2: contentArea.x1 + contentWidth * 0.75, y2: contentArea.y2 }, highlightArea: { x1: contentArea.x1, y1: contentArea.y1 + contentHeight * 0.5, x2: contentArea.x2, y2: contentArea.y2 } }; return getArea.call( this, this.element ); }, _highlightHeaderDropZone: function( x ) { var i, tabElement, tabsLength = this.header.tabs.length, isAboveTab = false, tabTop, tabLeft, offset, placeHolderLeft, headerOffset, tabWidth, halfX; // Empty stack if( tabsLength === 0 ) { headerOffset = this.header.element.offset(); this.layoutManager.dropTargetIndicator.highlightArea({ x1: headerOffset.left, x2: headerOffset.left + 100, y1: headerOffset.top + this.header.element.height() - 20, y2: headerOffset.top + this.header.element.height() }); return; } for( i = 0; i < tabsLength; i++ ) { tabElement = this.header.tabs[ i ].element; offset = tabElement.offset(); tabLeft = offset.left; tabTop = offset.top; tabWidth = tabElement.width(); if( x > tabLeft && x < tabLeft + tabWidth ) { isAboveTab = true; break; } } if( isAboveTab === false && x < tabLeft ) { return; } halfX = tabLeft + tabWidth / 2; if( x < halfX ) { this._dropIndex = i; tabElement.before( this.layoutManager.tabDropPlaceholder ); } else { this._dropIndex = Math.min( i + 1, tabsLength ); tabElement.after( this.layoutManager.tabDropPlaceholder ); } placeHolderLeft = this.layoutManager.tabDropPlaceholder.offset().left; this.layoutManager.dropTargetIndicator.highlightArea({ x1: placeHolderLeft, x2: placeHolderLeft + this.layoutManager.tabDropPlaceholder.width(), y1: tabTop, y2: tabTop + tabElement.innerHeight() }); }, _resetHeaderDropZone: function() { this.layoutManager.tabDropPlaceholder.remove(); }, _highlightBodyDropZone: function( segment ) { var highlightArea = this._contentAreaDimensions[ segment ].highlightArea; this.layoutManager.dropTargetIndicator.highlightArea( highlightArea ); this._dropSegment = segment; } }); lm.utils.BubblingEvent = function( name, origin ) { this.name = name; this.origin = origin; this.isPropagationStopped = false; }; lm.utils.BubblingEvent.prototype.stopPropagation = function() { this.isPropagationStopped = true; }; /** * Minifies and unminifies configs by replacing frequent keys * and values with one letter substitutes * * @constructor */ lm.utils.ConfigMinifier = function(){ this._keys = [ 'settings', 'hasHeaders', 'constrainDragToContainer', 'selectionEnabled', 'dimensions', 'borderWidth', 'minItemHeight', 'minItemWidth', 'headerHeight', 'dragProxyWidth', 'dragProxyHeight', 'labels', 'close', 'maximise', 'minimise', 'popout', 'content', 'componentName', 'componentState', 'id', 'width', 'type', 'height', 'isClosable', 'title', 'popoutWholeStack', 'openPopouts', 'parentId', 'activeItemIndex', 'reorderEnabled' //Maximum 36 entries, do not cross this line! ]; this._values = [ true, false, 'row', 'column', 'stack', 'component', 'close', 'maximise', 'minimise', 'open in new window' ]; }; lm.utils.copy( lm.utils.ConfigMinifier.prototype, { /** * Takes a GoldenLayout configuration object and * replaces its keys and values recoursively with * one letter counterparts * * @param {Object} config A GoldenLayout config object * * @returns {Object} minified config */ minifyConfig: function( config ) { var min = {}; this._nextLevel( config, min, '_min' ); return min; }, /** * Takes a configuration Object that was previously minified * using minifyConfig and returns its original version * * @param {Object} minifiedConfig * * @returns {Object} the original configuration */ unminifyConfig: function( minifiedConfig ) { var orig = {}; this._nextLevel( minifiedConfig, orig, '_max' ); return orig; }, /** * Recoursive function, called for every level of the config structure * * @param {Array|Object} orig * @param {Array|Object} min * @param {String} translationFn * * @returns {void} */ _nextLevel: function( from, to, translationFn ) { var key, minKey; for( key in from ) { /** * For in returns array indices as keys, so let's cast them to numbers */ if( from instanceof Array ) key = parseInt( key, 10 ); /** * In case something has extended Object prototypes */ if( !from.hasOwnProperty( key ) ) continue; /** * Translate the key to a one letter substitute */ minKey = this[ translationFn ]( key, this._keys ); /** * For Arrays and Objects, create a new Array/Object * on the minified object and recourse into it */ if( typeof from[ key ] === 'object' ) { to[ minKey ] = from[ key ] instanceof Array ? [] : {}; this._nextLevel( from[ key ], to[ minKey ], translationFn ); /** * For primitive values (Strings, Numbers, Boolean etc.) * minify the value */ } else { to[ minKey ] = this[ translationFn ]( from[ key ], this._values ); } } }, /** * Minifies value based on a dictionary * * @param {String|Boolean} value * @param {Array<String|Boolean>} dictionary * * @returns {String} The minified version */ _min: function( value, dictionary ) { /** * If a value actually is a single character, prefix it * with ___ to avoid mistaking it for a minification code */ if( typeof value === 'string' && value.length === 1 ) { return '___' + value; } var index = lm.utils.indexOf( value, dictionary ); /** * value not found in the dictionary, return it unmodified */ if( index === -1 ) { return value; /** * value found in dictionary, return its base36 counterpart */ } else { return index.toString( 36 ); } }, _max: function( value, dictionary ) { /** * value is a single character. Assume that it's a translation * and return the original value from the dictionary */ if( typeof value === 'string' && value.length === 1 ) { return dictionary[ parseInt( value, 36 ) ]; } /** * value originally was a single character and was prefixed with ___ * to avoid mistaking it for a translation. Remove the prefix * and return the original character */ if( typeof value === 'string' && value.substr( 0, 3 ) === '___' ) { return value[ 3 ]; } /** * value was not minified */ return value; } }); /** * An EventEmitter singleton that propagates events * across multiple windows. This is a little bit trickier since * windows are allowed to open childWindows in their own right * * This means that we deal with a tree of windows. Hence the rules for event propagation are: * * - Propagate events from this layout to both parents and children * - Propagate events from parent to this and children * - Propagate events from children to the other children (but not the emitting one) and the parent * * @constructor * * @param {lm.LayoutManager} layoutManager */ lm.utils.EventHub = function( layoutManager ) { lm.utils.EventEmitter.call( this ); this._layoutManager = layoutManager; this._dontPropagateToParent = null; this._childEventSource = null; this.on( lm.utils.EventEmitter.ALL_EVENT, lm.utils.fnBind( this._onEventFromThis, this ) ); $(window).on( 'gl_child_event', lm.utils.fnBind( this._onEventFromChild, this ) ); }; /** * Called on every event emitted on this eventHub, regardles of origin. * * @private * * @param {Mixed} * * @returns {void} */ lm.utils.EventHub.prototype._onEventFromThis = function() { var args = Array.prototype.slice.call( arguments ); if( this._layoutManager.isSubWindow && args[ 0 ] !== this._dontPropagateToParent ) { this._propagateToParent( args ); } this._propagateToChildren( args ); //Reset this._dontPropagateToParent = null; this._childEventSource = null; }; /** * Called by the parent layout. * * @param {Array} args Event name + arguments * * @returns {void} */ lm.utils.EventHub.prototype._$onEventFromParent = function( args ) { this._dontPropagateToParent = args[ 0 ]; this.emit.apply( this, args ); }; /** * Callback for child events raised on the window * * @param {DOMEvent} event * @private * * @returns {void} */ lm.utils.EventHub.prototype._onEventFromChild = function( event ) { this._childEventSource = event.originalEvent.__gl; this.emit.apply( this, event.originalEvent.__glArgs ); }; /** * Propagates the event to the parent by emitting * it on the parent's DOM window * * @param {Array} args Event name + arguments * @private * * @returns {void} */ lm.utils.EventHub.prototype._propagateToParent = function( args ) { var event, eventName = 'gl_child_event'; if (document.createEvent) { event = window.opener.document.createEvent( 'HTMLEvents' ); event.initEvent( eventName, true, true); } else { event = window.opener.document.createEventObject(); event.eventType = eventName; } event.eventName = eventName; event.__glArgs = args; event.__gl = this._layoutManager; if (document.createEvent) { window.opener.dispatchEvent(event); } else { window.opener.fireEvent( 'on' + event.eventType, event ); } }; /** * Propagate events to children * * @param {Array} args Event name + arguments * @private * * @returns {void} */ lm.utils.EventHub.prototype._propagateToChildren = function( args ) { var childGl, i; for( i = 0; i < this._layoutManager.openPopouts.length; i++ ) { childGl = this._layoutManager.openPopouts[ i ].getGlInstance(); if( childGl !== this._childEventSource ) { childGl.eventHub._$onEventFromParent( args ); } } }; /** * A specialised GoldenLayout component that binds GoldenLayout container * lifecycle events to react components * * @constructor * * @param {lm.container.ItemContainer} container * @param {Object} state state is not required for react components */ lm.utils.ReactComponentHandler = function( container, state ) { this._reactComponent = null; this._originalComponentWillUpdate = null; this._container = container; this._initialState = state; this._reactClass = this._getReactClass(); this._container.on( 'open', this._render, this ); this._container.on( 'destroy', this._destroy, this ); }; lm.utils.copy( lm.utils.ReactComponentHandler.prototype, { /** * Creates the react class and component and hydrates it with * the initial state - if one is present * * By default, react's getInitialState will be used * * @private * @returns {void} */ _render: function() { this._reactComponent = ReactDOM.render( this._getReactComponent(), this._container.getElement()[ 0 ]); this._originalComponentWillUpdate = this._reactComponent.componentWillUpdate || function(){}; this._reactComponent.componentWillUpdate = this._onUpdate.bind( this ); if( this._container.getState() ) { this._reactComponent.setState( this._container.getState() ); } }, /** * Removes the component from the DOM and thus invokes React's unmount lifecycle * * @private * @returns {void} */ _destroy: function() { ReactDOM.unmountComponentAtNode( this._container.getElement()[ 0 ]); this._container.off( 'open', this._render, this ); this._container.off( 'destroy', this._destroy, this ); }, /** * Hooks into React's state management and applies the componentstate * to GoldenLayout * * @private * @returns {void} */ _onUpdate: function( nextProps, nextState ) { this._container.setState( nextState ); this._originalComponentWillUpdate( nextProps, nextState ); }, /** * Retrieves the react class from GoldenLayout's registry * * @private * @returns {React.Class} */ _getReactClass: function() { var componentName = this._container._config.component; var reactClass; if( !componentName ) { throw new Error( 'No react component name. type: react-component needs a field `component`' ); } reactClass = this._container.layoutManager.getComponent( componentName ); if( !reactClass ) { throw new Error( 'React component "' + componentName + '" not found. ' + 'Please register all components with GoldenLayout using `registerComponent(name, component)`' ); } return reactClass; }, /** * Copies and extends the properties array and returns the React element * * @private * @returns {React.Element} */ _getReactComponent: function() { var defaultProps = { glEventHub: this._container.layoutManager.eventHub, glContainer: this._container, }; var props = $.extend( defaultProps, this._container._config.props ); return React.createElement( this._reactClass, props ); } });})(window.$);
ajax/libs/react-dom/16.1.0-rc/cjs/react-dom-unstable-native-dependencies.production.min.js
BenjaminVanRyseghem/cdnjs
/** @license React v16.1.0-rc * react-dom-unstable-native-dependencies.production.min.js * * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict';var h=require("react-dom"),k=require("object-assign"),l=require("fbjs/lib/emptyFunction"); function n(a){for(var b=arguments.length-1,c="Minified React error #"+a+"; visit http://facebook.github.io/react/docs/error-decoder.html?invariant\x3d"+a,f=0;f<b;f++)c+="\x26args[]\x3d"+encodeURIComponent(arguments[f+1]);b=Error(c+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.");b.name="Invariant Violation";b.framesToPop=1;throw b;}var p=null,q=null,t=null; function u(a){return"topMouseUp"===a||"topTouchEnd"===a||"topTouchCancel"===a}function v(a){return"topMouseMove"===a||"topTouchMove"===a}function w(a){return"topMouseDown"===a||"topTouchStart"===a}function x(a){var b=a._dispatchListeners,c=a._dispatchInstances;Array.isArray(b)?n("103"):void 0;a.currentTarget=b?t(c):null;b=b?b(a):null;a.currentTarget=null;a._dispatchListeners=null;a._dispatchInstances=null;return b}function y(a){do a=a["return"];while(a&&5!==a.tag);return a?a:null} function z(a,b,c){for(var f=[];a;)f.push(a),a=y(a);for(a=f.length;0<a--;)b(f[a],"captured",c);for(a=0;a<f.length;a++)b(f[a],"bubbled",c)}function A(a,b){null==b?n("30"):void 0;if(null==a)return b;if(Array.isArray(a)){if(Array.isArray(b))return a.push.apply(a,b),a;a.push(b);return a}return Array.isArray(b)?[a].concat(b):[a,b]}function B(a,b,c){Array.isArray(a)?a.forEach(b,c):a&&b.call(c,a)} function C(a,b){var c=a.stateNode;if(!c)return null;var f=p(c);if(!f)return null;c=f[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":(f=!f.disabled)||(a=a.type,f=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!f;break a;default:a=!1}if(a)return null;c&&"function"!==typeof c?n("231",b,typeof c):void 0; return c}function D(a,b,c){if(b=C(a,c.dispatchConfig.phasedRegistrationNames[b]))c._dispatchListeners=A(c._dispatchListeners,b),c._dispatchInstances=A(c._dispatchInstances,a)}function E(a){a&&a.dispatchConfig.phasedRegistrationNames&&z(a._targetInst,D,a)}function aa(a){if(a&&a.dispatchConfig.phasedRegistrationNames){var b=a._targetInst;b=b?y(b):null;z(b,D,a)}} function F(a){if(a&&a.dispatchConfig.registrationName){var b=a._targetInst;if(b&&a&&a.dispatchConfig.registrationName){var c=C(b,a.dispatchConfig.registrationName);c&&(a._dispatchListeners=A(a._dispatchListeners,c),a._dispatchInstances=A(a._dispatchInstances,b))}}} var G="dispatchConfig _targetInst nativeEvent isDefaultPrevented isPropagationStopped _dispatchListeners _dispatchInstances".split(" "),ba={type:null,target:null,currentTarget:l.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null}; function H(a,b,c,f){this.dispatchConfig=a;this._targetInst=b;this.nativeEvent=c;a=this.constructor.Interface;for(var d in a)a.hasOwnProperty(d)&&((b=a[d])?this[d]=b(c):"target"===d?this.target=f:this[d]=c[d]);this.isDefaultPrevented=(null!=c.defaultPrevented?c.defaultPrevented:!1===c.returnValue)?l.thatReturnsTrue:l.thatReturnsFalse;this.isPropagationStopped=l.thatReturnsFalse;return this} k(H.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&(a.returnValue=!1),this.isDefaultPrevented=l.thatReturnsTrue)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=l.thatReturnsTrue)},persist:function(){this.isPersistent=l.thatReturnsTrue},isPersistent:l.thatReturnsFalse, destructor:function(){var a=this.constructor.Interface,b;for(b in a)this[b]=null;for(a=0;a<G.length;a++)this[G[a]]=null}});H.Interface=ba;H.augmentClass=function(a,b){function c(){}c.prototype=this.prototype;var f=new c;k(f,a.prototype);a.prototype=f;a.prototype.constructor=a;a.Interface=k({},this.Interface,b);a.augmentClass=this.augmentClass;I(a)};I(H);function ca(a,b,c,f){if(this.eventPool.length){var d=this.eventPool.pop();this.call(d,a,b,c,f);return d}return new this(a,b,c,f)} function da(a){a instanceof this?void 0:n("223");a.destructor();10>this.eventPool.length&&this.eventPool.push(a)}function I(a){a.eventPool=[];a.getPooled=ca;a.release=da}function J(a,b,c,f){return H.call(this,a,b,c,f)}H.augmentClass(J,{touchHistory:function(){return null}});var L=[],M={touchBank:L,numberActiveTouches:0,indexOfSingleActiveTouch:-1,mostRecentTimeStamp:0};function N(a){return a.timeStamp||a.timestamp}function O(a){a=a.identifier;null==a?n("138"):void 0;return a} function ea(a){var b=O(a),c=L[b];c?(c.touchActive=!0,c.startPageX=a.pageX,c.startPageY=a.pageY,c.startTimeStamp=N(a),c.currentPageX=a.pageX,c.currentPageY=a.pageY,c.currentTimeStamp=N(a),c.previousPageX=a.pageX,c.previousPageY=a.pageY,c.previousTimeStamp=N(a)):(c={touchActive:!0,startPageX:a.pageX,startPageY:a.pageY,startTimeStamp:N(a),currentPageX:a.pageX,currentPageY:a.pageY,currentTimeStamp:N(a),previousPageX:a.pageX,previousPageY:a.pageY,previousTimeStamp:N(a)},L[b]=c);M.mostRecentTimeStamp=N(a)} function fa(a){var b=L[O(a)];b?(b.touchActive=!0,b.previousPageX=b.currentPageX,b.previousPageY=b.currentPageY,b.previousTimeStamp=b.currentTimeStamp,b.currentPageX=a.pageX,b.currentPageY=a.pageY,b.currentTimeStamp=N(a),M.mostRecentTimeStamp=N(a)):console.error("Cannot record touch move without a touch start.\nTouch Move: %s\n","Touch Bank: %s",P(a),Q())} function ha(a){var b=L[O(a)];b?(b.touchActive=!1,b.previousPageX=b.currentPageX,b.previousPageY=b.currentPageY,b.previousTimeStamp=b.currentTimeStamp,b.currentPageX=a.pageX,b.currentPageY=a.pageY,b.currentTimeStamp=N(a),M.mostRecentTimeStamp=N(a)):console.error("Cannot record touch end without a touch start.\nTouch End: %s\n","Touch Bank: %s",P(a),Q())}function P(a){return JSON.stringify({identifier:a.identifier,pageX:a.pageX,pageY:a.pageY,timestamp:N(a)})} function Q(){var a=JSON.stringify(L.slice(0,20));20<L.length&&(a+=" (original size: "+L.length+")");return a} var R={recordTouchTrack:function(a,b){if(v(a))b.changedTouches.forEach(fa);else if(w(a))b.changedTouches.forEach(ea),M.numberActiveTouches=b.touches.length,1===M.numberActiveTouches&&(M.indexOfSingleActiveTouch=b.touches[0].identifier);else if(u(a)&&(b.changedTouches.forEach(ha),M.numberActiveTouches=b.touches.length,1===M.numberActiveTouches))for(a=0;a<L.length;a++)if(b=L[a],null!=b&&b.touchActive){M.indexOfSingleActiveTouch=a;break}},touchHistory:M}; function S(a,b){null==b?n("29"):void 0;return null==a?b:Array.isArray(a)?a.concat(b):Array.isArray(b)?[a].concat(b):[a,b]}var T=null,U=0,V=0;function W(a,b){var c=T;T=a;if(null!==X.GlobalResponderHandler)X.GlobalResponderHandler.onChange(c,a,b)} var Y={startShouldSetResponder:{phasedRegistrationNames:{bubbled:"onStartShouldSetResponder",captured:"onStartShouldSetResponderCapture"}},scrollShouldSetResponder:{phasedRegistrationNames:{bubbled:"onScrollShouldSetResponder",captured:"onScrollShouldSetResponderCapture"}},selectionChangeShouldSetResponder:{phasedRegistrationNames:{bubbled:"onSelectionChangeShouldSetResponder",captured:"onSelectionChangeShouldSetResponderCapture"}},moveShouldSetResponder:{phasedRegistrationNames:{bubbled:"onMoveShouldSetResponder", captured:"onMoveShouldSetResponderCapture"}},responderStart:{registrationName:"onResponderStart"},responderMove:{registrationName:"onResponderMove"},responderEnd:{registrationName:"onResponderEnd"},responderRelease:{registrationName:"onResponderRelease"},responderTerminationRequest:{registrationName:"onResponderTerminationRequest"},responderGrant:{registrationName:"onResponderGrant"},responderReject:{registrationName:"onResponderReject"},responderTerminate:{registrationName:"onResponderTerminate"}}, X={_getResponder:function(){return T},eventTypes:Y,extractEvents:function(a,b,c,f){if(w(a))U+=1;else if(u(a))if(0<=U)--U;else return console.error("Ended a touch event which was not counted in `trackedTouchCount`."),null;R.recordTouchTrack(a,c);if(b&&("topScroll"===a&&!c.responderIgnoreScroll||0<U&&"topSelectionChange"===a||w(a)||v(a))){var d=w(a)?Y.startShouldSetResponder:v(a)?Y.moveShouldSetResponder:"topSelectionChange"===a?Y.selectionChangeShouldSetResponder:Y.scrollShouldSetResponder;if(T)b:{var e= T;for(var g=0,r=e;r;r=y(r))g++;r=0;for(var K=b;K;K=y(K))r++;for(;0<g-r;)e=y(e),g--;for(;0<r-g;)b=y(b),r--;for(;g--;){if(e===b||e===b.alternate)break b;e=y(e);b=y(b)}e=null}else e=b;b=e===T;e=J.getPooled(d,e,c,f);e.touchHistory=R.touchHistory;b?B(e,aa):B(e,E);b:{d=e._dispatchListeners;b=e._dispatchInstances;if(Array.isArray(d))for(g=0;g<d.length&&!e.isPropagationStopped();g++){if(d[g](e,b[g])){d=b[g];break b}}else if(d&&d(e,b)){d=b;break b}d=null}e._dispatchInstances=null;e._dispatchListeners=null; e.isPersistent()||e.constructor.release(e);if(d&&d!==T)if(e=J.getPooled(Y.responderGrant,d,c,f),e.touchHistory=R.touchHistory,B(e,F),b=!0===x(e),T)if(g=J.getPooled(Y.responderTerminationRequest,T,c,f),g.touchHistory=R.touchHistory,B(g,F),r=!g._dispatchListeners||x(g),g.isPersistent()||g.constructor.release(g),r){g=J.getPooled(Y.responderTerminate,T,c,f);g.touchHistory=R.touchHistory;B(g,F);var m=S(m,[e,g]);W(d,b)}else d=J.getPooled(Y.responderReject,d,c,f),d.touchHistory=R.touchHistory,B(d,F),m=S(m, d);else m=S(m,e),W(d,b);else m=null}else m=null;d=T&&w(a);e=T&&v(a);b=T&&u(a);if(d=d?Y.responderStart:e?Y.responderMove:b?Y.responderEnd:null)d=J.getPooled(d,T,c,f),d.touchHistory=R.touchHistory,B(d,F),m=S(m,d);d=T&&"topTouchCancel"===a;if(a=T&&!d&&u(a))a:{if((a=c.touches)&&0!==a.length)for(e=0;e<a.length;e++)if(b=a[e].target,null!==b&&void 0!==b&&0!==b){g=q(b);b:{for(b=T;g;){if(b===g||b===g.alternate){b=!0;break b}g=y(g)}b=!1}if(b){a=!1;break a}}a=!0}if(a=d?Y.responderTerminate:a?Y.responderRelease: null)c=J.getPooled(a,T,c,f),c.touchHistory=R.touchHistory,B(c,F),m=S(m,c),W(null);c=R.touchHistory.numberActiveTouches;if(X.GlobalInteractionHandler&&c!==V)X.GlobalInteractionHandler.onChange(c);V=c;return m},GlobalResponderHandler:null,GlobalInteractionHandler:null,injection:{injectGlobalResponderHandler:function(a){X.GlobalResponderHandler=a},injectGlobalInteractionHandler:function(a){X.GlobalInteractionHandler=a}}}; function Z(a){p=a.getFiberCurrentPropsFromNode;q=a.getInstanceFromNode;t=a.getNodeFromInstance}Z(h.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactDOMComponentTree);var ia=Object.freeze({injectComponentTree:Z,ResponderEventPlugin:X,ResponderTouchHistoryStore:R});module.exports=ia;
app/javascript/mastodon/components/loading_indicator.js
8796n/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; const LoadingIndicator = () => ( <div className='loading-indicator'> <FormattedMessage id='loading_indicator.label' defaultMessage='Loading...' /> </div> ); export default LoadingIndicator;
app/src/Frontend/modules/crm/containers/contact/index.js
ptphp/ptphp
/** * Created by jf on 15/12/10. */ //"use strict"; import React from 'react'; import Departments from './Departments' import Contacts from './Contacts' import ContactDetail from './Detail' export { Departments, Contacts, ContactDetail }
src/tools/code-template/ui/OrgList.js
steem/qwp-antd
import React from 'react' import PropTypes from 'prop-types' import { Form } from 'antd' import List from 'components/List' import { l } from 'utils/localization' import { uriOfList } from 'requests/org' import styles from './OrgList.less' let OrgListWithSearchForm = React.createClass({ updateModalOrgSelection(selectedOrgKeys) { this.props.dispatch({ type: 'user/updateState', payload: { selectedOrgKeys, }, }) }, onSelectionChanged(selectedOrgKeys, selectedRows) { this.updateModalOrgSelection(selectedOrgKeys) }, onDataUpdated() { this.updateModalOrgSelection([]) }, render () { const { user, location, form, appSettings, ...listProps, } = this.props const searchContent = { form, appSettings, formItems:{ name: 'org', fields: [{ id: 'name', input: 'text', placeholder: l('Organization name'), inputProps: { size: 'large', }, }, { id: 'createTime', datePicker: true, placeholder: l('Create time'), }], } } let props = { header: l('Organizations'), selectionType: { type: 'checkbox', onChange: this.onSelectionChanged, selectedRowKeys: user.selectedOrgKeys, }, sort: { order: 'desc', field: 'id', fields: [{ id: 'id', name: l('ID'), }, { id: 'name', name: l('Name'), },], }, fetch: uriOfList(), dataIndex: 'name', searchContent, onDataUpdated: this.onDataUpdated, clickedKeyId: location.query.org || -1, } return (<List {...listProps} { ...props} />) } }) OrgListWithSearchForm.propTypes = { location: PropTypes.object, appSettings: PropTypes.object, form: PropTypes.object, user: PropTypes.object, dispatch: PropTypes.func, } export default Form.create()(OrgListWithSearchForm)
ReactNative/node_modules/react-navigation/src/PlatformHelpers.web.js
tahashahid/cloud-computing-2017
import React from 'react'; import { BackHandler, View } from 'react-native'; const MaskedViewIOS = () => <View>{this.props.children}</View>; export { BackHandler, MaskedViewIOS };
src/parser/monk/windwalker/CONFIG.js
FaideWW/WoWAnalyzer
import React from 'react'; import { Juko8 } from 'CONTRIBUTORS'; import retryingPromise from 'common/retryingPromise'; import SPECS from 'game/SPECS'; import CHANGELOG from './CHANGELOG'; export default { // The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion. contributors: [Juko8], // The WoW client patch this spec was last updated to be fully compatible with. patchCompatibility: '8.0', // If set to false`, the spec will show up as unsupported. isSupported: true, // Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more. // If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component. description: ( <> Hello! We have been working hard to make the Windwalker analyzer good, but there is always stuff to add or improve. We hope that the suggestions and statistics will be helpful in improving your overall performance. It takes time to learn the Windwalker resource and cooldown management, so be patient with yourself while getting used to it. <br /> <br /> If you have any questions about the analyzer or Windwalker monks in general, join us in the <a href="https://discord.gg/0dkfBMAxzTkWj21F" target="_blank" rel="noopener noreferrer">Peak of Serenity discord server</a> and talk to us. You can reach me there as Juko8. Make sure to also check out our resources on the <a href="http://peakofserenity.com/windwalker/">Peak of Serenity website</a> as well, it has pretty much everything you need to know. </> ), // A recent example report to see interesting parts of the spec. Will be shown on the homepage. exampleReport: '/report/Bg96KMa72x4kY8nV/16-Heroic+Vectis+-+Kill+(6:44)/3-Boeboe', // Don't change anything below this line; // The current spec identifier. This is the only place (in code) that specifies which spec this parser is about. spec: SPECS.WINDWALKER_MONK, // The contents of your changelog. changelog: CHANGELOG, // The CombatLogParser class for your spec. parser: () => retryingPromise(() => import('./CombatLogParser' /* webpackChunkName: "WindwalkerMonk" */).then(exports => exports.default)), // The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code. path: __dirname, };
src/interface/statistics/StatisticBar.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import STATISTIC_CATEGORY from 'interface/others/STATISTIC_CATEGORY'; import './Statistic.scss'; import './StatisticBar.scss'; const StatisticBar = ({ children, large, wide, ultrawide, ...others }) => ( <div className={ultrawide ? 'col-md-12' : (wide ? 'col-md-6 col-sm-12 col-xs-12' : 'col-lg-3 col-md-4 col-sm-6 col-xs-12')}> <div className="panel statistic bar" {...others}> <div className="panel-body"> {children} </div> </div> </div> ); StatisticBar.propTypes = { children: PropTypes.node.isRequired, large: PropTypes.bool, wide: PropTypes.bool, ultrawide: PropTypes.bool, // eslint-disable-next-line react/no-unused-prop-types category: PropTypes.oneOf(Object.values(STATISTIC_CATEGORY)), // eslint-disable-next-line react/no-unused-prop-types position: PropTypes.number, }; export default StatisticBar;
core/src/plugins/gui.ajax/res/js/ui/Workspaces/search/components/DatePanel.js
ChuckDaniels87/pydio-core
import React from 'react'; const {PydioContextConsumer} = require('pydio').requireLib('boot') import {Subheader, DropDownMenu, MenuItem, DatePicker, TextField, Toggle, FlatButton} from 'material-ui'; class SearchDatePanel extends React.Component { static get styles() { return { dropdownLabel: { padding: 0 }, dropdownUnderline: { marginLeft: 0, marginRight: 0 }, dropdownIcon: { right: 0 }, datePickerGroup: { display: "flex", justifyContent: "space-between" }, datePicker: { flex: 1 }, dateInput: { width: "auto", flex: 1 }, dateClose: { lineHeight: "48px", right: 5, position: "relative" } } } constructor(props) { super(props) this.state = { value:'custom', startDate: null, endDate: null } } componentDidUpdate(prevProps, prevState) { if (prevState != this.state) { let {value, startDate, endDate} = this.state if (value === 'custom') { if (!startDate && !endDate) { this.props.onChange({ajxp_modiftime: null}) } else { if(!startDate) startDate = new Date(0); if(!endDate) { // Next year endDate = new Date(); endDate.setFullYear(endDate.getFullYear()+1); } const format = (d) => { return d.getFullYear() + "" + ("0"+(d.getMonth()+1)).slice(-2) + "" + ("0" + d.getDate()).slice(-2); } this.props.onChange({ajxp_modiftime: '['+format(startDate)+' TO '+format(endDate)+']'}) } } else { this.props.onChange({ajxp_modiftime: value}) } } } render() { const today = new Date(); const {dropdownLabel, dropdownUnderline, dropdownIcon, datePickerGroup, datePicker, dateInput, dateClose} = SearchDatePanel.styles const {inputStyle, getMessage} = this.props const {value, startDate, endDate} = this.state; return ( <div> <DatePickerFeed pydio={this.props.pydio}> {items => <DropDownMenu autoWidth={false} labelStyle={dropdownLabel} underlineStyle={dropdownUnderline} iconStyle={dropdownIcon} style={inputStyle} value={value} onChange={(e, index, value) => this.setState({value})}> {items.map((item) => <MenuItem value={item.payload} label={item.text} primaryText={item.text} />)} </DropDownMenu> } </DatePickerFeed> {value === 'custom' && <div style={{...datePickerGroup, ...inputStyle}}> <DatePicker textFieldStyle={dateInput} style={datePicker} value={startDate} onChange={(e, date) => this.setState({startDate: date})} hintText={getMessage(491)} autoOk={true} maxDate={endDate || today} defaultDate={startDate} /> <span className="mdi mdi-close" style={dateClose} onClick={() => this.setState({startDate: null})} /> <DatePicker textFieldStyle={dateInput} style={datePicker} value={endDate} onChange={(e, date) => this.setState({endDate: date})} hintText={getMessage(492)} autoOk={true} minDate={startDate} maxDate={today} defaultDate={endDate} /> <span className="mdi mdi-close" style={dateClose} onClick={() => this.setState({endDate: null})} /> </div> } </div> ); } } let DatePickerFeed = ({pydio, getMessage, children}) => { const items = [ {payload: 'custom', text: getMessage('612')}, {payload: 'AJXP_SEARCH_RANGE_TODAY', text: getMessage('493')}, {payload: 'AJXP_SEARCH_RANGE_YESTERDAY', text: getMessage('494')}, {payload: 'AJXP_SEARCH_RANGE_LAST_WEEK', text: getMessage('495')}, {payload: 'AJXP_SEARCH_RANGE_LAST_MONTH', text: getMessage('496')}, {payload: 'AJXP_SEARCH_RANGE_LAST_YEAR', text: getMessage('497')} ]; return children(items) } SearchDatePanel = PydioContextConsumer(SearchDatePanel) DatePickerFeed = PydioContextConsumer(DatePickerFeed) export default SearchDatePanel
src/js/components/cardUsers/CardUserPlaceholder.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import ProgressBar from '../ui/ProgressBar'; import Image from '../ui/Image'; import CardUserTopLinks from '../recommendations/CardUserTopLinks'; import translate from '../../i18n/Translate'; import PercentageValue from "./PercentageValue"; @translate('CardUserPlaceholder') export default class CardUserPlaceholder extends Component { static propTypes = { // Injected by @translate: strings: PropTypes.object }; render() { const {strings} = this.props; return ( <div className="card person-card"> <div className="card-header"> <div className="card-content"> <div className="card-content-inner"> <div className="image fixed-max-height-image"> <Image src='img/loading.gif'/> </div> </div> </div> </div> <CardUserTopLinks topLinks={[]} sharedLinks={0}/> <div className={"card-footer"}> <div> <div className="card-title"> {strings.loading} </div> <PercentageValue percentage={0} text={strings.matching}/> <div className="matching-progress"> <ProgressBar percentage={0}/> </div> <PercentageValue percentage={0} text={strings.similarity}/> <div className="similarity-progress"> <ProgressBar percentage={0}/> </div> </div> </div> </div> ); } } CardUserPlaceholder.defaultProps = { strings: { matching : 'Matching', similarity: 'Similarity', loading : 'Loading...', } };
src/AutoComplete/index.js
reactivers/react-material-design
/** * Created by Utku on 28/03/2017. */ import React from 'react'; import PropTypes from 'prop-types'; import '@material/menu/dist/mdc.menu.css' import {MDCSimpleMenu} from '@material/menu/dist/mdc.menu'; import '../index.scss'; import TextField from '../TextField/index'; import generateId from '../utils/generateId'; export default class AutoComplete extends React.Component { static propTypes = { label: PropTypes.string, rightIcon : PropTypes.string, data: PropTypes.array, error: PropTypes.string, floatingLabel: PropTypes.bool, helpText: PropTypes.string, dscField: PropTypes.string, valueField: PropTypes.string, className: PropTypes.string, style: PropTypes.object, placeholder: PropTypes.string, disabled: PropTypes.bool, onChange: PropTypes.func, }; static defaultProps = { onChange: () => null, }; state = { hasVal: "", value: "", textFieldWidth: null, }; defaultId; componentWillMount() { this.defaultId = generateId("autocomplete"); } componentDidMount() { this.menu = new MDCSimpleMenu(document.querySelector(".mdc-simple-menu")); this.menu.foundation_.focusOnOpen_ = () => null; this.tempClose = this.menu.foundation_; this.setState({textFieldWidth: document.getElementById(this.defaultId).clientWidth}) }; render() { const {label, error, floatingLabel, helpText, placeholder,rightIcon, disabled, dscField, valueField, onChange, data, className, style, ...otherProps} = this.props; let fieldDsc = "dsc"; let fieldValue = "value"; if (dscField) fieldDsc = dscField; if (valueField) fieldValue = valueField; if (this.state.hasVal !== "" && !this.menu.foundation_.isOpen()) { this.menu.show(); } return ( <div className={className} style={style} {...otherProps}> <TextField value={this.state.hasVal} rightIcon={rightIcon} id={this.defaultId} disabled={disabled} placeholder={placeholder} helpText={helpText} error={error} onChange={ (e) => { this.setState({hasVal: e.target.value}) }} floatingLabel={floatingLabel} label={label}/> <div className="mdc-simple-menu" tabIndex="-1"> <ul className="mdc-simple-menu__items mdc-list deleleteMargin" role="menu" aria-hidden="true" style={{minWidth: this.state.textFieldWidth}}> {data && data.filter(text => !this.state.hasVal || text[fieldDsc].indexOf(this.state.hasVal) > -1).map((text, index) => { return ( <li key={index} onKeyPress={e => { e.key === "Enter" && this.setState({hasVal: text[fieldDsc]}, () => onChange(text[fieldValue])) }} onClick={() => this.setState({hasVal: text[fieldDsc]}, () => onChange(text[fieldValue]))} className="rmd-menu-item mdc-list-item" role="menuitem" tabIndex="0"> {text[fieldDsc]} </li> ) })} </ul> </div> </div> ) } }
ajax/libs/forerunnerdb/1.3.488/fdb-core+persist.min.js
dada0423/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./core");a("../lib/Persist");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Persist":26,"./core":2}],2:[function(a,b,c){var d=a("../lib/Core");a("../lib/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":6,"../lib/Shim.IE8":32}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a,b,c){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c,d){this._store=[],this._keys=[],void 0!==b&&this.index(b),void 0!==c&&this.compareFunc(c),void 0!==d&&this.hashFunc(d),void 0!==a&&this.data(a)},d.addModule("BinaryTree",f),d.mixin(f.prototype,"Mixin.ChainReactor"),d.mixin(f.prototype,"Mixin.Sorting"),d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"compareFunc"),d.synthesize(f.prototype,"hashFunc"),d.synthesize(f.prototype,"indexDir"),d.synthesize(f.prototype,"keys"),d.synthesize(f.prototype,"index",function(a){return void 0!==a&&this.keys(this.extractKeys(a)),this.$super.call(this,a)}),f.prototype.extractKeys=function(a){var b,c=[];for(b in a)a.hasOwnProperty(b)&&c.push({key:b,val:a[b]});return c},f.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},f.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},f.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},f.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.val?e=this.sortAsc(a[d.key],b[d.key]):-1===d.val&&(e=this.sortDesc(a[d.key],b[d.key])),0!==e)return e;return e},f.prototype._hashFunc=function(a){return a[this._keys[0].key]},f.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this._data?(b=this._compareFunc(this._data,a),0===b?(this.push(a),this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):-1===b?(this._right?this._right.insert(a):this._right=new f(a,this._index,this._compareFunc,this._hashFunc),!0):1===b?(this._left?this._left.insert(a):this._left=new f(a,this._index,this._compareFunc,this._hashFunc),!0):!1):(this.data(a),!0)},f.prototype.lookup=function(a,b){var c=this._compareFunc(this._data,a);return b=b||[],0===c&&(this._left&&this._left.lookup(a,b),b.push(this._data),this._right&&this._right.lookup(a,b)),-1===c&&this._right&&this._right.lookup(a,b),1===c&&this._left&&this._left.lookup(a,b),b},f.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},f.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},f.prototype.match=function(a,b){var c,d,f,g=new e,h=[],i=0;for(c=g.parseArr(this._index,{verbose:!0}),d=g.parseArr(a,{ignore:/\$/,verbose:!0}),f=0;f<c.length;f++)d[f]===c[f]&&(i++,h.push(d[f]));return{matchedKeys:h,totalKeyCount:d.length,score:i}},d.finishModule("BinaryTree"),b.exports=f},{"./Path":25,"./Shared":31}],4:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m;d=a("./Shared");var n=function(a){this.init.apply(this,arguments)};n.prototype.init=function(a,b){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",n),d.mixin(n.prototype,"Mixin.Common"),d.mixin(n.prototype,"Mixin.Events"),d.mixin(n.prototype,"Mixin.ChainReactor"),d.mixin(n.prototype,"Mixin.CRUD"),d.mixin(n.prototype,"Mixin.Constants"),d.mixin(n.prototype,"Mixin.Triggers"),d.mixin(n.prototype,"Mixin.Sorting"),d.mixin(n.prototype,"Mixin.Matching"),d.mixin(n.prototype,"Mixin.Updating"),d.mixin(n.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n.prototype.crc=k,d.synthesize(n.prototype,"deferredCalls"),d.synthesize(n.prototype,"state"),d.synthesize(n.prototype,"name"),d.synthesize(n.prototype,"metaData"),d.synthesize(n.prototype,"capped"),d.synthesize(n.prototype,"cappedSize"),n.prototype.data=function(){return this._data},n.prototype.drop=function(a){var b;if(this.isDropped())return a&&a(!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._name,delete this._data,delete this._metrics,a&&a(!1,!0),!0}return a&&a(!1,!0),!1},n.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",a,{oldData:b})}return this}return this._primaryKey},n.prototype._onInsert=function(a,b){this.emit("insert",a,b)},n.prototype._onUpdate=function(a){this.emit("update",a)},n.prototype._onRemove=function(a){this.emit("remove",a)},n.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=new Date)},d.synthesize(n.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(n.prototype,"mongoEmulation"),n.prototype.setData=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this._metrics.create("setData");d.start(),b=this.options(b),this.preSetData(a,b,c),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),d.time("transformIn"),a=this.transformIn(a),d.time("transformIn");var e=[].concat(this._data);this._dataReplace(a),d.time("Rebuild Primary Key Index"),this.rebuildPrimaryKeyIndex(b),d.time("Rebuild Primary Key Index"),d.time("Rebuild All Other Indexes"),this._rebuildIndexes(),d.time("Rebuild All Other Indexes"),d.time("Resolve chains"),this.chainSend("setData",a,{oldData:e}),d.time("Resolve chains"),d.stop(),this._onChange(),this.emit("setData",this._data,e)}return c&&c(!1),this},n.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.jStringify(d),i.set(d[k],e),j.set(e,d)}},n.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},n.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.deferEmit("change",{type:"truncate"}),this},n.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b(),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a);break;case"update":g.result=this.update(c,a)}return g}return b&&b(),{}},n.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},n.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},n.prototype.update=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";b=this.decouple(b),this.mongoEmulation()&&(this.convertToFdb(a),this.convertToFdb(b)),b=this.transformIn(b),this.debug()&&console.log(this.logIdentifier()+" Updating some data");var d,e,f=this,g=this._metrics.create("update"),h=function(d){var e,h,i,j=f.decouple(d);return f.willTrigger(f.TYPE_UPDATE,f.PHASE_BEFORE)||f.willTrigger(f.TYPE_UPDATE,f.PHASE_AFTER)?(e=f.decouple(d),h={type:"update",query:f.decouple(a),update:f.decouple(b),options:f.decouple(c),op:g},i=f.updateObject(e,h.update,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_BEFORE,d,e)!==!1?(i=f.updateObject(d,e,h.query,h.options,""),f.processTrigger(h,f.TYPE_UPDATE,f.PHASE_AFTER,j,e)):i=!1):i=f.updateObject(d,b,a,c,""),f._updateIndexes(j,d),i};return g.start(),g.time("Retrieve documents to update"),d=this.find(a,{$decouple:!1}),g.time("Retrieve documents to update"),d.length&&(g.time("Update documents"),e=d.filter(h),g.time("Update documents"),e.length&&(g.time("Resolve chains"),this.chainSend("update",{query:a,update:b,dataSet:e},c),g.time("Resolve chains"),this._onUpdate(e),this._onChange(),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},n.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},n.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)},n.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q=!1,r=!1;for(p in b)if(b.hasOwnProperty(p)){if(g=!1,"$"===p.substr(0,1))switch(p){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)r=this.updateObject(a,b.$each[j],c,d,e),r&&(q=!0);q=q||r;break;default:g=!0,r=this.updateObject(a,b[p],c,d,e,p),q=q||r}if(this._isPositionalKey(p)&&(g=!0,p=p.substr(0,p.length-2),m=new h(e+"."+p),a[p]&&a[p]instanceof Array&&a[p].length)){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],m.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)r=this.updateObject(a[p][i[j]],b[p+".$"],c,d,e+"."+p,f),q=q||r}if(!g)if(f||"object"!=typeof b[p])switch(f){case"$inc":var s=!0;b[p]>0?b.$max&&a[p]>=b.$max&&(s=!1):b[p]<0&&b.$min&&a[p]<=b.$min&&(s=!1),s&&(this._updateIncrement(a,p,b[p]),q=!0);break;case"$cast":switch(b[p]){case"array":a[p]instanceof Array||(this._updateProperty(a,p,b.$data||[]),q=!0);break;case"object":(!(a[p]instanceof Object)||a[p]instanceof Array)&&(this._updateProperty(a,p,b.$data||{}),q=!0);break;case"number":"number"!=typeof a[p]&&(this._updateProperty(a,p,Number(a[p])),q=!0);break;case"string":"string"!=typeof a[p]&&(this._updateProperty(a,p,String(a[p])),q=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[p]}break;case"$push":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+p+")";if(void 0!==b[p].$position&&b[p].$each instanceof Array)for(l=b[p].$position,k=b[p].$each.length,j=0;k>j;j++)this._updateSplicePush(a[p],l+j,b[p].$each[j]);else if(b[p].$each instanceof Array)for(k=b[p].$each.length,j=0;k>j;j++)this._updatePush(a[p],b[p].$each[j]);else this._updatePush(a[p],b[p]);q=!0;break;case"$pull":if(a[p]instanceof Array){for(i=[],j=0;j<a[p].length;j++)this._match(a[p][j],b[p],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[p],i[k]),q=!0}break;case"$pullAll":if(a[p]instanceof Array){if(!(b[p]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+p+")";if(i=a[p],k=i.length,k>0)for(;k--;){for(l=0;l<b[p].length;l++)i[k]===b[p][l]&&(this._updatePull(a[p],k),k--,q=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+p+")";var t,u,v,w,x=a[p],y=x.length,z=!0,A=d&&d.$addToSet;for(b[p].$key?(v=!1,w=new h(b[p].$key),u=w.value(b[p])[0],delete b[p].$key):A&&A.key?(v=!1,w=new h(A.key),u=w.value(b[p])[0]):(u=this.jStringify(b[p]),v=!0),t=0;y>t;t++)if(v){if(this.jStringify(x[t])===u){z=!1;break}}else if(u===w.value(x[t])[0]){z=!1;break}z&&(this._updatePush(a[p],b[p]),q=!0);break;case"$splicePush":if(void 0===a[p]&&this._updateProperty(a,p,[]),!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+p+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[p].length&&(l=a[p].length),this._updateSplicePush(a[p],l,b[p]),q=!0;break;case"$move":if(!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+p+")";for(j=0;j<a[p].length;j++)if(this._match(a[p][j],b[p],d,"",{})){var B=b.$index;if(void 0===B)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[p],j,B),q=!0;break}break;case"$mul":this._updateMultiply(a,p,b[p]),q=!0;break;case"$rename":this._updateRename(a,p,b[p]),q=!0;break;case"$overwrite":this._updateOverwrite(a,p,b[p]),q=!0;break;case"$unset":this._updateUnset(a,p),q=!0;break;case"$clear":this._updateClear(a,p),q=!0;break;case"$pop":if(!(a[p]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+p+")";this._updatePop(a[p],b[p])&&(q=!0);break;case"$toggle":this._updateProperty(a,p,!a[p]),q=!0;break;default:a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}else if(null!==a[p]&&"object"==typeof a[p])if(n=a[p]instanceof Array,o=b[p]instanceof Array,n||o)if(!o&&n)for(j=0;j<a[p].length;j++)r=this.updateObject(a[p][j],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0);else r=this.updateObject(a[p],b[p],c,d,e+"."+p,f),q=q||r;else a[p]!==b[p]&&(this._updateProperty(a,p,b[p]),q=!0)}return q},n.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},n.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c(!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.deferEmit("change",{type:"remove",data:g}))}return c&&c(!1,g),g},n.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)},n.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){if(g.length)switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b(c);this.isProcessingQueue()||this.emit("queuesComplete")},n.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},n.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},n.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c(e),this._onChange(),this.deferEmit("change",{type:"insert",data:i}),e},n.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainSend("insert",a,{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},n.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},n.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},n.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},n.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.jStringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},n.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.jStringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},n.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},n.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},n.prototype.subset=function(a,b){var c=this.find(a,b);return(new n).subsetOf(this).primaryKey(this._primaryKey).setData(c)},d.synthesize(n.prototype,"subsetOf"),n.prototype.isSubsetOf=function(a){return this._subsetOf===a},n.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},n.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},n.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new n,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},n.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},n.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},n.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.apply(this,arguments)},n.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I=this._metrics.create("find"),J=this.primaryKey(),K=this,L=!0,M={},N=[],O=[],P=[],Q={},R={},S=function(c){return K._match(c,a,b,"and",Q)};if(I.start(),a){if(I.time("analyseQuery"),c=this._analyseQuery(K.decouple(a),b,I),I.time("analyseQuery"),I.data("analysis",c),c.hasJoin&&c.queriesJoin){for(I.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],M[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];I.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(I.data("index.potential",c.indexMatch),I.data("index.used",c.indexMatch[0].index),I.time("indexLookup"),e=c.indexMatch[0].lookup||[],I.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(L=!1)):I.flag("usedIndex",!1),L&&(e&&e.length?(d=e.length,I.time("tableScan: "+d),e=e.filter(S)):(d=this._data.length,I.time("tableScan: "+d),e=this._data.filter(S)),I.time("tableScan: "+d)),b.$orderBy&&(I.time("sort"),e=this.sort(b.$orderBy,e),I.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(R.page=b.$page,R.pages=Math.ceil(e.length/b.$limit),R.records=e.length,b.$page&&b.$limit>0&&(I.data("cursor",R),e.splice(0,b.$page*b.$limit))),b.$skip&&(R.skip=b.$skip,e.splice(0,b.$skip),I.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(R.limit=b.$limit,e.length=b.$limit,I.data("limit",b.$limit)),b.$decouple&&(I.time("decouple"),e=this.decouple(e),I.time("decouple"),I.data("flag.decouple",!0)),b.$join){for(f=0;f<b.$join.length;f++)for(k in b.$join[f])if(b.$join[f].hasOwnProperty(k))for(w=k,l=M[k]?M[k]:this._db.collection(k),m=b.$join[f][k],x=0;x<e.length;x++){o={},q=!1,r=!1,v="";for(n in m)if(m.hasOwnProperty(n))if("$"===n.substr(0,1))switch(n){case"$where":m[n].query&&(o=K._resolveDynamicQuery(m[n].query,e[x])),m[n].options&&(p=m[n].options);break;case"$as":w=m[n];break;case"$multi":q=m[n];break;case"$require":r=m[n];break;case"$prefix":v=m[n]}else o[n]=K._resolveDynamicQuery(m[n],e[x]);if(s=l.find(o,p),!r||r&&s[0])if("$root"===w){if(q!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';t=s[0],u=e[x];for(C in t)t.hasOwnProperty(C)&&void 0===u[v+C]&&(u[v+C]=t[C])}else e[x][w]=q===!1?s[0]:s;else N.push(e[x])}I.data("flag.join",!0)}if(N.length){for(I.time("removalQueue"),z=0;z<N.length;z++)y=e.indexOf(N[z]),y>-1&&e.splice(y,1);I.time("removalQueue")}if(b.$transform){for(I.time("transform"),z=0;z<e.length;z++)e.splice(z,1,b.$transform(e[z]));I.time("transform"),I.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(I.time("transformOut"),e=this.transformOut(e),I.time("transformOut")),I.data("results",e.length)}else e=[];if(!b.$aggregate){I.time("scanFields");for(z in b)b.hasOwnProperty(z)&&0!==z.indexOf("$")&&(1===b[z]?O.push(z):0===b[z]&&P.push(z));if(I.time("scanFields"),O.length||P.length){for(I.data("flag.limitFields",!0),I.data("limitFields.on",O),I.data("limitFields.off",P),I.time("limitFields"),z=0;z<e.length;z++){G=e[z];for(A in G)G.hasOwnProperty(A)&&(O.length&&A!==J&&-1===O.indexOf(A)&&delete G[A],P.length&&P.indexOf(A)>-1&&delete G[A])}I.time("limitFields")}if(b.$elemMatch){I.data("flag.elemMatch",!0),I.time("projection-elemMatch");for(z in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length)for(B=0;B<E.length;B++)if(K._match(E[B],b.$elemMatch[z],b,"",{})){D.set(e[A],z,[E[B]]);break}I.time("projection-elemMatch")}if(b.$elemsMatch){I.data("flag.elemsMatch",!0),I.time("projection-elemsMatch");for(z in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(z))for(D=new h(z),A=0;A<e.length;A++)if(E=D.value(e[A])[0],E&&E.length){for(F=[],B=0;B<E.length;B++)K._match(E[B],b.$elemsMatch[z],b,"",{})&&F.push(E[B]);D.set(e[A],z,F)}I.time("projection-elemsMatch")}}return b.$aggregate&&(I.data("flag.aggregate",!0),I.time("aggregate"),H=new h(b.$aggregate),e=H.value(e),I.time("aggregate")),I.stop(),e.__fdbOp=I,e.$cursor=R,e},n.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g,i=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b):new h(a).value(b),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=new h(e.substr(3,e.length-3)).value(b)[0]:c[g]=e;break;case"object":c[g]=i._resolveDynamicQuery(e,b);break;default:c[g]=e}return c},n.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},n.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},n.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},n.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},n.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},n.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},n.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c=[];for(b=0;b<a.length;b++)c[b]=this._transformOut(a[b]);return c}return this._transformOut(a)}return a},n.prototype.sort=function(a,b){b=b||[];var c,d,e=[];for(c in a)a.hasOwnProperty(c)&&(d={},d[c]=a[c],d.___fdbKey=String(c),e.push(d));return e.length<2?this._sort(a,b):this._bucketSort(e,b)},n.prototype._bucketSort=function(a,b){var c,d,e,f,g,h,i=a.shift(),j=[];if(a.length>0){for(b=this._sort(i,b),d=this.bucket(i.___fdbKey,b),e=d.order,g=d.buckets,h=0;h<e.length;h++)f=e[h],c=[].concat(a),j=j.concat(this._bucketSort(c,g[f]));return j}return this._sort(i,b)},n.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},n.prototype.bucket=function(a,b){var c,d,e,f=[],g={};for(c=0;c<b.length;c++)e=String(b[c][a]),d!==e&&(f.push(e),d=e),g[e]=g[e]||[],g[e].push(b[c]);return{buckets:g,order:f}},n.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},q=[],r=[];if(c.time("checkIndexes"),m=new h,n=m.countKeys(a)){void 0!==a[this._primaryKey]&&(c.time("checkIndexMatch: Primary Key"),p.indexMatch.push({lookup:this._primaryIndex.lookup(a,b),keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key"));for(o in this._indexById)if(this._indexById.hasOwnProperty(o)&&(j=this._indexById[o],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),p.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),p.indexMatch.length>1&&(c.time("findOptimalIndex"),p.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(p.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(q.push(e),"$as"in b.$join[d][e]?r.push(b.$join[d][e].$as):r.push(e));for(g=0;g<r.length;g++)f=this._queryReferencesCollection(a,r[g],""),f&&(p.joinQueries[q[g]]=f,p.queriesJoin=!0);p.joinsOn=q,p.queriesOn=p.queriesOn.concat(q)}return p},n.prototype._queryReferencesCollection=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesCollection(a[d],b,c)}return!1},n.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},n.prototype.findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=this.find(a),k=j.length,l=this._db.collection("__FDB_temp_"+this.objectId()),m={parents:k,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;k>e;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?m.subDocs.push(g):m.subDocs=m.subDocs.concat(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.$stats?m:m.subDocs},n.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},n.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},n.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:this._indexById[c.id()]?{err:"Index with those keys already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},n.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},n.prototype.lastOp=function(){return this._metrics.list()},n.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!"; for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},n.prototype.collateAdd=new l({"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data),c.update({},e)):c.insert(d.data);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),n.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l({"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof n?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=a.name;if(b){if(!this._collection[b]){if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+b+" because it does not exist and auto-create has been disabled!";return}this.debug()&&console.log(this.logIdentifier()+" Creating collection "+b)}if(this._collection[b]=this._collection[b]||new n(b,a).db(this),this._collection[b].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[b].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[b].capped(a.capped),this._collection[b].cappedSize(a.size)}return this._collection[b]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=n},{"./Crc":7,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":25,"./ReactorIO":29,"./Shared":31}],5:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){return a?a instanceof h?a:(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":4,"./Shared":31}],6:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":8,"./Metrics.js":12,"./Overload":24,"./Shared":31}],7:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],8:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Crc.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.crc=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":12,"./Overload":24,"./Shared":31}],9:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=new f,h=function(){};g.inOrder("hash");var i=function(){this.init.apply(this,arguments)};i.prototype.init=function(a,b,c){this._btree=new(h.create(2,this.sortAsc)),this._size=0,this._id=this._itemKeyHash(a,a),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexBinaryTree",i),d.mixin(i.prototype,"Mixin.ChainReactor"),d.mixin(i.prototype,"Mixin.Sorting"),i.prototype.id=function(){return this._id},i.prototype.state=function(){return this._state},i.prototype.size=function(){return this._size},d.synthesize(i.prototype,"data"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"collection"),d.synthesize(i.prototype,"type"),d.synthesize(i.prototype,"unique"),i.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},i.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree=new(h.create(2,this.sortAsc)),this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},i.prototype.insert=function(a,b){var c,d,e=this._unique,f=this._itemKeyHash(a,this._keys);e&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._btree.get(f),void 0===d&&(d=[],this._btree.put(f,d)),d.push(a),this._size++},i.prototype.remove=function(a,b){var c,d,e,f=this._unique,g=this._itemKeyHash(a,this._keys);f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._btree.get(g),void 0!==d&&(e=d.indexOf(a),e>-1&&(1===d.length?this._btree.del(g):d.splice(e,1),this._size--))},i.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},i.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},i.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},i.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},i.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},i.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},i.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexBinaryTree"),b.exports=i},{"./BinaryTree":3,"./Path":25,"./Shared":31}],10:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.finishModule("IndexHashMap"),b.exports=f},{"./Path":25,"./Shared":31}],11:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e,f=a[this._primaryKey];if(f instanceof Array){for(c=f.length,e=[],b=0;c>b;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b<f.$or.length;b++)e=e.concat(this.lookup(f.$or[b]));return e}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":31}],12:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":23,"./Shared":31}],13:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],14:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length;for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive(this,a,b,c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};this.debug&&this.debug()&&console.log(this.logIdentifier()+"Received data from parent reactor node"),(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],15:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return h.parse(a)},jStringify:function(a){return h.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return this.classIdentifier()+": "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state}},b.exports=d},{"./Overload":24,"./Serialiser":30}],16:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],17:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=function(){c.off(a,d),b.apply(c,arguments)};return this.on(a,d)},"string, *, function":function(a,b,c){var d=this,e=function(){d.off(a,b,e),c.apply(d,arguments)};return this.on(a,b,e)}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":24}],18:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if(e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0; }else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}if("object"==typeof c)return this._match(b,c,d,"and",e);throw this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a;case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}if("object"==typeof c)return this._match(b,c,d,"and",e);throw this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a;case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!this.db())throw"Cannot operate a "+a+" sub-query on an anonymous collection (one with no db set)!";if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1}};b.exports=d},{}],19:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],21:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":24}],22:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],23:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":25,"./Shared":31}],24:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,e,f,g,h=this;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(e=b.replace(/ /g,""),-1===e.indexOf("*"))d[e]=a[b];else for(g=this.generateSignaturePermutations(e),f=0;f<g.length;f++)d[g[f]]||(d[g[f]]=a[b]);a=d}return function(){var d,e,f,g=[];if(a instanceof Array){for(c=a.length,b=0;c>b;b++)if(a[b].length===arguments.length)return h.callExtend(this,"$main",a,a[b],arguments)}else{for(b=0;b<arguments.length&&(e=typeof arguments[b],"object"===e&&arguments[b]instanceof Array&&(e="array"),1!==arguments.length||"undefined"!==e);b++)g.push(e);if(d=g.join(","),a[d])return h.callExtend(this,"$main",a,a[d],arguments);for(b=g.length;b>=0;b--)if(d=g.slice(0,b).join(","),a[d+",..."])return h.callExtend(this,"$main",a,a[d+",..."],arguments)}throw f="function"==typeof this.name?this.name():"Unknown",console.log("Overload: ",a),'ForerunnerDB.Overload "'+f+'": Overloaded method does not have a matching signature for the passed arguments: '+this.jStringify(g)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],25:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.valueOne=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.valueOne(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":31}],26:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("async"),o=a("localforage");a("./PersistCompress"),a("./PersistCrypto");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=o,k.prototype.init=function(a){var b=this;this._encodeSteps=[function(){return b._encode.apply(b,arguments)}],this._decodeSteps=[function(){return b._decode.apply(b,arguments)}],a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),o.config({driver:[o.INDEXEDDB,o.WEBSQL,o.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),m.mixin(k.prototype,"Mixin.Common"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":o.setDriver(o.LOCALSTORAGE);break;case"WEBSQL":o.setDriver(o.WEBSQL);break;case"INDEXEDDB":o.setDriver(o.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return o.driver()},k.prototype.decode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._decodeSteps),b)},k.prototype.encode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._encodeSteps),b)},m.synthesize(k.prototype,"encodeSteps"),m.synthesize(k.prototype,"decodeSteps"),k.prototype.addStep=new l({object:function(a){this.$main.call(this,function(){a.encode.apply(a,arguments)},function(){a.decode.apply(a,arguments)},0)},"function, function":function(a,b){this.$main.call(this,a,b,0)},"function, function, number":function(a,b,c){this.$main.call(this,a,b,c)},$main:function(a,b,c){0===c||void 0===c?(this._encodeSteps.push(a),this._decodeSteps.unshift(b)):(this._encodeSteps.splice(c,0,a),this._decodeSteps.splice(this._decodeSteps.length-c,0,b))}}),k.prototype.unwrap=function(a){var b,c=a.split("::fdb::");switch(c[0]){case"json":b=this.jParse(c[1]);break;case"raw":b=c[1]}},k.prototype._decode=function(a,b,c){var d,e;if(a){switch(d=a.split("::fdb::"),d[0]){case"json":e=this.jParse(d[1]);break;case"raw":e=d[1]}e?(b.foundData=!0,b.rowCount=e.length):b.foundData=!1,c&&c(!1,e,b)}else b.foundData=!1,b.rowCount=0,c&&c(!1,a,b)},k.prototype._encode=function(a,b,c){var d=a;a="object"==typeof a?"json::fdb::"+this.jStringify(a):"raw::fdb::"+a,d?(b.foundData=!0,b.rowCount=d.length):b.foundData=!1,c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){o.setItem(a,d).then(function(a){c&&c(!1,a,e)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":o.getItem(a).then(function(a){c.decode(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":o.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){this.isDropped()||this.drop(!0)},"function":function(a){this.isDropped()||this.drop(!0,a)},"boolean":function(a){if(!this.isDropped()){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";this._db&&(this._db.persist.drop(this._db._name+"-"+this._name),this._db.persist.drop(this._db._name+"-"+this._name+"-metaData"))}f.call(this)}},"boolean, function":function(a,b){var c=this;if(!this.isDropped()){if(!a)return f.call(this,b);if(this._name){if(this._db)return this._db.persist.drop(this._db._name+"-"+this._name,function(){c._db.persist.drop(c._db._name+"-"+c._name+"-metaData",b)}),f.call(this);b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!")}else b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")}}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"-"+c._name,c._data,function(b,d,e){b?a&&a(b):c._db.persist.save(c._db._name+"-"+c._name+"-metaData",c.metaData(),function(b,c,d){a&&a(b,c,e,d)})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"-"+b._name,function(c,d,e){c?a&&a(c):(d&&(b.remove({}),b.insert(d)),b._db.persist.load(b._db._name+"-"+b._name+"-metaData",function(c,d,f){c||d&&b.metaData(d),a&&a(c,e,f)}))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},e.prototype.saveCustom=function(a){var b,c=this,d={};c._name?c._db?(b=function(){c.encode(c._data,function(b,e,f){b?a(b):(d.data={name:c._db._name+"-"+c._name,store:e,tableStats:f},c.encode(c._data,function(b,e,f){b?a(b):(d.metaData={name:c._db._name+"-"+c._name+"-metaData",store:e,tableStats:f},a(!1,d))}))})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.loadCustom=function(a,b){var c=this;c._name?c._db?a.data&&a.data.store?a.metaData&&a.metaData.store?c.decode(a.data.store,function(d,e,f){d?b(d):e&&(c.remove({}),c.insert(e),c.decode(a.metaData.store,function(a,d,e){a?b(a):d&&(c.metaData(d),b&&b(a,f,e))}))}):b('No "metaData" key found in passed object!'):b('No "data" key found in passed object!'):b&&b("Cannot load a collection that is not attached to a database!"):b&&b("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a?e[d].loadCustom(a,c):e[d].load(c))}}),d.prototype.save=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a.custom?e[d].saveCustom(c):e[d].save(c))}}),m.finishModule("Persist"),b.exports=k},{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":27,"./PersistCrypto":28,"./Shared":31,async:33,localforage:69}],27:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("pako"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){},d.mixin(f.prototype,"Mixin.Common"),f.prototype.encode=function(a,b,c){var d,f,g,h={data:a,type:"fdbCompress",enabled:!1};d=a.length,g=e.deflate(a,{to:"string"}),f=g.length,d>f&&(h.data=g,h.enabled=!0),b.compression={enabled:h.enabled,compressedBytes:f,uncompressedBytes:d,effect:Math.round(100/d*f)+"%"},c(!1,this.jStringify(h),b)},f.prototype.decode=function(a,b,c){var d,f=!1;a?(a=this.jParse(a),a.enabled?(d=e.inflate(a.data,{to:"string"}),f=!0):(d=a.data,f=!1),b.compression={enabled:f},c&&c(!1,d,b)):c&&c(!1,d,b)},d.plugins.FdbCompress=f,b.exports=f},{"./Shared":31,pako:70}],28:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("crypto-js"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){if(!a||!a.pass)throw'Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.';this._algo=a.algo||"AES",this._pass=a.pass},d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"pass"),f.prototype.stringify=function(a){var b={ct:a.ciphertext.toString(e.enc.Base64)};return a.iv&&(b.iv=a.iv.toString()),a.salt&&(b.s=a.salt.toString()),this.jStringify(b)},f.prototype.parse=function(a){var b=this.jParse(a),c=e.lib.CipherParams.create({ciphertext:e.enc.Base64.parse(b.ct)});return b.iv&&(c.iv=e.enc.Hex.parse(b.iv)),b.s&&(c.salt=e.enc.Hex.parse(b.s)),c},f.prototype.encode=function(a,b,c){var d,f=this,g={type:"fdbCrypto"};d=e[this._algo].encrypt(a,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}),g.data=d.toString(),g.enabled=!0,b.encryption={enabled:g.enabled},c&&c(!1,this.jStringify(g),b)},f.prototype.decode=function(a,b,c){var d,f=this;a?(a=this.jParse(a),d=e[this._algo].decrypt(a.data,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}).toString(e.enc.Utf8),c&&c(!1,d,b)):c&&c(!1,a,b)},d.plugins.FdbCrypto=f,b.exports=f},{"./Shared":31,"crypto-js":42}],29:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain||!b.chainReceive)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":31}],30:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){this._encoder=[],this._decoder={},this.registerEncoder("$date",function(a){return a instanceof Date?a.toISOString():void 0}),this.registerDecoder("$date",function(a){return new Date(a)})},d.prototype.registerEncoder=function(a,b){this._encoder.push(function(c){var d,e=b(c);return void 0!==e&&(d={},d[a]=e),d})},d.prototype.registerDecoder=function(a,b){this._decoder[a]=b},d.prototype._encode=function(a){for(var b,c=this._encoder.length;c--&&!b;)b=this._encoder[c](a);return b},d.prototype.parse=function(a){return this._parse(JSON.parse(a))},d.prototype._parse=function(a,b){var c;if("object"==typeof a&&null!==a){b=a instanceof Array?b||[]:b||{};for(c in a)if(a.hasOwnProperty(c)){if("$"===c.substr(0,1)&&this._decoder[c])return this._decoder[c](a[c]);b[c]=this._parse(a[c],b[c])}}else b=a;return b},d.prototype.stringify=function(a){return JSON.stringify(this._stringify(a))},d.prototype._stringify=function(a,b){var c,d;if("object"==typeof a&&null!==a){if(c=this._encode(a))return c;b=a instanceof Array?b||[]:b||{};for(d in a)a.hasOwnProperty(d)&&(b[d]=this._stringify(a[d],b[d]))}else b=a;return b},b.exports=d},{}],31:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.488",modules:{},plugins:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Tags":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],32:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}],33:[function(a,b,c){(function(a,c){!function(){function d(){}function e(a){return a}function f(a){return!!a}function g(a){return!a}function h(a){return function(){if(null===a)throw new Error("Callback was already called.");a.apply(this,arguments),a=null}}function i(a){return function(){null!==a&&(a.apply(this,arguments),a=null)}}function j(a){return N(a)||"number"==typeof a.length&&a.length>=0&&a.length%1===0}function k(a,b){for(var c=-1,d=a.length;++c<d;)b(a[c],c,a)}function l(a,b){for(var c=-1,d=a.length,e=Array(d);++c<d;)e[c]=b(a[c],c,a);return e}function m(a){return l(Array(a),function(a,b){return b})}function n(a,b,c){return k(a,function(a,d,e){c=b(c,a,d,e)}),c}function o(a,b){k(P(a),function(c){b(a[c],c)})}function p(a,b){for(var c=0;c<a.length;c++)if(a[c]===b)return c;return-1}function q(a){var b,c,d=-1;return j(a)?(b=a.length,function(){return d++,b>d?d:null}):(c=P(a),b=c.length,function(){return d++,b>d?c[d]:null})}function r(a,b){return b=null==b?a.length-1:+b,function(){for(var c=Math.max(arguments.length-b,0),d=Array(c),e=0;c>e;e++)d[e]=arguments[e+b];switch(b){case 0:return a.call(this,d);case 1:return a.call(this,arguments[0],d)}}}function s(a){return function(b,c,d){return a(b,d)}}function t(a){return function(b,c,e){e=i(e||d),b=b||[];var f=q(b);if(0>=a)return e(null);var g=!1,j=0,k=!1;!function l(){if(g&&0>=j)return e(null);for(;a>j&&!k;){var d=f();if(null===d)return g=!0,void(0>=j&&e(null));j+=1,c(b[d],d,h(function(a){j-=1,a?(e(a),k=!0):l()}))}}()}}function u(a){return function(b,c,d){return a(K.eachOf,b,c,d)}}function v(a){return function(b,c,d,e){return a(t(c),b,d,e)}}function w(a){return function(b,c,d){return a(K.eachOfSeries,b,c,d)}}function x(a,b,c,e){e=i(e||d),b=b||[];var f=j(b)?[]:{};a(b,function(a,b,d){c(a,function(a,c){f[b]=c,d(a)})},function(a){e(a,f)})}function y(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(c){c&&e.push({index:b,value:a}),d()})},function(){d(l(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})}function z(a,b,c,d){y(a,b,function(a,b){c(a,function(a){b(!a)})},d)}function A(a,b,c){return function(d,e,f,g){function h(){g&&g(c(!1,void 0))}function i(a,d,e){return g?void f(a,function(d){g&&b(d)&&(g(c(!0,a)),g=f=!1),e()}):e()}arguments.length>3?a(d,e,i,h):(g=f,f=e,a(d,i,h))}}function B(a,b){return b}function C(a,b,c){c=c||d;var e=j(b)?[]:{};a(b,function(a,b,c){a(r(function(a,d){d.length<=1&&(d=d[0]),e[b]=d,c(a)}))},function(a){c(a,e)})}function D(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(a,b){e=e.concat(b||[]),d(a)})},function(a){d(a,e)})}function E(a,b,c){function e(a,b,c,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length&&a.idle()?K.setImmediate(function(){a.drain()}):(k(b,function(b){var f={data:b,callback:e||d};c?a.tasks.unshift(f):a.tasks.push(f),a.tasks.length===a.concurrency&&a.saturated()}),void K.setImmediate(a.process))}function f(a,b){return function(){g-=1;var c=!1,d=arguments;k(b,function(a){k(i,function(b,d){b!==a||c||(i.splice(d,1),c=!0)}),a.callback.apply(a,d)}),a.tasks.length+g===0&&a.drain(),a.process()}}if(null==b)b=1;else if(0===b)throw new Error("Concurrency must not be zero");var g=0,i=[],j={tasks:[],concurrency:b,payload:c,saturated:d,empty:d,drain:d,started:!1,paused:!1,push:function(a,b){e(j,a,!1,b)},kill:function(){j.drain=d,j.tasks=[]},unshift:function(a,b){e(j,a,!0,b)},process:function(){if(!j.paused&&g<j.concurrency&&j.tasks.length)for(;g<j.concurrency&&j.tasks.length;){var b=j.payload?j.tasks.splice(0,j.payload):j.tasks.splice(0,j.tasks.length),c=l(b,function(a){return a.data});0===j.tasks.length&&j.empty(),g+=1,i.push(b[0]);var d=h(f(j,b));a(c,d)}},length:function(){return j.tasks.length},running:function(){return g},workersList:function(){return i},idle:function(){return j.tasks.length+g===0},pause:function(){j.paused=!0},resume:function(){if(j.paused!==!1){j.paused=!1;for(var a=Math.min(j.concurrency,j.tasks.length),b=1;a>=b;b++)K.setImmediate(j.process)}}};return j}function F(a){return r(function(b,c){b.apply(null,c.concat([r(function(b,c){"object"==typeof console&&(b?console.error&&console.error(b):console[a]&&k(c,function(b){console[a](b)}))})]))})}function G(a){return function(b,c,d){a(m(b),c,d)}}function H(a){return r(function(b,c){var d=r(function(c){var d=this,e=c.pop();return a(b,function(a,b,e){a.apply(d,c.concat([e]))},e)});return c.length?d.apply(this,c):d})}function I(a){return r(function(b){var c=b.pop();b.push(function(){var a=arguments;d?K.setImmediate(function(){c.apply(null,a)}):c.apply(null,a)});var d=!0;a.apply(this,b),d=!1})}var J,K={},L="object"==typeof self&&self.self===self&&self||"object"==typeof c&&c.global===c&&c||this; null!=L&&(J=L.async),K.noConflict=function(){return L.async=J,K};var M=Object.prototype.toString,N=Array.isArray||function(a){return"[object Array]"===M.call(a)},O=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a},P=Object.keys||function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b},Q="function"==typeof setImmediate&&setImmediate,R=Q?function(a){Q(a)}:function(a){setTimeout(a,0)};"object"==typeof a&&"function"==typeof a.nextTick?K.nextTick=a.nextTick:K.nextTick=R,K.setImmediate=Q?R:K.nextTick,K.forEach=K.each=function(a,b,c){return K.eachOf(a,s(b),c)},K.forEachSeries=K.eachSeries=function(a,b,c){return K.eachOfSeries(a,s(b),c)},K.forEachLimit=K.eachLimit=function(a,b,c,d){return t(b)(a,s(c),d)},K.forEachOf=K.eachOf=function(a,b,c){function e(a){j--,a?c(a):null===f&&0>=j&&c(null)}c=i(c||d),a=a||[];for(var f,g=q(a),j=0;null!=(f=g());)j+=1,b(a[f],f,h(e));0===j&&c(null)},K.forEachOfSeries=K.eachOfSeries=function(a,b,c){function e(){var d=!0;return null===g?c(null):(b(a[g],g,h(function(a){if(a)c(a);else{if(g=f(),null===g)return c(null);d?K.setImmediate(e):e()}})),void(d=!1))}c=i(c||d),a=a||[];var f=q(a),g=f();e()},K.forEachOfLimit=K.eachOfLimit=function(a,b,c,d){t(b)(a,c,d)},K.map=u(x),K.mapSeries=w(x),K.mapLimit=v(x),K.inject=K.foldl=K.reduce=function(a,b,c,d){K.eachOfSeries(a,function(a,d,e){c(b,a,function(a,c){b=c,e(a)})},function(a){d(a,b)})},K.foldr=K.reduceRight=function(a,b,c,d){var f=l(a,e).reverse();K.reduce(f,b,c,d)},K.transform=function(a,b,c,d){3===arguments.length&&(d=c,c=b,b=N(a)?[]:{}),K.eachOf(a,function(a,d,e){c(b,a,d,e)},function(a){d(a,b)})},K.select=K.filter=u(y),K.selectLimit=K.filterLimit=v(y),K.selectSeries=K.filterSeries=w(y),K.reject=u(z),K.rejectLimit=v(z),K.rejectSeries=w(z),K.any=K.some=A(K.eachOf,f,e),K.someLimit=A(K.eachOfLimit,f,e),K.all=K.every=A(K.eachOf,g,g),K.everyLimit=A(K.eachOfLimit,g,g),K.detect=A(K.eachOf,e,B),K.detectSeries=A(K.eachOfSeries,e,B),K.detectLimit=A(K.eachOfLimit,e,B),K.sortBy=function(a,b,c){function d(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0}K.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){return a?c(a):void c(null,l(b.sort(d),function(a){return a.value}))})},K.auto=function(a,b,c){function e(a){q.unshift(a)}function f(a){var b=p(q,a);b>=0&&q.splice(b,1)}function g(){j--,k(q.slice(0),function(a){a()})}c||(c=b,b=null),c=i(c||d);var h=P(a),j=h.length;if(!j)return c(null);b||(b=j);var l={},m=0,q=[];e(function(){j||c(null,l)}),k(h,function(d){function h(){return b>m&&n(s,function(a,b){return a&&l.hasOwnProperty(b)},!0)&&!l.hasOwnProperty(d)}function i(){h()&&(m++,f(i),k[k.length-1](q,l))}for(var j,k=N(a[d])?a[d]:[a[d]],q=r(function(a,b){if(m--,b.length<=1&&(b=b[0]),a){var e={};o(l,function(a,b){e[b]=a}),e[d]=b,c(a,e)}else l[d]=b,K.setImmediate(g)}),s=k.slice(0,k.length-1),t=s.length;t--;){if(!(j=a[s[t]]))throw new Error("Has inexistant dependency");if(N(j)&&p(j,d)>=0)throw new Error("Has cyclic dependencies")}h()?(m++,k[k.length-1](q,l)):e(i)})},K.retry=function(a,b,c){function d(a,b){if("number"==typeof b)a.times=parseInt(b,10)||f;else{if("object"!=typeof b)throw new Error("Unsupported argument type for 'times': "+typeof b);a.times=parseInt(b.times,10)||f,a.interval=parseInt(b.interval,10)||g}}function e(a,b){function c(a,c){return function(d){a(function(a,b){d(!a||c,{err:a,result:b})},b)}}function d(a){return function(b){setTimeout(function(){b(null)},a)}}for(;i.times;){var e=!(i.times-=1);h.push(c(i.task,e)),!e&&i.interval>0&&h.push(d(i.interval))}K.series(h,function(b,c){c=c[c.length-1],(a||i.callback)(c.err,c.result)})}var f=5,g=0,h=[],i={times:f,interval:g},j=arguments.length;if(1>j||j>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=j&&"function"==typeof a&&(c=b,b=a),"function"!=typeof a&&d(i,a),i.callback=c,i.task=b,i.callback?e():e},K.waterfall=function(a,b){function c(a){return r(function(d,e){if(d)b.apply(null,[d].concat(e));else{var f=a.next();f?e.push(c(f)):e.push(b),I(a).apply(null,e)}})}if(b=i(b||d),!N(a)){var e=new Error("First argument to waterfall must be an array of functions");return b(e)}return a.length?void c(K.iterator(a))():b()},K.parallel=function(a,b){C(K.eachOf,a,b)},K.parallelLimit=function(a,b,c){C(t(b),a,c)},K.series=function(a,b){C(K.eachOfSeries,a,b)},K.iterator=function(a){function b(c){function d(){return a.length&&a[c].apply(null,arguments),d.next()}return d.next=function(){return c<a.length-1?b(c+1):null},d}return b(0)},K.apply=r(function(a,b){return r(function(c){return a.apply(null,b.concat(c))})}),K.concat=u(D),K.concatSeries=w(D),K.whilst=function(a,b,c){if(c=c||d,a()){var e=r(function(d,f){d?c(d):a.apply(this,f)?b(e):c(null)});b(e)}else c(null)},K.doWhilst=function(a,b,c){var d=0;return K.whilst(function(){return++d<=1||b.apply(this,arguments)},a,c)},K.until=function(a,b,c){return K.whilst(function(){return!a.apply(this,arguments)},b,c)},K.doUntil=function(a,b,c){return K.doWhilst(a,function(){return!b.apply(this,arguments)},c)},K.during=function(a,b,c){c=c||d;var e=r(function(b,d){b?c(b):(d.push(f),a.apply(this,d))}),f=function(a,d){a?c(a):d?b(e):c(null)};a(f)},K.doDuring=function(a,b,c){var d=0;K.during(function(a){d++<1?a(null,!0):b.apply(this,arguments)},a,c)},K.queue=function(a,b){var c=E(function(b,c){a(b[0],c)},b,1);return c},K.priorityQueue=function(a,b){function c(a,b){return a.priority-b.priority}function e(a,b,c){for(var d=-1,e=a.length-1;e>d;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function f(a,b,f,g){if(null!=g&&"function"!=typeof g)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length?K.setImmediate(function(){a.drain()}):void k(b,function(b){var h={data:b,priority:f,callback:"function"==typeof g?g:d};a.tasks.splice(e(a.tasks,h,c)+1,0,h),a.tasks.length===a.concurrency&&a.saturated(),K.setImmediate(a.process)})}var g=K.queue(a,b);return g.push=function(a,b,c){f(g,a,b,c)},delete g.unshift,g},K.cargo=function(a,b){return E(a,1,b)},K.log=F("log"),K.dir=F("dir"),K.memoize=function(a,b){var c={},d={};b=b||e;var f=r(function(e){var f=e.pop(),g=b.apply(null,e);g in c?K.setImmediate(function(){f.apply(null,c[g])}):g in d?d[g].push(f):(d[g]=[f],a.apply(null,e.concat([r(function(a){c[g]=a;var b=d[g];delete d[g];for(var e=0,f=b.length;f>e;e++)b[e].apply(null,a)})])))});return f.memo=c,f.unmemoized=a,f},K.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},K.times=G(K.map),K.timesSeries=G(K.mapSeries),K.timesLimit=function(a,b,c,d){return K.mapLimit(m(a),b,c,d)},K.seq=function(){var a=arguments;return r(function(b){var c=this,e=b[b.length-1];"function"==typeof e?b.pop():e=d,K.reduce(a,b,function(a,b,d){b.apply(c,a.concat([r(function(a,b){d(a,b)})]))},function(a,b){e.apply(c,[a].concat(b))})})},K.compose=function(){return K.seq.apply(null,Array.prototype.reverse.call(arguments))},K.applyEach=H(K.eachOf),K.applyEachSeries=H(K.eachOfSeries),K.forever=function(a,b){function c(a){return a?e(a):void f(c)}var e=h(b||d),f=I(a);c()},K.ensureAsync=I,K.constant=r(function(a){var b=[null].concat(a);return function(a){return a.apply(this,b)}}),K.wrapSync=K.asyncify=function(a){return r(function(b){var c,d=b.pop();try{c=a.apply(this,b)}catch(e){return d(e)}O(c)&&"function"==typeof c.then?c.then(function(a){d(null,a)})["catch"](function(a){d(a.message?a:new Error(a))}):d(null,c)})},"object"==typeof b&&b.exports?b.exports=K:"function"==typeof define&&define.amd?define([],function(){return K}):L.async=K}()}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:68}],34:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.BlockCipher,e=b.algo,f=[],g=[],h=[],i=[],j=[],k=[],l=[],m=[],n=[],o=[];!function(){for(var a=[],b=0;256>b;b++)128>b?a[b]=b<<1:a[b]=b<<1^283;for(var c=0,d=0,b=0;256>b;b++){var e=d^d<<1^d<<2^d<<3^d<<4;e=e>>>8^255&e^99,f[c]=e,g[e]=c;var p=a[c],q=a[p],r=a[q],s=257*a[e]^16843008*e;h[c]=s<<24|s>>>8,i[c]=s<<16|s>>>16,j[c]=s<<8|s>>>24,k[c]=s;var s=16843009*r^65537*q^257*p^16843008*c;l[e]=s<<24|s>>>8,m[e]=s<<16|s>>>16,n[e]=s<<8|s>>>24,o[e]=s,c?(c=p^a[a[a[r^p]]],d^=a[a[d]]):c=d=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],q=e.AES=d.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes/4,d=this._nRounds=c+6,e=4*(d+1),g=this._keySchedule=[],h=0;e>h;h++)if(c>h)g[h]=b[h];else{var i=g[h-1];h%c?c>6&&h%c==4&&(i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i]):(i=i<<8|i>>>24,i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i],i^=p[h/c|0]<<24),g[h]=g[h-c]^i}for(var j=this._invKeySchedule=[],k=0;e>k;k++){var h=e-k;if(k%4)var i=g[h];else var i=g[h-4];4>k||4>=h?j[k]=i:j[k]=l[f[i>>>24]]^m[f[i>>>16&255]]^n[f[i>>>8&255]]^o[f[255&i]]}},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,h,i,j,k,f)},decryptBlock:function(a,b){var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c,this._doCryptBlock(a,b,this._invKeySchedule,l,m,n,o,g);var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c},_doCryptBlock:function(a,b,c,d,e,f,g,h){for(var i=this._nRounds,j=a[b]^c[0],k=a[b+1]^c[1],l=a[b+2]^c[2],m=a[b+3]^c[3],n=4,o=1;i>o;o++){var p=d[j>>>24]^e[k>>>16&255]^f[l>>>8&255]^g[255&m]^c[n++],q=d[k>>>24]^e[l>>>16&255]^f[m>>>8&255]^g[255&j]^c[n++],r=d[l>>>24]^e[m>>>16&255]^f[j>>>8&255]^g[255&k]^c[n++],s=d[m>>>24]^e[j>>>16&255]^f[k>>>8&255]^g[255&l]^c[n++];j=p,k=q,l=r,m=s}var p=(h[j>>>24]<<24|h[k>>>16&255]<<16|h[l>>>8&255]<<8|h[255&m])^c[n++],q=(h[k>>>24]<<24|h[l>>>16&255]<<16|h[m>>>8&255]<<8|h[255&j])^c[n++],r=(h[l>>>24]<<24|h[m>>>16&255]<<16|h[j>>>8&255]<<8|h[255&k])^c[n++],s=(h[m>>>24]<<24|h[j>>>16&255]<<16|h[k>>>8&255]<<8|h[255&l])^c[n++];a[b]=p,a[b+1]=q,a[b+2]=r,a[b+3]=s},keySize:8});b.AES=d._createHelper(q)}(),a.AES})},{"./cipher-core":35,"./core":36,"./enc-base64":37,"./evpkdf":39,"./md5":44}],35:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){a.lib.Cipher||function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=d.BufferedBlockAlgorithm,h=c.enc,i=(h.Utf8,h.Base64),j=c.algo,k=j.EvpKDF,l=d.Cipher=g.extend({cfg:e.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c),this._xformMode=a,this._key=b,this.reset()},reset:function(){g.reset.call(this),this._doReset()},process:function(a){return this._append(a),this._process()},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function a(a){return"string"==typeof a?x:u}return function(b){return{encrypt:function(c,d,e){return a(d).encrypt(b,c,d,e)},decrypt:function(c,d,e){return a(d).decrypt(b,c,d,e)}}}}()}),m=(d.StreamCipher=l.extend({_doFinalize:function(){var a=this._process(!0);return a},blockSize:1}),c.mode={}),n=d.BlockCipherMode=e.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a,this._iv=b}}),o=m.CBC=function(){function a(a,c,d){var e=this._iv;if(e){var f=e;this._iv=b}else var f=this._prevBlock;for(var g=0;d>g;g++)a[c+g]^=f[g]}var c=n.extend();return c.Encryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize;a.call(this,b,c,e),d.encryptBlock(b,c),this._prevBlock=b.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize,f=b.slice(c,c+e);d.decryptBlock(b,c),a.call(this,b,c,e),this._prevBlock=f}}),c}(),p=c.pad={},q=p.Pkcs7={pad:function(a,b){for(var c=4*b,d=c-a.sigBytes%c,e=d<<24|d<<16|d<<8|d,g=[],h=0;d>h;h+=4)g.push(e);var i=f.create(g,d);a.concat(i)},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},r=(d.BlockCipher=l.extend({cfg:l.cfg.extend({mode:o,padding:q}),reset:function(){l.reset.call(this);var a=this.cfg,b=a.iv,c=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=c.createEncryptor;else{var d=c.createDecryptor;this._minBufferSize=1}this._mode=d.call(c,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else{var b=this._process(!0);a.unpad(b)}return b},blockSize:4}),d.CipherParams=e.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}})),s=c.format={},t=s.OpenSSL={stringify:function(a){var b=a.ciphertext,c=a.salt;if(c)var d=f.create([1398893684,1701076831]).concat(c).concat(b);else var d=b;return d.toString(i)},parse:function(a){var b=i.parse(a),c=b.words;if(1398893684==c[0]&&1701076831==c[1]){var d=f.create(c.slice(2,4));c.splice(0,4),b.sigBytes-=16}return r.create({ciphertext:b,salt:d})}},u=d.SerializableCipher=e.extend({cfg:e.extend({format:t}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d),f=e.finalize(b),g=e.cfg;return r.create({ciphertext:f,key:c,iv:g.iv,algorithm:a,mode:g.mode,padding:g.padding,blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=a.createDecryptor(c,d).finalize(b.ciphertext);return e},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),v=c.kdf={},w=v.OpenSSL={execute:function(a,b,c,d){d||(d=f.random(8));var e=k.create({keySize:b+c}).compute(a,d),g=f.create(e.words.slice(b),4*c);return e.sigBytes=4*b,r.create({key:e,iv:g,salt:d})}},x=d.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:w}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=e.iv;var f=u.encrypt.call(this,a,b,e.key,d);return f.mixIn(e),f},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=e.iv;var f=u.decrypt.call(this,a,b,e.key,d);return f}})}()})},{"./core":36}],36:[function(a,b,c){!function(a,d){"object"==typeof c?b.exports=c=d():"function"==typeof define&&define.amd?define([],d):a.CryptoJS=d()}(this,function(){var a=a||function(a,b){var c={},d=c.lib={},e=d.Base=function(){function a(){}return{extend:function(b){a.prototype=this;var c=new a;return b&&c.mixIn(b),c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)}),c.init.prototype=c,c.$super=this,c},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),f=d.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes,e=a.sigBytes;if(this.clamp(),d%4)for(var f=0;e>f;f++){var g=c[f>>>2]>>>24-f%4*8&255;b[d+f>>>2]|=g<<24-(d+f)%4*8}else for(var f=0;e>f;f+=4)b[d+f>>>2]=c[f>>>2];return this.sigBytes+=e,this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<<32-c%4*8,b.length=a.ceil(c/4)},clone:function(){var a=e.clone.call(this);return a.words=this.words.slice(0),a},random:function(b){for(var c,d=[],e=function(b){var b=b,c=987654321,d=4294967295;return function(){c=36969*(65535&c)+(c>>16)&d,b=18e3*(65535&b)+(b>>16)&d;var e=(c<<16)+b&d;return e/=4294967296,e+=.5,e*(a.random()>.5?1:-1)}},g=0;b>g;g+=4){var h=e(4294967296*(c||a.random()));c=987654071*h(),d.push(4294967296*h()|0)}return new f.init(d,b)}}),g=c.enc={},h=g.Hex={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push((f>>>4).toString(16)),d.push((15&f).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new f.init(c,b/2)}},i=g.Latin1={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>2]|=(255&a.charCodeAt(d))<<24-d%4*8;return new f.init(c,b)}},j=g.Utf8={stringify:function(a){try{return decodeURIComponent(escape(i.stringify(a)))}catch(b){throw new Error("Malformed UTF-8 data")}},parse:function(a){return i.parse(unescape(encodeURIComponent(a)))}},k=d.BufferedBlockAlgorithm=e.extend({reset:function(){this._data=new f.init,this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,g=this.blockSize,h=4*g,i=e/h;i=b?a.ceil(i):a.max((0|i)-this._minBufferSize,0);var j=i*g,k=a.min(4*j,e);if(j){for(var l=0;j>l;l+=g)this._doProcessBlock(d,l);var m=d.splice(0,j);c.sigBytes-=k}return new f.init(m,k)},clone:function(){var a=e.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),l=(d.Hasher=k.extend({cfg:e.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){k.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},blockSize:16,_createHelper:function(a){return function(b,c){return new a.init(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return new l.HMAC.init(a,c).finalize(b)}}}),c.algo={});return c}(Math);return a})},{}],37:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.enc;e.Base64={stringify:function(a){var b=a.words,c=a.sigBytes,d=this._map;a.clamp();for(var e=[],f=0;c>f;f+=3)for(var g=b[f>>>2]>>>24-f%4*8&255,h=b[f+1>>>2]>>>24-(f+1)%4*8&255,i=b[f+2>>>2]>>>24-(f+2)%4*8&255,j=g<<16|h<<8|i,k=0;4>k&&c>f+.75*k;k++)e.push(d.charAt(j>>>6*(3-k)&63));var l=d.charAt(64);if(l)for(;e.length%4;)e.push(l);return e.join("")},parse:function(a){var b=a.length,c=this._map,e=c.charAt(64);if(e){var f=a.indexOf(e);-1!=f&&(b=f)}for(var g=[],h=0,i=0;b>i;i++)if(i%4){var j=c.indexOf(a.charAt(i-1))<<i%4*2,k=c.indexOf(a.charAt(i))>>>6-i%4*2;g[h>>>2]|=(j|k)<<24-h%4*8,h++}return d.create(g,h)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":36}],38:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a){return a<<8&4278255360|a>>>8&16711935}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Utf16=f.Utf16BE={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e+=2){var f=b[e>>>2]>>>16-e%4*8&65535;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>1]|=a.charCodeAt(d)<<16-d%2*16;return e.create(c,2*b)}};f.Utf16LE={stringify:function(a){for(var c=a.words,d=a.sigBytes,e=[],f=0;d>f;f+=2){var g=b(c[f>>>2]>>>16-f%4*8&65535);e.push(String.fromCharCode(g))}return e.join("")},parse:function(a){for(var c=a.length,d=[],f=0;c>f;f++)d[f>>>1]|=b(a.charCodeAt(f)<<16-f%2*16);return e.create(d,2*c)}}}(),a.enc.Utf16})},{"./core":36}],39:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.MD5,h=f.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=c.hasher.create(),f=e.create(),g=f.words,h=c.keySize,i=c.iterations;g.length<h;){j&&d.update(j);var j=d.update(a).finalize(b);d.reset();for(var k=1;i>k;k++)j=d.finalize(j),d.reset();f.concat(j)}return f.sigBytes=4*h,f}});b.EvpKDF=function(a,b,c){return h.create(c).compute(a,b)}}(),a.EvpKDF})},{"./core":36,"./hmac":41,"./sha1":60}],40:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.CipherParams,f=c.enc,g=f.Hex,h=c.format;h.Hex={stringify:function(a){return a.ciphertext.toString(g)},parse:function(a){var b=g.parse(a);return e.create({ciphertext:b})}}}(),a.format.Hex})},{"./cipher-core":35,"./core":36}],41:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){!function(){var b=a,c=b.lib,d=c.Base,e=b.enc,f=e.Utf8,g=b.algo;g.HMAC=d.extend({init:function(a,b){a=this._hasher=new a.init,"string"==typeof b&&(b=f.parse(b));var c=a.blockSize,d=4*c;b.sigBytes>d&&(b=a.finalize(b)),b.clamp();for(var e=this._oKey=b.clone(),g=this._iKey=b.clone(),h=e.words,i=g.words,j=0;c>j;j++)h[j]^=1549556828,i[j]^=909522486;e.sigBytes=g.sigBytes=d,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var b=this._hasher,c=b.finalize(a);b.reset();var d=b.finalize(this._oKey.clone().concat(c));return d}})}()})},{"./core":36}],42:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./lib-typedarrays"),a("./enc-utf16"),a("./enc-base64"),a("./md5"),a("./sha1"),a("./sha256"),a("./sha224"),a("./sha512"),a("./sha384"),a("./sha3"),a("./ripemd160"),a("./hmac"),a("./pbkdf2"),a("./evpkdf"),a("./cipher-core"),a("./mode-cfb"),a("./mode-ctr"),a("./mode-ctr-gladman"),a("./mode-ofb"),a("./mode-ecb"),a("./pad-ansix923"),a("./pad-iso10126"),a("./pad-iso97971"),a("./pad-zeropadding"),a("./pad-nopadding"),a("./format-hex"),a("./aes"),a("./tripledes"),a("./rc4"),a("./rabbit"),a("./rabbit-legacy")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy"],e):d.CryptoJS=e(d.CryptoJS)}(this,function(a){return a})},{"./aes":34,"./cipher-core":35,"./core":36,"./enc-base64":37,"./enc-utf16":38,"./evpkdf":39,"./format-hex":40,"./hmac":41,"./lib-typedarrays":43,"./md5":44,"./mode-cfb":45,"./mode-ctr":47,"./mode-ctr-gladman":46,"./mode-ecb":48,"./mode-ofb":49,"./pad-ansix923":50,"./pad-iso10126":51,"./pad-iso97971":52,"./pad-nopadding":53,"./pad-zeropadding":54,"./pbkdf2":55,"./rabbit":57,"./rabbit-legacy":56,"./rc4":58,"./ripemd160":59,"./sha1":60,"./sha224":61,"./sha256":62,"./sha3":63,"./sha384":64,"./sha512":65,"./tripledes":66,"./x64-core":67}],43:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){if("function"==typeof ArrayBuffer){var b=a,c=b.lib,d=c.WordArray,e=d.init,f=d.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,c=[],d=0;b>d;d++)c[d>>>2]|=a[d]<<24-d%4*8;e.call(this,c,b)}else e.apply(this,arguments)};f.prototype=d}}(),a.lib.WordArray})},{"./core":36}],44:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c,d,e,f,g){var h=a+(b&c|~b&d)+e+g;return(h<<f|h>>>32-f)+b}function d(a,b,c,d,e,f,g){var h=a+(b&d|c&~d)+e+g;return(h<<f|h>>>32-f)+b}function e(a,b,c,d,e,f,g){var h=a+(b^c^d)+e+g;return(h<<f|h>>>32-f)+b}function f(a,b,c,d,e,f,g){var h=a+(c^(b|~d))+e+g;return(h<<f|h>>>32-f)+b}var g=a,h=g.lib,i=h.WordArray,j=h.Hasher,k=g.algo,l=[];!function(){for(var a=0;64>a;a++)l[a]=4294967296*b.abs(b.sin(a+1))|0}();var m=k.MD5=j.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(a,b){for(var g=0;16>g;g++){var h=b+g,i=a[h];a[h]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var j=this._hash.words,k=a[b+0],m=a[b+1],n=a[b+2],o=a[b+3],p=a[b+4],q=a[b+5],r=a[b+6],s=a[b+7],t=a[b+8],u=a[b+9],v=a[b+10],w=a[b+11],x=a[b+12],y=a[b+13],z=a[b+14],A=a[b+15],B=j[0],C=j[1],D=j[2],E=j[3];B=c(B,C,D,E,k,7,l[0]),E=c(E,B,C,D,m,12,l[1]),D=c(D,E,B,C,n,17,l[2]),C=c(C,D,E,B,o,22,l[3]),B=c(B,C,D,E,p,7,l[4]),E=c(E,B,C,D,q,12,l[5]),D=c(D,E,B,C,r,17,l[6]),C=c(C,D,E,B,s,22,l[7]),B=c(B,C,D,E,t,7,l[8]),E=c(E,B,C,D,u,12,l[9]),D=c(D,E,B,C,v,17,l[10]),C=c(C,D,E,B,w,22,l[11]),B=c(B,C,D,E,x,7,l[12]),E=c(E,B,C,D,y,12,l[13]),D=c(D,E,B,C,z,17,l[14]),C=c(C,D,E,B,A,22,l[15]),B=d(B,C,D,E,m,5,l[16]),E=d(E,B,C,D,r,9,l[17]),D=d(D,E,B,C,w,14,l[18]),C=d(C,D,E,B,k,20,l[19]),B=d(B,C,D,E,q,5,l[20]),E=d(E,B,C,D,v,9,l[21]),D=d(D,E,B,C,A,14,l[22]),C=d(C,D,E,B,p,20,l[23]),B=d(B,C,D,E,u,5,l[24]),E=d(E,B,C,D,z,9,l[25]),D=d(D,E,B,C,o,14,l[26]),C=d(C,D,E,B,t,20,l[27]),B=d(B,C,D,E,y,5,l[28]),E=d(E,B,C,D,n,9,l[29]),D=d(D,E,B,C,s,14,l[30]),C=d(C,D,E,B,x,20,l[31]),B=e(B,C,D,E,q,4,l[32]),E=e(E,B,C,D,t,11,l[33]),D=e(D,E,B,C,w,16,l[34]),C=e(C,D,E,B,z,23,l[35]),B=e(B,C,D,E,m,4,l[36]),E=e(E,B,C,D,p,11,l[37]),D=e(D,E,B,C,s,16,l[38]),C=e(C,D,E,B,v,23,l[39]),B=e(B,C,D,E,y,4,l[40]),E=e(E,B,C,D,k,11,l[41]),D=e(D,E,B,C,o,16,l[42]),C=e(C,D,E,B,r,23,l[43]),B=e(B,C,D,E,u,4,l[44]),E=e(E,B,C,D,x,11,l[45]),D=e(D,E,B,C,A,16,l[46]),C=e(C,D,E,B,n,23,l[47]),B=f(B,C,D,E,k,6,l[48]),E=f(E,B,C,D,s,10,l[49]),D=f(D,E,B,C,z,15,l[50]),C=f(C,D,E,B,q,21,l[51]),B=f(B,C,D,E,x,6,l[52]),E=f(E,B,C,D,o,10,l[53]),D=f(D,E,B,C,v,15,l[54]),C=f(C,D,E,B,m,21,l[55]),B=f(B,C,D,E,t,6,l[56]),E=f(E,B,C,D,A,10,l[57]),D=f(D,E,B,C,r,15,l[58]),C=f(C,D,E,B,y,21,l[59]),B=f(B,C,D,E,p,6,l[60]),E=f(E,B,C,D,w,10,l[61]),D=f(D,E,B,C,n,15,l[62]),C=f(C,D,E,B,u,21,l[63]),j[0]=j[0]+B|0,j[1]=j[1]+C|0,j[2]=j[2]+D|0,j[3]=j[3]+E|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;c[e>>>5]|=128<<24-e%32;var f=b.floor(d/4294967296),g=d;c[(e+64>>>9<<4)+15]=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),c[(e+64>>>9<<4)+14]=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8),a.sigBytes=4*(c.length+1),this._process();for(var h=this._hash,i=h.words,j=0;4>j;j++){var k=i[j];i[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}return h},clone:function(){var a=j.clone.call(this);return a._hash=this._hash.clone(),a}});g.MD5=j._createHelper(m),g.HmacMD5=j._createHmacHelper(m)}(Math),a.MD5})},{"./core":36}],45:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CFB=function(){function b(a,b,c,d){var e=this._iv;if(e){var f=e.slice(0);this._iv=void 0}else var f=this._prevBlock;d.encryptBlock(f,0);for(var g=0;c>g;g++)a[b+g]^=f[g]}var c=a.lib.BlockCipherMode.extend();return c.Encryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize;b.call(this,a,c,e,d),this._prevBlock=a.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize,f=a.slice(c,c+e);b.call(this,a,c,e,d),this._prevBlock=f}}),c}(),a.mode.CFB})},{"./cipher-core":35,"./core":36}],46:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTRGladman=function(){function b(a){if(255===(a>>24&255)){var b=a>>16&255,c=a>>8&255,d=255&a;255===b?(b=0,255===c?(c=0,255===d?d=0:++d):++c):++b,a=0,a+=b<<16,a+=c<<8,a+=d}else a+=1<<24;return a}function c(a){return 0===(a[0]=b(a[0]))&&(a[1]=b(a[1])),a}var d=a.lib.BlockCipherMode.extend(),e=d.Encryptor=d.extend({processBlock:function(a,b){var d=this._cipher,e=d.blockSize,f=this._iv,g=this._counter;f&&(g=this._counter=f.slice(0),this._iv=void 0),c(g);var h=g.slice(0);d.encryptBlock(h,0);for(var i=0;e>i;i++)a[b+i]^=h[i]}});return d.Decryptor=e,d}(),a.mode.CTRGladman})},{"./cipher-core":35,"./core":36}],47:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTR=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._counter;e&&(f=this._counter=e.slice(0),this._iv=void 0);var g=f.slice(0);c.encryptBlock(g,0),f[d-1]=f[d-1]+1|0;for(var h=0;d>h;h++)a[b+h]^=g[h]}});return b.Decryptor=c,b}(),a.mode.CTR})},{"./cipher-core":35,"./core":36}],48:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.ECB=function(){var b=a.lib.BlockCipherMode.extend();return b.Encryptor=b.extend({processBlock:function(a,b){this._cipher.encryptBlock(a,b)}}),b.Decryptor=b.extend({processBlock:function(a,b){this._cipher.decryptBlock(a,b)}}),b}(),a.mode.ECB})},{"./cipher-core":35,"./core":36}],49:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.OFB=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._keystream;e&&(f=this._keystream=e.slice(0),this._iv=void 0),c.encryptBlock(f,0);for(var g=0;d>g;g++)a[b+g]^=f[g]}});return b.Decryptor=c,b}(),a.mode.OFB})},{"./cipher-core":35,"./core":36}],50:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.AnsiX923={pad:function(a,b){var c=a.sigBytes,d=4*b,e=d-c%d,f=c+e-1;a.clamp(),a.words[f>>>2]|=e<<24-f%4*8,a.sigBytes+=e},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Ansix923})},{"./cipher-core":35,"./core":36}],51:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso10126={pad:function(b,c){var d=4*c,e=d-b.sigBytes%d;b.concat(a.lib.WordArray.random(e-1)).concat(a.lib.WordArray.create([e<<24],1))},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Iso10126})},{"./cipher-core":35,"./core":36}],52:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso97971={ pad:function(b,c){b.concat(a.lib.WordArray.create([2147483648],1)),a.pad.ZeroPadding.pad(b,c)},unpad:function(b){a.pad.ZeroPadding.unpad(b),b.sigBytes--}},a.pad.Iso97971})},{"./cipher-core":35,"./core":36}],53:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":35,"./core":36}],54:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.ZeroPadding={pad:function(a,b){var c=4*b;a.clamp(),a.sigBytes+=c-(a.sigBytes%c||c)},unpad:function(a){for(var b=a.words,c=a.sigBytes-1;!(b[c>>>2]>>>24-c%4*8&255);)c--;a.sigBytes=c+1}},a.pad.ZeroPadding})},{"./cipher-core":35,"./core":36}],55:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.SHA1,h=f.HMAC,i=f.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=h.create(c.hasher,a),f=e.create(),g=e.create([1]),i=f.words,j=g.words,k=c.keySize,l=c.iterations;i.length<k;){var m=d.update(b).finalize(g);d.reset();for(var n=m.words,o=n.length,p=m,q=1;l>q;q++){p=d.finalize(p),d.reset();for(var r=p.words,s=0;o>s;s++)n[s]^=r[s]}f.concat(m),j[0]++}return f.sigBytes=4*k,f}});b.PBKDF2=function(a,b,c){return i.create(c).compute(a,b)}}(),a.PBKDF2})},{"./core":36,"./hmac":41,"./sha1":60}],56:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.RabbitLegacy=e.extend({_doReset:function(){var a=this._key.words,c=this.cfg.iv,d=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],e=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var f=0;4>f;f++)b.call(this);for(var f=0;8>f;f++)e[f]^=d[f+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;e[0]^=j,e[1]^=l,e[2]^=k,e[3]^=m,e[4]^=j,e[5]^=l,e[6]^=k,e[7]^=m;for(var f=0;4>f;f++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.RabbitLegacy=e._createHelper(j)}(),a.RabbitLegacy})},{"./cipher-core":35,"./core":36,"./enc-base64":37,"./evpkdf":39,"./md5":44}],57:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.Rabbit=e.extend({_doReset:function(){for(var a=this._key.words,c=this.cfg.iv,d=0;4>d;d++)a[d]=16711935&(a[d]<<8|a[d]>>>24)|4278255360&(a[d]<<24|a[d]>>>8);var e=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],f=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var d=0;4>d;d++)b.call(this);for(var d=0;8>d;d++)f[d]^=e[d+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;f[0]^=j,f[1]^=l,f[2]^=k,f[3]^=m,f[4]^=j,f[5]^=l,f[6]^=k,f[7]^=m;for(var d=0;4>d;d++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.Rabbit=e._createHelper(j)}(),a.Rabbit})},{"./cipher-core":35,"./core":36,"./enc-base64":37,"./evpkdf":39,"./md5":44}],58:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._S,b=this._i,c=this._j,d=0,e=0;4>e;e++){b=(b+1)%256,c=(c+a[b])%256;var f=a[b];a[b]=a[c],a[c]=f,d|=a[(a[b]+a[c])%256]<<24-8*e}return this._i=b,this._j=c,d}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=f.RC4=e.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes,d=this._S=[],e=0;256>e;e++)d[e]=e;for(var e=0,f=0;256>e;e++){var g=e%c,h=b[g>>>2]>>>24-g%4*8&255;f=(f+d[e]+h)%256;var i=d[e];d[e]=d[f],d[f]=i}this._i=this._j=0},_doProcessBlock:function(a,c){a[c]^=b.call(this)},keySize:8,ivSize:0});c.RC4=e._createHelper(g);var h=f.RC4Drop=g.extend({cfg:g.cfg.extend({drop:192}),_doReset:function(){g._doReset.call(this);for(var a=this.cfg.drop;a>0;a--)b.call(this)}});c.RC4Drop=e._createHelper(h)}(),a.RC4})},{"./cipher-core":35,"./core":36,"./enc-base64":37,"./evpkdf":39,"./md5":44}],59:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c){return a^b^c}function d(a,b,c){return a&b|~a&c}function e(a,b,c){return(a|~b)^c}function f(a,b,c){return a&c|b&~c}function g(a,b,c){return a^(b|~c)}function h(a,b){return a<<b|a>>>32-b}var i=a,j=i.lib,k=j.WordArray,l=j.Hasher,m=i.algo,n=k.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=k.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),p=k.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),q=k.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),r=k.create([0,1518500249,1859775393,2400959708,2840853838]),s=k.create([1352829926,1548603684,1836072691,2053994217,0]),t=m.RIPEMD160=l.extend({_doReset:function(){this._hash=k.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var i=0;16>i;i++){var j=b+i,k=a[j];a[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}var l,m,t,u,v,w,x,y,z,A,B=this._hash.words,C=r.words,D=s.words,E=n.words,F=o.words,G=p.words,H=q.words;w=l=B[0],x=m=B[1],y=t=B[2],z=u=B[3],A=v=B[4];for(var I,i=0;80>i;i+=1)I=l+a[b+E[i]]|0,I+=16>i?c(m,t,u)+C[0]:32>i?d(m,t,u)+C[1]:48>i?e(m,t,u)+C[2]:64>i?f(m,t,u)+C[3]:g(m,t,u)+C[4],I=0|I,I=h(I,G[i]),I=I+v|0,l=v,v=u,u=h(t,10),t=m,m=I,I=w+a[b+F[i]]|0,I+=16>i?g(x,y,z)+D[0]:32>i?f(x,y,z)+D[1]:48>i?e(x,y,z)+D[2]:64>i?d(x,y,z)+D[3]:c(x,y,z)+D[4],I=0|I,I=h(I,H[i]),I=I+A|0,w=A,A=z,z=h(y,10),y=x,x=I;I=B[1]+t+z|0,B[1]=B[2]+u+A|0,B[2]=B[3]+v+w|0,B[3]=B[4]+l+x|0,B[4]=B[0]+m+y|0,B[0]=I},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=16711935&(c<<8|c>>>24)|4278255360&(c<<24|c>>>8),a.sigBytes=4*(b.length+1),this._process();for(var e=this._hash,f=e.words,g=0;5>g;g++){var h=f[g];f[g]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return e},clone:function(){var a=l.clone.call(this);return a._hash=this._hash.clone(),a}});i.RIPEMD160=l._createHelper(t),i.HmacRIPEMD160=l._createHmacHelper(t)}(Math),a.RIPEMD160})},{"./core":36}],60:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=c.Hasher,f=b.algo,g=[],h=f.SHA1=e.extend({_doReset:function(){this._hash=new d.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],i=c[4],j=0;80>j;j++){if(16>j)g[j]=0|a[b+j];else{var k=g[j-3]^g[j-8]^g[j-14]^g[j-16];g[j]=k<<1|k>>>31}var l=(d<<5|d>>>27)+i+g[j];l+=20>j?(e&f|~e&h)+1518500249:40>j?(e^f^h)+1859775393:60>j?(e&f|e&h|f&h)-1894007588:(e^f^h)-899497514,i=h,h=f,f=e<<30|e>>>2,e=d,d=l}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+h|0,c[4]=c[4]+i|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;return b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=Math.floor(c/4294967296),b[(d+64>>>9<<4)+15]=c,a.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a}});b.SHA1=e._createHelper(h),b.HmacSHA1=e._createHmacHelper(h)}(),a.SHA1})},{"./core":36}],61:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha256")):"function"==typeof define&&define.amd?define(["./core","./sha256"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.algo,f=e.SHA256,g=e.SHA224=f.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=f._doFinalize.call(this);return a.sigBytes-=4,a}});b.SHA224=f._createHelper(g),b.HmacSHA224=f._createHmacHelper(g)}(),a.SHA224})},{"./core":36,"./sha256":62}],62:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.algo,h=[],i=[];!function(){function a(a){for(var c=b.sqrt(a),d=2;c>=d;d++)if(!(a%d))return!1;return!0}function c(a){return 4294967296*(a-(0|a))|0}for(var d=2,e=0;64>e;)a(d)&&(8>e&&(h[e]=c(b.pow(d,.5))),i[e]=c(b.pow(d,1/3)),e++),d++}();var j=[],k=g.SHA256=f.extend({_doReset:function(){this._hash=new e.init(h.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],m=c[7],n=0;64>n;n++){if(16>n)j[n]=0|a[b+n];else{var o=j[n-15],p=(o<<25|o>>>7)^(o<<14|o>>>18)^o>>>3,q=j[n-2],r=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;j[n]=p+j[n-7]+r+j[n-16]}var s=h&k^~h&l,t=d&e^d&f^e&f,u=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),v=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=m+v+s+i[n]+j[n],x=u+t;m=l,l=k,k=h,h=g+w|0,g=f,f=e,e=d,d=w+x|0}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+g|0,c[4]=c[4]+h|0,c[5]=c[5]+k|0,c[6]=c[6]+l|0,c[7]=c[7]+m|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;return c[e>>>5]|=128<<24-e%32,c[(e+64>>>9<<4)+14]=b.floor(d/4294967296),c[(e+64>>>9<<4)+15]=d,a.sigBytes=4*c.length,this._process(),this._hash},clone:function(){var a=f.clone.call(this);return a._hash=this._hash.clone(),a}});c.SHA256=f._createHelper(k),c.HmacSHA256=f._createHmacHelper(k)}(Math),a.SHA256})},{"./core":36}],63:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.x64,h=g.Word,i=c.algo,j=[],k=[],l=[];!function(){for(var a=1,b=0,c=0;24>c;c++){j[a+5*b]=(c+1)*(c+2)/2%64;var d=b%5,e=(2*a+3*b)%5;a=d,b=e}for(var a=0;5>a;a++)for(var b=0;5>b;b++)k[a+5*b]=b+(2*a+3*b)%5*5;for(var f=1,g=0;24>g;g++){for(var i=0,m=0,n=0;7>n;n++){if(1&f){var o=(1<<n)-1;32>o?m^=1<<o:i^=1<<o-32}128&f?f=f<<1^113:f<<=1}l[g]=h.create(i,m)}}();var m=[];!function(){for(var a=0;25>a;a++)m[a]=h.create()}();var n=i.SHA3=f.extend({cfg:f.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=[],b=0;25>b;b++)a[b]=new h.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var c=this._state,d=this.blockSize/2,e=0;d>e;e++){var f=a[b+2*e],g=a[b+2*e+1];f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),g=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8);var h=c[e];h.high^=g,h.low^=f}for(var i=0;24>i;i++){for(var n=0;5>n;n++){for(var o=0,p=0,q=0;5>q;q++){var h=c[n+5*q];o^=h.high,p^=h.low}var r=m[n];r.high=o,r.low=p}for(var n=0;5>n;n++)for(var s=m[(n+4)%5],t=m[(n+1)%5],u=t.high,v=t.low,o=s.high^(u<<1|v>>>31),p=s.low^(v<<1|u>>>31),q=0;5>q;q++){var h=c[n+5*q];h.high^=o,h.low^=p}for(var w=1;25>w;w++){var h=c[w],x=h.high,y=h.low,z=j[w];if(32>z)var o=x<<z|y>>>32-z,p=y<<z|x>>>32-z;else var o=y<<z-32|x>>>64-z,p=x<<z-32|y>>>64-z;var A=m[k[w]];A.high=o,A.low=p}var B=m[0],C=c[0];B.high=C.high,B.low=C.low;for(var n=0;5>n;n++)for(var q=0;5>q;q++){var w=n+5*q,h=c[w],D=m[w],E=m[(n+1)%5+5*q],F=m[(n+2)%5+5*q];h.high=D.high^~E.high&F.high,h.low=D.low^~E.low&F.low}var h=c[0],G=l[i];h.high^=G.high,h.low^=G.low}},_doFinalize:function(){var a=this._data,c=a.words,d=(8*this._nDataBytes,8*a.sigBytes),f=32*this.blockSize;c[d>>>5]|=1<<24-d%32,c[(b.ceil((d+1)/f)*f>>>5)-1]|=128,a.sigBytes=4*c.length,this._process();for(var g=this._state,h=this.cfg.outputLength/8,i=h/8,j=[],k=0;i>k;k++){var l=g[k],m=l.high,n=l.low;m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),n=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),j.push(n),j.push(m)}return new e.init(j,h)},clone:function(){for(var a=f.clone.call(this),b=a._state=this._state.slice(0),c=0;25>c;c++)b[c]=b[c].clone();return a}});c.SHA3=f._createHelper(n),c.HmacSHA3=f._createHmacHelper(n)}(Math),a.SHA3})},{"./core":36,"./x64-core":67}],64:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./sha512")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./sha512"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.x64,d=c.Word,e=c.WordArray,f=b.algo,g=f.SHA512,h=f.SHA384=g.extend({_doReset:function(){this._hash=new e.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)])},_doFinalize:function(){var a=g._doFinalize.call(this);return a.sigBytes-=16,a}});b.SHA384=g._createHelper(h),b.HmacSHA384=g._createHmacHelper(h)}(),a.SHA384})},{"./core":36,"./sha512":65,"./x64-core":67}],65:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){return g.create.apply(g,arguments)}var c=a,d=c.lib,e=d.Hasher,f=c.x64,g=f.Word,h=f.WordArray,i=c.algo,j=[b(1116352408,3609767458),b(1899447441,602891725),b(3049323471,3964484399),b(3921009573,2173295548),b(961987163,4081628472),b(1508970993,3053834265),b(2453635748,2937671579),b(2870763221,3664609560),b(3624381080,2734883394),b(310598401,1164996542),b(607225278,1323610764),b(1426881987,3590304994),b(1925078388,4068182383),b(2162078206,991336113),b(2614888103,633803317),b(3248222580,3479774868),b(3835390401,2666613458),b(4022224774,944711139),b(264347078,2341262773),b(604807628,2007800933),b(770255983,1495990901),b(1249150122,1856431235),b(1555081692,3175218132),b(1996064986,2198950837),b(2554220882,3999719339),b(2821834349,766784016),b(2952996808,2566594879),b(3210313671,3203337956),b(3336571891,1034457026),b(3584528711,2466948901),b(113926993,3758326383),b(338241895,168717936),b(666307205,1188179964),b(773529912,1546045734),b(1294757372,1522805485),b(1396182291,2643833823),b(1695183700,2343527390),b(1986661051,1014477480),b(2177026350,1206759142),b(2456956037,344077627),b(2730485921,1290863460),b(2820302411,3158454273),b(3259730800,3505952657),b(3345764771,106217008),b(3516065817,3606008344),b(3600352804,1432725776),b(4094571909,1467031594),b(275423344,851169720),b(430227734,3100823752),b(506948616,1363258195),b(659060556,3750685593),b(883997877,3785050280),b(958139571,3318307427),b(1322822218,3812723403),b(1537002063,2003034995),b(1747873779,3602036899),b(1955562222,1575990012),b(2024104815,1125592928),b(2227730452,2716904306),b(2361852424,442776044),b(2428436474,593698344),b(2756734187,3733110249),b(3204031479,2999351573),b(3329325298,3815920427),b(3391569614,3928383900),b(3515267271,566280711),b(3940187606,3454069534),b(4118630271,4000239992),b(116418474,1914138554),b(174292421,2731055270),b(289380356,3203993006),b(460393269,320620315),b(685471733,587496836),b(852142971,1086792851),b(1017036298,365543100),b(1126000580,2618297676),b(1288033470,3409855158),b(1501505948,4234509866),b(1607167915,987167468),b(1816402316,1246189591)],k=[];!function(){for(var a=0;80>a;a++)k[a]=b()}();var l=i.SHA512=e.extend({_doReset:function(){this._hash=new h.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],l=c[6],m=c[7],n=d.high,o=d.low,p=e.high,q=e.low,r=f.high,s=f.low,t=g.high,u=g.low,v=h.high,w=h.low,x=i.high,y=i.low,z=l.high,A=l.low,B=m.high,C=m.low,D=n,E=o,F=p,G=q,H=r,I=s,J=t,K=u,L=v,M=w,N=x,O=y,P=z,Q=A,R=B,S=C,T=0;80>T;T++){var U=k[T];if(16>T)var V=U.high=0|a[b+2*T],W=U.low=0|a[b+2*T+1];else{var X=k[T-15],Y=X.high,Z=X.low,$=(Y>>>1|Z<<31)^(Y>>>8|Z<<24)^Y>>>7,_=(Z>>>1|Y<<31)^(Z>>>8|Y<<24)^(Z>>>7|Y<<25),aa=k[T-2],ba=aa.high,ca=aa.low,da=(ba>>>19|ca<<13)^(ba<<3|ca>>>29)^ba>>>6,ea=(ca>>>19|ba<<13)^(ca<<3|ba>>>29)^(ca>>>6|ba<<26),fa=k[T-7],ga=fa.high,ha=fa.low,ia=k[T-16],ja=ia.high,ka=ia.low,W=_+ha,V=$+ga+(_>>>0>W>>>0?1:0),W=W+ea,V=V+da+(ea>>>0>W>>>0?1:0),W=W+ka,V=V+ja+(ka>>>0>W>>>0?1:0);U.high=V,U.low=W}var la=L&N^~L&P,ma=M&O^~M&Q,na=D&F^D&H^F&H,oa=E&G^E&I^G&I,pa=(D>>>28|E<<4)^(D<<30|E>>>2)^(D<<25|E>>>7),qa=(E>>>28|D<<4)^(E<<30|D>>>2)^(E<<25|D>>>7),ra=(L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9),sa=(M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9),ta=j[T],ua=ta.high,va=ta.low,wa=S+sa,xa=R+ra+(S>>>0>wa>>>0?1:0),wa=wa+ma,xa=xa+la+(ma>>>0>wa>>>0?1:0),wa=wa+va,xa=xa+ua+(va>>>0>wa>>>0?1:0),wa=wa+W,xa=xa+V+(W>>>0>wa>>>0?1:0),ya=qa+oa,za=pa+na+(qa>>>0>ya>>>0?1:0);R=P,S=Q,P=N,Q=O,N=L,O=M,M=K+wa|0,L=J+xa+(K>>>0>M>>>0?1:0)|0,J=H,K=I,H=F,I=G,F=D,G=E,E=wa+ya|0,D=xa+za+(wa>>>0>E>>>0?1:0)|0}o=d.low=o+E,d.high=n+D+(E>>>0>o>>>0?1:0),q=e.low=q+G,e.high=p+F+(G>>>0>q>>>0?1:0),s=f.low=s+I,f.high=r+H+(I>>>0>s>>>0?1:0),u=g.low=u+K,g.high=t+J+(K>>>0>u>>>0?1:0),w=h.low=w+M,h.high=v+L+(M>>>0>w>>>0?1:0),y=i.low=y+O,i.high=x+N+(O>>>0>y>>>0?1:0),A=l.low=A+Q,l.high=z+P+(Q>>>0>A>>>0?1:0),C=m.low=C+S,m.high=B+R+(S>>>0>C>>>0?1:0)},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+128>>>10<<5)+30]=Math.floor(c/4294967296),b[(d+128>>>10<<5)+31]=c,a.sigBytes=4*b.length,this._process();var e=this._hash.toX32();return e},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a},blockSize:32});c.SHA512=e._createHelper(l),c.HmacSHA512=e._createHmacHelper(l)}(),a.SHA512})},{"./core":36,"./x64-core":67}],66:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b){var c=(this._lBlock>>>a^this._rBlock)&b;this._rBlock^=c,this._lBlock^=c<<a}function c(a,b){var c=(this._rBlock>>>a^this._lBlock)&b;this._lBlock^=c,this._rBlock^=c<<a}var d=a,e=d.lib,f=e.WordArray,g=e.BlockCipher,h=d.algo,i=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],j=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],k=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],m=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],n=h.DES=g.extend({_doReset:function(){for(var a=this._key,b=a.words,c=[],d=0;56>d;d++){var e=i[d]-1;c[d]=b[e>>>5]>>>31-e%32&1}for(var f=this._subKeys=[],g=0;16>g;g++){for(var h=f[g]=[],l=k[g],d=0;24>d;d++)h[d/6|0]|=c[(j[d]-1+l)%28]<<31-d%6,h[4+(d/6|0)]|=c[28+(j[d+24]-1+l)%28]<<31-d%6;h[0]=h[0]<<1|h[0]>>>31;for(var d=1;7>d;d++)h[d]=h[d]>>>4*(d-1)+3;h[7]=h[7]<<5|h[7]>>>27}for(var m=this._invSubKeys=[],d=0;16>d;d++)m[d]=f[15-d]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._subKeys)},decryptBlock:function(a,b){this._doCryptBlock(a,b,this._invSubKeys)},_doCryptBlock:function(a,d,e){this._lBlock=a[d],this._rBlock=a[d+1],b.call(this,4,252645135),b.call(this,16,65535),c.call(this,2,858993459),c.call(this,8,16711935),b.call(this,1,1431655765);for(var f=0;16>f;f++){for(var g=e[f],h=this._lBlock,i=this._rBlock,j=0,k=0;8>k;k++)j|=l[k][((i^g[k])&m[k])>>>0];this._lBlock=i,this._rBlock=h^j}var n=this._lBlock;this._lBlock=this._rBlock,this._rBlock=n,b.call(this,1,1431655765),c.call(this,8,16711935),c.call(this,2,858993459),b.call(this,16,65535),b.call(this,4,252645135),a[d]=this._lBlock,a[d+1]=this._rBlock; },keySize:2,ivSize:2,blockSize:2});d.DES=g._createHelper(n);var o=h.TripleDES=g.extend({_doReset:function(){var a=this._key,b=a.words;this._des1=n.createEncryptor(f.create(b.slice(0,2))),this._des2=n.createEncryptor(f.create(b.slice(2,4))),this._des3=n.createEncryptor(f.create(b.slice(4,6)))},encryptBlock:function(a,b){this._des1.encryptBlock(a,b),this._des2.decryptBlock(a,b),this._des3.encryptBlock(a,b)},decryptBlock:function(a,b){this._des3.decryptBlock(a,b),this._des2.encryptBlock(a,b),this._des1.decryptBlock(a,b)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=g._createHelper(o)}(),a.TripleDES})},{"./cipher-core":35,"./core":36,"./enc-base64":37,"./evpkdf":39,"./md5":44}],67:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=c.x64={};g.Word=e.extend({init:function(a,b){this.high=a,this.low=b}}),g.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=8*a.length},toX32:function(){for(var a=this.words,b=a.length,c=[],d=0;b>d;d++){var e=a[d];c.push(e.high),c.push(e.low)}return f.create(c,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),b=a.words=this.words.slice(0),c=b.length,d=0;c>d;d++)b[d]=b[d].clone();return a}})}(),a})},{"./core":36}],68:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h&&h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],69:[function(a,b,c){(function(a,d){!function(){var b,c,e,f;!function(){var a={},d={};b=function(b,c,d){a[b]={deps:c,callback:d}},f=e=c=function(b){function e(a){if("."!==a.charAt(0))return a;for(var c=a.split("/"),d=b.split("/").slice(0,-1),e=0,f=c.length;f>e;e++){var g=c[e];if(".."===g)d.pop();else{if("."===g)continue;d.push(g)}}return d.join("/")}if(f._eak_seen=a,d[b])return d[b];if(d[b]={},!a[b])throw new Error("Could not find module "+b);for(var g,h=a[b],i=h.deps,j=h.callback,k=[],l=0,m=i.length;m>l;l++)"exports"===i[l]?k.push(g={}):k.push(c(e(i[l])));var n=j.apply(this,k);return d[b]=g||n}}(),b("promise/all",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to all.");return new b(function(b,c){function d(a){return function(b){f(a,b)}}function f(a,c){h[a]=c,0===--i&&b(h)}var g,h=[],i=a.length;0===i&&b([]);for(var j=0;j<a.length;j++)g=a[j],g&&e(g.then)?g.then(d(j),c):f(j,g)})}var d=a.isArray,e=a.isFunction;b.all=c}),b("promise/asap",["exports"],function(b){"use strict";function c(){return function(){a.nextTick(g)}}function e(){var a=0,b=new k(g),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){c.data=a=++a%2}}function f(){return function(){l.setTimeout(g,1)}}function g(){for(var a=0;a<m.length;a++){var b=m[a],c=b[0],d=b[1];c(d)}m=[]}function h(a,b){var c=m.push([a,b]);1===c&&i()}var i,j="undefined"!=typeof window?window:{},k=j.MutationObserver||j.WebKitMutationObserver,l="undefined"!=typeof d?d:void 0===this?window:this,m=[];i="undefined"!=typeof a&&"[object process]"==={}.toString.call(a)?c():k?e():f(),b.asap=h}),b("promise/config",["exports"],function(a){"use strict";function b(a,b){return 2!==arguments.length?c[a]:void(c[a]=b)}var c={instrument:!1};a.config=c,a.configure=b}),b("promise/polyfill",["./promise","./utils","exports"],function(a,b,c){"use strict";function e(){var a;a="undefined"!=typeof d?d:"undefined"!=typeof window&&window.document?window:self;var b="Promise"in a&&"resolve"in a.Promise&&"reject"in a.Promise&&"all"in a.Promise&&"race"in a.Promise&&function(){var b;return new a.Promise(function(a){b=a}),g(b)}();b||(a.Promise=f)}var f=a.Promise,g=b.isFunction;c.polyfill=e}),b("promise/promise",["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"],function(a,b,c,d,e,f,g,h){"use strict";function i(a){if(!v(a))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof i))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this._subscribers=[],j(a,this)}function j(a,b){function c(a){o(b,a)}function d(a){q(b,a)}try{a(c,d)}catch(e){d(e)}}function k(a,b,c,d){var e,f,g,h,i=v(c);if(i)try{e=c(d),g=!0}catch(j){h=!0,f=j}else e=d,g=!0;n(b,e)||(i&&g?o(b,e):h?q(b,f):a===D?o(b,e):a===E&&q(b,e))}function l(a,b,c,d){var e=a._subscribers,f=e.length;e[f]=b,e[f+D]=c,e[f+E]=d}function m(a,b){for(var c,d,e=a._subscribers,f=a._detail,g=0;g<e.length;g+=3)c=e[g],d=e[g+b],k(b,c,d,f);a._subscribers=null}function n(a,b){var c,d=null;try{if(a===b)throw new TypeError("A promises callback cannot return that same promise.");if(u(b)&&(d=b.then,v(d)))return d.call(b,function(d){return c?!0:(c=!0,void(b!==d?o(a,d):p(a,d)))},function(b){return c?!0:(c=!0,void q(a,b))}),!0}catch(e){return c?!0:(q(a,e),!0)}return!1}function o(a,b){a===b?p(a,b):n(a,b)||p(a,b)}function p(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(r,a))}function q(a,b){a._state===B&&(a._state=C,a._detail=b,t.async(s,a))}function r(a){m(a,a._state=D)}function s(a){m(a,a._state=E)}var t=a.config,u=(a.configure,b.objectOrFunction),v=b.isFunction,w=(b.now,c.all),x=d.race,y=e.resolve,z=f.reject,A=g.asap;t.async=A;var B=void 0,C=0,D=1,E=2;i.prototype={constructor:i,_state:void 0,_detail:void 0,_subscribers:void 0,then:function(a,b){var c=this,d=new this.constructor(function(){});if(this._state){var e=arguments;t.async(function(){k(c._state,d,e[c._state-1],c._detail)})}else l(this,d,a,b);return d},"catch":function(a){return this.then(null,a)}},i.all=w,i.race=x,i.resolve=y,i.reject=z,h.Promise=i}),b("promise/race",["./utils","exports"],function(a,b){"use strict";function c(a){var b=this;if(!d(a))throw new TypeError("You must pass an array to race.");return new b(function(b,c){for(var d,e=0;e<a.length;e++)d=a[e],d&&"function"==typeof d.then?d.then(b,c):b(d)})}var d=a.isArray;b.race=c}),b("promise/reject",["exports"],function(a){"use strict";function b(a){var b=this;return new b(function(b,c){c(a)})}a.reject=b}),b("promise/resolve",["exports"],function(a){"use strict";function b(a){if(a&&"object"==typeof a&&a.constructor===this)return a;var b=this;return new b(function(b){b(a)})}a.resolve=b}),b("promise/utils",["exports"],function(a){"use strict";function b(a){return c(a)||"object"==typeof a&&null!==a}function c(a){return"function"==typeof a}function d(a){return"[object Array]"===Object.prototype.toString.call(a)}var e=Date.now||function(){return(new Date).getTime()};a.objectOrFunction=b,a.isFunction=c,a.isArray=d,a.now=e}),c("promise/polyfill").polyfill()}(),function(a,d){"object"==typeof c&&"object"==typeof b?b.exports=d():"function"==typeof define&&define.amd?define([],d):"object"==typeof c?c.localforage=d():a.localforage=d()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}b.__esModule=!0,function(){function a(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function e(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(m(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function f(a){for(var b in h)if(h.hasOwnProperty(b)&&h[b]===a)return!0;return!1}var g={},h={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},i=[h.INDEXEDDB,h.WEBSQL,h.LOCALSTORAGE],j=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],k={description:"",driver:i.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},l=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[h.WEBSQL]=!!a.openDatabase,c[h.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),c[h.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),m=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},n=function(){function b(a){d(this,b),this.INDEXEDDB=h.INDEXEDDB,this.LOCALSTORAGE=h.LOCALSTORAGE,this.WEBSQL=h.WEBSQL,this._defaultConfig=e({},k),this._config=e({},this._defaultConfig,a),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver)}return b.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},b.prototype.defineDriver=function(a,b,c){var d=new Promise(function(b,c){try{var d=a._driver,e=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),h=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(e);if(f(a._driver))return void c(h);for(var i=j.concat("_initStorage"),k=0;k<i.length;k++){var m=i[k];if(!m||!a[m]||"function"!=typeof a[m])return void c(e)}var n=Promise.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():Promise.resolve(!!a._support)),n.then(function(c){l[d]=c,g[d]=a,b()},c)}catch(o){c(o)}});return d.then(b,c),d},b.prototype.driver=function(){return this._driver||null},b.prototype.getDriver=function(a,b,d){var e=this,h=function(){if(f(a))switch(a){case e.INDEXEDDB:return new Promise(function(a,b){a(c(1))});case e.LOCALSTORAGE:return new Promise(function(a,b){a(c(2))});case e.WEBSQL:return new Promise(function(a,b){a(c(4))})}else if(g[a])return Promise.resolve(g[a]);return Promise.reject(new Error("Driver not found."))}();return h.then(b,d),h},b.prototype.getSerializer=function(a){var b=new Promise(function(a,b){a(c(3))});return a&&"function"==typeof a&&b.then(function(b){a(b)}),b},b.prototype.ready=function(a){var b=this,c=b._driverSet.then(function(){return null===b._ready&&(b._ready=b._initDriver()),b._ready});return c.then(a,a),c},b.prototype.setDriver=function(a,b,c){function d(){f._config.driver=f.driver()}function e(a){return function(){function b(){for(;c<a.length;){var e=a[c];return c++,f._dbInfo=null,f._ready=null,f.getDriver(e).then(function(a){return f._extend(a),d(),f._ready=f._initStorage(f._config),f._ready})["catch"](b)}d();var g=new Error("No available storage method found.");return f._driverSet=Promise.reject(g),f._driverSet}var c=0;return b()}}var f=this;m(a)||(a=[a]);var g=this._getSupportedDrivers(a),h=null!==this._driverSet?this._driverSet["catch"](function(){return Promise.resolve()}):Promise.resolve();return this._driverSet=h.then(function(){var a=g[0];return f._dbInfo=null,f._ready=null,f.getDriver(a).then(function(a){f._driver=a._driver,d(),f._wrapLibraryMethodsWithReady(),f._initDriver=e(g)})})["catch"](function(){d();var a=new Error("No available storage method found.");return f._driverSet=Promise.reject(a),f._driverSet}),this._driverSet.then(b,c),this._driverSet},b.prototype.supports=function(a){return!!l[a]},b.prototype._extend=function(a){e(this,a)},b.prototype._getSupportedDrivers=function(a){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c];this.supports(e)&&b.push(e)}return b},b.prototype._wrapLibraryMethodsWithReady=function(){for(var b=0;b<j.length;b++)a(this,j[b])},b.prototype.createInstance=function(a){return new b(a)},b}(),o=new n;b["default"]=o}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,function(){function a(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=x.BlobBuilder||x.MSBlobBuilder||x.MozBlobBuilder||x.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function c(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function d(a){return new Promise(function(b,c){var d=new XMLHttpRequest;d.open("GET",a),d.withCredentials=!0,d.responseType="arraybuffer",d.onreadystatechange=function(){return 4===d.readyState?200===d.status?b({response:d.response,type:d.getResponseHeader("Content-Type")}):void c({status:d.status,response:d.response}):void 0},d.send()})}function e(b){return new Promise(function(c,e){var f=a([""],{type:"image/png"}),g=b.transaction([B],"readwrite");g.objectStore(B).put(f,"key"),g.oncomplete=function(){var a=b.transaction([B],"readwrite"),f=a.objectStore(B).get("key");f.onerror=e,f.onsuccess=function(a){var b=a.target.result,e=URL.createObjectURL(b);d(e).then(function(a){c(!(!a||"image/png"!==a.type))},function(){c(!1)}).then(function(){URL.revokeObjectURL(e)})}}})["catch"](function(){return!1})}function f(a){return"boolean"==typeof z?Promise.resolve(z):e(a).then(function(a){return z=a})}function g(a){return new Promise(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function h(b){var d=c(atob(b.data));return a([d],{type:b.type})}function i(a){return a&&a.__local_forage_encoded_blob}function j(a){function b(){return Promise.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];A||(A={});var f=A[d.name];f||(f={forages:[],db:null},A[d.name]=f),f.forages.push(this);for(var g=[],h=0;h<f.forages.length;h++){var i=f.forages[h];i!==this&&g.push(i.ready()["catch"](b))}var j=f.forages.slice(0);return Promise.all(g).then(function(){return d.db=f.db,k(d)}).then(function(a){return d.db=a,n(d,c._defaultConfig.version)?l(d):a}).then(function(a){d.db=f.db=a,c._dbInfo=d;for(var b in j){var e=j[b];e!==c&&(e._dbInfo.db=d.db,e._dbInfo.version=d.version)}})}function k(a){return m(a,!1)}function l(a){return m(a,!0)}function m(a,b){return new Promise(function(c,d){if(a.db){if(!b)return c(a.db);a.db.close()}var e=[a.name];b&&e.push(a.version);var f=y.open.apply(y,e);b&&(f.onupgradeneeded=function(b){var c=f.result;try{c.createObjectStore(a.storeName),b.oldVersion<=1&&c.createObjectStore(B)}catch(d){if("ConstraintError"!==d.name)throw d;x.console.warn('The database "'+a.name+'" has been upgraded from version '+b.oldVersion+" to version "+b.newVersion+', but the storage "'+a.storeName+'" already exists.')}}),f.onerror=function(){d(f.error)},f.onsuccess=function(){c(f.result)}})}function n(a,b){if(!a.db)return!0;var c=!a.db.objectStoreNames.contains(a.storeName),d=a.version<a.db.version,e=a.version>a.db.version;if(d&&(a.version!==b&&x.console.warn('The database "'+a.name+"\" can't be downgraded from version "+a.db.version+" to version "+a.version+"."),a.version=a.db.version),e||c){if(c){var f=a.db.version+1;f>a.version&&(a.version=f)}return!0}return!1}function o(a,b){var c=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),i(a)&&(a=h(a)),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return w(d,b),d}function p(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),j=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;i(d)&&(d=h(d));var e=a(d,c.key,j++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return w(d,b),d}function q(a,b,c){var d=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new Promise(function(c,e){var h;d.ready().then(function(){return h=d._dbInfo,f(h.db)}).then(function(a){return!a&&b instanceof Blob?g(b):b}).then(function(b){var d=h.db.transaction(h.storeName,"readwrite"),f=d.objectStore(h.storeName);null===b&&(b=void 0);var g=f.put(b,a);d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=g.error?g.error:g.transaction.error;e(a)}})["catch"](e)});return w(e,c),e}function r(a,b){var c=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}})["catch"](d)});return w(d,b),d}function s(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return w(c,a),c}function t(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return w(c,a),c}function u(a,b){var c=this,d=new Promise(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return w(d,b),d}function v(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return w(c,a),c}function w(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var x=this,y=y||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(y){var z,A,B="local-forage-detect-blob-support",C={_driver:"asyncStorage",_initStorage:j,iterate:p,getItem:o,setItem:q,removeItem:r,clear:s,length:t,key:u,keys:v};b["default"]=C}}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0,function(){function a(a){var b=this,d={};if(a)for(var e in a)d[e]=a[e];return d.keyPrefix=d.name+"/",d.storeName!==b._defaultConfig.storeName&&(d.keyPrefix+=d.storeName+"/"),b._dbInfo=d,new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,Promise.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=n.length-1;c>=0;c--){var d=n.key(c);0===d.indexOf(a)&&n.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=n.getItem(b.keyPrefix+a);return d&&(d=b.serializer.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo,d=b.keyPrefix,e=d.length,f=n.length,g=1,h=0;f>h;h++){var i=n.key(h);if(0===i.indexOf(d)){var j=n.getItem(i);if(j&&(j=b.serializer.deserialize(j)),j=a(j,i.substring(e),g++),void 0!==j)return j}}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=n.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=n.length,d=[],e=0;c>e;e++)0===n.key(e).indexOf(a.keyPrefix)&&d.push(n.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;n.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new Promise(function(e,f){var g=d._dbInfo;g.serializer.serialize(b,function(b,d){if(d)f(d);else try{n.setItem(g.keyPrefix+a,b),e(c)}catch(h){("QuotaExceededError"===h.name||"NS_ERROR_DOM_QUOTA_REACHED"===h.name)&&f(h),f(h)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=this,n=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;n=this.localStorage}catch(o){return}var p={_driver:"localStorageWrapper",_initStorage:a,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};b["default"]=p}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,function(){function a(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=x.BlobBuilder||x.MSBlobBuilder||x.MozBlobBuilder||x.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function c(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=j;a instanceof ArrayBuffer?(d=a,e+=l):(d=a.buffer,"[object Int8Array]"===c?e+=n:"[object Uint8Array]"===c?e+=o:"[object Uint8ClampedArray]"===c?e+=p:"[object Int16Array]"===c?e+=q:"[object Uint16Array]"===c?e+=s:"[object Int32Array]"===c?e+=r:"[object Uint32Array]"===c?e+=t:"[object Float32Array]"===c?e+=u:"[object Float64Array]"===c?e+=v:b(new Error("Failed to get type for BinaryArray"))),b(e+f(d))}else if("[object Blob]"===c){var g=new FileReader;g.onload=function(){var c=h+a.type+"~"+f(this.result);b(j+m+c)},g.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(i){console.error("Couldn't convert value into a JSON string: ",a),b(null,i)}}function d(b){if(b.substring(0,k)!==j)return JSON.parse(b);var c,d=b.substring(w),f=b.substring(k,w);if(f===m&&i.test(d)){var g=d.match(i);c=g[1],d=d.substring(g[0].length)}var h=e(d);switch(f){case l:return h;case m:return a([h],{type:c});case n:return new Int8Array(h);case o:return new Uint8Array(h);case p:return new Uint8ClampedArray(h);case q:return new Int16Array(h);case s:return new Uint16Array(h);case r:return new Int32Array(h);case t:return new Uint32Array(h);case u:return new Float32Array(h);case v:return new Float64Array(h);default:throw new Error("Unkown type: "+f)}}function e(a){var b,c,d,e,f,h=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(h--,"="===a[a.length-2]&&h--);var k=new ArrayBuffer(h),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=g.indexOf(a[b]),d=g.indexOf(a[b+1]),e=g.indexOf(a[b+2]),f=g.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function f(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=g[c[b]>>2],d+=g[(3&c[b])<<4|c[b+1]>>4],d+=g[(15&c[b+1])<<2|c[b+2]>>6],d+=g[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h="~~local_forage_type~",i=/^~~local_forage_type~([^~]+)~/,j="__lfsc__:",k=j.length,l="arbf",m="blob",n="si08",o="ui08",p="uic8",q="si16",r="si32",s="ur16",t="ui32",u="fl32",v="fl64",w=k+l.length,x=this,y={serialize:c,deserialize:d,stringToBuffer:e,bufferToString:f};b["default"]=y}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0,function(){function a(a){var b=this,d={db:null};if(a)for(var e in a)d[e]="string"!=typeof a[e]?a[e].toString():a[e];var f=new Promise(function(c,e){try{d.db=n(d.name,String(d.version),d.description,d.size)}catch(f){return b.setDriver(b.LOCALSTORAGE).then(function(){return b._initStorage(a)}).then(c)["catch"](e)}d.db.transaction(function(a){a.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=d,c()},function(a,b){e(b)})})});return new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,f})}function d(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var f=d.rows,g=f.length,h=0;g>h;h++){var i=f.item(h),j=i.value;if(j&&(j=e.serializer.deserialize(j)),j=a(j,i.key,h+1),void 0!==j)return void b(j)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new Promise(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b,g=d._dbInfo;g.serializer.serialize(b,function(b,d){d?e(d):g.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+g.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new Promise(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new Promise(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=this,n=this.openDatabase;if(n){var o={_driver:"webSQLStorage",_initStorage:a,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};b["default"]=o}}.call("undefined"!=typeof window?window:self),a.exports=b["default"]}])})}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:68}],70:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":71,"./lib/inflate":72,"./lib/utils/common":73,"./lib/zlib/constants":76}],71:[function(a,b,c){"use strict";function d(a,b){var c=new u(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}function f(a,b){return b=b||{},b.gzip=!0,d(a,b)}var g=a("./zlib/deflate.js"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=Object.prototype.toString,m=0,n=4,o=0,p=1,q=2,r=-1,s=0,t=8,u=function(a){this.options=h.assign({level:r,method:t,chunkSize:16384,windowBits:15,memLevel:8,strategy:s,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==o)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header)};u.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?n:m,"string"==typeof a?e.input=i.string2buf(a):"[object ArrayBuffer]"===l.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new h.Buf8(f),e.next_out=0,e.avail_out=f),c=g.deflate(e,d),c!==p&&c!==o)return this.onEnd(c),this.ended=!0,!1;(0===e.avail_out||0===e.avail_in&&(d===n||d===q))&&("string"===this.options.to?this.onData(i.buf2binstring(h.shrinkBuf(e.output,e.next_out))):this.onData(h.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==p);return d===n?(c=g.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===o):d===q?(this.onEnd(o),e.avail_out=0,!0):!0},u.prototype.onData=function(a){this.chunks.push(a)},u.prototype.onEnd=function(a){a===o&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=u,c.deflate=d,c.deflateRaw=e,c.gzip=f},{"./utils/common":73,"./utils/strings":74,"./zlib/deflate.js":78,"./zlib/messages":83,"./zlib/zstream":85}],72:[function(a,b,c){"use strict";function d(a,b){var c=new n(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}var f=a("./zlib/inflate.js"),g=a("./utils/common"),h=a("./utils/strings"),i=a("./zlib/constants"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=a("./zlib/gzheader"),m=Object.prototype.toString,n=function(a){this.options=g.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1, this.chunks=[],this.strm=new k,this.strm.avail_out=0;var c=f.inflateInit2(this.strm,b.windowBits);if(c!==i.Z_OK)throw new Error(j[c]);this.header=new l,f.inflateGetHeader(this.strm,this.header)};n.prototype.push=function(a,b){var c,d,e,j,k,l=this.strm,n=this.options.chunkSize,o=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?i.Z_FINISH:i.Z_NO_FLUSH,"string"==typeof a?l.input=h.binstring2buf(a):"[object ArrayBuffer]"===m.call(a)?l.input=new Uint8Array(a):l.input=a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new g.Buf8(n),l.next_out=0,l.avail_out=n),c=f.inflate(l,i.Z_NO_FLUSH),c===i.Z_BUF_ERROR&&o===!0&&(c=i.Z_OK,o=!1),c!==i.Z_STREAM_END&&c!==i.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0===l.avail_out||c===i.Z_STREAM_END||0===l.avail_in&&(d===i.Z_FINISH||d===i.Z_SYNC_FLUSH))&&("string"===this.options.to?(e=h.utf8border(l.output,l.next_out),j=l.next_out-e,k=h.buf2string(l.output,e),l.next_out=j,l.avail_out=n-j,j&&g.arraySet(l.output,l.output,e,j,0),this.onData(k)):this.onData(g.shrinkBuf(l.output,l.next_out))),0===l.avail_in&&0===l.avail_out&&(o=!0)}while((l.avail_in>0||0===l.avail_out)&&c!==i.Z_STREAM_END);return c===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(c=f.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===i.Z_OK):d===i.Z_SYNC_FLUSH?(this.onEnd(i.Z_OK),l.avail_out=0,!0):!0},n.prototype.onData=function(a){this.chunks.push(a)},n.prototype.onEnd=function(a){a===i.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=g.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=n,c.inflate=d,c.inflateRaw=e,c.ungzip=d},{"./utils/common":73,"./utils/strings":74,"./zlib/constants":76,"./zlib/gzheader":79,"./zlib/inflate.js":81,"./zlib/messages":83,"./zlib/zstream":85}],73:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],74:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":73}],75:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=d},{}],76:[function(a,b,c){b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],77:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a=-1^a;for(var h=d;g>h;h++)a=a>>>8^e[255&(a^b[h])];return-1^a}var f=d();b.exports=e},{}],78:[function(a,b,c){"use strict";function d(a,b){return a.msg=G[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(C.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){D._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,C.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=E(a.adler,b,e,c):2===a.state.wrap&&(a.adler=F(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-ja?a.strstart-(a.w_size-ja):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ia,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ia-(m-f),f=m-ia,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-ja)){C.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ha)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ha-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ha)););}while(a.lookahead<ja&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===H)return sa;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return sa;if(a.strstart-a.block_start>=a.w_size-ja&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?sa:sa}function o(a,b){for(var c,d;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c)),a.match_length>=ha)if(d=D._tr_tally(a,a.strstart-a.match_start,a.match_length-ha),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ha){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function p(a,b){for(var c,d,e;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ha-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===S||a.match_length===ha&&a.strstart-a.match_start>4096)&&(a.match_length=ha-1)),a.prev_length>=ha&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ha,d=D._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ha),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ha-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return sa}else if(a.match_available){if(d=D._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return sa}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=D._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ia){if(m(a),a.lookahead<=ia&&b===H)return sa;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ha&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ia;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ia-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ha?(c=D._tr_tally(a,1,a.match_length-ha),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===H)return sa;break}if(a.match_length=0,c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function s(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=B[a.level].max_lazy,a.good_match=B[a.level].good_length,a.nice_match=B[a.level].nice_length,a.max_chain_length=B[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ha-1,a.match_available=0,a.ins_h=0}function t(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Y,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new C.Buf16(2*fa),this.dyn_dtree=new C.Buf16(2*(2*da+1)),this.bl_tree=new C.Buf16(2*(2*ea+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new C.Buf16(ga+1),this.heap=new C.Buf16(2*ca+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new C.Buf16(2*ca+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function u(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=X,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?la:qa,a.adler=2===b.wrap?0:1,b.last_flush=H,D._tr_init(b),M):d(a,O)}function v(a){var b=u(a);return b===M&&s(a.state),b}function w(a,b){return a&&a.state?2!==a.state.wrap?O:(a.state.gzhead=b,M):O}function x(a,b,c,e,f,g){if(!a)return O;var h=1;if(b===R&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>Z||c!==Y||8>e||e>15||0>b||b>9||0>g||g>V)return d(a,O);8===e&&(e=9);var i=new t;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ha-1)/ha),i.window=new C.Buf8(2*i.w_size),i.head=new C.Buf16(i.hash_size),i.prev=new C.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new C.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,v(a)}function y(a,b){return x(a,b,Y,$,_,W)}function z(a,b){var c,h,k,l;if(!a||!a.state||b>L||0>b)return a?d(a,O):O;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===ra&&b!==K)return d(a,0===a.avail_out?Q:O);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===la)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=F(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=ma):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,wa),h.status=qa);else{var m=Y+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=T||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=ka),m+=31-m%31,h.status=qa,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===ma)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=na)}else h.status=na;if(h.status===na)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=pa)}else h.status=pa;if(h.status===pa&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=qa)):h.status=qa),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,M}else if(0===a.avail_in&&e(b)<=e(c)&&b!==K)return d(a,Q);if(h.status===ra&&0!==a.avail_in)return d(a,Q);if(0!==a.avail_in||0!==h.lookahead||b!==H&&h.status!==ra){var o=h.strategy===T?r(h,b):h.strategy===U?q(h,b):B[h.level].func(h,b);if((o===ua||o===va)&&(h.status=ra),o===sa||o===ua)return 0===a.avail_out&&(h.last_flush=-1),M;if(o===ta&&(b===I?D._tr_align(h):b!==L&&(D._tr_stored_block(h,0,0,!1),b===J&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,M}return b!==K?M:h.wrap<=0?N:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?M:N)}function A(a){var b;return a&&a.state?(b=a.state.status,b!==la&&b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra?d(a,O):(a.state=null,b===qa?d(a,P):M)):O}var B,C=a("../utils/common"),D=a("./trees"),E=a("./adler32"),F=a("./crc32"),G=a("./messages"),H=0,I=1,J=3,K=4,L=5,M=0,N=1,O=-2,P=-3,Q=-5,R=-1,S=1,T=2,U=3,V=4,W=0,X=2,Y=8,Z=9,$=15,_=8,aa=29,ba=256,ca=ba+1+aa,da=30,ea=19,fa=2*ca+1,ga=15,ha=3,ia=258,ja=ia+ha+1,ka=32,la=42,ma=69,na=73,oa=91,pa=103,qa=113,ra=666,sa=1,ta=2,ua=3,va=4,wa=3,xa=function(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e};B=[new xa(0,0,0,0,n),new xa(4,4,8,4,o),new xa(4,5,16,8,o),new xa(4,6,32,32,o),new xa(4,4,16,16,p),new xa(8,16,32,32,p),new xa(8,16,128,128,p),new xa(8,32,128,256,p),new xa(32,128,258,1024,p),new xa(32,258,258,4096,p)],c.deflateInit=y,c.deflateInit2=x,c.deflateReset=v,c.deflateResetKeep=u,c.deflateSetHeader=w,c.deflate=z,c.deflateEnd=A,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":73,"./adler32":75,"./crc32":77,"./messages":83,"./trees":84}],79:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],80:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],81:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(oa),b.distcode=b.distdyn=new r.Buf32(pa),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,ra)}function k(a){if(sa){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sa=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,oa,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new r.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=la;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=la;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=la;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=la;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=la;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=t(c.check,Ba,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=la;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ia;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=ba,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=la}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=la;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=la;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=v(w,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=la;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sa)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=la;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=la;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===la)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=la;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=la;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=la;break}if(c.mode=ba,b===B)break a;case ba:c.mode=ca;case ca:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ha;break}if(32&ra){c.back=-1,c.mode=V;break}if(64&ra){a.msg="invalid literal/length code",c.mode=la;break}c.extra=15&ra,c.mode=da;case da:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=ea;case ea:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=la;break}c.offset=sa,c.extra=15&ra,c.mode=fa;case fa:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=la;break}c.mode=ga;case ga:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=la;break}q>c.wnext?(q-=c.wnext,oa=c.wsize-q):oa=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,oa=h-c.offset,q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[oa++];while(--q);0===c.length&&(c.mode=ca);break;case ha:if(0===j)break a;f[h++]=c.length,j--,c.mode=ca;break;case ia:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=la;break}m=0,n=0}c.mode=ja;case ja:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=la;break}m=0,n=0}c.mode=ka;case ka:xa=D;break a;case la:xa=G;break a;case ma:return H;case na:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<la&&(c.mode<ia||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=ma,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===ba||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xa===C&&(xa=I),xa)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.window&&(b.window=null), a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,aa=19,ba=20,ca=21,da=22,ea=23,fa=24,ga=25,ha=26,ia=27,ja=28,ka=29,la=30,ma=31,na=32,oa=852,pa=592,qa=15,ra=qa,sa=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":73,"./adler32":75,"./crc32":77,"./inffast":80,"./inftrees":82}],82:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;e>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;e>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;e>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":73}],83:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],84:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a){return 256>a?ga[a]:ga[256+(a>>>7)]}function f(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function g(a,b,c){a.bi_valid>V-c?(a.bi_buf|=b<<a.bi_valid&65535,f(a,a.bi_buf),a.bi_buf=b>>V-a.bi_valid,a.bi_valid+=c-V):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function h(a,b,c){g(a,c[2*b],c[2*b+1])}function i(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function j(a){16===a.bi_valid?(f(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function k(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;U>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;T>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function l(a,b,c){var d,e,f=new Array(U+1),g=0;for(d=1;U>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=i(f[h]++,h))}}function m(){var a,b,c,d,e,f=new Array(U+1);for(c=0,d=0;O-1>d;d++)for(ia[d]=c,a=0;a<1<<_[d];a++)ha[c++]=d;for(ha[c-1]=d,e=0,d=0;16>d;d++)for(ja[d]=e,a=0;a<1<<aa[d];a++)ga[e++]=d;for(e>>=7;R>d;d++)for(ja[d]=e<<7,a=0;a<1<<aa[d]-7;a++)ga[256+e++]=d;for(b=0;U>=b;b++)f[b]=0;for(a=0;143>=a;)ea[2*a+1]=8,a++,f[8]++;for(;255>=a;)ea[2*a+1]=9,a++,f[9]++;for(;279>=a;)ea[2*a+1]=7,a++,f[7]++;for(;287>=a;)ea[2*a+1]=8,a++,f[8]++;for(l(ea,Q+1,f),a=0;R>a;a++)fa[2*a+1]=5,fa[2*a]=i(a,5);ka=new na(ea,_,P+1,Q,U),la=new na(fa,aa,0,R,U),ma=new na(new Array(0),ba,0,S,W)}function n(a){var b;for(b=0;Q>b;b++)a.dyn_ltree[2*b]=0;for(b=0;R>b;b++)a.dyn_dtree[2*b]=0;for(b=0;S>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*X]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function o(a){a.bi_valid>8?f(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function p(a,b,c,d){o(a),d&&(f(a,c),f(a,~c)),E.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function q(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function r(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&q(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!q(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function s(a,b,c){var d,f,i,j,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],f=a.pending_buf[a.l_buf+k],k++,0===d?h(a,f,b):(i=ha[f],h(a,i+P+1,b),j=_[i],0!==j&&(f-=ia[i],g(a,f,j)),d--,i=e(d),h(a,i,c),j=aa[i],0!==j&&(d-=ja[i],g(a,d,j)));while(k<a.last_lit);h(a,X,b)}function t(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=T,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)r(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],r(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,r(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],k(a,b),l(f,j,a.bl_count)}function u(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*Y]++):10>=h?a.bl_tree[2*Z]++:a.bl_tree[2*$]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function v(a,b,c){var d,e,f=-1,i=b[1],j=0,k=7,l=4;for(0===i&&(k=138,l=3),d=0;c>=d;d++)if(e=i,i=b[2*(d+1)+1],!(++j<k&&e===i)){if(l>j){do h(a,e,a.bl_tree);while(0!==--j)}else 0!==e?(e!==f&&(h(a,e,a.bl_tree),j--),h(a,Y,a.bl_tree),g(a,j-3,2)):10>=j?(h(a,Z,a.bl_tree),g(a,j-3,3)):(h(a,$,a.bl_tree),g(a,j-11,7));j=0,f=e,0===i?(k=138,l=3):e===i?(k=6,l=3):(k=7,l=4)}}function w(a){var b;for(u(a,a.dyn_ltree,a.l_desc.max_code),u(a,a.dyn_dtree,a.d_desc.max_code),t(a,a.bl_desc),b=S-1;b>=3&&0===a.bl_tree[2*ca[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function x(a,b,c,d){var e;for(g(a,b-257,5),g(a,c-1,5),g(a,d-4,4),e=0;d>e;e++)g(a,a.bl_tree[2*ca[e]+1],3);v(a,a.dyn_ltree,b-1),v(a,a.dyn_dtree,c-1)}function y(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return G;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return H;for(b=32;P>b;b++)if(0!==a.dyn_ltree[2*b])return H;return G}function z(a){pa||(m(),pa=!0),a.l_desc=new oa(a.dyn_ltree,ka),a.d_desc=new oa(a.dyn_dtree,la),a.bl_desc=new oa(a.bl_tree,ma),a.bi_buf=0,a.bi_valid=0,n(a)}function A(a,b,c,d){g(a,(J<<1)+(d?1:0),3),p(a,b,c,!0)}function B(a){g(a,K<<1,3),h(a,X,ea),j(a)}function C(a,b,c,d){var e,f,h=0;a.level>0?(a.strm.data_type===I&&(a.strm.data_type=y(a)),t(a,a.l_desc),t(a,a.d_desc),h=w(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?A(a,b,c,d):a.strategy===F||f===e?(g(a,(K<<1)+(d?1:0),3),s(a,ea,fa)):(g(a,(L<<1)+(d?1:0),3),x(a,a.l_desc.max_code+1,a.d_desc.max_code+1,h+1),s(a,a.dyn_ltree,a.dyn_dtree)),n(a),d&&o(a)}function D(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ha[c]+P+1)]++,a.dyn_dtree[2*e(b)]++),a.last_lit===a.lit_bufsize-1}var E=a("../utils/common"),F=4,G=0,H=1,I=2,J=0,K=1,L=2,M=3,N=258,O=29,P=256,Q=P+1+O,R=30,S=19,T=2*Q+1,U=15,V=16,W=7,X=256,Y=16,Z=17,$=18,_=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],aa=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],ba=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],da=512,ea=new Array(2*(Q+2));d(ea);var fa=new Array(2*R);d(fa);var ga=new Array(da);d(ga);var ha=new Array(N-M+1);d(ha);var ia=new Array(O);d(ia);var ja=new Array(R);d(ja);var ka,la,ma,na=function(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length},oa=function(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b},pa=!1;c._tr_init=z,c._tr_stored_block=A,c._tr_flush_block=C,c._tr_tally=D,c._tr_align=B},{"../utils/common":73}],85:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}]},{},[1]);
lib/components/material/Material.js
eibay/react-color
'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var React = require('react'); var ReactCSS = require('reactcss'); var color = require('../../helpers/color'); var _require = require('../../../modules/react-material-design'); var Raised = _require.Raised; var _require2 = require('../common'); var EditableInput = _require2.EditableInput; var Material = (function (_ReactCSS$Component) { _inherits(Material, _ReactCSS$Component); function Material() { _classCallCheck(this, Material); _get(Object.getPrototypeOf(Material.prototype), 'constructor', this).call(this); this.handleChange = this.handleChange.bind(this); } _createClass(Material, [{ key: 'classes', value: function classes() { return { 'default': { material: { width: '98px', height: '98px', padding: '16px', fontFamily: 'Roboto' }, Hex: { style: { wrap: { position: 'relative' }, input: { width: '100%', marginTop: '12px', fontSize: '15px', color: '#333', padding: '0', border: '0', borderBottom: '2px solid #' + this.props.hex, outline: 'none', height: '30px' }, label: { position: 'absolute', top: '0', left: '0', fontSize: '11px', color: '#999999', textTransform: 'capitalize' } } }, Input: { style: { wrap: { position: 'relative' }, input: { width: '100%', marginTop: '12px', fontSize: '15px', color: '#333', padding: '0', border: '0', borderBottom: '1px solid #eee', outline: 'none', height: '30px' }, label: { position: 'absolute', top: '0', left: '0', fontSize: '11px', color: '#999999', textTransform: 'capitalize' } } }, split: { display: 'flex', marginRight: '-10px', paddingTop: '11px' }, third: { flex: '1', paddingRight: '10px' } } }; } }, { key: 'handleChange', value: function handleChange(data) { if (data.hex) { color.isValidHex(data.hex) && this.props.onChange(data.hex); } else if (data.r || data.g || data.b) { this.props.onChange({ r: data.r || this.props.rgb.r, g: data.g || this.props.rgb.g, b: data.b || this.props.rgb.b }); } } }, { key: 'render', value: function render() { return React.createElement( Raised, null, React.createElement( 'div', { style: this.styles().material }, React.createElement(EditableInput, _extends({}, this.styles().Hex, { label: 'hex', value: '#' + this.props.hex, onChange: this.handleChange })), React.createElement( 'div', { style: this.styles().split, className: 'flexbox-fix' }, React.createElement( 'div', { style: this.styles().third }, React.createElement(EditableInput, _extends({}, this.styles().Input, { label: 'r', value: this.props.rgb.r, onChange: this.handleChange })) ), React.createElement( 'div', { style: this.styles().third }, React.createElement(EditableInput, _extends({}, this.styles().Input, { label: 'g', value: this.props.rgb.g, onChange: this.handleChange })) ), React.createElement( 'div', { style: this.styles().third }, React.createElement(EditableInput, _extends({}, this.styles().Input, { label: 'b', value: this.props.rgb.b, onChange: this.handleChange })) ) ) ) ); } }]); return Material; })(ReactCSS.Component); module.exports = Material;
third_party/prometheus_ui/base/web/ui/node_modules/reactstrap/es/BreadcrumbItem.js
GoogleCloudPlatform/prometheus-engine
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; var _excluded = ["className", "cssModule", "active", "tag"]; import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { mapToCssModules, tagPropType } from './utils'; var propTypes = { tag: tagPropType, active: PropTypes.bool, className: PropTypes.string, cssModule: PropTypes.object }; var defaultProps = { tag: 'li' }; var BreadcrumbItem = function BreadcrumbItem(props) { var className = props.className, cssModule = props.cssModule, active = props.active, Tag = props.tag, attributes = _objectWithoutPropertiesLoose(props, _excluded); var classes = mapToCssModules(classNames(className, active ? 'active' : false, 'breadcrumb-item'), cssModule); return /*#__PURE__*/React.createElement(Tag, _extends({}, attributes, { className: classes, "aria-current": active ? 'page' : undefined })); }; BreadcrumbItem.propTypes = propTypes; BreadcrumbItem.defaultProps = defaultProps; export default BreadcrumbItem;
node_modules/reactify/node_modules/react-tools/src/classic/types/__tests__/ReactPropTypes-test.js
dominikgar/flask-search-engine
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; var PropTypes; var React; var ReactFragment; var ReactPropTypeLocations; var ReactTestUtils; var Component; var MyComponent; var requiredMessage = 'Required prop `testProp` was not specified in `testComponent`.'; function typeCheckFail(declaration, value, message) { var props = {testProp: value}; var error = declaration( props, 'testProp', 'testComponent', ReactPropTypeLocations.prop ); expect(error instanceof Error).toBe(true); expect(error.message).toBe(message); } function typeCheckPass(declaration, value) { var props = {testProp: value}; var error = declaration( props, 'testProp', 'testComponent', ReactPropTypeLocations.prop ); expect(error).toBe(null); } describe('ReactPropTypes', function() { beforeEach(function() { PropTypes = require('ReactPropTypes'); React = require('React'); ReactFragment = require('ReactFragment'); ReactPropTypeLocations = require('ReactPropTypeLocations'); ReactTestUtils = require('ReactTestUtils'); }); describe('Primitive Types', function() { it("should warn for invalid strings", function() { typeCheckFail( PropTypes.string, [], 'Invalid prop `testProp` of type `array` supplied to ' + '`testComponent`, expected `string`.' ); typeCheckFail( PropTypes.string, false, 'Invalid prop `testProp` of type `boolean` supplied to ' + '`testComponent`, expected `string`.' ); typeCheckFail( PropTypes.string, 0, 'Invalid prop `testProp` of type `number` supplied to ' + '`testComponent`, expected `string`.' ); typeCheckFail( PropTypes.string, {}, 'Invalid prop `testProp` of type `object` supplied to ' + '`testComponent`, expected `string`.' ); }); it('should fail date and regexp correctly', function() { typeCheckFail( PropTypes.string, new Date(), 'Invalid prop `testProp` of type `date` supplied to ' + '`testComponent`, expected `string`.' ); typeCheckFail( PropTypes.string, /please/, 'Invalid prop `testProp` of type `regexp` supplied to ' + '`testComponent`, expected `string`.' ); }); it("should not warn for valid values", function() { typeCheckPass(PropTypes.array, []); typeCheckPass(PropTypes.bool, false); typeCheckPass(PropTypes.func, function() {}); typeCheckPass(PropTypes.number, 0); typeCheckPass(PropTypes.string, ''); typeCheckPass(PropTypes.object, {}); typeCheckPass(PropTypes.object, new Date()); typeCheckPass(PropTypes.object, /please/); }); it("should be implicitly optional and not warn without values", function() { typeCheckPass(PropTypes.string, null); typeCheckPass(PropTypes.string, undefined); }); it("should warn for missing required values", function() { typeCheckFail(PropTypes.string.isRequired, null, requiredMessage); typeCheckFail(PropTypes.string.isRequired, undefined, requiredMessage); }); }); describe('Any type', function() { it('should should accept any value', function() { typeCheckPass(PropTypes.any, 0); typeCheckPass(PropTypes.any, 'str'); typeCheckPass(PropTypes.any, []); }); it("should be implicitly optional and not warn without values", function() { typeCheckPass(PropTypes.any, null); typeCheckPass(PropTypes.any, undefined); }); it("should warn for missing required values", function() { typeCheckFail(PropTypes.any.isRequired, null, requiredMessage); typeCheckFail(PropTypes.any.isRequired, undefined, requiredMessage); }); }); describe('ArrayOf Type', function() { it('should support the arrayOf propTypes', function() { typeCheckPass(PropTypes.arrayOf(PropTypes.number), [1, 2, 3]); typeCheckPass(PropTypes.arrayOf(PropTypes.string), ['a', 'b', 'c']); typeCheckPass(PropTypes.arrayOf(PropTypes.oneOf(['a', 'b'])), ['a', 'b']); }); it('should support arrayOf with complex types', function() { typeCheckPass( PropTypes.arrayOf(PropTypes.shape({a: PropTypes.number.isRequired})), [{a: 1}, {a: 2}] ); function Thing() {} typeCheckPass( PropTypes.arrayOf(PropTypes.instanceOf(Thing)), [new Thing(), new Thing()] ); }); it('should warn with invalid items in the array', function() { typeCheckFail( PropTypes.arrayOf(PropTypes.number), [1, 2, 'b'], 'Invalid prop `2` of type `string` supplied to `testComponent`, ' + 'expected `number`.' ); }); it('should warn with invalid complex types', function() { function Thing() {} var name = Thing.name || '<<anonymous>>'; typeCheckFail( PropTypes.arrayOf(PropTypes.instanceOf(Thing)), [new Thing(), 'xyz'], 'Invalid prop `1` supplied to `testComponent`, expected instance of `' + name + '`.' ); }); it('should warn when passed something other than an array', function() { typeCheckFail( PropTypes.arrayOf(PropTypes.number), {'0': 'maybe-array', length: 1}, 'Invalid prop `testProp` of type `object` supplied to ' + '`testComponent`, expected an array.' ); typeCheckFail( PropTypes.arrayOf(PropTypes.number), 123, 'Invalid prop `testProp` of type `number` supplied to ' + '`testComponent`, expected an array.' ); typeCheckFail( PropTypes.arrayOf(PropTypes.number), 'string', 'Invalid prop `testProp` of type `string` supplied to ' + '`testComponent`, expected an array.' ); }); it('should not warn when passing an empty array', function() { typeCheckPass(PropTypes.arrayOf(PropTypes.number), []); }); it("should be implicitly optional and not warn without values", function() { typeCheckPass(PropTypes.arrayOf(PropTypes.number), null); typeCheckPass(PropTypes.arrayOf(PropTypes.number), undefined); }); it("should warn for missing required values", function() { typeCheckFail( PropTypes.arrayOf(PropTypes.number).isRequired, null, requiredMessage ); typeCheckFail( PropTypes.arrayOf(PropTypes.number).isRequired, undefined, requiredMessage ); }); }); describe('Component Type', function() { beforeEach(function() { Component = React.createClass({ propTypes: { label: PropTypes.element.isRequired }, render: function() { return <div>{this.props.label}</div>; } }); spyOn(console, 'warn'); }); it('should support components', () => { typeCheckPass(PropTypes.element, <div />); }); it('should not support multiple components or scalar values', () => { var message = 'Invalid prop `testProp` supplied to `testComponent`, ' + 'expected a ReactElement.'; typeCheckFail(PropTypes.element, [<div />, <div />], message); typeCheckFail(PropTypes.element, 123, message); typeCheckFail(PropTypes.element, 'foo', message); typeCheckFail(PropTypes.element, false, message); }); it('should be able to define a single child as label', () => { var instance = <Component label={<div />} />; instance = ReactTestUtils.renderIntoDocument(instance); expect(console.warn.argsForCall.length).toBe(0); }); it('should warn when passing no label and isRequired is set', () => { var instance = <Component />; instance = ReactTestUtils.renderIntoDocument(instance); expect(console.warn.argsForCall.length).toBe(1); }); it("should be implicitly optional and not warn without values", function() { typeCheckPass(PropTypes.element, null); typeCheckPass(PropTypes.element, undefined); }); it("should warn for missing required values", function() { typeCheckFail(PropTypes.element.isRequired, null, requiredMessage); typeCheckFail(PropTypes.element.isRequired, undefined, requiredMessage); }); }); describe('Instance Types', function() { it("should warn for invalid instances", function() { function Person() {} var personName = Person.name || '<<anonymous>>'; var dateName = Date.name || '<<anonymous>>'; var regExpName = RegExp.name || '<<anonymous>>'; typeCheckFail( PropTypes.instanceOf(Person), false, 'Invalid prop `testProp` supplied to `testComponent`, expected ' + 'instance of `' + personName + '`.' ); typeCheckFail( PropTypes.instanceOf(Person), {}, 'Invalid prop `testProp` supplied to `testComponent`, expected ' + 'instance of `' + personName + '`.' ); typeCheckFail( PropTypes.instanceOf(Person), '', 'Invalid prop `testProp` supplied to `testComponent`, expected ' + 'instance of `' + personName + '`.' ); typeCheckFail( PropTypes.instanceOf(Date), {}, 'Invalid prop `testProp` supplied to `testComponent`, expected ' + 'instance of `' + dateName + '`.' ); typeCheckFail( PropTypes.instanceOf(RegExp), {}, 'Invalid prop `testProp` supplied to `testComponent`, expected ' + 'instance of `' + regExpName + '`.' ); }); it("should not warn for valid values", function() { function Person() {} function Engineer() {} Engineer.prototype = new Person(); typeCheckPass(PropTypes.instanceOf(Person), new Person()); typeCheckPass(PropTypes.instanceOf(Person), new Engineer()); typeCheckPass(PropTypes.instanceOf(Date), new Date()); typeCheckPass(PropTypes.instanceOf(RegExp), /please/); }); it("should be implicitly optional and not warn without values", function() { typeCheckPass(PropTypes.instanceOf(String), null); typeCheckPass(PropTypes.instanceOf(String), undefined); }); it("should warn for missing required values", function() { typeCheckFail( PropTypes.instanceOf(String).isRequired, null, requiredMessage ); typeCheckFail( PropTypes.instanceOf(String).isRequired, undefined, requiredMessage ); }); }); describe('React Component Types', function() { beforeEach(function() { MyComponent = React.createClass({ render: function() { return <div />; } }); }); it('should warn for invalid values', function() { var failMessage = 'Invalid prop `testProp` supplied to ' + '`testComponent`, expected a ReactNode.'; typeCheckFail(PropTypes.node, true, failMessage); typeCheckFail(PropTypes.node, function() {}, failMessage); typeCheckFail(PropTypes.node, {key: function() {}}, failMessage); }); it('should not warn for valid values', function() { spyOn(console, 'warn'); typeCheckPass(PropTypes.node, <div />); typeCheckPass(PropTypes.node, false); typeCheckPass(PropTypes.node, <MyComponent />); typeCheckPass(PropTypes.node, 'Some string'); typeCheckPass(PropTypes.node, []); typeCheckPass(PropTypes.node, {}); typeCheckPass(PropTypes.node, [ 123, 'Some string', <div />, ['Another string', [456], <span />, <MyComponent />], <MyComponent /> ]); // Object of renderable things var frag = ReactFragment.create; typeCheckPass(PropTypes.node, frag({ k0: 123, k1: 'Some string', k2: <div />, k3: frag({ k30: <MyComponent />, k31: frag({k310: <a />}), k32: 'Another string' }), k4: null, k5: undefined })); expect(console.warn.calls).toEqual([]); // This should also pass, though it warns typeCheckPass(PropTypes.node, { k0: 123, k1: 'Some string', k2: <div />, k3: { k30: <MyComponent />, k31: {k310: <a />}, k32: 'Another string' }, k4: null, k5: undefined }); }); it('should not warn for null/undefined if not required', function() { typeCheckPass(PropTypes.node, null); typeCheckPass(PropTypes.node, undefined); }); it('should warn for missing required values', function() { typeCheckFail( PropTypes.node.isRequired, null, 'Required prop `testProp` was not specified in `testComponent`.' ); typeCheckFail( PropTypes.node.isRequired, undefined, 'Required prop `testProp` was not specified in `testComponent`.' ); }); it('should accept empty array for required props', function() { typeCheckPass(PropTypes.node.isRequired, []); }); }); describe('ObjectOf Type', function() { it('should support the objectOf propTypes', function() { typeCheckPass(PropTypes.objectOf(PropTypes.number), {a: 1, b: 2, c: 3}); typeCheckPass( PropTypes.objectOf(PropTypes.string), {a: 'a', b: 'b', c: 'c'} ); typeCheckPass( PropTypes.objectOf(PropTypes.oneOf(['a', 'b'])), {a: 'a', b: 'b'} ); }); it('should support objectOf with complex types', function() { typeCheckPass( PropTypes.objectOf(PropTypes.shape({a: PropTypes.number.isRequired})), {a: {a: 1}, b: {a: 2}} ); function Thing() {} typeCheckPass( PropTypes.objectOf(PropTypes.instanceOf(Thing)), {a: new Thing(), b: new Thing()} ); }); it('should warn with invalid items in the object', function() { typeCheckFail( PropTypes.objectOf(PropTypes.number), {a: 1, b: 2, c: 'b'}, 'Invalid prop `c` of type `string` supplied to `testComponent`, ' + 'expected `number`.' ); }); it('should warn with invalid complex types', function() { function Thing() {} var name = Thing.name || '<<anonymous>>'; typeCheckFail( PropTypes.objectOf(PropTypes.instanceOf(Thing)), {a: new Thing(), b: 'xyz'}, 'Invalid prop `b` supplied to `testComponent`, expected instance of `' + name + '`.' ); }); it('should warn when passed something other than an object', function() { typeCheckFail( PropTypes.objectOf(PropTypes.number), [1, 2], 'Invalid prop `testProp` of type `array` supplied to ' + '`testComponent`, expected an object.' ); typeCheckFail( PropTypes.objectOf(PropTypes.number), 123, 'Invalid prop `testProp` of type `number` supplied to ' + '`testComponent`, expected an object.' ); typeCheckFail( PropTypes.objectOf(PropTypes.number), 'string', 'Invalid prop `testProp` of type `string` supplied to ' + '`testComponent`, expected an object.' ); }); it('should not warn when passing an empty object', function() { typeCheckPass(PropTypes.objectOf(PropTypes.number), {}); }); it("should be implicitly optional and not warn without values", function() { typeCheckPass(PropTypes.objectOf(PropTypes.number), null); typeCheckPass(PropTypes.objectOf(PropTypes.number), undefined); }); it("should warn for missing required values", function() { typeCheckFail( PropTypes.objectOf(PropTypes.number).isRequired, null, requiredMessage ); typeCheckFail( PropTypes.objectOf(PropTypes.number).isRequired, undefined, requiredMessage ); }); }); describe('OneOf Types', function() { it("should warn for invalid strings", function() { typeCheckFail( PropTypes.oneOf(['red', 'blue']), true, 'Invalid prop `testProp` of value `true` supplied to ' + '`testComponent`, expected one of ["red","blue"].' ); typeCheckFail( PropTypes.oneOf(['red', 'blue']), [], 'Invalid prop `testProp` of value `` supplied to `testComponent`, ' + 'expected one of ["red","blue"].' ); typeCheckFail( PropTypes.oneOf(['red', 'blue']), '', 'Invalid prop `testProp` of value `` supplied to `testComponent`, ' + 'expected one of ["red","blue"].' ); typeCheckFail( PropTypes.oneOf([0, 'false']), false, 'Invalid prop `testProp` of value `false` supplied to ' + '`testComponent`, expected one of [0,"false"].' ); }); it("should not warn for valid values", function() { typeCheckPass(PropTypes.oneOf(['red', 'blue']), 'red'); typeCheckPass(PropTypes.oneOf(['red', 'blue']), 'blue'); }); it("should be implicitly optional and not warn without values", function() { typeCheckPass(PropTypes.oneOf(['red', 'blue']), null); typeCheckPass(PropTypes.oneOf(['red', 'blue']), undefined); }); it("should warn for missing required values", function() { typeCheckFail( PropTypes.oneOf(['red', 'blue']).isRequired, null, requiredMessage ); typeCheckFail( PropTypes.oneOf(['red', 'blue']).isRequired, undefined, requiredMessage ); }); }); describe('Union Types', function() { it('should warn if none of the types are valid', function() { typeCheckFail( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), [], 'Invalid prop `testProp` supplied to `testComponent`.' ); var checker = PropTypes.oneOfType([ PropTypes.shape({a: PropTypes.number.isRequired}), PropTypes.shape({b: PropTypes.number.isRequired}) ]); typeCheckFail( checker, {c: 1}, 'Invalid prop `testProp` supplied to `testComponent`.' ); }); it('should not warn if one of the types are valid', function() { var checker = PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]); typeCheckPass(checker, null); typeCheckPass(checker, 'foo'); typeCheckPass(checker, 123); checker = PropTypes.oneOfType([ PropTypes.shape({a: PropTypes.number.isRequired}), PropTypes.shape({b: PropTypes.number.isRequired}) ]); typeCheckPass(checker, {a: 1}); typeCheckPass(checker, {b: 1}); }); it("should be implicitly optional and not warn without values", function() { typeCheckPass( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), null ); typeCheckPass( PropTypes.oneOfType([PropTypes.string, PropTypes.number]), undefined ); }); it("should warn for missing required values", function() { typeCheckFail( PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, null, requiredMessage ); typeCheckFail( PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired, undefined, requiredMessage ); }); }); describe('Shape Types', function() { it("should warn for non objects", function() { typeCheckFail( PropTypes.shape({}), 'some string', 'Invalid prop `testProp` of type `string` supplied to ' + '`testComponent`, expected `object`.' ); typeCheckFail( PropTypes.shape({}), ['array'], 'Invalid prop `testProp` of type `array` supplied to ' + '`testComponent`, expected `object`.' ); }); it("should not warn for empty values", function() { typeCheckPass(PropTypes.shape({}), undefined); typeCheckPass(PropTypes.shape({}), null); typeCheckPass(PropTypes.shape({}), {}); }); it("should not warn for an empty object", function() { typeCheckPass(PropTypes.shape({}).isRequired, {}); }); it("should not warn for non specified types", function() { typeCheckPass(PropTypes.shape({}), {key: 1}); }); it("should not warn for valid types", function() { typeCheckPass(PropTypes.shape({key: PropTypes.number}), {key: 1}); }); it("should warn for required valid types", function() { typeCheckFail( PropTypes.shape({key: PropTypes.number.isRequired}), {}, 'Required prop `key` was not specified in `testComponent`.' ); }); it("should warn for the first required type", function() { typeCheckFail( PropTypes.shape({ key: PropTypes.number.isRequired, secondKey: PropTypes.number.isRequired }), {}, 'Required prop `key` was not specified in `testComponent`.' ); }); it("should warn for invalid key types", function() { typeCheckFail(PropTypes.shape({key: PropTypes.number}), {key: 'abc'}, 'Invalid prop `key` of type `string` supplied to `testComponent`, ' + 'expected `number`.' ); }); it("should be implicitly optional and not warn without values", function() { typeCheckPass( PropTypes.shape(PropTypes.shape({key: PropTypes.number})), null ); typeCheckPass( PropTypes.shape(PropTypes.shape({key: PropTypes.number})), undefined ); }); it("should warn for missing required values", function() { typeCheckFail( PropTypes.shape({key: PropTypes.number}).isRequired, null, requiredMessage ); typeCheckFail( PropTypes.shape({key: PropTypes.number}).isRequired, undefined, requiredMessage ); }); }); describe('Custom validator', function() { beforeEach(function() { require('mock-modules').dumpCache(); spyOn(console, 'warn'); }); it('should have been called with the right params', function() { var spy = jasmine.createSpy(); var Component = React.createClass({ propTypes: {num: spy}, render: function() { return <div />; } }); var instance = <Component num={5} />; instance = ReactTestUtils.renderIntoDocument(instance); expect(spy.argsForCall.length).toBe(2); // temp double validation expect(spy.argsForCall[0][1]).toBe('num'); expect(spy.argsForCall[0][2]).toBe('Component'); }); it('should have been called even if the prop is not present', function() { var spy = jasmine.createSpy(); var Component = React.createClass({ propTypes: {num: spy}, render: function() { return <div />; } }); var instance = <Component bla={5} />; instance = ReactTestUtils.renderIntoDocument(instance); expect(spy.argsForCall.length).toBe(2); // temp double validation }); it('should have received the validator\'s return value', function() { var spy = jasmine.createSpy().andCallFake( function(props, propName, componentName) { if (props[propName] !== 5) { return new Error('num must be 5!'); } } ); var Component = React.createClass({ propTypes: {num: spy}, render: function() { return <div />; } }); var instance = <Component num={6} />; instance = ReactTestUtils.renderIntoDocument(instance); expect(console.warn.argsForCall.length).toBe(1); expect(console.warn.argsForCall[0][0]).toBe( 'Warning: Failed propType: num must be 5!'); }); it('should not warn if the validator returned anything else than an error', function() { var spy = jasmine.createSpy().andCallFake( function(props, propName, componentName) { return 'This message will never reach anyone'; } ); var Component = React.createClass({ propTypes: {num: spy}, render: function() { return <div />; } }); var instance = <Component num={5} />; instance = ReactTestUtils.renderIntoDocument(instance); expect(console.warn.argsForCall.length).toBe(0); } ); }); });
frontend/components/Recorder.js
ParroApp/parro
import React from 'react'; import { captureUserMedia, takePhoto, uploadImage, uploadAudio } from './AppUtils'; import Webcam from './Webcam.react'; import RecordRTC from 'recordrtc'; const StereoAudioRecorder = RecordRTC.StereoAudioRecorder; const hasGetUserMedia = !!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia); class Recorder extends React.Component { constructor(props) { super(props); this.state = { recordVideo: null, src: null, intervalId: null, userId: null, modalOpen: this.props.modal, isRecording: false, clarity: null, speed: null, }; this.requestUserMedia = this.requestUserMedia.bind(this); this.startRecord = this.startRecord.bind(this); this.stopRecord = this.stopRecord.bind(this); this.closeModal = this.closeModal.bind(this); } componentDidMount() { this.setState({userId: '1234'}) if(!hasGetUserMedia) { alert("Your browser cannot stream from your webcam. Please switch to Chrome or Firefox."); return; } this.requestUserMedia(); } requestUserMedia() { captureUserMedia((stream) => { this.setState({ stream: stream, src: window.URL.createObjectURL(stream) }); }); } startRecord() { this.setState({isRecording: true}) // start recording video console.log('start video recording'); var recordVideo = RecordRTC(this.state.stream, { type: 'video', mimeType: 'video/webm', bitsPerSecond: 128000 }); recordVideo.startRecording(); var videoElement = document.querySelector('video'); var intervalId = setInterval(() => { var photo = takePhoto(videoElement); uploadImage(photo, this.state.userId); }, 2000)//333) // start recording audio console.log('start audio recording'); var recordAudio = RecordRTC(this.state.stream, { recorderType: StereoAudioRecorder, mimeType: 'audio/wav' }); recordAudio.startRecording(); // stores state this.setState({ recordVideo: recordVideo, recordAudio: recordAudio, intervalId: intervalId }); } stopRecord() { this.setState({isRecording: false}); this.state.recordVideo.stopRecording(() => { console.log('Stop recording video'); let params = { type: 'video/webm', data: this.state.recordVideo.blob, id: Math.floor(Math.random() * 90000) + 10000 } clearInterval(this.state.intervalId); this.setState({ uploading: true, intervalId: null }); }); this.state.recordAudio.stopRecording(() => { console.log('Stop recording audio'); uploadAudio(this.state.recordAudio.getBlob(), this.state.userId); }); } closeModal() { this.state.stream.getVideoTracks().forEach(function(track) { track.stop(); }); this.props.modalClose(); } render() { return( <div className={this.props.modal ? "modal is-active" : "modal"}> <div className="modal-background"></div> <div className="modal-content"> <div><Webcam src={this.state.src}/></div> {this.state.isRecording ? <a onClick={this.stopRecord} className="button is-danger"> <span className="icon"> <i className="fa fa-stop-circle"></i> </span> <span>Stop Record</span> </a> : <a onClick={this.startRecord} className="button is-success"> <span className="icon"> <i className="fa fa-play-circle"></i> </span> <span>Start Record</span> </a> } </div> <button onClick={this.closeModal} className="modal-close is-large"></button> </div> // <div> // <div className="columns"> // <div className="column is-one-third is-center"> // </div> // </div> // </div> ) } } export default Recorder;
src/components/TextInputCSSModules/TextInputCSSModules.js
noumanberlas/prime-react
import React from 'react'; import PropTypes from 'prop-types'; import Label from '../Label'; import styles from './textInput.css'; /** Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker. */ function TextInput({htmlId, name, label, type = "text", required = false, onChange, placeholder, value, error, children, ...props}) { return ( <div className={styles.fieldset}> <Label htmlFor={htmlId} label={label} required={required} /> <input id={htmlId} type={type} name={name} placeholder={placeholder} value={value} onChange={onChange} className={error && styles.inputError} {...props}/> {children} {error && <div className={styles.error}>{error}</div>} </div> ); }; TextInput.propTypes = { /** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */ htmlId: PropTypes.string.isRequired, /** Input name. Recommend setting this to match object's property so a single change handler can be used. */ name: PropTypes.string.isRequired, /** Input label */ label: PropTypes.string.isRequired, /** Input type */ type: PropTypes.oneOf(['text', 'number', 'password']), /** Mark label with asterisk if set to true */ required: PropTypes.bool, /** Function to call onChange */ onChange: PropTypes.func.isRequired, /** Placeholder to display when empty */ placeholder: PropTypes.string, /** Value */ value: PropTypes.any, /** String to display when error occurs */ error: PropTypes.string, /** Child component to display next to the input */ children: PropTypes.node }; export default TextInput;
src/containers/search/index.js
MHanslo/swapi-ui
/* * * Search Page * * */ import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import classNames from 'classnames'; import sortby from 'lodash.sortby'; import { searchChanged, searchSubmit, searchNext, searchPrev, sort } from './actions'; import Box from '../../components/Box'; class search extends React.Component { render() { const inputClass = classNames({ 'control': true, 'is-expanded': true, 'is-loading': this.props.searchLoading }); return ( <div> <section className="section"> <div className="container"> <div className="notification"> <label className="label">Character search</label> <div className="control is-grouped"> <p className={inputClass}> <input className="input" type="text" placeholder="Search" onChange={(e) => this.props.searchChanged(e.target.value)} /> </p> <p className="control"> <button type="submit" className="button is-primary" onClick={() => this.props.searchSubmit()}>Search</button> </p> </div> </div> {this.props.searchResults && ( <div className="control is-grouped"> <p className="subtitle"><strong>{this.props.searchResults.count}</strong> results found</p> <p className="control" style={{ marginLeft: 30 }}> <span className="select"> <select value={this.props.searchSort} onChange={(e) => this.props.sort(e.target.value)}> <option value="none">Sort: none</option> <option value="name">Sort: name</option> </select> </span> </p> </div> )} {this.props.searchResults && this.props.searchPersons.map((char, index) => <Box key={index} name={char.name} url={char.url} />)} {this.props.searchResults && <nav className="pagination"> <a disabled={!this.props.searchResults.previous} className="button" onClick={this.props.searchPrev}>Previous</a> <a disabled={!this.props.searchResults.next} className="button" onClick={this.props.searchNext}>Next page</a> <ul><li></li></ul> </nav>} </div> </section> </div> ); } } const mapStateToProps = (state) => { let sortedPersons = []; if (state.search.searchResults && state.search.sort === 'name') { sortedPersons = sortby(state.search.searchResults.results, [ 'name' ]); } else if (state.search.searchResults) { sortedPersons = state.search.searchResults.results; } return { searchInput: state.search.searchInput, searchResults: state.search.searchResults, searchPersons: sortedPersons, searchLoading: state.search.searchLoading, searchSort: state.search.sort }; }; const mapDispatchToProps = (dispatch) => bindActionCreators({ searchChanged, searchSubmit, searchNext, searchPrev, sort }, dispatch); const Search = connect(mapStateToProps, mapDispatchToProps)(search); export default Search;
src/components/TableAgreement.js
aurigadl/EnvReactAsk
import React from 'react' import {makeRequest as mReq} from '../utils/mrequest'; import {Table, Card, Col, Row, Button, Icon} from 'antd'; const columns = [{ title: 'No del contrato', dataIndex: 'no_agreement', key: 'no_agreement', render: text => <Button type="primary" shape="circle" icon="download"/>, }, { title: 'Fecha de creación', dataIndex: 'created_at', key: 'created_at', }, { title: 'Creado Por', dataIndex: 'created_by', key: 'created_by', }, { title: 'Fecha Inicial', dataIndex: 'init_date', key: 'init_date', }, { title: 'Fecha Final', dataIndex: 'last_date', key: 'last_date', }, { title: 'No del viaje', dataIndex: 'no_trip', key: 'no_trip', }, { title: 'Contratante', dataIndex: 'person', key: 'person', }]; var TableAgreement = React.createClass({ getInitialState: function () { return { dataValue: [], filetoload: '' }; }, getRemoteData: function (parreq, cb_success, cb_error) { mReq(parreq) .then(function (response) { cb_success(response) }.bind(this)) .catch(function (err) { cb_error(err); console.log('TableAgreement, there was an error!', err.statusText); }); }, componentDidMount: function () { var parreq = { method: 'GET', url: 'apiFuec/fullAllAgreement' }; this.getRemoteData(parreq, this.successLoadData, this.errorLoadData ); }, successLoadData: function (data) { this.setState({ dataValue: data.result }); }, errorLoadData: function (err) { }, handleGetFile: function (record, index) { var params = { 'agreement': record.no_agreement }; var parreq = { method: 'GET', url: 'apiFuec/fileAgreement', params: params }; this.getRemoteData(parreq, this.successLoadFile, this.errorLoadFile ); }, successLoadFile: function (remoteData) { this.setState({ filetoload: remoteData.result }); }, errorLoadFile: function () { }, render: function () { var pdf; var showClass = this.state.filetoload ? '' : 'is-hidden'; if(this.state.filetoload != ""){ pdf = "data:application/pdf;base64," + this.state.filetoload; } return ( <Card title="Listado de contratos" bordered={false}> <Table rowKey="id" onRowClick={this.handleGetFile} dataSource={this.state.dataValue} columns={columns} /> <iframe src={pdf} className={showClass} width="100%" height="500px" alt="pdf" type="application/pdf" /> </Card> ) } }); export default TableAgreement;
src/svg-icons/hardware/smartphone.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareSmartphone = (props) => ( <SvgIcon {...props}> <path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"/> </SvgIcon> ); HardwareSmartphone = pure(HardwareSmartphone); HardwareSmartphone.displayName = 'HardwareSmartphone'; HardwareSmartphone.muiName = 'SvgIcon'; export default HardwareSmartphone;
docs/src/app/components/pages/get-started/Examples.js
ruifortes/material-ui
import React from 'react'; import Title from 'react-title-component'; import MarkdownElement from '../../MarkdownElement'; import examplesText from './examples.md'; const Examples = () => ( <div> <Title render={(previousTitle) => `Examples - ${previousTitle}`} /> <MarkdownElement text={examplesText} /> </div> ); export default Examples;
client/src/app/primitives/__tests__/KeyboardInteractionTrapSpec.js
camunda/bpmn-io-modeler
/** * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. * * Camunda licenses this file to you under the MIT; you may not use this file * except in compliance with the MIT License. */ /* global sinon */ import React from 'react'; import { mount } from 'enzyme'; import KeyboardInteractionTrap, { KeyboardInteractionTrapContext } from './../modal/KeyboardInteractionTrap'; describe('<KeyboardInteractionTrap>', function() { let wrapper; afterEach(function() { if (wrapper && wrapper.exists()) { wrapper.unmount(); } }); it('should dispatch update-menu action', function() { // given const triggerAction = sinon.spy(); // when wrapper = mount( <KeyboardInteractionTrapContext.Provider value={ triggerAction }> <KeyboardInteractionTrap /> </KeyboardInteractionTrapContext.Provider> ); // then expect(wrapper).to.exist; expect(triggerAction).to.have.been.calledOnce; }); it('should NOT trigger error outside of context', function() { // when wrapper = mount( <KeyboardInteractionTrap /> ); // then expect(wrapper).to.exist; }); });
src/svg-icons/image/filter-none.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilterNone = (props) => ( <SvgIcon {...props}> <path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14z"/> </SvgIcon> ); ImageFilterNone = pure(ImageFilterNone); ImageFilterNone.displayName = 'ImageFilterNone'; export default ImageFilterNone;
src/js/components/ListCoworker.js
belatrix/ConnectAdmin
import React from 'react'; import { List, Image } from 'semantic-ui-react'; function ListCoworker() { return ( <List> <List.Item> <Image avatar src="http://semantic-ui.com/images/avatar2/small/rachel.png" /> <List.Content> <List.Header as="a">Rachel</List.Header> <List.Description> Last seen watching <a><b>Arrested Development</b></a> just now. </List.Description> </List.Content> </List.Item> <List.Item> <Image avatar src="http://semantic-ui.com/images/avatar2/small/lindsay.png" /> <List.Content> <List.Header as="a">Lindsay</List.Header> <List.Description> Last seen watching <a><b>Bobs Burgers</b></a> 10 hours ago. </List.Description> </List.Content> </List.Item> <List.Item> <Image avatar src="http://semantic-ui.com/images/avatar2/small/matthew.png" /> <List.Content> <List.Header as="a">Matthew</List.Header> <List.Description> Last seen watching <a><b>The Godfather Part 2</b></a> yesterday. </List.Description> </List.Content> </List.Item> <List.Item> <Image avatar src="http://semantic-ui.com/images/avatar/small/jenny.jpg" /> <List.Content> <List.Header as="a">Jenny Hess</List.Header> <List.Description> Last seen watching <a><b>Twin Peaks</b></a> 3 days ago. </List.Description> </List.Content> </List.Item> <List.Item> <Image avatar src="http://semantic-ui.com/images/avatar/small/veronika.jpg" /> <List.Content> <List.Header as="a">Veronika Ossi</List.Header> <List.Description> Has not watched anything recently </List.Description> </List.Content> </List.Item> </List> ); } export default ListCoworker;
src/svg-icons/action/schedule.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSchedule = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"/> </SvgIcon> ); ActionSchedule = pure(ActionSchedule); ActionSchedule.displayName = 'ActionSchedule'; ActionSchedule.muiName = 'SvgIcon'; export default ActionSchedule;
src/main/resources/public/js/components/dropdown_menus/instance/instance-dropdown.js
ozwillo/ozwillo-portal
import React from 'react'; import PropTypes from 'prop-types'; import Popup from 'react-popup'; import DropDownMenu from '../../dropdown-menu'; import InstanceInvitationForm from '../../forms/instance-invitation-form'; import InstanceDropdownHeader from './instance-dropdown-header'; import InstanceConfigForm from '../../forms/instance-config-form'; import CustomTooltip from '../../custom-tooltip'; import Config from '../../../config/config'; const instanceStatus = Config.instanceStatus; import InstanceService from "../../../util/instance-service"; import { i18n } from "../../../config/i18n-config" import { t } from "@lingui/macro" import { CSSTransition, TransitionGroup} from 'react-transition-group'; import customFetch from "../../../util/custom-fetch"; class InstanceDropdown extends React.Component { static propTypes = { organization: PropTypes.object.isRequired, instance: PropTypes.object.isRequired, organizationMembers: PropTypes.array, isAdmin: PropTypes.bool, onChangeInstanceStatus: PropTypes.func.isRequired }; static defaultProps = { isAdmin: false }; constructor(props) { super(props); this.state = { error: null, status: {}, isLoading: false, services: [], members: null, }; this._instanceService = new InstanceService(); } updateServiceConfig = (instanceId, catalogEntry) => { return customFetch(`/my/api/service/${catalogEntry.id}`, { method: 'PUT', json: catalogEntry }).then(() => { Popup.close(); }); }; onClickConfigIcon = (instance) => { Popup.create({ title: instance.name, content: <InstanceConfigForm instance={instance} onSubmit={this.updateServiceConfig}/> }, true); }; onRemoveInstance = (instance) => { this._instanceService.updateInstanceStatus(instance, instanceStatus.stopped) .then(() => this.props.onChangeInstanceStatus(instance.id, instanceStatus.stopped)); }; onCancelRemoveInstance = (instance) => { this._instanceService.updateInstanceStatus(instance, instanceStatus.running) .then(() => this.props.onChangeInstanceStatus(instance.id, instanceStatus.running)); }; filterMemberWithoutAccess = (member) => { const {members} = this.state; if (!members) { return true; } return !members.find((user) => { return user.id === member.id; }) }; createUserAccessToInstance = async (user) => { const {members, services} = this.state; try { await this._instanceService.fetchCreateAcl(user, this.props.instance); members.push(user); this.setState({members}); user.id && services.map(async (service) => { await this._createSubscription(service.catalogEntry.id, user.id); }); await this._refreshServices(); return {error: false} } catch (e) { return {error: true, message: e}; } }; removeUserAccessToInstance = (e) => { let {members} = this.state; const i = e.currentTarget.dataset.member; const member = members[i]; this._instanceService.fetchDeleteAcl(member, this.props.instance) .then(() => { members.splice(members.findIndex(elem => elem.id === member.id), 1); this.setState({ status: Object.assign({}, this.state.status, { [member.id]: {error: null} }, members) }); }) .catch((err) => { this.setState({ status: Object.assign({}, this.state.status, { [member.id]: {error: err.error} }) }); }); }; _createSubscription = async (serviceId, userId) => { this.setState({ status: {[userId]: {isLoading: true}} }); return await this.fetchCreateSubscription(serviceId, userId); }; createSubscriptionFromEvent = async (e) => { const el = e.currentTarget; const userId = el.dataset.user; const serviceId = el.dataset.service; try { await this._createSubscription(serviceId, userId); await this._refreshServices(); }catch(e){ this.setState({ status: Object.assign({}, this.state.status, { [userId]: {error: e.error, isLoading: false} }) }); } }; deleteSubscription = async (e) => { const el = e.currentTarget; const userId = el.dataset.user; const serviceId = el.dataset.service; this.setState({ status: Object.assign({}, this.state.status, { [userId]: {isLoading: true} }) }); await this.fetchDeleteSubscription(serviceId, userId); await this._refreshServices(); }; fetchCreateSubscription = async (serviceId, userId) => { this._instanceService.fetchCreateSubscription(serviceId, userId).then(() => { this.setState({ status: Object.assign({}, this.state.status, { [userId]: {error: null, isLoading: false} }) }); }) }; fetchDeleteSubscription = async (serviceId, userId) => { this._instanceService.fetchDeleteSubscription(serviceId, userId).then(() => { this.setState({ status: Object.assign({}, this.state.status, { [userId]: {error: null, isLoading: false} }) }); }) .catch((err) => { this.setState({ status: Object.assign({}, this.state.status, { [userId]: {error: err.error, isLoading: false} }) }); }); }; searchSubForUser = (user, service) => { if (!service.subscriptions) { return null; } return service.subscriptions.find((sub) => { return sub.user_id === user.id; }); }; _refreshServices = async () => { const newServices = await this._instanceService.fetchInstanceServices(this.props.instance.id, true); this.setState({services: newServices}) }; handleDropDown = async (dropDownState) => { if (dropDownState) { //Fetch users for the instance if (this.props.isAdmin) { this.setState({isLoading: true}); const newServices = await this._instanceService.fetchInstanceServices(this.props.instance.id, true); const members = await this._instanceService.fetchUsersOfInstance(this.props.instance.id); this.setState({services: newServices, isLoading: false, members: members}); } } }; render() { const isAdmin = this.props.isAdmin; const instance = this.props.instance; const {services, isLoading, members} = this.state; const {organizationMembers} = this.props; const isRunning = instance.applicationInstance.status === instanceStatus.running; const isAvailable = isAdmin && !instance.isPublic && isRunning; const isOpen = false; const membersWithoutAccess = organizationMembers ? organizationMembers.filter(this.filterMemberWithoutAccess) : null; const Header = <InstanceDropdownHeader isAdmin={isAdmin} instance={instance} onClickConfigIcon={this.onClickConfigIcon} onRemoveInstance={this.onRemoveInstance} onCancelRemoveInstance={this.onCancelRemoveInstance}/>; const usersIconDropDown = <i className="fa fa-users"/>; return <DropDownMenu header={Header} isAvailable={isAvailable} isOpen={isOpen} dropDownIcon={usersIconDropDown} dropDownChange={this.handleDropDown}> <section className='dropdown-content'> { !members && isLoading && <div className="container-loading text-center"> <i className="fa fa-spinner fa-spin loading"/> </div> } <table className="table table-striped"> <thead> {/* Header: size: 3+ n (services) user's name; error message; n services; options */} <tr> <th className="fill-content" colSpan={1}/> { services && services.length > 0 ? services.map((service) => { return <th key={service.catalogEntry.id} className="center"> { services.length > 1 && <span className="service" title={service.name}>{service.name.toAcronyme()}</span> } </th> }) : null } <th/> </tr> </thead> <tbody> <TransitionGroup component={null}> { members && members.map((user, i) => { const status = this.state.status[user.id]; return <CSSTransition timeout={50 * (i+1)} key={user.id || user.email} classNames={"fade"} > <tr> <td className="fill-content"> <article className="item"> { user.id && <span className="name">{user.name}</span> } { user.email && <span className={`email ${(user.id && 'separator') || ''}`}>{user.email}</span> } </article> </td> {/* error messages */} { status && status.error && <td className="fill-content"> <span className="error">{status.error}</span> </td> } {/* Services */} { user.id && services && services.map((service) => { const sub = this.searchSubForUser(user, service); return <td key={service.catalogEntry.id} className="fill-content col-md-1"> { !sub && <CustomTooltip title={i18n._(t`tooltip.add.icon`)}> <button className="btn icon" onClick={this.createSubscriptionFromEvent} disabled={status && status.isLoading} data-user={user.id} data-service={service.catalogEntry.id}> <i className="fas fa-plus option-icon service"/> </button> </CustomTooltip> } { sub && <CustomTooltip title={i18n._(t`tooltip.remove.icon`)}> <button className="btn icon" onClick={this.deleteSubscription} disabled={status && status.isLoading} data-sub={sub.id} data-user={user.id} data-service={service.catalogEntry.id}> <i className="fas fa-home option-icon service"/> </button> </CustomTooltip> } </td> }) } {/* Options */} { !user.id && services && <React.Fragment> {/* empty space to replace services */} { (services.length - 1) > 0 && <td className="fill-content center empty" colSpan={services.length - 1}/> } <td className="fill-content col-md-1"> <CustomTooltip title={i18n._(t`tooltip.pending`)}> <button type="button" className="btn icon"> <i className="fa fa-stopwatch option-icon loading"/> </button> </CustomTooltip> </td> </React.Fragment> } <td className="fill-content col-md-1"> <CustomTooltip title={i18n._(t`tooltip.remove.member`)}> <button className="btn icon delete" data-member={i} onClick={this.removeUserAccessToInstance}> <i className="fa fa-trash option-icon delete"/> </button> </CustomTooltip> </td> </tr> </CSSTransition> }) } </TransitionGroup> </tbody> </table> <InstanceInvitationForm members={membersWithoutAccess} instance={instance} sendInvitation={this.createUserAccessToInstance}/> </section> </DropDownMenu>; } } export default InstanceDropdown;
packages/material-ui-icons/src/UnfoldMoreTwoTone.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M12 5.83L15.17 9l1.41-1.41L12 3 7.41 7.59 8.83 9 12 5.83zm0 12.34L8.83 15l-1.41 1.41L12 21l4.59-4.59L15.17 15 12 18.17z" /> , 'UnfoldMoreTwoTone');
src/__tests__/components/plans/PlansList.tests.js
knowncitizen/tripleo-ui
/** * Copyright 2017 Red Hat Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import { IntlProvider } from 'react-intl'; import { Map, Set } from 'immutable'; import React from 'react'; import ReactShallowRenderer from 'react-test-renderer/shallow'; import { mockStore } from '../../actions/utils'; import PlansList from '../../../js/components/plan/PlansList'; import FileList from '../../../js/components/plan/FileList'; import { InitialPlanState } from '../../../js/immutableRecords/plans'; describe('PlansList component', () => { let output; const store = mockStore({ plans: new InitialPlanState({ currentPlanName: 'overcloud' }), deploymentStatus: { deploymentStatusByPlan: Map(), deploymentStatusUI: Map() } }); beforeEach(() => { let shallowRenderer = new ReactShallowRenderer(); const intlProvider = new IntlProvider({ locale: 'en' }, {}); const { intl } = intlProvider.getChildContext(); shallowRenderer.render( <PlansList.WrappedComponent store={store} intl={intl} /> ); output = shallowRenderer.getRenderOutput(); }); it('renders a table of plan names', () => { expect(output.type.name).toEqual('PlansList'); }); }); let getTableRows = (planFiles, selectedFiles) => { let result; let shallowRenderer = new ReactShallowRenderer(); shallowRenderer.render( <FileList planFiles={planFiles} selectedFiles={selectedFiles} /> ); result = shallowRenderer.getRenderOutput(); return result.props.children[1].props.children.props.children; }; describe('FileList component', () => { it('renders a list of plan files, ordered alphabetically', () => { let tableRows = getTableRows(Set(['foo.yaml', 'bar.yaml']), []); expect(tableRows[0].key).toBe('bar.yaml'); expect(tableRows[1].key).toBe('foo.yaml'); }); it('renders a list of selected files, ordered alphabetically', () => { let tableRows = getTableRows(Set(), [ { filePath: 'foo.yaml', contents: 'foo' }, { filePath: 'bar.yaml', contents: 'bar' } ]); expect(tableRows[0].key).toBe('bar.yaml'); expect(tableRows[1].key).toBe('foo.yaml'); }); it('merges a list of selected files and planfiles', () => { let tableRows = getTableRows(Set(['foobar.yaml', 'foo.yaml', 'bar.yaml']), [ { filePath: 'foo.yaml', contents: 'foo' }, { filePath: 'bar.yaml', contents: 'bar' } ]); expect(tableRows[0].key).toBe('bar.yaml'); expect(tableRows[1].key).toBe('foo.yaml'); expect(tableRows[2].key).toBe('foobar.yaml'); }); it('adds classes and sorts files based on differences in selected files and planfiles', () => { let tableRows = getTableRows(Set(['old.yaml', 'foo.yaml', 'bar.yaml']), [ { filePath: 'foo.yaml', contents: 'foo' }, { filePath: 'bar.yaml', contents: 'changed' }, { filePath: 'foobar.yaml', contents: 'foobar' } ]); expect(tableRows[0].key).toBe('bar.yaml'); expect(tableRows[0].props.children.props.className).toBe('new-plan-file'); expect(tableRows[1].key).toBe('foo.yaml'); expect(tableRows[1].props.children.props.className).toBe('new-plan-file'); expect(tableRows[2].key).toBe('foobar.yaml'); expect(tableRows[2].props.children.props.className).toBe('new-plan-file'); expect(tableRows[3].key).toBe('old.yaml'); expect(tableRows[3].props.children.props.className).toBe(''); }); });
src/components/grid/grid_icon.js
n7best/react-weui
import React from 'react'; import classNames from '../../utils/classnames'; /** * WeUI Grid Icon Wrapper * */ export default class GridIcon extends React.Component { render() { const {children, className, ...others} = this.props; const cls = classNames({ 'weui-grid__icon': true }, className); return ( <div className={cls} {...others}>{children}</div> ); } };
packages/react-scripts/fixtures/kitchensink/src/index.js
1Body/prayer-app
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ClassProperties.js
johnslay/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; users = [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, { id: 4, name: '4' }, ]; componentDidMount() { this.props.onReady(); } render() { return ( <div id="feature-class-properties"> {this.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
app/javascript/mastodon/components/__tests__/display_name-test.js
clworld/mastodon
import React from 'react'; import renderer from 'react-test-renderer'; import { fromJS } from 'immutable'; import DisplayName from '../display_name'; describe('<DisplayName />', () => { it('renders display name + account name', () => { const account = fromJS({ username: 'bar', acct: 'bar@baz', display_name_html: '<p>Foo</p>', }); const component = renderer.create(<DisplayName account={account} />); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); });
node_modules/socket.io-client/dist/socket.io.js
Vas2016/HomeRaspi
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["io"] = factory(); else root["io"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** * Module dependencies. */ var url = __webpack_require__(1); var parser = __webpack_require__(7); var Manager = __webpack_require__(17); var debug = __webpack_require__(3)('socket.io-client'); /** * Module exports. */ module.exports = exports = lookup; /** * Managers cache. */ var cache = exports.managers = {}; /** * Looks up an existing `Manager` for multiplexing. * If the user summons: * * `io('http://localhost/a');` * `io('http://localhost/b');` * * We reuse the existing instance based on same scheme/port/host, * and we initialize sockets for each namespace. * * @api public */ function lookup(uri, opts) { if ((typeof uri === 'undefined' ? 'undefined' : _typeof(uri)) === 'object') { opts = uri; uri = undefined; } opts = opts || {}; var parsed = url(uri); var source = parsed.source; var id = parsed.id; var path = parsed.path; var sameNamespace = cache[id] && path in cache[id].nsps; var newConnection = opts.forceNew || opts['force new connection'] || false === opts.multiplex || sameNamespace; var io; if (newConnection) { debug('ignoring socket cache for %s', source); io = Manager(source, opts); } else { if (!cache[id]) { debug('new io instance for %s', source); cache[id] = Manager(source, opts); } io = cache[id]; } if (parsed.query && !opts.query) { opts.query = parsed.query; } else if (opts && 'object' === _typeof(opts.query)) { opts.query = encodeQueryString(opts.query); } return io.socket(parsed.path, opts); } /** * Helper method to parse query objects to string. * @param {object} query * @returns {string} */ function encodeQueryString(obj) { var str = []; for (var p in obj) { if (obj.hasOwnProperty(p)) { str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])); } } return str.join('&'); } /** * Protocol version. * * @api public */ exports.protocol = parser.protocol; /** * `connect`. * * @param {String} uri * @api public */ exports.connect = lookup; /** * Expose constructors for standalone build. * * @api public */ exports.Manager = __webpack_require__(17); exports.Socket = __webpack_require__(44); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {'use strict'; /** * Module dependencies. */ var parseuri = __webpack_require__(2); var debug = __webpack_require__(3)('socket.io-client:url'); /** * Module exports. */ module.exports = url; /** * URL parser. * * @param {String} url * @param {Object} An object meant to mimic window.location. * Defaults to window.location. * @api public */ function url(uri, loc) { var obj = uri; // default to window.location loc = loc || global.location; if (null == uri) uri = loc.protocol + '//' + loc.host; // relative path support if ('string' === typeof uri) { if ('/' === uri.charAt(0)) { if ('/' === uri.charAt(1)) { uri = loc.protocol + uri; } else { uri = loc.host + uri; } } if (!/^(https?|wss?):\/\//.test(uri)) { debug('protocol-less url %s', uri); if ('undefined' !== typeof loc) { uri = loc.protocol + '//' + uri; } else { uri = 'https://' + uri; } } // parse debug('parse %s', uri); obj = parseuri(uri); } // make sure we treat `localhost:80` and `localhost` equally if (!obj.port) { if (/^(http|ws)$/.test(obj.protocol)) { obj.port = '80'; } else if (/^(http|ws)s$/.test(obj.protocol)) { obj.port = '443'; } } obj.path = obj.path || '/'; var ipv6 = obj.host.indexOf(':') !== -1; var host = ipv6 ? '[' + obj.host + ']' : obj.host; // define unique id obj.id = obj.protocol + '://' + host + ':' + obj.port; // define href obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : ':' + obj.port); return obj; } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 2 */ /***/ function(module, exports) { /** * Parses an URI * * @author Steven Levithan <stevenlevithan.com> (MIT license) * @api private */ var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; var parts = [ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' ]; module.exports = function parseuri(str) { var src = str, b = str.indexOf('['), e = str.indexOf(']'); if (b != -1 && e != -1) { str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); } var m = re.exec(str || ''), uri = {}, i = 14; while (i--) { uri[parts[i]] = m[i] || ''; } if (b != -1 && e != -1) { uri.source = src; uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); uri.ipv6uri = true; } return uri; }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) { /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = __webpack_require__(5); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs() { var args = arguments; var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return args; var c = 'color: ' + this.color; args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); return args; } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { return exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (typeof process !== 'undefined' && 'env' in process) { return process.env.DEBUG; } } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage(){ try { return window.localStorage; } catch (e) {} } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4))) /***/ }, /* 4 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = debug.debug = debug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = __webpack_require__(6); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lowercased letter, i.e. "n". */ exports.formatters = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * * @return {Number} * @api private */ function selectColor() { return exports.colors[prevColor++ % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function debug(namespace) { // define the `disabled` version function disabled() { } disabled.enabled = false; // define the `enabled` version function enabled() { var self = enabled; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // add the `color` if not set if (null == self.useColors) self.useColors = exports.useColors(); if (null == self.color && self.useColors) self.color = selectColor(); var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %o args = ['%o'].concat(args); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting args = exports.formatArgs.apply(self, args); var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); } enabled.enabled = true; var fn = exports.enabled(namespace) ? enabled : disabled; fn.namespace = namespace; return fn; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); var split = (namespaces || '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } /***/ }, /* 6 */ /***/ function(module, exports) { /** * Helpers. */ var s = 1000 var m = s * 60 var h = m * 60 var d = h * 24 var y = d * 365.25 /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} options * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ module.exports = function (val, options) { options = options || {} var type = typeof val if (type === 'string' && val.length > 0) { return parse(val) } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val) } throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)) } /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str) if (str.length > 10000) { return } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str) if (!match) { return } var n = parseFloat(match[1]) var type = (match[2] || 'ms').toLowerCase() switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y case 'days': case 'day': case 'd': return n * d case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n default: return undefined } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd' } if (ms >= h) { return Math.round(ms / h) + 'h' } if (ms >= m) { return Math.round(ms / m) + 'm' } if (ms >= s) { return Math.round(ms / s) + 's' } return ms + 'ms' } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms' } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name } return Math.ceil(ms / n) + ' ' + name + 's' } /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /** * Module dependencies. */ var debug = __webpack_require__(8)('socket.io-parser'); var json = __webpack_require__(11); var Emitter = __webpack_require__(13); var binary = __webpack_require__(14); var isBuf = __webpack_require__(16); /** * Protocol version. * * @api public */ exports.protocol = 4; /** * Packet types. * * @api public */ exports.types = [ 'CONNECT', 'DISCONNECT', 'EVENT', 'ACK', 'ERROR', 'BINARY_EVENT', 'BINARY_ACK' ]; /** * Packet type `connect`. * * @api public */ exports.CONNECT = 0; /** * Packet type `disconnect`. * * @api public */ exports.DISCONNECT = 1; /** * Packet type `event`. * * @api public */ exports.EVENT = 2; /** * Packet type `ack`. * * @api public */ exports.ACK = 3; /** * Packet type `error`. * * @api public */ exports.ERROR = 4; /** * Packet type 'binary event' * * @api public */ exports.BINARY_EVENT = 5; /** * Packet type `binary ack`. For acks with binary arguments. * * @api public */ exports.BINARY_ACK = 6; /** * Encoder constructor. * * @api public */ exports.Encoder = Encoder; /** * Decoder constructor. * * @api public */ exports.Decoder = Decoder; /** * A socket.io Encoder instance * * @api public */ function Encoder() {} /** * Encode a packet as a single string if non-binary, or as a * buffer sequence, depending on packet type. * * @param {Object} obj - packet object * @param {Function} callback - function to handle encodings (likely engine.write) * @return Calls callback with Array of encodings * @api public */ Encoder.prototype.encode = function(obj, callback){ debug('encoding packet %j', obj); if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) { encodeAsBinary(obj, callback); } else { var encoding = encodeAsString(obj); callback([encoding]); } }; /** * Encode packet as string. * * @param {Object} packet * @return {String} encoded * @api private */ function encodeAsString(obj) { var str = ''; var nsp = false; // first is type str += obj.type; // attachments if we have them if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) { str += obj.attachments; str += '-'; } // if we have a namespace other than `/` // we append it followed by a comma `,` if (obj.nsp && '/' != obj.nsp) { nsp = true; str += obj.nsp; } // immediately followed by the id if (null != obj.id) { if (nsp) { str += ','; nsp = false; } str += obj.id; } // json data if (null != obj.data) { if (nsp) str += ','; str += json.stringify(obj.data); } debug('encoded %j as %s', obj, str); return str; } /** * Encode packet as 'buffer sequence' by removing blobs, and * deconstructing packet into object with placeholders and * a list of buffers. * * @param {Object} packet * @return {Buffer} encoded * @api private */ function encodeAsBinary(obj, callback) { function writeEncoding(bloblessData) { var deconstruction = binary.deconstructPacket(bloblessData); var pack = encodeAsString(deconstruction.packet); var buffers = deconstruction.buffers; buffers.unshift(pack); // add packet info to beginning of data list callback(buffers); // write all the buffers } binary.removeBlobs(obj, writeEncoding); } /** * A socket.io Decoder instance * * @return {Object} decoder * @api public */ function Decoder() { this.reconstructor = null; } /** * Mix in `Emitter` with Decoder. */ Emitter(Decoder.prototype); /** * Decodes an ecoded packet string into packet JSON. * * @param {String} obj - encoded packet * @return {Object} packet * @api public */ Decoder.prototype.add = function(obj) { var packet; if ('string' == typeof obj) { packet = decodeString(obj); if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json this.reconstructor = new BinaryReconstructor(packet); // no attachments, labeled binary but no binary data to follow if (this.reconstructor.reconPack.attachments === 0) { this.emit('decoded', packet); } } else { // non-binary full packet this.emit('decoded', packet); } } else if (isBuf(obj) || obj.base64) { // raw binary data if (!this.reconstructor) { throw new Error('got binary data when not reconstructing a packet'); } else { packet = this.reconstructor.takeBinaryData(obj); if (packet) { // received final buffer this.reconstructor = null; this.emit('decoded', packet); } } } else { throw new Error('Unknown type: ' + obj); } }; /** * Decode a packet String (JSON data) * * @param {String} str * @return {Object} packet * @api private */ function decodeString(str) { var p = {}; var i = 0; // look up type p.type = Number(str.charAt(0)); if (null == exports.types[p.type]) return error(); // look up attachments if type binary if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) { var buf = ''; while (str.charAt(++i) != '-') { buf += str.charAt(i); if (i == str.length) break; } if (buf != Number(buf) || str.charAt(i) != '-') { throw new Error('Illegal attachments'); } p.attachments = Number(buf); } // look up namespace (if any) if ('/' == str.charAt(i + 1)) { p.nsp = ''; while (++i) { var c = str.charAt(i); if (',' == c) break; p.nsp += c; if (i == str.length) break; } } else { p.nsp = '/'; } // look up id var next = str.charAt(i + 1); if ('' !== next && Number(next) == next) { p.id = ''; while (++i) { var c = str.charAt(i); if (null == c || Number(c) != c) { --i; break; } p.id += str.charAt(i); if (i == str.length) break; } p.id = Number(p.id); } // look up json data if (str.charAt(++i)) { p = tryParse(p, str.substr(i)); } debug('decoded %s as %j', str, p); return p; } function tryParse(p, str) { try { p.data = json.parse(str); } catch(e){ return error(); } return p; }; /** * Deallocates a parser's resources * * @api public */ Decoder.prototype.destroy = function() { if (this.reconstructor) { this.reconstructor.finishedReconstruction(); } }; /** * A manager of a binary event's 'buffer sequence'. Should * be constructed whenever a packet of type BINARY_EVENT is * decoded. * * @param {Object} packet * @return {BinaryReconstructor} initialized reconstructor * @api private */ function BinaryReconstructor(packet) { this.reconPack = packet; this.buffers = []; } /** * Method to be called when binary data received from connection * after a BINARY_EVENT packet. * * @param {Buffer | ArrayBuffer} binData - the raw binary data received * @return {null | Object} returns null if more binary data is expected or * a reconstructed packet object if all buffers have been received. * @api private */ BinaryReconstructor.prototype.takeBinaryData = function(binData) { this.buffers.push(binData); if (this.buffers.length == this.reconPack.attachments) { // done with buffer list var packet = binary.reconstructPacket(this.reconPack, this.buffers); this.finishedReconstruction(); return packet; } return null; }; /** * Cleans up binary packet reconstruction variables. * * @api private */ BinaryReconstructor.prototype.finishedReconstruction = function() { this.reconPack = null; this.buffers = []; }; function error(data){ return { type: exports.ERROR, data: 'parser error' }; } /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = __webpack_require__(9); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // is webkit? http://stackoverflow.com/a/16459606/376773 return ('WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { return JSON.stringify(v); }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs() { var args = arguments; var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return args; var c = 'color: ' + this.color; args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); return args; } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { r = exports.storage.debug; } catch(e) {} return r; } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage(){ try { return window.localStorage; } catch (e) {} } /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = debug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = __webpack_require__(10); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lowercased letter, i.e. "n". */ exports.formatters = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * * @return {Number} * @api private */ function selectColor() { return exports.colors[prevColor++ % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function debug(namespace) { // define the `disabled` version function disabled() { } disabled.enabled = false; // define the `enabled` version function enabled() { var self = enabled; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // add the `color` if not set if (null == self.useColors) self.useColors = exports.useColors(); if (null == self.color && self.useColors) self.color = selectColor(); var args = Array.prototype.slice.call(arguments); args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %o args = ['%o'].concat(args); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); if ('function' === typeof exports.formatArgs) { args = exports.formatArgs.apply(self, args); } var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); } enabled.enabled = true; var fn = exports.enabled(namespace) ? enabled : disabled; fn.namespace = namespace; return fn; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); var split = (namespaces || '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } /***/ }, /* 10 */ /***/ function(module, exports) { /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} options * @return {String|Number} * @api public */ module.exports = function(val, options){ options = options || {}; if ('string' == typeof val) return parse(val); return options.long ? long(val) : short(val); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = '' + str; if (str.length > 10000) return; var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str); if (!match) return; var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function short(ms) { if (ms >= d) return Math.round(ms / d) + 'd'; if (ms >= h) return Math.round(ms / h) + 'h'; if (ms >= m) return Math.round(ms / m) + 'm'; if (ms >= s) return Math.round(ms / s) + 's'; return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function long(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) return; if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; return Math.ceil(ms / n) + ' ' + name + 's'; } /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module, global) {/*** IMPORTS FROM imports-loader ***/ var define = false; /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */ ;(function () { // Detect the `define` function exposed by asynchronous module loaders. The // strict `define` check is necessary for compatibility with `r.js`. var isLoader = typeof define === "function" && define.amd; // A set of types used to distinguish objects from primitives. var objectTypes = { "function": true, "object": true }; // Detect the `exports` object exposed by CommonJS implementations. var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; // Use the `global` object exposed by Node (including Browserify via // `insert-module-globals`), Narwhal, and Ringo as the default context, // and the `window` object in browsers. Rhino exports a `global` function // instead. var root = objectTypes[typeof window] && window || this, freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global; if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) { root = freeGlobal; } // Public: Initializes JSON 3 using the given `context` object, attaching the // `stringify` and `parse` functions to the specified `exports` object. function runInContext(context, exports) { context || (context = root["Object"]()); exports || (exports = root["Object"]()); // Native constructor aliases. var Number = context["Number"] || root["Number"], String = context["String"] || root["String"], Object = context["Object"] || root["Object"], Date = context["Date"] || root["Date"], SyntaxError = context["SyntaxError"] || root["SyntaxError"], TypeError = context["TypeError"] || root["TypeError"], Math = context["Math"] || root["Math"], nativeJSON = context["JSON"] || root["JSON"]; // Delegate to the native `stringify` and `parse` implementations. if (typeof nativeJSON == "object" && nativeJSON) { exports.stringify = nativeJSON.stringify; exports.parse = nativeJSON.parse; } // Convenience aliases. var objectProto = Object.prototype, getClass = objectProto.toString, isProperty, forEach, undef; // Test the `Date#getUTC*` methods. Based on work by @Yaffle. var isExtended = new Date(-3509827334573292); try { // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical // results for certain dates in Opera >= 10.53. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 && // Safari < 2.0.2 stores the internal millisecond time value correctly, // but clips the values returned by the date methods to the range of // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]). isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708; } catch (exception) {} // Internal: Determines whether the native `JSON.stringify` and `parse` // implementations are spec-compliant. Based on work by Ken Snyder. function has(name) { if (has[name] !== undef) { // Return cached feature test result. return has[name]; } var isSupported; if (name == "bug-string-char-index") { // IE <= 7 doesn't support accessing string characters using square // bracket notation. IE 8 only supports this for primitives. isSupported = "a"[0] != "a"; } else if (name == "json") { // Indicates whether both `JSON.stringify` and `JSON.parse` are // supported. isSupported = has("json-stringify") && has("json-parse"); } else { var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}'; // Test `JSON.stringify`. if (name == "json-stringify") { var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended; if (stringifySupported) { // A test function object with a custom `toJSON` method. (value = function () { return 1; }).toJSON = value; try { stringifySupported = // Firefox 3.1b1 and b2 serialize string, number, and boolean // primitives as object literals. stringify(0) === "0" && // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object // literals. stringify(new Number()) === "0" && stringify(new String()) == '""' && // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or // does not define a canonical JSON representation (this applies to // objects with `toJSON` properties as well, *unless* they are nested // within an object or array). stringify(getClass) === undef && // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and // FF 3.1b3 pass this test. stringify(undef) === undef && // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s, // respectively, if the value is omitted entirely. stringify() === undef && // FF 3.1b1, 2 throw an error if the given value is not a number, // string, array, object, Boolean, or `null` literal. This applies to // objects with custom `toJSON` methods as well, unless they are nested // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON` // methods entirely. stringify(value) === "1" && stringify([value]) == "[1]" && // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of // `"[null]"`. stringify([undef]) == "[null]" && // YUI 3.0.0b1 fails to serialize `null` literals. stringify(null) == "null" && // FF 3.1b1, 2 halts serialization if an array contains a function: // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3 // elides non-JSON values from objects and arrays, unless they // define custom `toJSON` methods. stringify([undef, getClass, null]) == "[null,null,null]" && // Simple serialization test. FF 3.1b1 uses Unicode escape sequences // where character escape codes are expected (e.g., `\b` => `\u0008`). stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized && // FF 3.1b1 and b2 ignore the `filter` and `width` arguments. stringify(null, value) === "1" && stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" && // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly // serialize extended years. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' && // The milliseconds are optional in ES 5, but required in 5.1. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' && // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative // four-digit years instead of six-digit years. Credits: @Yaffle. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' && // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond // values less than 1000. Credits: @Yaffle. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"'; } catch (exception) { stringifySupported = false; } } isSupported = stringifySupported; } // Test `JSON.parse`. if (name == "json-parse") { var parse = exports.parse; if (typeof parse == "function") { try { // FF 3.1b1, b2 will throw an exception if a bare literal is provided. // Conforming implementations should also coerce the initial argument to // a string prior to parsing. if (parse("0") === 0 && !parse(false)) { // Simple parsing test. value = parse(serialized); var parseSupported = value["a"].length == 5 && value["a"][0] === 1; if (parseSupported) { try { // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings. parseSupported = !parse('"\t"'); } catch (exception) {} if (parseSupported) { try { // FF 4.0 and 4.0.1 allow leading `+` signs and leading // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow // certain octal literals. parseSupported = parse("01") !== 1; } catch (exception) {} } if (parseSupported) { try { // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal // points. These environments, along with FF 3.1b1 and 2, // also allow trailing commas in JSON objects and arrays. parseSupported = parse("1.") !== 1; } catch (exception) {} } } } } catch (exception) { parseSupported = false; } } isSupported = parseSupported; } } return has[name] = !!isSupported; } if (!has("json")) { // Common `[[Class]]` name aliases. var functionClass = "[object Function]", dateClass = "[object Date]", numberClass = "[object Number]", stringClass = "[object String]", arrayClass = "[object Array]", booleanClass = "[object Boolean]"; // Detect incomplete support for accessing string characters by index. var charIndexBuggy = has("bug-string-char-index"); // Define additional utility methods if the `Date` methods are buggy. if (!isExtended) { var floor = Math.floor; // A mapping between the months of the year and the number of days between // January 1st and the first of the respective month. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; // Internal: Calculates the number of days between the Unix epoch and the // first day of the given month. var getDay = function (year, month) { return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); }; } // Internal: Determines if a property is a direct property of the given // object. Delegates to the native `Object#hasOwnProperty` method. if (!(isProperty = objectProto.hasOwnProperty)) { isProperty = function (property) { var members = {}, constructor; if ((members.__proto__ = null, members.__proto__ = { // The *proto* property cannot be set multiple times in recent // versions of Firefox and SeaMonkey. "toString": 1 }, members).toString != getClass) { // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but // supports the mutable *proto* property. isProperty = function (property) { // Capture and break the object's prototype chain (see section 8.6.2 // of the ES 5.1 spec). The parenthesized expression prevents an // unsafe transformation by the Closure Compiler. var original = this.__proto__, result = property in (this.__proto__ = null, this); // Restore the original prototype chain. this.__proto__ = original; return result; }; } else { // Capture a reference to the top-level `Object` constructor. constructor = members.constructor; // Use the `constructor` property to simulate `Object#hasOwnProperty` in // other environments. isProperty = function (property) { var parent = (this.constructor || constructor).prototype; return property in this && !(property in parent && this[property] === parent[property]); }; } members = null; return isProperty.call(this, property); }; } // Internal: Normalizes the `for...in` iteration algorithm across // environments. Each enumerated key is yielded to a `callback` function. forEach = function (object, callback) { var size = 0, Properties, members, property; // Tests for bugs in the current environment's `for...in` algorithm. The // `valueOf` property inherits the non-enumerable flag from // `Object.prototype` in older versions of IE, Netscape, and Mozilla. (Properties = function () { this.valueOf = 0; }).prototype.valueOf = 0; // Iterate over a new instance of the `Properties` class. members = new Properties(); for (property in members) { // Ignore all properties inherited from `Object.prototype`. if (isProperty.call(members, property)) { size++; } } Properties = members = null; // Normalize the iteration algorithm. if (!size) { // A list of non-enumerable properties inherited from `Object.prototype`. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable // properties. forEach = function (object, callback) { var isFunction = getClass.call(object) == functionClass, property, length; var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty; for (property in object) { // Gecko <= 1.0 enumerates the `prototype` property of functions under // certain conditions; IE does not. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { callback(property); } } // Manually invoke the callback for each non-enumerable property. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)); }; } else if (size == 2) { // Safari <= 2.0.4 enumerates shadowed properties twice. forEach = function (object, callback) { // Create a set of iterated properties. var members = {}, isFunction = getClass.call(object) == functionClass, property; for (property in object) { // Store each property name to prevent double enumeration. The // `prototype` property of functions is not enumerated due to cross- // environment inconsistencies. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) { callback(property); } } }; } else { // No bugs detected; use the standard `for...in` algorithm. forEach = function (object, callback) { var isFunction = getClass.call(object) == functionClass, property, isConstructor; for (property in object) { if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { callback(property); } } // Manually invoke the callback for the `constructor` property due to // cross-environment inconsistencies. if (isConstructor || isProperty.call(object, (property = "constructor"))) { callback(property); } }; } return forEach(object, callback); }; // Public: Serializes a JavaScript `value` as a JSON string. The optional // `filter` argument may specify either a function that alters how object and // array members are serialized, or an array of strings and numbers that // indicates which properties should be serialized. The optional `width` // argument may be either a string or number that specifies the indentation // level of the output. if (!has("json-stringify")) { // Internal: A map of control characters and their escaped equivalents. var Escapes = { 92: "\\\\", 34: '\\"', 8: "\\b", 12: "\\f", 10: "\\n", 13: "\\r", 9: "\\t" }; // Internal: Converts `value` into a zero-padded string such that its // length is at least equal to `width`. The `width` must be <= 6. var leadingZeroes = "000000"; var toPaddedString = function (width, value) { // The `|| 0` expression is necessary to work around a bug in // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`. return (leadingZeroes + (value || 0)).slice(-width); }; // Internal: Double-quotes a string `value`, replacing all ASCII control // characters (characters with code unit values between 0 and 31) with // their escaped equivalents. This is an implementation of the // `Quote(value)` operation defined in ES 5.1 section 15.12.3. var unicodePrefix = "\\u00"; var quote = function (value) { var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10; var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value); for (; index < length; index++) { var charCode = value.charCodeAt(index); // If the character is a control character, append its Unicode or // shorthand escape sequence; otherwise, append the character as-is. switch (charCode) { case 8: case 9: case 10: case 12: case 13: case 34: case 92: result += Escapes[charCode]; break; default: if (charCode < 32) { result += unicodePrefix + toPaddedString(2, charCode.toString(16)); break; } result += useCharIndex ? symbols[index] : value.charAt(index); } } return result + '"'; }; // Internal: Recursively serializes an object. Implements the // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result; try { // Necessary for host object support. value = object[property]; } catch (exception) {} if (typeof value == "object" && value) { className = getClass.call(value); if (className == dateClass && !isProperty.call(value, "toJSON")) { if (value > -1 / 0 && value < 1 / 0) { // Dates are serialized according to the `Date#toJSON` method // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15 // for the ISO 8601 date time string format. if (getDay) { // Manually compute the year, month, date, hours, minutes, // seconds, and milliseconds if the `getUTC*` methods are // buggy. Adapted from @Yaffle's `date-shim` project. date = floor(value / 864e5); for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); date = 1 + date - getDay(year, month); // The `time` value specifies the time within the day (see ES // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used // to compute `A modulo B`, as the `%` operator does not // correspond to the `modulo` operation for negative numbers. time = (value % 864e5 + 864e5) % 864e5; // The hours, minutes, seconds, and milliseconds are obtained by // decomposing the time within the day. See section 15.9.1.10. hours = floor(time / 36e5) % 24; minutes = floor(time / 6e4) % 60; seconds = floor(time / 1e3) % 60; milliseconds = time % 1e3; } else { year = value.getUTCFullYear(); month = value.getUTCMonth(); date = value.getUTCDate(); hours = value.getUTCHours(); minutes = value.getUTCMinutes(); seconds = value.getUTCSeconds(); milliseconds = value.getUTCMilliseconds(); } // Serialize extended years correctly. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + // Months, dates, hours, minutes, and seconds should have two // digits; milliseconds should have three. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + // Milliseconds are optional in ES 5.0, but required in 5.1. "." + toPaddedString(3, milliseconds) + "Z"; } else { value = null; } } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) { // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3 // ignores all `toJSON` methods on these objects unless they are // defined directly on an instance. value = value.toJSON(property); } } if (callback) { // If a replacement function was provided, call it to obtain the value // for serialization. value = callback.call(object, property, value); } if (value === null) { return "null"; } className = getClass.call(value); if (className == booleanClass) { // Booleans are represented literally. return "" + value; } else if (className == numberClass) { // JSON numbers must be finite. `Infinity` and `NaN` are serialized as // `"null"`. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; } else if (className == stringClass) { // Strings are double-quoted and escaped. return quote("" + value); } // Recursively serialize objects and arrays. if (typeof value == "object") { // Check for cyclic structures. This is a linear search; performance // is inversely proportional to the number of unique nested objects. for (length = stack.length; length--;) { if (stack[length] === value) { // Cyclic structures cannot be serialized by `JSON.stringify`. throw TypeError(); } } // Add the object to the stack of traversed objects. stack.push(value); results = []; // Save the current indentation level and indent one additional level. prefix = indentation; indentation += whitespace; if (className == arrayClass) { // Recursively serialize array elements. for (index = 0, length = value.length; index < length; index++) { element = serialize(index, value, callback, properties, whitespace, indentation, stack); results.push(element === undef ? "null" : element); } result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]"; } else { // Recursively serialize object members. Members are selected from // either a user-specified list of property names, or the object // itself. forEach(properties || value, function (property) { var element = serialize(property, value, callback, properties, whitespace, indentation, stack); if (element !== undef) { // According to ES 5.1 section 15.12.3: "If `gap` {whitespace} // is not the empty string, let `member` {quote(property) + ":"} // be the concatenation of `member` and the `space` character." // The "`space` character" refers to the literal space // character, not the `space` {width} argument provided to // `JSON.stringify`. results.push(quote(property) + ":" + (whitespace ? " " : "") + element); } }); result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}"; } // Remove the object from the traversed object stack. stack.pop(); return result; } }; // Public: `JSON.stringify`. See ES 5.1 section 15.12.3. exports.stringify = function (source, filter, width) { var whitespace, callback, properties, className; if (objectTypes[typeof filter] && filter) { if ((className = getClass.call(filter)) == functionClass) { callback = filter; } else if (className == arrayClass) { // Convert the property names array into a makeshift set. properties = {}; for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1)); } } if (width) { if ((className = getClass.call(width)) == numberClass) { // Convert the `width` to an integer and create a string containing // `width` number of space characters. if ((width -= width % 1) > 0) { for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " "); } } else if (className == stringClass) { whitespace = width.length <= 10 ? width : width.slice(0, 10); } } // Opera <= 7.54u2 discards the values associated with empty string keys // (`""`) only if they are used directly within an object member list // (e.g., `!("" in { "": 1})`). return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); }; } // Public: Parses a JSON source string. if (!has("json-parse")) { var fromCharCode = String.fromCharCode; // Internal: A map of escaped control characters and their unescaped // equivalents. var Unescapes = { 92: "\\", 34: '"', 47: "/", 98: "\b", 116: "\t", 110: "\n", 102: "\f", 114: "\r" }; // Internal: Stores the parser state. var Index, Source; // Internal: Resets the parser state and throws a `SyntaxError`. var abort = function () { Index = Source = null; throw SyntaxError(); }; // Internal: Returns the next token, or `"$"` if the parser has reached // the end of the source string. A token may be a string, number, `null` // literal, or Boolean literal. var lex = function () { var source = Source, length = source.length, value, begin, position, isSigned, charCode; while (Index < length) { charCode = source.charCodeAt(Index); switch (charCode) { case 9: case 10: case 13: case 32: // Skip whitespace tokens, including tabs, carriage returns, line // feeds, and space characters. Index++; break; case 123: case 125: case 91: case 93: case 58: case 44: // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at // the current position. value = charIndexBuggy ? source.charAt(Index) : source[Index]; Index++; return value; case 34: // `"` delimits a JSON string; advance to the next character and // begin parsing the string. String tokens are prefixed with the // sentinel `@` character to distinguish them from punctuators and // end-of-string tokens. for (value = "@", Index++; Index < length;) { charCode = source.charCodeAt(Index); if (charCode < 32) { // Unescaped ASCII control characters (those with a code unit // less than the space character) are not permitted. abort(); } else if (charCode == 92) { // A reverse solidus (`\`) marks the beginning of an escaped // control character (including `"`, `\`, and `/`) or Unicode // escape sequence. charCode = source.charCodeAt(++Index); switch (charCode) { case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114: // Revive escaped control characters. value += Unescapes[charCode]; Index++; break; case 117: // `\u` marks the beginning of a Unicode escape sequence. // Advance to the first character and validate the // four-digit code point. begin = ++Index; for (position = Index + 4; Index < position; Index++) { charCode = source.charCodeAt(Index); // A valid sequence comprises four hexdigits (case- // insensitive) that form a single hexadecimal value. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { // Invalid Unicode escape sequence. abort(); } } // Revive the escaped character. value += fromCharCode("0x" + source.slice(begin, Index)); break; default: // Invalid escape sequence. abort(); } } else { if (charCode == 34) { // An unescaped double-quote character marks the end of the // string. break; } charCode = source.charCodeAt(Index); begin = Index; // Optimize for the common case where a string is valid. while (charCode >= 32 && charCode != 92 && charCode != 34) { charCode = source.charCodeAt(++Index); } // Append the string as-is. value += source.slice(begin, Index); } } if (source.charCodeAt(Index) == 34) { // Advance to the next character and return the revived string. Index++; return value; } // Unterminated string. abort(); default: // Parse numbers and literals. begin = Index; // Advance past the negative sign, if one is specified. if (charCode == 45) { isSigned = true; charCode = source.charCodeAt(++Index); } // Parse an integer or floating-point value. if (charCode >= 48 && charCode <= 57) { // Leading zeroes are interpreted as octal literals. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) { // Illegal octal literal. abort(); } isSigned = false; // Parse the integer component. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++); // Floats cannot contain a leading decimal point; however, this // case is already accounted for by the parser. if (source.charCodeAt(Index) == 46) { position = ++Index; // Parse the decimal component. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); if (position == Index) { // Illegal trailing decimal. abort(); } Index = position; } // Parse exponents. The `e` denoting the exponent is // case-insensitive. charCode = source.charCodeAt(Index); if (charCode == 101 || charCode == 69) { charCode = source.charCodeAt(++Index); // Skip past the sign following the exponent, if one is // specified. if (charCode == 43 || charCode == 45) { Index++; } // Parse the exponential component. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); if (position == Index) { // Illegal empty exponent. abort(); } Index = position; } // Coerce the parsed value to a JavaScript number. return +source.slice(begin, Index); } // A negative sign may only precede numbers. if (isSigned) { abort(); } // `true`, `false`, and `null` literals. if (source.slice(Index, Index + 4) == "true") { Index += 4; return true; } else if (source.slice(Index, Index + 5) == "false") { Index += 5; return false; } else if (source.slice(Index, Index + 4) == "null") { Index += 4; return null; } // Unrecognized token. abort(); } } // Return the sentinel `$` character if the parser has reached the end // of the source string. return "$"; }; // Internal: Parses a JSON `value` token. var get = function (value) { var results, hasMembers; if (value == "$") { // Unexpected end of input. abort(); } if (typeof value == "string") { if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { // Remove the sentinel `@` character. return value.slice(1); } // Parse object and array literals. if (value == "[") { // Parses a JSON array, returning a new JavaScript array. results = []; for (;; hasMembers || (hasMembers = true)) { value = lex(); // A closing square bracket marks the end of the array literal. if (value == "]") { break; } // If the array literal contains elements, the current token // should be a comma separating the previous element from the // next. if (hasMembers) { if (value == ",") { value = lex(); if (value == "]") { // Unexpected trailing `,` in array literal. abort(); } } else { // A `,` must separate each array element. abort(); } } // Elisions and leading commas are not permitted. if (value == ",") { abort(); } results.push(get(value)); } return results; } else if (value == "{") { // Parses a JSON object, returning a new JavaScript object. results = {}; for (;; hasMembers || (hasMembers = true)) { value = lex(); // A closing curly brace marks the end of the object literal. if (value == "}") { break; } // If the object literal contains members, the current token // should be a comma separator. if (hasMembers) { if (value == ",") { value = lex(); if (value == "}") { // Unexpected trailing `,` in object literal. abort(); } } else { // A `,` must separate each object member. abort(); } } // Leading commas are not permitted, object property names must be // double-quoted strings, and a `:` must separate each property // name and value. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { abort(); } results[value.slice(1)] = get(lex()); } return results; } // Unexpected token encountered. abort(); } return value; }; // Internal: Updates a traversed object member. var update = function (source, property, callback) { var element = walk(source, property, callback); if (element === undef) { delete source[property]; } else { source[property] = element; } }; // Internal: Recursively traverses a parsed JSON object, invoking the // `callback` function for each value. This is an implementation of the // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2. var walk = function (source, property, callback) { var value = source[property], length; if (typeof value == "object" && value) { // `forEach` can't be used to traverse an array in Opera <= 8.54 // because its `Object#hasOwnProperty` implementation returns `false` // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`). if (getClass.call(value) == arrayClass) { for (length = value.length; length--;) { update(value, length, callback); } } else { forEach(value, function (property) { update(value, property, callback); }); } } return callback.call(source, property, value); }; // Public: `JSON.parse`. See ES 5.1 section 15.12.2. exports.parse = function (source, callback) { var result, value; Index = 0; Source = "" + source; result = get(lex()); // If a JSON string contains multiple tokens, it is invalid. if (lex() != "$") { abort(); } // Reset the parser state. Index = Source = null; return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; }; } } exports["runInContext"] = runInContext; return exports; } if (freeExports && !isLoader) { // Export for CommonJS environments. runInContext(root, freeExports); } else { // Export for web browsers and JavaScript engines. var nativeJSON = root.JSON, previousJSON = root["JSON3"], isRestored = false; var JSON3 = runInContext(root, (root["JSON3"] = { // Public: Restores the original value of the global `JSON` object and // returns a reference to the `JSON3` object. "noConflict": function () { if (!isRestored) { isRestored = true; root.JSON = nativeJSON; root["JSON3"] = previousJSON; nativeJSON = previousJSON = null; } return JSON3; } })); root.JSON = { "parse": JSON3.parse, "stringify": JSON3.stringify }; } // Export for asynchronous module loaders. if (isLoader) { define(function () { return JSON3; }); } }).call(this); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(12)(module), (function() { return this; }()))) /***/ }, /* 12 */ /***/ function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 13 */ /***/ function(module, exports) { /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/*global Blob,File*/ /** * Module requirements */ var isArray = __webpack_require__(15); var isBuf = __webpack_require__(16); /** * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder. * Anything with blobs or files should be fed through removeBlobs before coming * here. * * @param {Object} packet - socket.io event packet * @return {Object} with deconstructed packet and list of buffers * @api public */ exports.deconstructPacket = function(packet){ var buffers = []; var packetData = packet.data; function _deconstructPacket(data) { if (!data) return data; if (isBuf(data)) { var placeholder = { _placeholder: true, num: buffers.length }; buffers.push(data); return placeholder; } else if (isArray(data)) { var newData = new Array(data.length); for (var i = 0; i < data.length; i++) { newData[i] = _deconstructPacket(data[i]); } return newData; } else if ('object' == typeof data && !(data instanceof Date)) { var newData = {}; for (var key in data) { newData[key] = _deconstructPacket(data[key]); } return newData; } return data; } var pack = packet; pack.data = _deconstructPacket(packetData); pack.attachments = buffers.length; // number of binary 'attachments' return {packet: pack, buffers: buffers}; }; /** * Reconstructs a binary packet from its placeholder packet and buffers * * @param {Object} packet - event packet with placeholders * @param {Array} buffers - binary buffers to put in placeholder positions * @return {Object} reconstructed packet * @api public */ exports.reconstructPacket = function(packet, buffers) { var curPlaceHolder = 0; function _reconstructPacket(data) { if (data && data._placeholder) { var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway) return buf; } else if (isArray(data)) { for (var i = 0; i < data.length; i++) { data[i] = _reconstructPacket(data[i]); } return data; } else if (data && 'object' == typeof data) { for (var key in data) { data[key] = _reconstructPacket(data[key]); } return data; } return data; } packet.data = _reconstructPacket(packet.data); packet.attachments = undefined; // no longer useful return packet; }; /** * Asynchronously removes Blobs or Files from data via * FileReader's readAsArrayBuffer method. Used before encoding * data as msgpack. Calls callback with the blobless data. * * @param {Object} data * @param {Function} callback * @api private */ exports.removeBlobs = function(data, callback) { function _removeBlobs(obj, curKey, containingObject) { if (!obj) return obj; // convert any blob if ((global.Blob && obj instanceof Blob) || (global.File && obj instanceof File)) { pendingBlobs++; // async filereader var fileReader = new FileReader(); fileReader.onload = function() { // this.result == arraybuffer if (containingObject) { containingObject[curKey] = this.result; } else { bloblessData = this.result; } // if nothing pending its callback time if(! --pendingBlobs) { callback(bloblessData); } }; fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer } else if (isArray(obj)) { // handle array for (var i = 0; i < obj.length; i++) { _removeBlobs(obj[i], i, obj); } } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object for (var key in obj) { _removeBlobs(obj[key], key, obj); } } } var pendingBlobs = 0; var bloblessData = data; _removeBlobs(bloblessData); if (!pendingBlobs) { callback(bloblessData); } }; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 15 */ /***/ function(module, exports) { module.exports = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; /***/ }, /* 16 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) { module.exports = isBuf; /** * Returns true if obj is a buffer or an arraybuffer. * * @api private */ function isBuf(obj) { return (global.Buffer && global.Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer); } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** * Module dependencies. */ var eio = __webpack_require__(18); var Socket = __webpack_require__(44); var Emitter = __webpack_require__(35); var parser = __webpack_require__(7); var on = __webpack_require__(46); var bind = __webpack_require__(47); var debug = __webpack_require__(3)('socket.io-client:manager'); var indexOf = __webpack_require__(42); var Backoff = __webpack_require__(48); /** * IE6+ hasOwnProperty */ var has = Object.prototype.hasOwnProperty; /** * Module exports */ module.exports = Manager; /** * `Manager` constructor. * * @param {String} engine instance or engine uri/opts * @param {Object} options * @api public */ function Manager(uri, opts) { if (!(this instanceof Manager)) return new Manager(uri, opts); if (uri && 'object' === (typeof uri === 'undefined' ? 'undefined' : _typeof(uri))) { opts = uri; uri = undefined; } opts = opts || {}; opts.path = opts.path || '/socket.io'; this.nsps = {}; this.subs = []; this.opts = opts; this.reconnection(opts.reconnection !== false); this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); this.reconnectionDelay(opts.reconnectionDelay || 1000); this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); this.randomizationFactor(opts.randomizationFactor || 0.5); this.backoff = new Backoff({ min: this.reconnectionDelay(), max: this.reconnectionDelayMax(), jitter: this.randomizationFactor() }); this.timeout(null == opts.timeout ? 20000 : opts.timeout); this.readyState = 'closed'; this.uri = uri; this.connecting = []; this.lastPing = null; this.encoding = false; this.packetBuffer = []; this.encoder = new parser.Encoder(); this.decoder = new parser.Decoder(); this.autoConnect = opts.autoConnect !== false; if (this.autoConnect) this.open(); } /** * Propagate given event to sockets and emit on `this` * * @api private */ Manager.prototype.emitAll = function () { this.emit.apply(this, arguments); for (var nsp in this.nsps) { if (has.call(this.nsps, nsp)) { this.nsps[nsp].emit.apply(this.nsps[nsp], arguments); } } }; /** * Update `socket.id` of all sockets * * @api private */ Manager.prototype.updateSocketIds = function () { for (var nsp in this.nsps) { if (has.call(this.nsps, nsp)) { this.nsps[nsp].id = this.engine.id; } } }; /** * Mix in `Emitter`. */ Emitter(Manager.prototype); /** * Sets the `reconnection` config. * * @param {Boolean} true/false if it should automatically reconnect * @return {Manager} self or value * @api public */ Manager.prototype.reconnection = function (v) { if (!arguments.length) return this._reconnection; this._reconnection = !!v; return this; }; /** * Sets the reconnection attempts config. * * @param {Number} max reconnection attempts before giving up * @return {Manager} self or value * @api public */ Manager.prototype.reconnectionAttempts = function (v) { if (!arguments.length) return this._reconnectionAttempts; this._reconnectionAttempts = v; return this; }; /** * Sets the delay between reconnections. * * @param {Number} delay * @return {Manager} self or value * @api public */ Manager.prototype.reconnectionDelay = function (v) { if (!arguments.length) return this._reconnectionDelay; this._reconnectionDelay = v; this.backoff && this.backoff.setMin(v); return this; }; Manager.prototype.randomizationFactor = function (v) { if (!arguments.length) return this._randomizationFactor; this._randomizationFactor = v; this.backoff && this.backoff.setJitter(v); return this; }; /** * Sets the maximum delay between reconnections. * * @param {Number} delay * @return {Manager} self or value * @api public */ Manager.prototype.reconnectionDelayMax = function (v) { if (!arguments.length) return this._reconnectionDelayMax; this._reconnectionDelayMax = v; this.backoff && this.backoff.setMax(v); return this; }; /** * Sets the connection timeout. `false` to disable * * @return {Manager} self or value * @api public */ Manager.prototype.timeout = function (v) { if (!arguments.length) return this._timeout; this._timeout = v; return this; }; /** * Starts trying to reconnect if reconnection is enabled and we have not * started reconnecting yet * * @api private */ Manager.prototype.maybeReconnectOnOpen = function () { // Only try to reconnect if it's the first time we're connecting if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) { // keeps reconnection from firing twice for the same reconnection loop this.reconnect(); } }; /** * Sets the current transport `socket`. * * @param {Function} optional, callback * @return {Manager} self * @api public */ Manager.prototype.open = Manager.prototype.connect = function (fn, opts) { debug('readyState %s', this.readyState); if (~this.readyState.indexOf('open')) return this; debug('opening %s', this.uri); this.engine = eio(this.uri, this.opts); var socket = this.engine; var self = this; this.readyState = 'opening'; this.skipReconnect = false; // emit `open` var openSub = on(socket, 'open', function () { self.onopen(); fn && fn(); }); // emit `connect_error` var errorSub = on(socket, 'error', function (data) { debug('connect_error'); self.cleanup(); self.readyState = 'closed'; self.emitAll('connect_error', data); if (fn) { var err = new Error('Connection error'); err.data = data; fn(err); } else { // Only do this if there is no fn to handle the error self.maybeReconnectOnOpen(); } }); // emit `connect_timeout` if (false !== this._timeout) { var timeout = this._timeout; debug('connect attempt will timeout after %d', timeout); // set timer var timer = setTimeout(function () { debug('connect attempt timed out after %d', timeout); openSub.destroy(); socket.close(); socket.emit('error', 'timeout'); self.emitAll('connect_timeout', timeout); }, timeout); this.subs.push({ destroy: function destroy() { clearTimeout(timer); } }); } this.subs.push(openSub); this.subs.push(errorSub); return this; }; /** * Called upon transport open. * * @api private */ Manager.prototype.onopen = function () { debug('open'); // clear old subs this.cleanup(); // mark as open this.readyState = 'open'; this.emit('open'); // add new subs var socket = this.engine; this.subs.push(on(socket, 'data', bind(this, 'ondata'))); this.subs.push(on(socket, 'ping', bind(this, 'onping'))); this.subs.push(on(socket, 'pong', bind(this, 'onpong'))); this.subs.push(on(socket, 'error', bind(this, 'onerror'))); this.subs.push(on(socket, 'close', bind(this, 'onclose'))); this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded'))); }; /** * Called upon a ping. * * @api private */ Manager.prototype.onping = function () { this.lastPing = new Date(); this.emitAll('ping'); }; /** * Called upon a packet. * * @api private */ Manager.prototype.onpong = function () { this.emitAll('pong', new Date() - this.lastPing); }; /** * Called with data. * * @api private */ Manager.prototype.ondata = function (data) { this.decoder.add(data); }; /** * Called when parser fully decodes a packet. * * @api private */ Manager.prototype.ondecoded = function (packet) { this.emit('packet', packet); }; /** * Called upon socket error. * * @api private */ Manager.prototype.onerror = function (err) { debug('error', err); this.emitAll('error', err); }; /** * Creates a new socket for the given `nsp`. * * @return {Socket} * @api public */ Manager.prototype.socket = function (nsp, opts) { var socket = this.nsps[nsp]; if (!socket) { socket = new Socket(this, nsp, opts); this.nsps[nsp] = socket; var self = this; socket.on('connecting', onConnecting); socket.on('connect', function () { socket.id = self.engine.id; }); if (this.autoConnect) { // manually call here since connecting evnet is fired before listening onConnecting(); } } function onConnecting() { if (!~indexOf(self.connecting, socket)) { self.connecting.push(socket); } } return socket; }; /** * Called upon a socket close. * * @param {Socket} socket */ Manager.prototype.destroy = function (socket) { var index = indexOf(this.connecting, socket); if (~index) this.connecting.splice(index, 1); if (this.connecting.length) return; this.close(); }; /** * Writes a packet. * * @param {Object} packet * @api private */ Manager.prototype.packet = function (packet) { debug('writing packet %j', packet); var self = this; if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query; if (!self.encoding) { // encode, then write to engine with result self.encoding = true; this.encoder.encode(packet, function (encodedPackets) { for (var i = 0; i < encodedPackets.length; i++) { self.engine.write(encodedPackets[i], packet.options); } self.encoding = false; self.processPacketQueue(); }); } else { // add packet to the queue self.packetBuffer.push(packet); } }; /** * If packet buffer is non-empty, begins encoding the * next packet in line. * * @api private */ Manager.prototype.processPacketQueue = function () { if (this.packetBuffer.length > 0 && !this.encoding) { var pack = this.packetBuffer.shift(); this.packet(pack); } }; /** * Clean up transport subscriptions and packet buffer. * * @api private */ Manager.prototype.cleanup = function () { debug('cleanup'); var subsLength = this.subs.length; for (var i = 0; i < subsLength; i++) { var sub = this.subs.shift(); sub.destroy(); } this.packetBuffer = []; this.encoding = false; this.lastPing = null; this.decoder.destroy(); }; /** * Close the current socket. * * @api private */ Manager.prototype.close = Manager.prototype.disconnect = function () { debug('disconnect'); this.skipReconnect = true; this.reconnecting = false; if ('opening' === this.readyState) { // `onclose` will not fire because // an open event never happened this.cleanup(); } this.backoff.reset(); this.readyState = 'closed'; if (this.engine) this.engine.close(); }; /** * Called upon engine close. * * @api private */ Manager.prototype.onclose = function (reason) { debug('onclose'); this.cleanup(); this.backoff.reset(); this.readyState = 'closed'; this.emit('close', reason); if (this._reconnection && !this.skipReconnect) { this.reconnect(); } }; /** * Attempt a reconnection. * * @api private */ Manager.prototype.reconnect = function () { if (this.reconnecting || this.skipReconnect) return this; var self = this; if (this.backoff.attempts >= this._reconnectionAttempts) { debug('reconnect failed'); this.backoff.reset(); this.emitAll('reconnect_failed'); this.reconnecting = false; } else { var delay = this.backoff.duration(); debug('will wait %dms before reconnect attempt', delay); this.reconnecting = true; var timer = setTimeout(function () { if (self.skipReconnect) return; debug('attempting reconnect'); self.emitAll('reconnect_attempt', self.backoff.attempts); self.emitAll('reconnecting', self.backoff.attempts); // check again for the case socket closed in above events if (self.skipReconnect) return; self.open(function (err) { if (err) { debug('reconnect attempt error'); self.reconnecting = false; self.reconnect(); self.emitAll('reconnect_error', err.data); } else { debug('reconnect success'); self.onreconnect(); } }); }, delay); this.subs.push({ destroy: function destroy() { clearTimeout(timer); } }); } }; /** * Called upon successful reconnect. * * @api private */ Manager.prototype.onreconnect = function () { var attempt = this.backoff.attempts; this.reconnecting = false; this.backoff.reset(); this.updateSocketIds(); this.emitAll('reconnect', attempt); }; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(19); /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(20); /** * Exports parser * * @api public * */ module.exports.parser = __webpack_require__(27); /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Module dependencies. */ var transports = __webpack_require__(21); var Emitter = __webpack_require__(35); var debug = __webpack_require__(3)('engine.io-client:socket'); var index = __webpack_require__(42); var parser = __webpack_require__(27); var parseuri = __webpack_require__(2); var parsejson = __webpack_require__(43); var parseqs = __webpack_require__(36); /** * Module exports. */ module.exports = Socket; /** * Socket constructor. * * @param {String|Object} uri or options * @param {Object} options * @api public */ function Socket (uri, opts) { if (!(this instanceof Socket)) return new Socket(uri, opts); opts = opts || {}; if (uri && 'object' === typeof uri) { opts = uri; uri = null; } if (uri) { uri = parseuri(uri); opts.hostname = uri.host; opts.secure = uri.protocol === 'https' || uri.protocol === 'wss'; opts.port = uri.port; if (uri.query) opts.query = uri.query; } else if (opts.host) { opts.hostname = parseuri(opts.host).host; } this.secure = null != opts.secure ? opts.secure : (global.location && 'https:' === location.protocol); if (opts.hostname && !opts.port) { // if no port is specified manually, use the protocol default opts.port = this.secure ? '443' : '80'; } this.agent = opts.agent || false; this.hostname = opts.hostname || (global.location ? location.hostname : 'localhost'); this.port = opts.port || (global.location && location.port ? location.port : (this.secure ? 443 : 80)); this.query = opts.query || {}; if ('string' === typeof this.query) this.query = parseqs.decode(this.query); this.upgrade = false !== opts.upgrade; this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/'; this.forceJSONP = !!opts.forceJSONP; this.jsonp = false !== opts.jsonp; this.forceBase64 = !!opts.forceBase64; this.enablesXDR = !!opts.enablesXDR; this.timestampParam = opts.timestampParam || 't'; this.timestampRequests = opts.timestampRequests; this.transports = opts.transports || ['polling', 'websocket']; this.readyState = ''; this.writeBuffer = []; this.prevBufferLen = 0; this.policyPort = opts.policyPort || 843; this.rememberUpgrade = opts.rememberUpgrade || false; this.binaryType = null; this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades; this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false; if (true === this.perMessageDeflate) this.perMessageDeflate = {}; if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) { this.perMessageDeflate.threshold = 1024; } // SSL options for Node.js client this.pfx = opts.pfx || null; this.key = opts.key || null; this.passphrase = opts.passphrase || null; this.cert = opts.cert || null; this.ca = opts.ca || null; this.ciphers = opts.ciphers || null; this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? null : opts.rejectUnauthorized; this.forceNode = !!opts.forceNode; // other options for Node.js client var freeGlobal = typeof global === 'object' && global; if (freeGlobal.global === freeGlobal) { if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) { this.extraHeaders = opts.extraHeaders; } if (opts.localAddress) { this.localAddress = opts.localAddress; } } // set on handshake this.id = null; this.upgrades = null; this.pingInterval = null; this.pingTimeout = null; // set on heartbeat this.pingIntervalTimer = null; this.pingTimeoutTimer = null; this.open(); } Socket.priorWebsocketSuccess = false; /** * Mix in `Emitter`. */ Emitter(Socket.prototype); /** * Protocol version. * * @api public */ Socket.protocol = parser.protocol; // this is an int /** * Expose deps for legacy compatibility * and standalone browser access. */ Socket.Socket = Socket; Socket.Transport = __webpack_require__(26); Socket.transports = __webpack_require__(21); Socket.parser = __webpack_require__(27); /** * Creates transport of the given type. * * @param {String} transport name * @return {Transport} * @api private */ Socket.prototype.createTransport = function (name) { debug('creating transport "%s"', name); var query = clone(this.query); // append engine.io protocol identifier query.EIO = parser.protocol; // transport name query.transport = name; // session id if we already have one if (this.id) query.sid = this.id; var transport = new transports[name]({ agent: this.agent, hostname: this.hostname, port: this.port, secure: this.secure, path: this.path, query: query, forceJSONP: this.forceJSONP, jsonp: this.jsonp, forceBase64: this.forceBase64, enablesXDR: this.enablesXDR, timestampRequests: this.timestampRequests, timestampParam: this.timestampParam, policyPort: this.policyPort, socket: this, pfx: this.pfx, key: this.key, passphrase: this.passphrase, cert: this.cert, ca: this.ca, ciphers: this.ciphers, rejectUnauthorized: this.rejectUnauthorized, perMessageDeflate: this.perMessageDeflate, extraHeaders: this.extraHeaders, forceNode: this.forceNode, localAddress: this.localAddress }); return transport; }; function clone (obj) { var o = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { o[i] = obj[i]; } } return o; } /** * Initializes transport to use and starts probe. * * @api private */ Socket.prototype.open = function () { var transport; if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) { transport = 'websocket'; } else if (0 === this.transports.length) { // Emit error on next tick so it can be listened to var self = this; setTimeout(function () { self.emit('error', 'No transports available'); }, 0); return; } else { transport = this.transports[0]; } this.readyState = 'opening'; // Retry with the next transport if the transport is disabled (jsonp: false) try { transport = this.createTransport(transport); } catch (e) { this.transports.shift(); this.open(); return; } transport.open(); this.setTransport(transport); }; /** * Sets the current transport. Disables the existing one (if any). * * @api private */ Socket.prototype.setTransport = function (transport) { debug('setting transport %s', transport.name); var self = this; if (this.transport) { debug('clearing existing transport %s', this.transport.name); this.transport.removeAllListeners(); } // set up transport this.transport = transport; // set up transport listeners transport .on('drain', function () { self.onDrain(); }) .on('packet', function (packet) { self.onPacket(packet); }) .on('error', function (e) { self.onError(e); }) .on('close', function () { self.onClose('transport close'); }); }; /** * Probes a transport. * * @param {String} transport name * @api private */ Socket.prototype.probe = function (name) { debug('probing transport "%s"', name); var transport = this.createTransport(name, { probe: 1 }); var failed = false; var self = this; Socket.priorWebsocketSuccess = false; function onTransportOpen () { if (self.onlyBinaryUpgrades) { var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; failed = failed || upgradeLosesBinary; } if (failed) return; debug('probe transport "%s" opened', name); transport.send([{ type: 'ping', data: 'probe' }]); transport.once('packet', function (msg) { if (failed) return; if ('pong' === msg.type && 'probe' === msg.data) { debug('probe transport "%s" pong', name); self.upgrading = true; self.emit('upgrading', transport); if (!transport) return; Socket.priorWebsocketSuccess = 'websocket' === transport.name; debug('pausing current transport "%s"', self.transport.name); self.transport.pause(function () { if (failed) return; if ('closed' === self.readyState) return; debug('changing transport and sending upgrade packet'); cleanup(); self.setTransport(transport); transport.send([{ type: 'upgrade' }]); self.emit('upgrade', transport); transport = null; self.upgrading = false; self.flush(); }); } else { debug('probe transport "%s" failed', name); var err = new Error('probe error'); err.transport = transport.name; self.emit('upgradeError', err); } }); } function freezeTransport () { if (failed) return; // Any callback called by transport should be ignored since now failed = true; cleanup(); transport.close(); transport = null; } // Handle any error that happens while probing function onerror (err) { var error = new Error('probe error: ' + err); error.transport = transport.name; freezeTransport(); debug('probe transport "%s" failed because of error: %s', name, err); self.emit('upgradeError', error); } function onTransportClose () { onerror('transport closed'); } // When the socket is closed while we're probing function onclose () { onerror('socket closed'); } // When the socket is upgraded while we're probing function onupgrade (to) { if (transport && to.name !== transport.name) { debug('"%s" works - aborting "%s"', to.name, transport.name); freezeTransport(); } } // Remove all listeners on the transport and on self function cleanup () { transport.removeListener('open', onTransportOpen); transport.removeListener('error', onerror); transport.removeListener('close', onTransportClose); self.removeListener('close', onclose); self.removeListener('upgrading', onupgrade); } transport.once('open', onTransportOpen); transport.once('error', onerror); transport.once('close', onTransportClose); this.once('close', onclose); this.once('upgrading', onupgrade); transport.open(); }; /** * Called when connection is deemed open. * * @api public */ Socket.prototype.onOpen = function () { debug('socket open'); this.readyState = 'open'; Socket.priorWebsocketSuccess = 'websocket' === this.transport.name; this.emit('open'); this.flush(); // we check for `readyState` in case an `open` // listener already closed the socket if ('open' === this.readyState && this.upgrade && this.transport.pause) { debug('starting upgrade probes'); for (var i = 0, l = this.upgrades.length; i < l; i++) { this.probe(this.upgrades[i]); } } }; /** * Handles a packet. * * @api private */ Socket.prototype.onPacket = function (packet) { if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { debug('socket receive: type "%s", data "%s"', packet.type, packet.data); this.emit('packet', packet); // Socket is live - any packet counts this.emit('heartbeat'); switch (packet.type) { case 'open': this.onHandshake(parsejson(packet.data)); break; case 'pong': this.setPing(); this.emit('pong'); break; case 'error': var err = new Error('server error'); err.code = packet.data; this.onError(err); break; case 'message': this.emit('data', packet.data); this.emit('message', packet.data); break; } } else { debug('packet received with socket readyState "%s"', this.readyState); } }; /** * Called upon handshake completion. * * @param {Object} handshake obj * @api private */ Socket.prototype.onHandshake = function (data) { this.emit('handshake', data); this.id = data.sid; this.transport.query.sid = data.sid; this.upgrades = this.filterUpgrades(data.upgrades); this.pingInterval = data.pingInterval; this.pingTimeout = data.pingTimeout; this.onOpen(); // In case open handler closes socket if ('closed' === this.readyState) return; this.setPing(); // Prolong liveness of socket on heartbeat this.removeListener('heartbeat', this.onHeartbeat); this.on('heartbeat', this.onHeartbeat); }; /** * Resets ping timeout. * * @api private */ Socket.prototype.onHeartbeat = function (timeout) { clearTimeout(this.pingTimeoutTimer); var self = this; self.pingTimeoutTimer = setTimeout(function () { if ('closed' === self.readyState) return; self.onClose('ping timeout'); }, timeout || (self.pingInterval + self.pingTimeout)); }; /** * Pings server every `this.pingInterval` and expects response * within `this.pingTimeout` or closes connection. * * @api private */ Socket.prototype.setPing = function () { var self = this; clearTimeout(self.pingIntervalTimer); self.pingIntervalTimer = setTimeout(function () { debug('writing ping packet - expecting pong within %sms', self.pingTimeout); self.ping(); self.onHeartbeat(self.pingTimeout); }, self.pingInterval); }; /** * Sends a ping packet. * * @api private */ Socket.prototype.ping = function () { var self = this; this.sendPacket('ping', function () { self.emit('ping'); }); }; /** * Called on `drain` event * * @api private */ Socket.prototype.onDrain = function () { this.writeBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important // for example, when upgrading, upgrade packet is sent over, // and a nonzero prevBufferLen could cause problems on `drain` this.prevBufferLen = 0; if (0 === this.writeBuffer.length) { this.emit('drain'); } else { this.flush(); } }; /** * Flush write buffers. * * @api private */ Socket.prototype.flush = function () { if ('closed' !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) { debug('flushing %d packets in socket', this.writeBuffer.length); this.transport.send(this.writeBuffer); // keep track of current length of writeBuffer // splice writeBuffer and callbackBuffer on `drain` this.prevBufferLen = this.writeBuffer.length; this.emit('flush'); } }; /** * Sends a message. * * @param {String} message. * @param {Function} callback function. * @param {Object} options. * @return {Socket} for chaining. * @api public */ Socket.prototype.write = Socket.prototype.send = function (msg, options, fn) { this.sendPacket('message', msg, options, fn); return this; }; /** * Sends a packet. * * @param {String} packet type. * @param {String} data. * @param {Object} options. * @param {Function} callback function. * @api private */ Socket.prototype.sendPacket = function (type, data, options, fn) { if ('function' === typeof data) { fn = data; data = undefined; } if ('function' === typeof options) { fn = options; options = null; } if ('closing' === this.readyState || 'closed' === this.readyState) { return; } options = options || {}; options.compress = false !== options.compress; var packet = { type: type, data: data, options: options }; this.emit('packetCreate', packet); this.writeBuffer.push(packet); if (fn) this.once('flush', fn); this.flush(); }; /** * Closes the connection. * * @api private */ Socket.prototype.close = function () { if ('opening' === this.readyState || 'open' === this.readyState) { this.readyState = 'closing'; var self = this; if (this.writeBuffer.length) { this.once('drain', function () { if (this.upgrading) { waitForUpgrade(); } else { close(); } }); } else if (this.upgrading) { waitForUpgrade(); } else { close(); } } function close () { self.onClose('forced close'); debug('socket closing - telling transport to close'); self.transport.close(); } function cleanupAndClose () { self.removeListener('upgrade', cleanupAndClose); self.removeListener('upgradeError', cleanupAndClose); close(); } function waitForUpgrade () { // wait for upgrade to finish since we can't send packets while pausing a transport self.once('upgrade', cleanupAndClose); self.once('upgradeError', cleanupAndClose); } return this; }; /** * Called upon transport error * * @api private */ Socket.prototype.onError = function (err) { debug('socket error %j', err); Socket.priorWebsocketSuccess = false; this.emit('error', err); this.onClose('transport error', err); }; /** * Called upon transport close. * * @api private */ Socket.prototype.onClose = function (reason, desc) { if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { debug('socket close with reason: "%s"', reason); var self = this; // clear timers clearTimeout(this.pingIntervalTimer); clearTimeout(this.pingTimeoutTimer); // stop event from firing again for transport this.transport.removeAllListeners('close'); // ensure transport won't stay open this.transport.close(); // ignore further transport communication this.transport.removeAllListeners(); // set ready state this.readyState = 'closed'; // clear session id this.id = null; // emit close event this.emit('close', reason, desc); // clean buffers after, so users can still // grab the buffers on `close` event self.writeBuffer = []; self.prevBufferLen = 0; } }; /** * Filters upgrades, returning only those matching client transports. * * @param {Array} server upgrades * @api private * */ Socket.prototype.filterUpgrades = function (upgrades) { var filteredUpgrades = []; for (var i = 0, j = upgrades.length; i < j; i++) { if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]); } return filteredUpgrades; }; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Module dependencies */ var XMLHttpRequest = __webpack_require__(22); var XHR = __webpack_require__(24); var JSONP = __webpack_require__(39); var websocket = __webpack_require__(40); /** * Export transports. */ exports.polling = polling; exports.websocket = websocket; /** * Polling transport polymorphic constructor. * Decides on xhr vs jsonp based on feature detection. * * @api private */ function polling (opts) { var xhr; var xd = false; var xs = false; var jsonp = false !== opts.jsonp; if (global.location) { var isSSL = 'https:' === location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } xd = opts.hostname !== location.hostname || port !== opts.port; xs = opts.secure !== isSSL; } opts.xdomain = xd; opts.xscheme = xs; xhr = new XMLHttpRequest(opts); if ('open' in xhr && !opts.forceJSONP) { return new XHR(opts); } else { if (!jsonp) throw new Error('JSONP disabled'); return new JSONP(opts); } } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {// browser shim for xmlhttprequest module var hasCORS = __webpack_require__(23); module.exports = function (opts) { var xdomain = opts.xdomain; // scheme must be same when usign XDomainRequest // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx var xscheme = opts.xscheme; // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default. // https://github.com/Automattic/engine.io-client/pull/217 var enablesXDR = opts.enablesXDR; // XMLHttpRequest can be disabled on IE try { if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) { return new XMLHttpRequest(); } } catch (e) { } // Use XDomainRequest for IE8 if enablesXDR is true // because loading bar keeps flashing when using jsonp-polling // https://github.com/yujiosaka/socke.io-ie8-loading-example try { if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) { return new XDomainRequest(); } } catch (e) { } if (!xdomain) { try { return new global[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP'); } catch (e) { } } }; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 23 */ /***/ function(module, exports) { /** * Module exports. * * Logic borrowed from Modernizr: * * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js */ try { module.exports = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest(); } catch (err) { // if XMLHttp support is disabled in IE then it will throw // when trying to create module.exports = false; } /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Module requirements. */ var XMLHttpRequest = __webpack_require__(22); var Polling = __webpack_require__(25); var Emitter = __webpack_require__(35); var inherit = __webpack_require__(37); var debug = __webpack_require__(3)('engine.io-client:polling-xhr'); /** * Module exports. */ module.exports = XHR; module.exports.Request = Request; /** * Empty function */ function empty () {} /** * XHR Polling constructor. * * @param {Object} opts * @api public */ function XHR (opts) { Polling.call(this, opts); this.requestTimeout = opts.requestTimeout; if (global.location) { var isSSL = 'https:' === location.protocol; var port = location.port; // some user agents have empty `location.port` if (!port) { port = isSSL ? 443 : 80; } this.xd = opts.hostname !== global.location.hostname || port !== opts.port; this.xs = opts.secure !== isSSL; } else { this.extraHeaders = opts.extraHeaders; } } /** * Inherits from Polling. */ inherit(XHR, Polling); /** * XHR supports binary */ XHR.prototype.supportsBinary = true; /** * Creates a request. * * @param {String} method * @api private */ XHR.prototype.request = function (opts) { opts = opts || {}; opts.uri = this.uri(); opts.xd = this.xd; opts.xs = this.xs; opts.agent = this.agent || false; opts.supportsBinary = this.supportsBinary; opts.enablesXDR = this.enablesXDR; // SSL options for Node.js client opts.pfx = this.pfx; opts.key = this.key; opts.passphrase = this.passphrase; opts.cert = this.cert; opts.ca = this.ca; opts.ciphers = this.ciphers; opts.rejectUnauthorized = this.rejectUnauthorized; opts.requestTimeout = this.requestTimeout; // other options for Node.js client opts.extraHeaders = this.extraHeaders; return new Request(opts); }; /** * Sends data. * * @param {String} data to send. * @param {Function} called upon flush. * @api private */ XHR.prototype.doWrite = function (data, fn) { var isBinary = typeof data !== 'string' && data !== undefined; var req = this.request({ method: 'POST', data: data, isBinary: isBinary }); var self = this; req.on('success', fn); req.on('error', function (err) { self.onError('xhr post error', err); }); this.sendXhr = req; }; /** * Starts a poll cycle. * * @api private */ XHR.prototype.doPoll = function () { debug('xhr poll'); var req = this.request(); var self = this; req.on('data', function (data) { self.onData(data); }); req.on('error', function (err) { self.onError('xhr poll error', err); }); this.pollXhr = req; }; /** * Request constructor * * @param {Object} options * @api public */ function Request (opts) { this.method = opts.method || 'GET'; this.uri = opts.uri; this.xd = !!opts.xd; this.xs = !!opts.xs; this.async = false !== opts.async; this.data = undefined !== opts.data ? opts.data : null; this.agent = opts.agent; this.isBinary = opts.isBinary; this.supportsBinary = opts.supportsBinary; this.enablesXDR = opts.enablesXDR; this.requestTimeout = opts.requestTimeout; // SSL options for Node.js client this.pfx = opts.pfx; this.key = opts.key; this.passphrase = opts.passphrase; this.cert = opts.cert; this.ca = opts.ca; this.ciphers = opts.ciphers; this.rejectUnauthorized = opts.rejectUnauthorized; // other options for Node.js client this.extraHeaders = opts.extraHeaders; this.create(); } /** * Mix in `Emitter`. */ Emitter(Request.prototype); /** * Creates the XHR object and sends the request. * * @api private */ Request.prototype.create = function () { var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR }; // SSL options for Node.js client opts.pfx = this.pfx; opts.key = this.key; opts.passphrase = this.passphrase; opts.cert = this.cert; opts.ca = this.ca; opts.ciphers = this.ciphers; opts.rejectUnauthorized = this.rejectUnauthorized; var xhr = this.xhr = new XMLHttpRequest(opts); var self = this; try { debug('xhr open %s: %s', this.method, this.uri); xhr.open(this.method, this.uri, this.async); try { if (this.extraHeaders) { xhr.setDisableHeaderCheck(true); for (var i in this.extraHeaders) { if (this.extraHeaders.hasOwnProperty(i)) { xhr.setRequestHeader(i, this.extraHeaders[i]); } } } } catch (e) {} if (this.supportsBinary) { // This has to be done after open because Firefox is stupid // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension xhr.responseType = 'arraybuffer'; } if ('POST' === this.method) { try { if (this.isBinary) { xhr.setRequestHeader('Content-type', 'application/octet-stream'); } else { xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8'); } } catch (e) {} } try { xhr.setRequestHeader('Accept', '*/*'); } catch (e) {} // ie6 check if ('withCredentials' in xhr) { xhr.withCredentials = true; } if (this.requestTimeout) { xhr.timeout = this.requestTimeout; } if (this.hasXDR()) { xhr.onload = function () { self.onLoad(); }; xhr.onerror = function () { self.onError(xhr.responseText); }; } else { xhr.onreadystatechange = function () { if (4 !== xhr.readyState) return; if (200 === xhr.status || 1223 === xhr.status) { self.onLoad(); } else { // make sure the `error` event handler that's user-set // does not throw in the same tick and gets caught here setTimeout(function () { self.onError(xhr.status); }, 0); } }; } debug('xhr data %s', this.data); xhr.send(this.data); } catch (e) { // Need to defer since .create() is called directly fhrom the constructor // and thus the 'error' event can only be only bound *after* this exception // occurs. Therefore, also, we cannot throw here at all. setTimeout(function () { self.onError(e); }, 0); return; } if (global.document) { this.index = Request.requestsCount++; Request.requests[this.index] = this; } }; /** * Called upon successful response. * * @api private */ Request.prototype.onSuccess = function () { this.emit('success'); this.cleanup(); }; /** * Called if we have data. * * @api private */ Request.prototype.onData = function (data) { this.emit('data', data); this.onSuccess(); }; /** * Called upon error. * * @api private */ Request.prototype.onError = function (err) { this.emit('error', err); this.cleanup(true); }; /** * Cleans up house. * * @api private */ Request.prototype.cleanup = function (fromError) { if ('undefined' === typeof this.xhr || null === this.xhr) { return; } // xmlhttprequest if (this.hasXDR()) { this.xhr.onload = this.xhr.onerror = empty; } else { this.xhr.onreadystatechange = empty; } if (fromError) { try { this.xhr.abort(); } catch (e) {} } if (global.document) { delete Request.requests[this.index]; } this.xhr = null; }; /** * Called upon load. * * @api private */ Request.prototype.onLoad = function () { var data; try { var contentType; try { contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0]; } catch (e) {} if (contentType === 'application/octet-stream') { data = this.xhr.response || this.xhr.responseText; } else { if (!this.supportsBinary) { data = this.xhr.responseText; } else { try { data = String.fromCharCode.apply(null, new Uint8Array(this.xhr.response)); } catch (e) { var ui8Arr = new Uint8Array(this.xhr.response); var dataArray = []; for (var idx = 0, length = ui8Arr.length; idx < length; idx++) { dataArray.push(ui8Arr[idx]); } data = String.fromCharCode.apply(null, dataArray); } } } } catch (e) { this.onError(e); } if (null != data) { this.onData(data); } }; /** * Check if it has XDomainRequest. * * @api private */ Request.prototype.hasXDR = function () { return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR; }; /** * Aborts the request. * * @api public */ Request.prototype.abort = function () { this.cleanup(); }; /** * Aborts pending requests when unloading the window. This is needed to prevent * memory leaks (e.g. when using IE) and to ensure that no spurious error is * emitted. */ Request.requestsCount = 0; Request.requests = {}; if (global.document) { if (global.attachEvent) { global.attachEvent('onunload', unloadHandler); } else if (global.addEventListener) { global.addEventListener('beforeunload', unloadHandler, false); } } function unloadHandler () { for (var i in Request.requests) { if (Request.requests.hasOwnProperty(i)) { Request.requests[i].abort(); } } } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { /** * Module dependencies. */ var Transport = __webpack_require__(26); var parseqs = __webpack_require__(36); var parser = __webpack_require__(27); var inherit = __webpack_require__(37); var yeast = __webpack_require__(38); var debug = __webpack_require__(3)('engine.io-client:polling'); /** * Module exports. */ module.exports = Polling; /** * Is XHR2 supported? */ var hasXHR2 = (function () { var XMLHttpRequest = __webpack_require__(22); var xhr = new XMLHttpRequest({ xdomain: false }); return null != xhr.responseType; })(); /** * Polling interface. * * @param {Object} opts * @api private */ function Polling (opts) { var forceBase64 = (opts && opts.forceBase64); if (!hasXHR2 || forceBase64) { this.supportsBinary = false; } Transport.call(this, opts); } /** * Inherits from Transport. */ inherit(Polling, Transport); /** * Transport name. */ Polling.prototype.name = 'polling'; /** * Opens the socket (triggers polling). We write a PING message to determine * when the transport is open. * * @api private */ Polling.prototype.doOpen = function () { this.poll(); }; /** * Pauses polling. * * @param {Function} callback upon buffers are flushed and transport is paused * @api private */ Polling.prototype.pause = function (onPause) { var self = this; this.readyState = 'pausing'; function pause () { debug('paused'); self.readyState = 'paused'; onPause(); } if (this.polling || !this.writable) { var total = 0; if (this.polling) { debug('we are currently polling - waiting to pause'); total++; this.once('pollComplete', function () { debug('pre-pause polling complete'); --total || pause(); }); } if (!this.writable) { debug('we are currently writing - waiting to pause'); total++; this.once('drain', function () { debug('pre-pause writing complete'); --total || pause(); }); } } else { pause(); } }; /** * Starts polling cycle. * * @api public */ Polling.prototype.poll = function () { debug('polling'); this.polling = true; this.doPoll(); this.emit('poll'); }; /** * Overloads onData to detect payloads. * * @api private */ Polling.prototype.onData = function (data) { var self = this; debug('polling got data %s', data); var callback = function (packet, index, total) { // if its the first message we consider the transport open if ('opening' === self.readyState) { self.onOpen(); } // if its a close packet, we close the ongoing requests if ('close' === packet.type) { self.onClose(); return false; } // otherwise bypass onData and handle the message self.onPacket(packet); }; // decode payload parser.decodePayload(data, this.socket.binaryType, callback); // if an event did not trigger closing if ('closed' !== this.readyState) { // if we got data we're not polling this.polling = false; this.emit('pollComplete'); if ('open' === this.readyState) { this.poll(); } else { debug('ignoring poll - transport state "%s"', this.readyState); } } }; /** * For polling, send a close packet. * * @api private */ Polling.prototype.doClose = function () { var self = this; function close () { debug('writing close packet'); self.write([{ type: 'close' }]); } if ('open' === this.readyState) { debug('transport open - closing'); close(); } else { // in case we're trying to close while // handshaking is in progress (GH-164) debug('transport not open - deferring close'); this.once('open', close); } }; /** * Writes a packets payload. * * @param {Array} data packets * @param {Function} drain callback * @api private */ Polling.prototype.write = function (packets) { var self = this; this.writable = false; var callbackfn = function () { self.writable = true; self.emit('drain'); }; parser.encodePayload(packets, this.supportsBinary, function (data) { self.doWrite(data, callbackfn); }); }; /** * Generates uri for connection. * * @api private */ Polling.prototype.uri = function () { var query = this.query || {}; var schema = this.secure ? 'https' : 'http'; var port = ''; // cache busting is forced if (false !== this.timestampRequests) { query[this.timestampParam] = yeast(); } if (!this.supportsBinary && !query.sid) { query.b64 = 1; } query = parseqs.encode(query); // avoid port if default for schema if (this.port && (('https' === schema && Number(this.port) !== 443) || ('http' === schema && Number(this.port) !== 80))) { port = ':' + this.port; } // prepend ? to query if (query.length) { query = '?' + query; } var ipv6 = this.hostname.indexOf(':') !== -1; return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query; }; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { /** * Module dependencies. */ var parser = __webpack_require__(27); var Emitter = __webpack_require__(35); /** * Module exports. */ module.exports = Transport; /** * Transport abstract constructor. * * @param {Object} options. * @api private */ function Transport (opts) { this.path = opts.path; this.hostname = opts.hostname; this.port = opts.port; this.secure = opts.secure; this.query = opts.query; this.timestampParam = opts.timestampParam; this.timestampRequests = opts.timestampRequests; this.readyState = ''; this.agent = opts.agent || false; this.socket = opts.socket; this.enablesXDR = opts.enablesXDR; // SSL options for Node.js client this.pfx = opts.pfx; this.key = opts.key; this.passphrase = opts.passphrase; this.cert = opts.cert; this.ca = opts.ca; this.ciphers = opts.ciphers; this.rejectUnauthorized = opts.rejectUnauthorized; this.forceNode = opts.forceNode; // other options for Node.js client this.extraHeaders = opts.extraHeaders; this.localAddress = opts.localAddress; } /** * Mix in `Emitter`. */ Emitter(Transport.prototype); /** * Emits an error. * * @param {String} str * @return {Transport} for chaining * @api public */ Transport.prototype.onError = function (msg, desc) { var err = new Error(msg); err.type = 'TransportError'; err.description = desc; this.emit('error', err); return this; }; /** * Opens the transport. * * @api public */ Transport.prototype.open = function () { if ('closed' === this.readyState || '' === this.readyState) { this.readyState = 'opening'; this.doOpen(); } return this; }; /** * Closes the transport. * * @api private */ Transport.prototype.close = function () { if ('opening' === this.readyState || 'open' === this.readyState) { this.doClose(); this.onClose(); } return this; }; /** * Sends multiple packets. * * @param {Array} packets * @api private */ Transport.prototype.send = function (packets) { if ('open' === this.readyState) { this.write(packets); } else { throw new Error('Transport not open'); } }; /** * Called upon open * * @api private */ Transport.prototype.onOpen = function () { this.readyState = 'open'; this.writable = true; this.emit('open'); }; /** * Called with data. * * @param {String} data * @api private */ Transport.prototype.onData = function (data) { var packet = parser.decodePacket(data, this.socket.binaryType); this.onPacket(packet); }; /** * Called with a decoded packet. */ Transport.prototype.onPacket = function (packet) { this.emit('packet', packet); }; /** * Called upon close. * * @api private */ Transport.prototype.onClose = function () { this.readyState = 'closed'; this.emit('close'); }; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Module dependencies. */ var keys = __webpack_require__(28); var hasBinary = __webpack_require__(29); var sliceBuffer = __webpack_require__(30); var after = __webpack_require__(31); var utf8 = __webpack_require__(32); var base64encoder; if (global && global.ArrayBuffer) { base64encoder = __webpack_require__(33); } /** * Check if we are running an android browser. That requires us to use * ArrayBuffer with polling transports... * * http://ghinda.net/jpeg-blob-ajax-android/ */ var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent); /** * Check if we are running in PhantomJS. * Uploading a Blob with PhantomJS does not work correctly, as reported here: * https://github.com/ariya/phantomjs/issues/11395 * @type boolean */ var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent); /** * When true, avoids using Blobs to encode payloads. * @type boolean */ var dontSendBlobs = isAndroid || isPhantomJS; /** * Current protocol version. */ exports.protocol = 3; /** * Packet types. */ var packets = exports.packets = { open: 0 // non-ws , close: 1 // non-ws , ping: 2 , pong: 3 , message: 4 , upgrade: 5 , noop: 6 }; var packetslist = keys(packets); /** * Premade error packet. */ var err = { type: 'error', data: 'parser error' }; /** * Create a blob api even for blob builder when vendor prefixes exist */ var Blob = __webpack_require__(34); /** * Encodes a packet. * * <packet type id> [ <data> ] * * Example: * * 5hello world * 3 * 4 * * Binary is encoded in an identical principle * * @api private */ exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) { if ('function' == typeof supportsBinary) { callback = supportsBinary; supportsBinary = false; } if ('function' == typeof utf8encode) { callback = utf8encode; utf8encode = null; } var data = (packet.data === undefined) ? undefined : packet.data.buffer || packet.data; if (global.ArrayBuffer && data instanceof ArrayBuffer) { return encodeArrayBuffer(packet, supportsBinary, callback); } else if (Blob && data instanceof global.Blob) { return encodeBlob(packet, supportsBinary, callback); } // might be an object with { base64: true, data: dataAsBase64String } if (data && data.base64) { return encodeBase64Object(packet, callback); } // Sending data as a utf-8 string var encoded = packets[packet.type]; // data fragment is optional if (undefined !== packet.data) { encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data); } return callback('' + encoded); }; function encodeBase64Object(packet, callback) { // packet data is an object { base64: true, data: dataAsBase64String } var message = 'b' + exports.packets[packet.type] + packet.data.data; return callback(message); } /** * Encode packet helpers for binary types */ function encodeArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var data = packet.data; var contentArray = new Uint8Array(data); var resultBuffer = new Uint8Array(1 + data.byteLength); resultBuffer[0] = packets[packet.type]; for (var i = 0; i < contentArray.length; i++) { resultBuffer[i+1] = contentArray[i]; } return callback(resultBuffer.buffer); } function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } var fr = new FileReader(); fr.onload = function() { packet.data = fr.result; exports.encodePacket(packet, supportsBinary, true, callback); }; return fr.readAsArrayBuffer(packet.data); } function encodeBlob(packet, supportsBinary, callback) { if (!supportsBinary) { return exports.encodeBase64Packet(packet, callback); } if (dontSendBlobs) { return encodeBlobAsArrayBuffer(packet, supportsBinary, callback); } var length = new Uint8Array(1); length[0] = packets[packet.type]; var blob = new Blob([length.buffer, packet.data]); return callback(blob); } /** * Encodes a packet with binary data in a base64 string * * @param {Object} packet, has `type` and `data` * @return {String} base64 encoded message */ exports.encodeBase64Packet = function(packet, callback) { var message = 'b' + exports.packets[packet.type]; if (Blob && packet.data instanceof global.Blob) { var fr = new FileReader(); fr.onload = function() { var b64 = fr.result.split(',')[1]; callback(message + b64); }; return fr.readAsDataURL(packet.data); } var b64data; try { b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data)); } catch (e) { // iPhone Safari doesn't let you apply with typed arrays var typed = new Uint8Array(packet.data); var basic = new Array(typed.length); for (var i = 0; i < typed.length; i++) { basic[i] = typed[i]; } b64data = String.fromCharCode.apply(null, basic); } message += global.btoa(b64data); return callback(message); }; /** * Decodes a packet. Changes format to Blob if requested. * * @return {Object} with `type` and `data` (if any) * @api private */ exports.decodePacket = function (data, binaryType, utf8decode) { if (data === undefined) { return err; } // String data if (typeof data == 'string') { if (data.charAt(0) == 'b') { return exports.decodeBase64Packet(data.substr(1), binaryType); } if (utf8decode) { data = tryDecode(data); if (data === false) { return err; } } var type = data.charAt(0); if (Number(type) != type || !packetslist[type]) { return err; } if (data.length > 1) { return { type: packetslist[type], data: data.substring(1) }; } else { return { type: packetslist[type] }; } } var asArray = new Uint8Array(data); var type = asArray[0]; var rest = sliceBuffer(data, 1); if (Blob && binaryType === 'blob') { rest = new Blob([rest]); } return { type: packetslist[type], data: rest }; }; function tryDecode(data) { try { data = utf8.decode(data); } catch (e) { return false; } return data; } /** * Decodes a packet encoded in a base64 string * * @param {String} base64 encoded message * @return {Object} with `type` and `data` (if any) */ exports.decodeBase64Packet = function(msg, binaryType) { var type = packetslist[msg.charAt(0)]; if (!base64encoder) { return { type: type, data: { base64: true, data: msg.substr(1) } }; } var data = base64encoder.decode(msg.substr(1)); if (binaryType === 'blob' && Blob) { data = new Blob([data]); } return { type: type, data: data }; }; /** * Encodes multiple messages (payload). * * <length>:data * * Example: * * 11:hello world2:hi * * If any contents are binary, they will be encoded as base64 strings. Base64 * encoded strings are marked with a b before the length specifier * * @param {Array} packets * @api private */ exports.encodePayload = function (packets, supportsBinary, callback) { if (typeof supportsBinary == 'function') { callback = supportsBinary; supportsBinary = null; } var isBinary = hasBinary(packets); if (supportsBinary && isBinary) { if (Blob && !dontSendBlobs) { return exports.encodePayloadAsBlob(packets, callback); } return exports.encodePayloadAsArrayBuffer(packets, callback); } if (!packets.length) { return callback('0:'); } function setLengthHeader(message) { return message.length + ':' + message; } function encodeOne(packet, doneCallback) { exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) { doneCallback(null, setLengthHeader(message)); }); } map(packets, encodeOne, function(err, results) { return callback(results.join('')); }); }; /** * Async array map using after */ function map(ary, each, done) { var result = new Array(ary.length); var next = after(ary.length, done); var eachWithIndex = function(i, el, cb) { each(el, function(error, msg) { result[i] = msg; cb(error, result); }); }; for (var i = 0; i < ary.length; i++) { eachWithIndex(i, ary[i], next); } } /* * Decodes data when a payload is maybe expected. Possible binary contents are * decoded from their base64 representation * * @param {String} data, callback method * @api public */ exports.decodePayload = function (data, binaryType, callback) { if (typeof data != 'string') { return exports.decodePayloadAsBinary(data, binaryType, callback); } if (typeof binaryType === 'function') { callback = binaryType; binaryType = null; } var packet; if (data == '') { // parser error - ignoring payload return callback(err, 0, 1); } var length = '' , n, msg; for (var i = 0, l = data.length; i < l; i++) { var chr = data.charAt(i); if (':' != chr) { length += chr; } else { if ('' == length || (length != (n = Number(length)))) { // parser error - ignoring payload return callback(err, 0, 1); } msg = data.substr(i + 1, n); if (length != msg.length) { // parser error - ignoring payload return callback(err, 0, 1); } if (msg.length) { packet = exports.decodePacket(msg, binaryType, true); if (err.type == packet.type && err.data == packet.data) { // parser error in individual packet - ignoring payload return callback(err, 0, 1); } var ret = callback(packet, i + n, l); if (false === ret) return; } // advance cursor i += n; length = ''; } } if (length != '') { // parser error - ignoring payload return callback(err, 0, 1); } }; /** * Encodes multiple messages (payload) as binary. * * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number * 255><data> * * Example: * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers * * @param {Array} packets * @return {ArrayBuffer} encoded payload * @api private */ exports.encodePayloadAsArrayBuffer = function(packets, callback) { if (!packets.length) { return callback(new ArrayBuffer(0)); } function encodeOne(packet, doneCallback) { exports.encodePacket(packet, true, true, function(data) { return doneCallback(null, data); }); } map(packets, encodeOne, function(err, encodedPackets) { var totalLength = encodedPackets.reduce(function(acc, p) { var len; if (typeof p === 'string'){ len = p.length; } else { len = p.byteLength; } return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2 }, 0); var resultArray = new Uint8Array(totalLength); var bufferIndex = 0; encodedPackets.forEach(function(p) { var isString = typeof p === 'string'; var ab = p; if (isString) { var view = new Uint8Array(p.length); for (var i = 0; i < p.length; i++) { view[i] = p.charCodeAt(i); } ab = view.buffer; } if (isString) { // not true binary resultArray[bufferIndex++] = 0; } else { // true binary resultArray[bufferIndex++] = 1; } var lenStr = ab.byteLength.toString(); for (var i = 0; i < lenStr.length; i++) { resultArray[bufferIndex++] = parseInt(lenStr[i]); } resultArray[bufferIndex++] = 255; var view = new Uint8Array(ab); for (var i = 0; i < view.length; i++) { resultArray[bufferIndex++] = view[i]; } }); return callback(resultArray.buffer); }); }; /** * Encode as Blob */ exports.encodePayloadAsBlob = function(packets, callback) { function encodeOne(packet, doneCallback) { exports.encodePacket(packet, true, true, function(encoded) { var binaryIdentifier = new Uint8Array(1); binaryIdentifier[0] = 1; if (typeof encoded === 'string') { var view = new Uint8Array(encoded.length); for (var i = 0; i < encoded.length; i++) { view[i] = encoded.charCodeAt(i); } encoded = view.buffer; binaryIdentifier[0] = 0; } var len = (encoded instanceof ArrayBuffer) ? encoded.byteLength : encoded.size; var lenStr = len.toString(); var lengthAry = new Uint8Array(lenStr.length + 1); for (var i = 0; i < lenStr.length; i++) { lengthAry[i] = parseInt(lenStr[i]); } lengthAry[lenStr.length] = 255; if (Blob) { var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]); doneCallback(null, blob); } }); } map(packets, encodeOne, function(err, results) { return callback(new Blob(results)); }); }; /* * Decodes data when a payload is maybe expected. Strings are decoded by * interpreting each byte as a key code for entries marked to start with 0. See * description of encodePayloadAsBinary * * @param {ArrayBuffer} data, callback method * @api public */ exports.decodePayloadAsBinary = function (data, binaryType, callback) { if (typeof binaryType === 'function') { callback = binaryType; binaryType = null; } var bufferTail = data; var buffers = []; var numberTooLong = false; while (bufferTail.byteLength > 0) { var tailArray = new Uint8Array(bufferTail); var isString = tailArray[0] === 0; var msgLength = ''; for (var i = 1; ; i++) { if (tailArray[i] == 255) break; if (msgLength.length > 310) { numberTooLong = true; break; } msgLength += tailArray[i]; } if(numberTooLong) return callback(err, 0, 1); bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length); msgLength = parseInt(msgLength); var msg = sliceBuffer(bufferTail, 0, msgLength); if (isString) { try { msg = String.fromCharCode.apply(null, new Uint8Array(msg)); } catch (e) { // iPhone Safari doesn't let you apply to typed arrays var typed = new Uint8Array(msg); msg = ''; for (var i = 0; i < typed.length; i++) { msg += String.fromCharCode(typed[i]); } } } buffers.push(msg); bufferTail = sliceBuffer(bufferTail, msgLength); } var total = buffers.length; buffers.forEach(function(buffer, i) { callback(exports.decodePacket(buffer, binaryType, true), i, total); }); }; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 28 */ /***/ function(module, exports) { /** * Gets the keys for an object. * * @return {Array} keys * @api private */ module.exports = Object.keys || function keys (obj){ var arr = []; var has = Object.prototype.hasOwnProperty; for (var i in obj) { if (has.call(obj, i)) { arr.push(i); } } return arr; }; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) { /* * Module requirements. */ var isArray = __webpack_require__(15); /** * Module exports. */ module.exports = hasBinary; /** * Checks for binary data. * * Right now only Buffer and ArrayBuffer are supported.. * * @param {Object} anything * @api public */ function hasBinary(data) { function _hasBinary(obj) { if (!obj) return false; if ( (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) || (global.ArrayBuffer && obj instanceof ArrayBuffer) || (global.Blob && obj instanceof Blob) || (global.File && obj instanceof File) ) { return true; } if (isArray(obj)) { for (var i = 0; i < obj.length; i++) { if (_hasBinary(obj[i])) { return true; } } } else if (obj && 'object' == typeof obj) { // see: https://github.com/Automattic/has-binary/pull/4 if (obj.toJSON && 'function' == typeof obj.toJSON) { obj = obj.toJSON(); } for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) { return true; } } } return false; } return _hasBinary(data); } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 30 */ /***/ function(module, exports) { /** * An abstraction for slicing an arraybuffer even when * ArrayBuffer.prototype.slice is not supported * * @api public */ module.exports = function(arraybuffer, start, end) { var bytes = arraybuffer.byteLength; start = start || 0; end = end || bytes; if (arraybuffer.slice) { return arraybuffer.slice(start, end); } if (start < 0) { start += bytes; } if (end < 0) { end += bytes; } if (end > bytes) { end = bytes; } if (start >= bytes || start >= end || bytes === 0) { return new ArrayBuffer(0); } var abv = new Uint8Array(arraybuffer); var result = new Uint8Array(end - start); for (var i = start, ii = 0; i < end; i++, ii++) { result[ii] = abv[i]; } return result.buffer; }; /***/ }, /* 31 */ /***/ function(module, exports) { module.exports = after function after(count, callback, err_cb) { var bail = false err_cb = err_cb || noop proxy.count = count return (count === 0) ? callback() : proxy function proxy(err, result) { if (proxy.count <= 0) { throw new Error('after called too many times') } --proxy.count // after first error, rest are passed to err_cb if (err) { bail = true callback(err) // future error callbacks will go to error handler callback = err_cb } else if (proxy.count === 0 && !bail) { callback(null, result) } } } function noop() {} /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module, global) {/*! https://mths.be/wtf8 v1.0.0 by @mathias */ ;(function(root) { // Detect free variables `exports` var freeExports = typeof exports == 'object' && exports; // Detect free variable `module` var freeModule = typeof module == 'object' && module && module.exports == freeExports && module; // Detect free variable `global`, from Node.js or Browserified code, // and use it as `root` var freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { root = freeGlobal; } /*--------------------------------------------------------------------------*/ var stringFromCharCode = String.fromCharCode; // Taken from https://mths.be/punycode function ucs2decode(string) { var output = []; var counter = 0; var length = string.length; var value; var extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } // Taken from https://mths.be/punycode function ucs2encode(array) { var length = array.length; var index = -1; var value; var output = ''; while (++index < length) { value = array[index]; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); } return output; } /*--------------------------------------------------------------------------*/ function createByte(codePoint, shift) { return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80); } function encodeCodePoint(codePoint) { if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence return stringFromCharCode(codePoint); } var symbol = ''; if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0); } else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0); symbol += createByte(codePoint, 6); } else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0); symbol += createByte(codePoint, 12); symbol += createByte(codePoint, 6); } symbol += stringFromCharCode((codePoint & 0x3F) | 0x80); return symbol; } function wtf8encode(string) { var codePoints = ucs2decode(string); var length = codePoints.length; var index = -1; var codePoint; var byteString = ''; while (++index < length) { codePoint = codePoints[index]; byteString += encodeCodePoint(codePoint); } return byteString; } /*--------------------------------------------------------------------------*/ function readContinuationByte() { if (byteIndex >= byteCount) { throw Error('Invalid byte index'); } var continuationByte = byteArray[byteIndex] & 0xFF; byteIndex++; if ((continuationByte & 0xC0) == 0x80) { return continuationByte & 0x3F; } // If we end up here, it’s not a continuation byte. throw Error('Invalid continuation byte'); } function decodeSymbol() { var byte1; var byte2; var byte3; var byte4; var codePoint; if (byteIndex > byteCount) { throw Error('Invalid byte index'); } if (byteIndex == byteCount) { return false; } // Read the first byte. byte1 = byteArray[byteIndex] & 0xFF; byteIndex++; // 1-byte sequence (no continuation bytes) if ((byte1 & 0x80) == 0) { return byte1; } // 2-byte sequence if ((byte1 & 0xE0) == 0xC0) { var byte2 = readContinuationByte(); codePoint = ((byte1 & 0x1F) << 6) | byte2; if (codePoint >= 0x80) { return codePoint; } else { throw Error('Invalid continuation byte'); } } // 3-byte sequence (may include unpaired surrogates) if ((byte1 & 0xF0) == 0xE0) { byte2 = readContinuationByte(); byte3 = readContinuationByte(); codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3; if (codePoint >= 0x0800) { return codePoint; } else { throw Error('Invalid continuation byte'); } } // 4-byte sequence if ((byte1 & 0xF8) == 0xF0) { byte2 = readContinuationByte(); byte3 = readContinuationByte(); byte4 = readContinuationByte(); codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) | (byte3 << 0x06) | byte4; if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { return codePoint; } } throw Error('Invalid WTF-8 detected'); } var byteArray; var byteCount; var byteIndex; function wtf8decode(byteString) { byteArray = ucs2decode(byteString); byteCount = byteArray.length; byteIndex = 0; var codePoints = []; var tmp; while ((tmp = decodeSymbol()) !== false) { codePoints.push(tmp); } return ucs2encode(codePoints); } /*--------------------------------------------------------------------------*/ var wtf8 = { 'version': '1.0.0', 'encode': wtf8encode, 'decode': wtf8decode }; // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( true ) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return wtf8; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (freeExports && !freeExports.nodeType) { if (freeModule) { // in Node.js or RingoJS v0.8.0+ freeModule.exports = wtf8; } else { // in Narwhal or RingoJS v0.7.0- var object = {}; var hasOwnProperty = object.hasOwnProperty; for (var key in wtf8) { hasOwnProperty.call(wtf8, key) && (freeExports[key] = wtf8[key]); } } } else { // in Rhino or a web browser root.wtf8 = wtf8; } }(this)); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(12)(module), (function() { return this; }()))) /***/ }, /* 33 */ /***/ function(module, exports) { /* * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function(){ "use strict"; var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // Use a lookup table to find the index. var lookup = new Uint8Array(256); for (var i = 0; i < chars.length; i++) { lookup[chars.charCodeAt(i)] = i; } exports.encode = function(arraybuffer) { var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = ""; for (i = 0; i < len; i+=3) { base64 += chars[bytes[i] >> 2]; base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; base64 += chars[bytes[i + 2] & 63]; } if ((len % 3) === 2) { base64 = base64.substring(0, base64.length - 1) + "="; } else if (len % 3 === 1) { base64 = base64.substring(0, base64.length - 2) + "=="; } return base64; }; exports.decode = function(base64) { var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4; if (base64[base64.length - 1] === "=") { bufferLength--; if (base64[base64.length - 2] === "=") { bufferLength--; } } var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); for (i = 0; i < len; i+=4) { encoded1 = lookup[base64.charCodeAt(i)]; encoded2 = lookup[base64.charCodeAt(i+1)]; encoded3 = lookup[base64.charCodeAt(i+2)]; encoded4 = lookup[base64.charCodeAt(i+3)]; bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } return arraybuffer; }; })(); /***/ }, /* 34 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {/** * Create a blob builder even when vendor prefixes exist */ var BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder || global.MSBlobBuilder || global.MozBlobBuilder; /** * Check if Blob constructor is supported */ var blobSupported = (function() { try { var a = new Blob(['hi']); return a.size === 2; } catch(e) { return false; } })(); /** * Check if Blob constructor supports ArrayBufferViews * Fails in Safari 6, so we need to map to ArrayBuffers there. */ var blobSupportsArrayBufferView = blobSupported && (function() { try { var b = new Blob([new Uint8Array([1,2])]); return b.size === 2; } catch(e) { return false; } })(); /** * Check if BlobBuilder is supported */ var blobBuilderSupported = BlobBuilder && BlobBuilder.prototype.append && BlobBuilder.prototype.getBlob; /** * Helper function that maps ArrayBufferViews to ArrayBuffers * Used by BlobBuilder constructor and old browsers that didn't * support it in the Blob constructor. */ function mapArrayBufferViews(ary) { for (var i = 0; i < ary.length; i++) { var chunk = ary[i]; if (chunk.buffer instanceof ArrayBuffer) { var buf = chunk.buffer; // if this is a subarray, make a copy so we only // include the subarray region from the underlying buffer if (chunk.byteLength !== buf.byteLength) { var copy = new Uint8Array(chunk.byteLength); copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength)); buf = copy.buffer; } ary[i] = buf; } } } function BlobBuilderConstructor(ary, options) { options = options || {}; var bb = new BlobBuilder(); mapArrayBufferViews(ary); for (var i = 0; i < ary.length; i++) { bb.append(ary[i]); } return (options.type) ? bb.getBlob(options.type) : bb.getBlob(); }; function BlobConstructor(ary, options) { mapArrayBufferViews(ary); return new Blob(ary, options || {}); }; module.exports = (function() { if (blobSupported) { return blobSupportsArrayBufferView ? global.Blob : BlobConstructor; } else if (blobBuilderSupported) { return BlobBuilderConstructor; } else { return undefined; } })(); /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { /** * Expose `Emitter`. */ if (true) { module.exports = Emitter; } /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks['$' + event] = this._callbacks['$' + event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ function on() { this.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks['$' + event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks['$' + event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks['$' + event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks['$' + event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; /***/ }, /* 36 */ /***/ function(module, exports) { /** * Compiles a querystring * Returns string representation of the object * * @param {Object} * @api private */ exports.encode = function (obj) { var str = ''; for (var i in obj) { if (obj.hasOwnProperty(i)) { if (str.length) str += '&'; str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); } } return str; }; /** * Parses a simple querystring into an object * * @param {String} qs * @api private */ exports.decode = function(qs){ var qry = {}; var pairs = qs.split('&'); for (var i = 0, l = pairs.length; i < l; i++) { var pair = pairs[i].split('='); qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); } return qry; }; /***/ }, /* 37 */ /***/ function(module, exports) { module.exports = function(a, b){ var fn = function(){}; fn.prototype = b.prototype; a.prototype = new fn; a.prototype.constructor = a; }; /***/ }, /* 38 */ /***/ function(module, exports) { 'use strict'; var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('') , length = 64 , map = {} , seed = 0 , i = 0 , prev; /** * Return a string representing the specified number. * * @param {Number} num The number to convert. * @returns {String} The string representation of the number. * @api public */ function encode(num) { var encoded = ''; do { encoded = alphabet[num % length] + encoded; num = Math.floor(num / length); } while (num > 0); return encoded; } /** * Return the integer value specified by the given string. * * @param {String} str The string to convert. * @returns {Number} The integer value represented by the string. * @api public */ function decode(str) { var decoded = 0; for (i = 0; i < str.length; i++) { decoded = decoded * length + map[str.charAt(i)]; } return decoded; } /** * Yeast: A tiny growing id generator. * * @returns {String} A unique id. * @api public */ function yeast() { var now = encode(+new Date()); if (now !== prev) return seed = 0, prev = now; return now +'.'+ encode(seed++); } // // Map each character to its index. // for (; i < length; i++) map[alphabet[i]] = i; // // Expose the `yeast`, `encode` and `decode` functions. // yeast.encode = encode; yeast.decode = decode; module.exports = yeast; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) { /** * Module requirements. */ var Polling = __webpack_require__(25); var inherit = __webpack_require__(37); /** * Module exports. */ module.exports = JSONPPolling; /** * Cached regular expressions. */ var rNewline = /\n/g; var rEscapedNewline = /\\n/g; /** * Global JSONP callbacks. */ var callbacks; /** * Noop. */ function empty () { } /** * JSONP Polling constructor. * * @param {Object} opts. * @api public */ function JSONPPolling (opts) { Polling.call(this, opts); this.query = this.query || {}; // define global callbacks array if not present // we do this here (lazily) to avoid unneeded global pollution if (!callbacks) { // we need to consider multiple engines in the same page if (!global.___eio) global.___eio = []; callbacks = global.___eio; } // callback identifier this.index = callbacks.length; // add callback to jsonp global var self = this; callbacks.push(function (msg) { self.onData(msg); }); // append to query string this.query.j = this.index; // prevent spurious errors from being emitted when the window is unloaded if (global.document && global.addEventListener) { global.addEventListener('beforeunload', function () { if (self.script) self.script.onerror = empty; }, false); } } /** * Inherits from Polling. */ inherit(JSONPPolling, Polling); /* * JSONP only supports binary as base64 encoded strings */ JSONPPolling.prototype.supportsBinary = false; /** * Closes the socket. * * @api private */ JSONPPolling.prototype.doClose = function () { if (this.script) { this.script.parentNode.removeChild(this.script); this.script = null; } if (this.form) { this.form.parentNode.removeChild(this.form); this.form = null; this.iframe = null; } Polling.prototype.doClose.call(this); }; /** * Starts a poll cycle. * * @api private */ JSONPPolling.prototype.doPoll = function () { var self = this; var script = document.createElement('script'); if (this.script) { this.script.parentNode.removeChild(this.script); this.script = null; } script.async = true; script.src = this.uri(); script.onerror = function (e) { self.onError('jsonp poll error', e); }; var insertAt = document.getElementsByTagName('script')[0]; if (insertAt) { insertAt.parentNode.insertBefore(script, insertAt); } else { (document.head || document.body).appendChild(script); } this.script = script; var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent); if (isUAgecko) { setTimeout(function () { var iframe = document.createElement('iframe'); document.body.appendChild(iframe); document.body.removeChild(iframe); }, 100); } }; /** * Writes with a hidden iframe. * * @param {String} data to send * @param {Function} called upon flush. * @api private */ JSONPPolling.prototype.doWrite = function (data, fn) { var self = this; if (!this.form) { var form = document.createElement('form'); var area = document.createElement('textarea'); var id = this.iframeId = 'eio_iframe_' + this.index; var iframe; form.className = 'socketio'; form.style.position = 'absolute'; form.style.top = '-1000px'; form.style.left = '-1000px'; form.target = id; form.method = 'POST'; form.setAttribute('accept-charset', 'utf-8'); area.name = 'd'; form.appendChild(area); document.body.appendChild(form); this.form = form; this.area = area; } this.form.action = this.uri(); function complete () { initIframe(); fn(); } function initIframe () { if (self.iframe) { try { self.form.removeChild(self.iframe); } catch (e) { self.onError('jsonp polling iframe removal error', e); } } try { // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) var html = '<iframe src="javascript:0" name="' + self.iframeId + '">'; iframe = document.createElement(html); } catch (e) { iframe = document.createElement('iframe'); iframe.name = self.iframeId; iframe.src = 'javascript:0'; } iframe.id = self.iframeId; self.form.appendChild(iframe); self.iframe = iframe; } initIframe(); // escape \n to prevent it from being converted into \r\n by some UAs // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side data = data.replace(rEscapedNewline, '\\\n'); this.area.value = data.replace(rNewline, '\\n'); try { this.form.submit(); } catch (e) {} if (this.iframe.attachEvent) { this.iframe.onreadystatechange = function () { if (self.iframe.readyState === 'complete') { complete(); } }; } else { this.iframe.onload = complete; } }; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/** * Module dependencies. */ var Transport = __webpack_require__(26); var parser = __webpack_require__(27); var parseqs = __webpack_require__(36); var inherit = __webpack_require__(37); var yeast = __webpack_require__(38); var debug = __webpack_require__(3)('engine.io-client:websocket'); var BrowserWebSocket = global.WebSocket || global.MozWebSocket; var NodeWebSocket; if (typeof window === 'undefined') { try { NodeWebSocket = __webpack_require__(41); } catch (e) { } } /** * Get either the `WebSocket` or `MozWebSocket` globals * in the browser or try to resolve WebSocket-compatible * interface exposed by `ws` for Node-like environment. */ var WebSocket = BrowserWebSocket; if (!WebSocket && typeof window === 'undefined') { WebSocket = NodeWebSocket; } /** * Module exports. */ module.exports = WS; /** * WebSocket transport constructor. * * @api {Object} connection options * @api public */ function WS (opts) { var forceBase64 = (opts && opts.forceBase64); if (forceBase64) { this.supportsBinary = false; } this.perMessageDeflate = opts.perMessageDeflate; this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode; if (!this.usingBrowserWebSocket) { WebSocket = NodeWebSocket; } Transport.call(this, opts); } /** * Inherits from Transport. */ inherit(WS, Transport); /** * Transport name. * * @api public */ WS.prototype.name = 'websocket'; /* * WebSockets support binary */ WS.prototype.supportsBinary = true; /** * Opens socket. * * @api private */ WS.prototype.doOpen = function () { if (!this.check()) { // let probe timeout return; } var uri = this.uri(); var protocols = void (0); var opts = { agent: this.agent, perMessageDeflate: this.perMessageDeflate }; // SSL options for Node.js client opts.pfx = this.pfx; opts.key = this.key; opts.passphrase = this.passphrase; opts.cert = this.cert; opts.ca = this.ca; opts.ciphers = this.ciphers; opts.rejectUnauthorized = this.rejectUnauthorized; if (this.extraHeaders) { opts.headers = this.extraHeaders; } if (this.localAddress) { opts.localAddress = this.localAddress; } try { this.ws = this.usingBrowserWebSocket ? new WebSocket(uri) : new WebSocket(uri, protocols, opts); } catch (err) { return this.emit('error', err); } if (this.ws.binaryType === undefined) { this.supportsBinary = false; } if (this.ws.supports && this.ws.supports.binary) { this.supportsBinary = true; this.ws.binaryType = 'nodebuffer'; } else { this.ws.binaryType = 'arraybuffer'; } this.addEventListeners(); }; /** * Adds event listeners to the socket * * @api private */ WS.prototype.addEventListeners = function () { var self = this; this.ws.onopen = function () { self.onOpen(); }; this.ws.onclose = function () { self.onClose(); }; this.ws.onmessage = function (ev) { self.onData(ev.data); }; this.ws.onerror = function (e) { self.onError('websocket error', e); }; }; /** * Writes data to socket. * * @param {Array} array of packets. * @api private */ WS.prototype.write = function (packets) { var self = this; this.writable = false; // encodePacket efficient as it uses WS framing // no need for encodePayload var total = packets.length; for (var i = 0, l = total; i < l; i++) { (function (packet) { parser.encodePacket(packet, self.supportsBinary, function (data) { if (!self.usingBrowserWebSocket) { // always create a new object (GH-437) var opts = {}; if (packet.options) { opts.compress = packet.options.compress; } if (self.perMessageDeflate) { var len = 'string' === typeof data ? global.Buffer.byteLength(data) : data.length; if (len < self.perMessageDeflate.threshold) { opts.compress = false; } } } // Sometimes the websocket has already been closed but the browser didn't // have a chance of informing us about it yet, in that case send will // throw an error try { if (self.usingBrowserWebSocket) { // TypeError is thrown when passing the second argument on Safari self.ws.send(data); } else { self.ws.send(data, opts); } } catch (e) { debug('websocket closed before onclose event'); } --total || done(); }); })(packets[i]); } function done () { self.emit('flush'); // fake drain // defer to next tick to allow Socket to clear writeBuffer setTimeout(function () { self.writable = true; self.emit('drain'); }, 0); } }; /** * Called upon close * * @api private */ WS.prototype.onClose = function () { Transport.prototype.onClose.call(this); }; /** * Closes socket. * * @api private */ WS.prototype.doClose = function () { if (typeof this.ws !== 'undefined') { this.ws.close(); } }; /** * Generates uri for connection. * * @api private */ WS.prototype.uri = function () { var query = this.query || {}; var schema = this.secure ? 'wss' : 'ws'; var port = ''; // avoid port if default for schema if (this.port && (('wss' === schema && Number(this.port) !== 443) || ('ws' === schema && Number(this.port) !== 80))) { port = ':' + this.port; } // append timestamp to URI if (this.timestampRequests) { query[this.timestampParam] = yeast(); } // communicate binary support capabilities if (!this.supportsBinary) { query.b64 = 1; } query = parseqs.encode(query); // prepend ? to query if (query.length) { query = '?' + query; } var ipv6 = this.hostname.indexOf(':') !== -1; return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query; }; /** * Feature detection for WebSocket. * * @return {Boolean} whether this transport is available. * @api public */ WS.prototype.check = function () { return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name); }; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 41 */ /***/ function(module, exports) { /* (ignored) */ /***/ }, /* 42 */ /***/ function(module, exports) { var indexOf = [].indexOf; module.exports = function(arr, obj){ if (indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; /***/ }, /* 43 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {/** * JSON parse. * * @see Based on jQuery#parseJSON (MIT) and JSON2 * @api private */ var rvalidchars = /^[\],:{}\s]*$/; var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g; var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g; var rtrimLeft = /^\s+/; var rtrimRight = /\s+$/; module.exports = function parsejson(data) { if ('string' != typeof data || !data) { return null; } data = data.replace(rtrimLeft, '').replace(rtrimRight, ''); // Attempt to parse using the native JSON parser first if (global.JSON && JSON.parse) { return JSON.parse(data); } if (rvalidchars.test(data.replace(rvalidescape, '@') .replace(rvalidtokens, ']') .replace(rvalidbraces, ''))) { return (new Function('return ' + data))(); } }; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Module dependencies. */ var parser = __webpack_require__(7); var Emitter = __webpack_require__(35); var toArray = __webpack_require__(45); var on = __webpack_require__(46); var bind = __webpack_require__(47); var debug = __webpack_require__(3)('socket.io-client:socket'); var hasBin = __webpack_require__(29); /** * Module exports. */ module.exports = exports = Socket; /** * Internal events (blacklisted). * These events can't be emitted by the user. * * @api private */ var events = { connect: 1, connect_error: 1, connect_timeout: 1, connecting: 1, disconnect: 1, error: 1, reconnect: 1, reconnect_attempt: 1, reconnect_failed: 1, reconnect_error: 1, reconnecting: 1, ping: 1, pong: 1 }; /** * Shortcut to `Emitter#emit`. */ var emit = Emitter.prototype.emit; /** * `Socket` constructor. * * @api public */ function Socket(io, nsp, opts) { this.io = io; this.nsp = nsp; this.json = this; // compat this.ids = 0; this.acks = {}; this.receiveBuffer = []; this.sendBuffer = []; this.connected = false; this.disconnected = true; if (opts && opts.query) { this.query = opts.query; } if (this.io.autoConnect) this.open(); } /** * Mix in `Emitter`. */ Emitter(Socket.prototype); /** * Subscribe to open, close and packet events * * @api private */ Socket.prototype.subEvents = function () { if (this.subs) return; var io = this.io; this.subs = [on(io, 'open', bind(this, 'onopen')), on(io, 'packet', bind(this, 'onpacket')), on(io, 'close', bind(this, 'onclose'))]; }; /** * "Opens" the socket. * * @api public */ Socket.prototype.open = Socket.prototype.connect = function () { if (this.connected) return this; this.subEvents(); this.io.open(); // ensure open if ('open' === this.io.readyState) this.onopen(); this.emit('connecting'); return this; }; /** * Sends a `message` event. * * @return {Socket} self * @api public */ Socket.prototype.send = function () { var args = toArray(arguments); args.unshift('message'); this.emit.apply(this, args); return this; }; /** * Override `emit`. * If the event is in `events`, it's emitted normally. * * @param {String} event name * @return {Socket} self * @api public */ Socket.prototype.emit = function (ev) { if (events.hasOwnProperty(ev)) { emit.apply(this, arguments); return this; } var args = toArray(arguments); var parserType = parser.EVENT; // default if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary var packet = { type: parserType, data: args }; packet.options = {}; packet.options.compress = !this.flags || false !== this.flags.compress; // event ack callback if ('function' === typeof args[args.length - 1]) { debug('emitting packet with ack id %d', this.ids); this.acks[this.ids] = args.pop(); packet.id = this.ids++; } if (this.connected) { this.packet(packet); } else { this.sendBuffer.push(packet); } delete this.flags; return this; }; /** * Sends a packet. * * @param {Object} packet * @api private */ Socket.prototype.packet = function (packet) { packet.nsp = this.nsp; this.io.packet(packet); }; /** * Called upon engine `open`. * * @api private */ Socket.prototype.onopen = function () { debug('transport is open - connecting'); // write connect packet if necessary if ('/' !== this.nsp) { if (this.query) { this.packet({ type: parser.CONNECT, query: this.query }); } else { this.packet({ type: parser.CONNECT }); } } }; /** * Called upon engine `close`. * * @param {String} reason * @api private */ Socket.prototype.onclose = function (reason) { debug('close (%s)', reason); this.connected = false; this.disconnected = true; delete this.id; this.emit('disconnect', reason); }; /** * Called with socket packet. * * @param {Object} packet * @api private */ Socket.prototype.onpacket = function (packet) { if (packet.nsp !== this.nsp) return; switch (packet.type) { case parser.CONNECT: this.onconnect(); break; case parser.EVENT: this.onevent(packet); break; case parser.BINARY_EVENT: this.onevent(packet); break; case parser.ACK: this.onack(packet); break; case parser.BINARY_ACK: this.onack(packet); break; case parser.DISCONNECT: this.ondisconnect(); break; case parser.ERROR: this.emit('error', packet.data); break; } }; /** * Called upon a server event. * * @param {Object} packet * @api private */ Socket.prototype.onevent = function (packet) { var args = packet.data || []; debug('emitting event %j', args); if (null != packet.id) { debug('attaching ack callback to event'); args.push(this.ack(packet.id)); } if (this.connected) { emit.apply(this, args); } else { this.receiveBuffer.push(args); } }; /** * Produces an ack callback to emit with an event. * * @api private */ Socket.prototype.ack = function (id) { var self = this; var sent = false; return function () { // prevent double callbacks if (sent) return; sent = true; var args = toArray(arguments); debug('sending ack %j', args); var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK; self.packet({ type: type, id: id, data: args }); }; }; /** * Called upon a server acknowlegement. * * @param {Object} packet * @api private */ Socket.prototype.onack = function (packet) { var ack = this.acks[packet.id]; if ('function' === typeof ack) { debug('calling ack %s with %j', packet.id, packet.data); ack.apply(this, packet.data); delete this.acks[packet.id]; } else { debug('bad ack %s', packet.id); } }; /** * Called upon server connect. * * @api private */ Socket.prototype.onconnect = function () { this.connected = true; this.disconnected = false; this.emit('connect'); this.emitBuffered(); }; /** * Emit buffered events (received and emitted). * * @api private */ Socket.prototype.emitBuffered = function () { var i; for (i = 0; i < this.receiveBuffer.length; i++) { emit.apply(this, this.receiveBuffer[i]); } this.receiveBuffer = []; for (i = 0; i < this.sendBuffer.length; i++) { this.packet(this.sendBuffer[i]); } this.sendBuffer = []; }; /** * Called upon server disconnect. * * @api private */ Socket.prototype.ondisconnect = function () { debug('server disconnect (%s)', this.nsp); this.destroy(); this.onclose('io server disconnect'); }; /** * Called upon forced client/server side disconnections, * this method ensures the manager stops tracking us and * that reconnections don't get triggered for this. * * @api private. */ Socket.prototype.destroy = function () { if (this.subs) { // clean subscriptions to avoid reconnections for (var i = 0; i < this.subs.length; i++) { this.subs[i].destroy(); } this.subs = null; } this.io.destroy(this); }; /** * Disconnects the socket manually. * * @return {Socket} self * @api public */ Socket.prototype.close = Socket.prototype.disconnect = function () { if (this.connected) { debug('performing disconnect (%s)', this.nsp); this.packet({ type: parser.DISCONNECT }); } // remove socket from pool this.destroy(); if (this.connected) { // fire events this.onclose('io client disconnect'); } return this; }; /** * Sets the compress flag. * * @param {Boolean} if `true`, compresses the sending data * @return {Socket} self * @api public */ Socket.prototype.compress = function (compress) { this.flags = this.flags || {}; this.flags.compress = compress; return this; }; /***/ }, /* 45 */ /***/ function(module, exports) { module.exports = toArray function toArray(list, index) { var array = [] index = index || 0 for (var i = index || 0; i < list.length; i++) { array[i - index] = list[i] } return array } /***/ }, /* 46 */ /***/ function(module, exports) { "use strict"; /** * Module exports. */ module.exports = on; /** * Helper for subscriptions. * * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter` * @param {String} event name * @param {Function} callback * @api public */ function on(obj, ev, fn) { obj.on(ev, fn); return { destroy: function destroy() { obj.removeListener(ev, fn); } }; } /***/ }, /* 47 */ /***/ function(module, exports) { /** * Slice reference. */ var slice = [].slice; /** * Bind `obj` to `fn`. * * @param {Object} obj * @param {Function|String} fn or string * @return {Function} * @api public */ module.exports = function(obj, fn){ if ('string' == typeof fn) fn = obj[fn]; if ('function' != typeof fn) throw new Error('bind() requires a function'); var args = slice.call(arguments, 2); return function(){ return fn.apply(obj, args.concat(slice.call(arguments))); } }; /***/ }, /* 48 */ /***/ function(module, exports) { /** * Expose `Backoff`. */ module.exports = Backoff; /** * Initialize backoff timer with `opts`. * * - `min` initial timeout in milliseconds [100] * - `max` max timeout [10000] * - `jitter` [0] * - `factor` [2] * * @param {Object} opts * @api public */ function Backoff(opts) { opts = opts || {}; this.ms = opts.min || 100; this.max = opts.max || 10000; this.factor = opts.factor || 2; this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; this.attempts = 0; } /** * Return the backoff duration. * * @return {Number} * @api public */ Backoff.prototype.duration = function(){ var ms = this.ms * Math.pow(this.factor, this.attempts++); if (this.jitter) { var rand = Math.random(); var deviation = Math.floor(rand * this.jitter * ms); ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation; } return Math.min(ms, this.max) | 0; }; /** * Reset the number of attempts. * * @api public */ Backoff.prototype.reset = function(){ this.attempts = 0; }; /** * Set the minimum duration * * @api public */ Backoff.prototype.setMin = function(min){ this.ms = min; }; /** * Set the maximum duration * * @api public */ Backoff.prototype.setMax = function(max){ this.max = max; }; /** * Set the jitter * * @api public */ Backoff.prototype.setJitter = function(jitter){ this.jitter = jitter; }; /***/ } /******/ ]) }); ; //# sourceMappingURL=socket.io.js.map
docs/app/index.js
VACO-GitHub/vaco-components-library
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route } from 'react-router'; import createHistory from 'history/lib/createBrowserHistory'; import Home from './components/layout/home'; import Install from './components/layout/install'; import Main from './components/layout/main'; const appHistory = createHistory( { hashType: 'slash' } ); appHistory.push('/'); ReactDOM.render(( <Router history={appHistory}> <Route path="/" component={Home} /> <Route path="/install" component={Install} /> <Route path="/components" component={Main}> <Route path=":component" /> </Route> </Router> ), document.getElementById('app'));
node_modules/react-icons/io/tshirt.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const IoTshirt = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m35 7.5l-2.5 6.9-5-0.6 1.3 22.5h-22.5l1.2-22.5-5 0.6-2.5-6.9 12.5-3.7c1.1 2.1 2.4 3 5 3.1 2.6 0 3.9-1 5-3.1z"/></g> </Icon> ) export default IoTshirt
src/svg-icons/image/filter-b-and-w.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilterBAndW = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16l-7-8v8H5l7-8V5h7v14z"/> </SvgIcon> ); ImageFilterBAndW = pure(ImageFilterBAndW); ImageFilterBAndW.displayName = 'ImageFilterBAndW'; ImageFilterBAndW.muiName = 'SvgIcon'; export default ImageFilterBAndW;
ajax/libs/6to5/1.12.10/browser-polyfill.js
ematsusaka/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){if(typeof Symbol==="undefined"){require("es6-symbol/implement")}require("es6-shim");require("regenerator-6to5/runtime")},{"es6-shim":3,"es6-symbol/implement":4,"regenerator-6to5/runtime":27}],2:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")}},{}],3:[function(require,module,exports){(function(process){(function(root,factory){if(typeof define==="function"&&define.amd){define(factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.returnExports=factory()}})(this,function(){"use strict";var isCallableWithoutNew=function(func){try{func()}catch(e){return false}return true};var supportsSubclassing=function(C,f){try{var Sub=function(){C.apply(this,arguments)};if(!Sub.__proto__){return false}Object.setPrototypeOf(Sub,C);Sub.prototype=Object.create(C.prototype,{constructor:{value:C}});return f(Sub)}catch(e){return false}};var arePropertyDescriptorsSupported=function(){try{Object.defineProperty({},"x",{});return true}catch(e){return false}};var startsWithRejectsRegex=function(){var rejectsRegex=false;if(String.prototype.startsWith){try{"/a/".startsWith(/a/)}catch(e){rejectsRegex=true}}return rejectsRegex};var getGlobal=new Function("return this;");var globals=getGlobal();var global_isFinite=globals.isFinite;var supportsDescriptors=!!Object.defineProperty&&arePropertyDescriptorsSupported();var startsWithIsCompliant=startsWithRejectsRegex();var _slice=Array.prototype.slice;var _indexOf=String.prototype.indexOf;var _toString=Object.prototype.toString;var _hasOwnProperty=Object.prototype.hasOwnProperty;var ArrayIterator;var defineProperty=function(object,name,value,force){if(!force&&name in object){return}if(supportsDescriptors){Object.defineProperty(object,name,{configurable:true,enumerable:false,writable:true,value:value})}else{object[name]=value}};var defineProperties=function(object,map){Object.keys(map).forEach(function(name){var method=map[name];defineProperty(object,name,method,false)})};var create=Object.create||function(prototype,properties){function Type(){}Type.prototype=prototype;var object=new Type;if(typeof properties!=="undefined"){defineProperties(object,properties)}return object};var $iterator$=typeof Symbol==="function"&&Symbol.iterator||"_es6shim_iterator_";if(globals.Set&&typeof(new globals.Set)["@@iterator"]==="function"){$iterator$="@@iterator"}var addIterator=function(prototype,impl){if(!impl){impl=function iterator(){return this}}var o={};o[$iterator$]=impl;defineProperties(prototype,o);if(!prototype[$iterator$]&&typeof $iterator$==="symbol"){prototype[$iterator$]=impl}};var isArguments=function isArguments(value){var str=_toString.call(value);var result=str==="[object Arguments]";if(!result){result=str!=="[object Array]"&&value!==null&&typeof value==="object"&&typeof value.length==="number"&&value.length>=0&&_toString.call(value.callee)==="[object Function]"}return result};var emulateES6construct=function(o){if(!ES.TypeIsObject(o)){throw new TypeError("bad object")}if(!o._es6construct){if(o.constructor&&ES.IsCallable(o.constructor["@@create"])){o=o.constructor["@@create"](o)}defineProperties(o,{_es6construct:true})}return o};var ES={CheckObjectCoercible:function(x,optMessage){if(x==null){throw new TypeError(optMessage||"Cannot call method on "+x)}return x},TypeIsObject:function(x){return x!=null&&Object(x)===x},ToObject:function(o,optMessage){return Object(ES.CheckObjectCoercible(o,optMessage))},IsCallable:function(x){return typeof x==="function"&&_toString.call(x)==="[object Function]"},ToInt32:function(x){return x>>0},ToUint32:function(x){return x>>>0},ToInteger:function(value){var number=+value;if(Number.isNaN(number)){return 0}if(number===0||!Number.isFinite(number)){return number}return(number>0?1:-1)*Math.floor(Math.abs(number))},ToLength:function(value){var len=ES.ToInteger(value);if(len<=0){return 0}if(len>Number.MAX_SAFE_INTEGER){return Number.MAX_SAFE_INTEGER}return len},SameValue:function(a,b){if(a===b){if(a===0){return 1/a===1/b}return true}return Number.isNaN(a)&&Number.isNaN(b)},SameValueZero:function(a,b){return a===b||Number.isNaN(a)&&Number.isNaN(b)},IsIterable:function(o){return ES.TypeIsObject(o)&&(typeof o[$iterator$]!=="undefined"||isArguments(o))},GetIterator:function(o){if(isArguments(o)){return new ArrayIterator(o,"value")}var it=o[$iterator$]();if(!ES.TypeIsObject(it)){throw new TypeError("bad iterator")}return it},IteratorNext:function(it){var result=arguments.length>1?it.next(arguments[1]):it.next();if(!ES.TypeIsObject(result)){throw new TypeError("bad iterator")}return result},Construct:function(C,args){var obj;if(ES.IsCallable(C["@@create"])){obj=C["@@create"]()}else{obj=create(C.prototype||null)}defineProperties(obj,{_es6construct:true});var result=C.apply(obj,args);return ES.TypeIsObject(result)?result:obj}};var numberConversion=function(){function roundToEven(n){var w=Math.floor(n),f=n-w;if(f<.5){return w}if(f>.5){return w+1}return w%2?w+1:w}function packIEEE754(v,ebits,fbits){var bias=(1<<ebits-1)-1,s,e,f,ln,i,bits,str,bytes;if(v!==v){e=(1<<ebits)-1;f=Math.pow(2,fbits-1);s=0}else if(v===Infinity||v===-Infinity){e=(1<<ebits)-1;f=0;s=v<0?1:0}else if(v===0){e=0;f=0;s=1/v===-Infinity?1:0}else{s=v<0;v=Math.abs(v);if(v>=Math.pow(2,1-bias)){e=Math.min(Math.floor(Math.log(v)/Math.LN2),1023);f=roundToEven(v/Math.pow(2,e)*Math.pow(2,fbits));if(f/Math.pow(2,fbits)>=2){e=e+1;f=1}if(e>bias){e=(1<<ebits)-1;f=0}else{e=e+bias;f=f-Math.pow(2,fbits)}}else{e=0;f=roundToEven(v/Math.pow(2,1-bias-fbits))}}bits=[];for(i=fbits;i;i-=1){bits.push(f%2?1:0);f=Math.floor(f/2)}for(i=ebits;i;i-=1){bits.push(e%2?1:0);e=Math.floor(e/2)}bits.push(s?1:0);bits.reverse();str=bits.join("");bytes=[];while(str.length){bytes.push(parseInt(str.slice(0,8),2));str=str.slice(8)}return bytes}function unpackIEEE754(bytes,ebits,fbits){var bits=[],i,j,b,str,bias,s,e,f;for(i=bytes.length;i;i-=1){b=bytes[i-1];for(j=8;j;j-=1){bits.push(b%2?1:0);b=b>>1}}bits.reverse();str=bits.join("");bias=(1<<ebits-1)-1;s=parseInt(str.slice(0,1),2)?-1:1;e=parseInt(str.slice(1,1+ebits),2);f=parseInt(str.slice(1+ebits),2);if(e===(1<<ebits)-1){return f!==0?NaN:s*Infinity}else if(e>0){return s*Math.pow(2,e-bias)*(1+f/Math.pow(2,fbits))}else if(f!==0){return s*Math.pow(2,-(bias-1))*(f/Math.pow(2,fbits))}else{return s<0?-0:0}}function unpackFloat64(b){return unpackIEEE754(b,11,52)}function packFloat64(v){return packIEEE754(v,11,52)}function unpackFloat32(b){return unpackIEEE754(b,8,23)}function packFloat32(v){return packIEEE754(v,8,23)}var conversions={toFloat32:function(num){return unpackFloat32(packFloat32(num))}};if(typeof Float32Array!=="undefined"){var float32array=new Float32Array(1);conversions.toFloat32=function(num){float32array[0]=num;return float32array[0]}}return conversions}();defineProperties(String,{fromCodePoint:function(_){var points=_slice.call(arguments,0,arguments.length);var result=[];var next;for(var i=0,length=points.length;i<length;i++){next=Number(points[i]);if(!ES.SameValue(next,ES.ToInteger(next))||next<0||next>1114111){throw new RangeError("Invalid code point "+next)}if(next<65536){result.push(String.fromCharCode(next))}else{next-=65536;result.push(String.fromCharCode((next>>10)+55296));result.push(String.fromCharCode(next%1024+56320))}}return result.join("")},raw:function(callSite){var substitutions=_slice.call(arguments,1,arguments.length);var cooked=ES.ToObject(callSite,"bad callSite");var rawValue=cooked.raw;var raw=ES.ToObject(rawValue,"bad raw value");var len=Object.keys(raw).length;var literalsegments=ES.ToLength(len);if(literalsegments===0){return""}var stringElements=[];var nextIndex=0;var nextKey,next,nextSeg,nextSub;while(nextIndex<literalsegments){nextKey=String(nextIndex);next=raw[nextKey];nextSeg=String(next);stringElements.push(nextSeg);if(nextIndex+1>=literalsegments){break}next=substitutions[nextKey];if(typeof next==="undefined"){break}nextSub=String(next);stringElements.push(nextSub);nextIndex++}return stringElements.join("")}});if(String.fromCodePoint.length!==1){var originalFromCodePoint=String.fromCodePoint;defineProperty(String,"fromCodePoint",function(_){return originalFromCodePoint.apply(this,arguments)},true)}var StringShims={repeat:function(){var repeat=function(s,times){if(times<1){return""}if(times%2){return repeat(s,times-1)+s}var half=repeat(s,times/2);return half+half};return function(times){var thisStr=String(ES.CheckObjectCoercible(this));times=ES.ToInteger(times);if(times<0||times===Infinity){throw new RangeError("Invalid String#repeat value")}return repeat(thisStr,times)}}(),startsWith:function(searchStr){var thisStr=String(ES.CheckObjectCoercible(this));if(_toString.call(searchStr)==="[object RegExp]"){throw new TypeError('Cannot call method "startsWith" with a regex')}searchStr=String(searchStr);var startArg=arguments.length>1?arguments[1]:void 0;var start=Math.max(ES.ToInteger(startArg),0);return thisStr.slice(start,start+searchStr.length)===searchStr},endsWith:function(searchStr){var thisStr=String(ES.CheckObjectCoercible(this));if(_toString.call(searchStr)==="[object RegExp]"){throw new TypeError('Cannot call method "endsWith" with a regex')}searchStr=String(searchStr);var thisLen=thisStr.length;var posArg=arguments.length>1?arguments[1]:void 0;var pos=typeof posArg==="undefined"?thisLen:ES.ToInteger(posArg);var end=Math.min(Math.max(pos,0),thisLen);return thisStr.slice(end-searchStr.length,end)===searchStr},contains:function(searchString){var position=arguments.length>1?arguments[1]:void 0;return _indexOf.call(this,searchString,position)!==-1},codePointAt:function(pos){var thisStr=String(ES.CheckObjectCoercible(this));var position=ES.ToInteger(pos);var length=thisStr.length;if(position<0||position>=length){return}var first=thisStr.charCodeAt(position);var isEnd=position+1===length;if(first<55296||first>56319||isEnd){return first}var second=thisStr.charCodeAt(position+1);if(second<56320||second>57343){return first}return(first-55296)*1024+(second-56320)+65536}};defineProperties(String.prototype,StringShims);var hasStringTrimBug="…".trim().length!==1;if(hasStringTrimBug){var originalStringTrim=String.prototype.trim;delete String.prototype.trim;var ws=[" \n \f\r   ᠎    ","          \u2028","\u2029"].join("");var trimRegexp=new RegExp("(^["+ws+"]+)|(["+ws+"]+$)","g");defineProperties(String.prototype,{trim:function(){if(typeof this==="undefined"||this===null){throw new TypeError("can't convert "+this+" to object")}return String(this).replace(trimRegexp,"")}})}var StringIterator=function(s){this._s=String(ES.CheckObjectCoercible(s));this._i=0};StringIterator.prototype.next=function(){var s=this._s,i=this._i;if(typeof s==="undefined"||i>=s.length){this._s=void 0;return{value:void 0,done:true}}var first=s.charCodeAt(i),second,len;if(first<55296||first>56319||i+1==s.length){len=1}else{second=s.charCodeAt(i+1);len=second<56320||second>57343?1:2}this._i=i+len;return{value:s.substr(i,len),done:false}};addIterator(StringIterator.prototype);addIterator(String.prototype,function(){return new StringIterator(this)});if(!startsWithIsCompliant){String.prototype.startsWith=StringShims.startsWith;String.prototype.endsWith=StringShims.endsWith}var ArrayShims={from:function(iterable){var mapFn=arguments.length>1?arguments[1]:void 0;var list=ES.ToObject(iterable,"bad iterable");if(typeof mapFn!=="undefined"&&!ES.IsCallable(mapFn)){throw new TypeError("Array.from: when provided, the second argument must be a function")}var hasThisArg=arguments.length>2;var thisArg=hasThisArg?arguments[2]:void 0;var usingIterator=ES.IsIterable(list);var length;var result,i,value;if(usingIterator){i=0;result=ES.IsCallable(this)?Object(new this):[];var it=usingIterator?ES.GetIterator(list):null;var iterationValue;do{iterationValue=ES.IteratorNext(it);if(!iterationValue.done){value=iterationValue.value;if(mapFn){result[i]=hasThisArg?mapFn.call(thisArg,value,i):mapFn(value,i)}else{result[i]=value}i+=1}}while(!iterationValue.done);length=i}else{length=ES.ToLength(list.length);result=ES.IsCallable(this)?Object(new this(length)):new Array(length);for(i=0;i<length;++i){value=list[i];if(mapFn){result[i]=hasThisArg?mapFn.call(thisArg,value,i):mapFn(value,i)}else{result[i]=value}}}result.length=length;return result},of:function(){return Array.from(arguments)}};defineProperties(Array,ArrayShims);var arrayFromSwallowsNegativeLengths=function(){try{return Array.from({length:-1}).length===0}catch(e){return false}};if(!arrayFromSwallowsNegativeLengths()){defineProperty(Array,"from",ArrayShims.from,true)}ArrayIterator=function(array,kind){this.i=0;this.array=array;this.kind=kind};defineProperties(ArrayIterator.prototype,{next:function(){var i=this.i,array=this.array;if(!(this instanceof ArrayIterator)){throw new TypeError("Not an ArrayIterator")}if(typeof array!=="undefined"){var len=ES.ToLength(array.length);for(;i<len;i++){var kind=this.kind;var retval;if(kind==="key"){retval=i}else if(kind==="value"){retval=array[i]}else if(kind==="entry"){retval=[i,array[i]]}this.i=i+1;return{value:retval,done:false}}}this.array=void 0;return{value:void 0,done:true}}});addIterator(ArrayIterator.prototype);var ArrayPrototypeShims={copyWithin:function(target,start){var end=arguments[2];var o=ES.ToObject(this);var len=ES.ToLength(o.length);target=ES.ToInteger(target);start=ES.ToInteger(start);var to=target<0?Math.max(len+target,0):Math.min(target,len);var from=start<0?Math.max(len+start,0):Math.min(start,len);end=typeof end==="undefined"?len:ES.ToInteger(end);var fin=end<0?Math.max(len+end,0):Math.min(end,len);var count=Math.min(fin-from,len-to);var direction=1;if(from<to&&to<from+count){direction=-1;from+=count-1;to+=count-1}while(count>0){if(_hasOwnProperty.call(o,from)){o[to]=o[from]}else{delete o[from]}from+=direction;to+=direction;count-=1}return o},fill:function(value){var start=arguments.length>1?arguments[1]:void 0;var end=arguments.length>2?arguments[2]:void 0;var O=ES.ToObject(this);var len=ES.ToLength(O.length);start=ES.ToInteger(typeof start==="undefined"?0:start);end=ES.ToInteger(typeof end==="undefined"?len:end);var relativeStart=start<0?Math.max(len+start,0):Math.min(start,len);var relativeEnd=end<0?len+end:end;for(var i=relativeStart;i<len&&i<relativeEnd;++i){O[i]=value}return O},find:function find(predicate){var list=ES.ToObject(this);var length=ES.ToLength(list.length);if(!ES.IsCallable(predicate)){throw new TypeError("Array#find: predicate must be a function")}var thisArg=arguments[1];for(var i=0,value;i<length;i++){value=list[i];if(predicate.call(thisArg,value,i,list)){return value}}return},findIndex:function findIndex(predicate){var list=ES.ToObject(this);var length=ES.ToLength(list.length);if(!ES.IsCallable(predicate)){throw new TypeError("Array#findIndex: predicate must be a function")}var thisArg=arguments[1];for(var i=0;i<length;i++){if(predicate.call(thisArg,list[i],i,list)){return i}}return-1},keys:function(){return new ArrayIterator(this,"key")},values:function(){return new ArrayIterator(this,"value")},entries:function(){return new ArrayIterator(this,"entry")}};if(Array.prototype.keys&&!ES.IsCallable([1].keys().next)){delete Array.prototype.keys}if(Array.prototype.entries&&!ES.IsCallable([1].entries().next)){delete Array.prototype.entries}defineProperties(Array.prototype,ArrayPrototypeShims);addIterator(Array.prototype,function(){return this.values()});if(Object.getPrototypeOf){addIterator(Object.getPrototypeOf([].values()))}var maxSafeInteger=Math.pow(2,53)-1;defineProperties(Number,{MAX_SAFE_INTEGER:maxSafeInteger,MIN_SAFE_INTEGER:-maxSafeInteger,EPSILON:2.220446049250313e-16,parseInt:globals.parseInt,parseFloat:globals.parseFloat,isFinite:function(value){return typeof value==="number"&&global_isFinite(value)},isInteger:function(value){return Number.isFinite(value)&&ES.ToInteger(value)===value},isSafeInteger:function(value){return Number.isInteger(value)&&Math.abs(value)<=Number.MAX_SAFE_INTEGER},isNaN:function(value){return value!==value}});if(![,1].find(function(item,idx){return idx===0})){defineProperty(Array.prototype,"find",ArrayPrototypeShims.find,true)}if([,1].findIndex(function(item,idx){return idx===0})!==0){defineProperty(Array.prototype,"findIndex",ArrayPrototypeShims.findIndex,true)}if(supportsDescriptors){defineProperties(Object,{getPropertyDescriptor:function(subject,name){var pd=Object.getOwnPropertyDescriptor(subject,name);var proto=Object.getPrototypeOf(subject);while(typeof pd==="undefined"&&proto!==null){pd=Object.getOwnPropertyDescriptor(proto,name);proto=Object.getPrototypeOf(proto)}return pd},getPropertyNames:function(subject){var result=Object.getOwnPropertyNames(subject);var proto=Object.getPrototypeOf(subject);var addProperty=function(property){if(result.indexOf(property)===-1){result.push(property)}};while(proto!==null){Object.getOwnPropertyNames(proto).forEach(addProperty);proto=Object.getPrototypeOf(proto)}return result}});defineProperties(Object,{assign:function(target,source){if(!ES.TypeIsObject(target)){throw new TypeError("target must be an object")}return Array.prototype.reduce.call(arguments,function(target,source){return Object.keys(Object(source)).reduce(function(target,key){target[key]=source[key];return target},target)})},is:function(a,b){return ES.SameValue(a,b)},setPrototypeOf:function(Object,magic){var set;var checkArgs=function(O,proto){if(!ES.TypeIsObject(O)){throw new TypeError("cannot set prototype on a non-object")}if(!(proto===null||ES.TypeIsObject(proto))){throw new TypeError("can only set prototype to an object or null"+proto)}};var setPrototypeOf=function(O,proto){checkArgs(O,proto);set.call(O,proto);return O};try{set=Object.getOwnPropertyDescriptor(Object.prototype,magic).set;set.call({},null)}catch(e){if(Object.prototype!=={}[magic]){return}set=function(proto){this[magic]=proto};setPrototypeOf.polyfill=setPrototypeOf(setPrototypeOf({},null),Object.prototype)instanceof Object}return setPrototypeOf}(Object,"__proto__")})}if(Object.setPrototypeOf&&Object.getPrototypeOf&&Object.getPrototypeOf(Object.setPrototypeOf({},null))!==null&&Object.getPrototypeOf(Object.create(null))===null){(function(){var FAKENULL=Object.create(null);var gpo=Object.getPrototypeOf,spo=Object.setPrototypeOf;Object.getPrototypeOf=function(o){var result=gpo(o);return result===FAKENULL?null:result};Object.setPrototypeOf=function(o,p){if(p===null){p=FAKENULL}return spo(o,p)};Object.setPrototypeOf.polyfill=false})()}try{Object.keys("foo")}catch(e){var originalObjectKeys=Object.keys;Object.keys=function(obj){return originalObjectKeys(ES.ToObject(obj))}}var MathShims={acosh:function(value){value=Number(value);if(Number.isNaN(value)||value<1){return NaN}if(value===1){return 0}if(value===Infinity){return value}return Math.log(value+Math.sqrt(value*value-1))},asinh:function(value){value=Number(value);if(value===0||!global_isFinite(value)){return value}return value<0?-Math.asinh(-value):Math.log(value+Math.sqrt(value*value+1))},atanh:function(value){value=Number(value);if(Number.isNaN(value)||value<-1||value>1){return NaN}if(value===-1){return-Infinity}if(value===1){return Infinity}if(value===0){return value}return.5*Math.log((1+value)/(1-value))},cbrt:function(value){value=Number(value);if(value===0){return value}var negate=value<0,result;if(negate){value=-value}result=Math.pow(value,1/3);return negate?-result:result},clz32:function(value){value=Number(value);var number=ES.ToUint32(value);if(number===0){return 32}return 32-number.toString(2).length},cosh:function(value){value=Number(value);if(value===0){return 1}if(Number.isNaN(value)){return NaN}if(!global_isFinite(value)){return Infinity}if(value<0){value=-value}if(value>21){return Math.exp(value)/2}return(Math.exp(value)+Math.exp(-value))/2},expm1:function(value){value=Number(value);if(value===-Infinity){return-1}if(!global_isFinite(value)||value===0){return value}return Math.exp(value)-1},hypot:function(x,y){var anyNaN=false;var allZero=true;var anyInfinity=false;var numbers=[];Array.prototype.every.call(arguments,function(arg){var num=Number(arg);if(Number.isNaN(num)){anyNaN=true}else if(num===Infinity||num===-Infinity){anyInfinity=true}else if(num!==0){allZero=false}if(anyInfinity){return false}else if(!anyNaN){numbers.push(Math.abs(num))}return true});if(anyInfinity){return Infinity}if(anyNaN){return NaN}if(allZero){return 0}numbers.sort(function(a,b){return b-a});var largest=numbers[0];var divided=numbers.map(function(number){return number/largest});var sum=divided.reduce(function(sum,number){return sum+=number*number},0);return largest*Math.sqrt(sum)},log2:function(value){return Math.log(value)*Math.LOG2E},log10:function(value){return Math.log(value)*Math.LOG10E},log1p:function(value){value=Number(value);if(value<-1||Number.isNaN(value)){return NaN}if(value===0||value===Infinity){return value}if(value===-1){return-Infinity}var result=0;var n=50;if(value<0||value>1){return Math.log(1+value)}for(var i=1;i<n;i++){if(i%2===0){result-=Math.pow(value,i)/i}else{result+=Math.pow(value,i)/i}}return result},sign:function(value){var number=+value;if(number===0){return number}if(Number.isNaN(number)){return number}return number<0?-1:1},sinh:function(value){value=Number(value);if(!global_isFinite(value)||value===0){return value}return(Math.exp(value)-Math.exp(-value))/2},tanh:function(value){value=Number(value);if(Number.isNaN(value)||value===0){return value}if(value===Infinity){return 1}if(value===-Infinity){return-1}return(Math.exp(value)-Math.exp(-value))/(Math.exp(value)+Math.exp(-value))},trunc:function(value){var number=Number(value);return number<0?-Math.floor(-number):Math.floor(number)},imul:function(x,y){x=ES.ToUint32(x);y=ES.ToUint32(y);var ah=x>>>16&65535;var al=x&65535;var bh=y>>>16&65535;var bl=y&65535;return al*bl+(ah*bl+al*bh<<16>>>0)|0},fround:function(x){if(x===0||x===Infinity||x===-Infinity||Number.isNaN(x)){return x}var num=Number(x);return numberConversion.toFloat32(num)}};defineProperties(Math,MathShims);if(Math.imul(4294967295,5)!==-5){Math.imul=MathShims.imul}var PromiseShim=function(){var Promise,Promise$prototype;ES.IsPromise=function(promise){if(!ES.TypeIsObject(promise)){return false}if(!promise._promiseConstructor){return false}if(typeof promise._status==="undefined"){return false}return true};var PromiseCapability=function(C){if(!ES.IsCallable(C)){throw new TypeError("bad promise constructor")}var capability=this;var resolver=function(resolve,reject){capability.resolve=resolve;capability.reject=reject};capability.promise=ES.Construct(C,[resolver]);if(!capability.promise._es6construct){throw new TypeError("bad promise constructor")}if(!(ES.IsCallable(capability.resolve)&&ES.IsCallable(capability.reject))){throw new TypeError("bad promise constructor")}};var setTimeout=globals.setTimeout;var makeZeroTimeout;if(typeof window!=="undefined"&&ES.IsCallable(window.postMessage)){makeZeroTimeout=function(){var timeouts=[];var messageName="zero-timeout-message";var setZeroTimeout=function(fn){timeouts.push(fn);window.postMessage(messageName,"*")};var handleMessage=function(event){if(event.source==window&&event.data==messageName){event.stopPropagation();if(timeouts.length===0){return}var fn=timeouts.shift();fn()}};window.addEventListener("message",handleMessage,true);return setZeroTimeout}}var makePromiseAsap=function(){var P=globals.Promise;return P&&P.resolve&&function(task){return P.resolve().then(task)}};var enqueue=ES.IsCallable(globals.setImmediate)?globals.setImmediate.bind(globals):typeof process==="object"&&process.nextTick?process.nextTick:makePromiseAsap()||(ES.IsCallable(makeZeroTimeout)?makeZeroTimeout():function(task){setTimeout(task,0)});var triggerPromiseReactions=function(reactions,x){reactions.forEach(function(reaction){enqueue(function(){var handler=reaction.handler;var capability=reaction.capability;var resolve=capability.resolve;var reject=capability.reject;try{var result=handler(x);if(result===capability.promise){throw new TypeError("self resolution")}var updateResult=updatePromiseFromPotentialThenable(result,capability);if(!updateResult){resolve(result)}}catch(e){reject(e)}})})};var updatePromiseFromPotentialThenable=function(x,capability){if(!ES.TypeIsObject(x)){return false}var resolve=capability.resolve;var reject=capability.reject;try{var then=x.then;if(!ES.IsCallable(then)){return false}then.call(x,resolve,reject)}catch(e){reject(e)}return true};var promiseResolutionHandler=function(promise,onFulfilled,onRejected){return function(x){if(x===promise){return onRejected(new TypeError("self resolution"))}var C=promise._promiseConstructor;var capability=new PromiseCapability(C);var updateResult=updatePromiseFromPotentialThenable(x,capability);if(updateResult){return capability.promise.then(onFulfilled,onRejected)}else{return onFulfilled(x)}}};Promise=function(resolver){var promise=this;promise=emulateES6construct(promise);if(!promise._promiseConstructor){throw new TypeError("bad promise")}if(typeof promise._status!=="undefined"){throw new TypeError("promise already initialized")}if(!ES.IsCallable(resolver)){throw new TypeError("not a valid resolver")}promise._status="unresolved";promise._resolveReactions=[];promise._rejectReactions=[];var resolve=function(resolution){if(promise._status!=="unresolved"){return}var reactions=promise._resolveReactions;promise._result=resolution;promise._resolveReactions=void 0;promise._rejectReactions=void 0;promise._status="has-resolution";triggerPromiseReactions(reactions,resolution)};var reject=function(reason){if(promise._status!=="unresolved"){return}var reactions=promise._rejectReactions;promise._result=reason;promise._resolveReactions=void 0;promise._rejectReactions=void 0;promise._status="has-rejection";triggerPromiseReactions(reactions,reason)};try{resolver(resolve,reject)}catch(e){reject(e)}return promise};Promise$prototype=Promise.prototype;defineProperties(Promise,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Promise$prototype;obj=obj||create(prototype);defineProperties(obj,{_status:void 0,_result:void 0,_resolveReactions:void 0,_rejectReactions:void 0,_promiseConstructor:void 0});obj._promiseConstructor=constructor;return obj}});var _promiseAllResolver=function(index,values,capability,remaining){var done=false;return function(x){if(done){return}done=true;values[index]=x;if(--remaining.count===0){var resolve=capability.resolve;resolve(values)}}};Promise.all=function(iterable){var C=this;var capability=new PromiseCapability(C);var resolve=capability.resolve;var reject=capability.reject;try{if(!ES.IsIterable(iterable)){throw new TypeError("bad iterable")}var it=ES.GetIterator(iterable);var values=[],remaining={count:1};for(var index=0;;index++){var next=ES.IteratorNext(it);if(next.done){break}var nextPromise=C.resolve(next.value);var resolveElement=_promiseAllResolver(index,values,capability,remaining);remaining.count++;nextPromise.then(resolveElement,capability.reject)}if(--remaining.count===0){resolve(values)}}catch(e){reject(e)}return capability.promise};Promise.race=function(iterable){var C=this;var capability=new PromiseCapability(C);var resolve=capability.resolve;var reject=capability.reject;try{if(!ES.IsIterable(iterable)){throw new TypeError("bad iterable")}var it=ES.GetIterator(iterable);while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextPromise=C.resolve(next.value);nextPromise.then(resolve,reject)}}catch(e){reject(e)}return capability.promise};Promise.reject=function(reason){var C=this;var capability=new PromiseCapability(C);var reject=capability.reject;reject(reason);return capability.promise};Promise.resolve=function(v){var C=this;if(ES.IsPromise(v)){var constructor=v._promiseConstructor;if(constructor===C){return v}}var capability=new PromiseCapability(C);var resolve=capability.resolve;resolve(v);return capability.promise};Promise.prototype["catch"]=function(onRejected){return this.then(void 0,onRejected)};Promise.prototype.then=function(onFulfilled,onRejected){var promise=this;if(!ES.IsPromise(promise)){throw new TypeError("not a promise")}var C=this.constructor;var capability=new PromiseCapability(C);if(!ES.IsCallable(onRejected)){onRejected=function(e){throw e}}if(!ES.IsCallable(onFulfilled)){onFulfilled=function(x){return x}}var resolutionHandler=promiseResolutionHandler(promise,onFulfilled,onRejected);var resolveReaction={capability:capability,handler:resolutionHandler};var rejectReaction={capability:capability,handler:onRejected};switch(promise._status){case"unresolved":promise._resolveReactions.push(resolveReaction);promise._rejectReactions.push(rejectReaction);break;case"has-resolution":triggerPromiseReactions([resolveReaction],promise._result);break;case"has-rejection":triggerPromiseReactions([rejectReaction],promise._result);break;default:throw new TypeError("unexpected")}return capability.promise};return Promise}();defineProperties(globals,{Promise:PromiseShim});var promiseSupportsSubclassing=supportsSubclassing(globals.Promise,function(S){return S.resolve(42)instanceof S});var promiseIgnoresNonFunctionThenCallbacks=function(){try{globals.Promise.reject(42).then(null,5).then(null,function(){});return true}catch(ex){return false}}();var promiseRequiresObjectContext=function(){try{Promise.call(3,function(){})}catch(e){return true}return false}();if(!promiseSupportsSubclassing||!promiseIgnoresNonFunctionThenCallbacks||!promiseRequiresObjectContext){globals.Promise=PromiseShim}var testOrder=function(a){var b=Object.keys(a.reduce(function(o,k){o[k]=true;return o},{}));return a.join(":")===b.join(":")};var preservesInsertionOrder=testOrder(["z","a","bb"]);var preservesNumericInsertionOrder=testOrder(["z",1,"a","3",2]);if(supportsDescriptors){var fastkey=function fastkey(key){if(!preservesInsertionOrder){return null}var type=typeof key;if(type==="string"){return"$"+key}else if(type==="number"){if(!preservesNumericInsertionOrder){return"n"+key}return key}return null};var emptyObject=function emptyObject(){return Object.create?Object.create(null):{}};var collectionShims={Map:function(){var empty={};function MapEntry(key,value){this.key=key;this.value=value;this.next=null;this.prev=null}MapEntry.prototype.isRemoved=function(){return this.key===empty };function MapIterator(map,kind){this.head=map._head;this.i=this.head;this.kind=kind}MapIterator.prototype={next:function(){var i=this.i,kind=this.kind,head=this.head,result;if(typeof this.i==="undefined"){return{value:void 0,done:true}}while(i.isRemoved()&&i!==head){i=i.prev}while(i.next!==head){i=i.next;if(!i.isRemoved()){if(kind==="key"){result=i.key}else if(kind==="value"){result=i.value}else{result=[i.key,i.value]}this.i=i;return{value:result,done:false}}}this.i=void 0;return{value:void 0,done:true}}};addIterator(MapIterator.prototype);function Map(iterable){var map=this;map=emulateES6construct(map);if(!map._es6map){throw new TypeError("bad map")}var head=new MapEntry(null,null);head.next=head.prev=head;defineProperties(map,{_head:head,_storage:emptyObject(),_size:0});if(typeof iterable!=="undefined"&&iterable!==null){var it=ES.GetIterator(iterable);var adder=map.set;if(!ES.IsCallable(adder)){throw new TypeError("bad map")}while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextItem=next.value;if(!ES.TypeIsObject(nextItem)){throw new TypeError("expected iterable of pairs")}adder.call(map,nextItem[0],nextItem[1])}}return map}var Map$prototype=Map.prototype;defineProperties(Map,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Map$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6map:true});return obj}});Object.defineProperty(Map.prototype,"size",{configurable:true,enumerable:false,get:function(){if(typeof this._size==="undefined"){throw new TypeError("size method called on incompatible Map")}return this._size}});defineProperties(Map.prototype,{get:function(key){var fkey=fastkey(key);if(fkey!==null){var entry=this._storage[fkey];if(entry){return entry.value}else{return}}var head=this._head,i=head;while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){return i.value}}return},has:function(key){var fkey=fastkey(key);if(fkey!==null){return typeof this._storage[fkey]!=="undefined"}var head=this._head,i=head;while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){return true}}return false},set:function(key,value){var head=this._head,i=head,entry;var fkey=fastkey(key);if(fkey!==null){if(typeof this._storage[fkey]!=="undefined"){this._storage[fkey].value=value;return}else{entry=this._storage[fkey]=new MapEntry(key,value);i=head.prev}}while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){i.value=value;return}}entry=entry||new MapEntry(key,value);if(ES.SameValue(-0,key)){entry.key=+0}entry.next=this._head;entry.prev=this._head.prev;entry.prev.next=entry;entry.next.prev=entry;this._size+=1;return this},"delete":function(key){var head=this._head,i=head;var fkey=fastkey(key);if(fkey!==null){if(typeof this._storage[fkey]==="undefined"){return false}i=this._storage[fkey].prev;delete this._storage[fkey]}while((i=i.next)!==head){if(ES.SameValueZero(i.key,key)){i.key=i.value=empty;i.prev.next=i.next;i.next.prev=i.prev;this._size-=1;return true}}return false},clear:function(){this._size=0;this._storage=emptyObject();var head=this._head,i=head,p=i.next;while((i=p)!==head){i.key=i.value=empty;p=i.next;i.next=i.prev=head}head.next=head.prev=head},keys:function(){return new MapIterator(this,"key")},values:function(){return new MapIterator(this,"value")},entries:function(){return new MapIterator(this,"key+value")},forEach:function(callback){var context=arguments.length>1?arguments[1]:null;var it=this.entries();for(var entry=it.next();!entry.done;entry=it.next()){callback.call(context,entry.value[1],entry.value[0],this)}}});addIterator(Map.prototype,function(){return this.entries()});return Map}(),Set:function(){var SetShim=function Set(iterable){var set=this;set=emulateES6construct(set);if(!set._es6set){throw new TypeError("bad set")}defineProperties(set,{"[[SetData]]":null,_storage:emptyObject()});if(typeof iterable!=="undefined"&&iterable!==null){var it=ES.GetIterator(iterable);var adder=set.add;if(!ES.IsCallable(adder)){throw new TypeError("bad set")}while(true){var next=ES.IteratorNext(it);if(next.done){break}var nextItem=next.value;adder.call(set,nextItem)}}return set};var Set$prototype=SetShim.prototype;defineProperties(SetShim,{"@@create":function(obj){var constructor=this;var prototype=constructor.prototype||Set$prototype;obj=obj||create(prototype);defineProperties(obj,{_es6set:true});return obj}});var ensureMap=function ensureMap(set){if(!set["[[SetData]]"]){var m=set["[[SetData]]"]=new collectionShims.Map;Object.keys(set._storage).forEach(function(k){if(k.charCodeAt(0)===36){k=k.slice(1)}else if(k.charAt(0)==="n"){k=+k.slice(1)}else{k=+k}m.set(k,k)});set._storage=null}};Object.defineProperty(SetShim.prototype,"size",{configurable:true,enumerable:false,get:function(){if(typeof this._storage==="undefined"){throw new TypeError("size method called on incompatible Set")}ensureMap(this);return this["[[SetData]]"].size}});defineProperties(SetShim.prototype,{has:function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){return!!this._storage[fkey]}ensureMap(this);return this["[[SetData]]"].has(key)},add:function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){this._storage[fkey]=true;return}ensureMap(this);this["[[SetData]]"].set(key,key);return this},"delete":function(key){var fkey;if(this._storage&&(fkey=fastkey(key))!==null){var hasFKey=_hasOwnProperty.call(this._storage,fkey);return delete this._storage[fkey]&&hasFKey}ensureMap(this);return this["[[SetData]]"]["delete"](key)},clear:function(){if(this._storage){this._storage=emptyObject();return}return this["[[SetData]]"].clear()},keys:function(){ensureMap(this);return this["[[SetData]]"].keys()},values:function(){ensureMap(this);return this["[[SetData]]"].values()},entries:function(){ensureMap(this);return this["[[SetData]]"].entries()},forEach:function(callback){var context=arguments.length>1?arguments[1]:null;var entireSet=this;ensureMap(this);this["[[SetData]]"].forEach(function(value,key){callback.call(context,key,key,entireSet)})}});addIterator(SetShim.prototype,function(){return this.values()});return SetShim}()};defineProperties(globals,collectionShims);if(globals.Map||globals.Set){if(typeof globals.Map.prototype.clear!=="function"||(new globals.Set).size!==0||(new globals.Map).size!==0||typeof globals.Map.prototype.keys!=="function"||typeof globals.Set.prototype.keys!=="function"||typeof globals.Map.prototype.forEach!=="function"||typeof globals.Set.prototype.forEach!=="function"||isCallableWithoutNew(globals.Map)||isCallableWithoutNew(globals.Set)||!supportsSubclassing(globals.Map,function(M){var m=new M([]);m.set(42,42);return m instanceof M})){globals.Map=collectionShims.Map;globals.Set=collectionShims.Set}}addIterator(Object.getPrototypeOf((new globals.Map).keys()));addIterator(Object.getPrototypeOf((new globals.Set).keys()))}return globals})}).call(this,require("_process"))},{_process:2}],4:[function(require,module,exports){"use strict";if(!require("./is-implemented")()){Object.defineProperty(require("es5-ext/global"),"Symbol",{value:require("./polyfill"),configurable:true,enumerable:false,writable:true})}},{"./is-implemented":5,"./polyfill":20,"es5-ext/global":7}],5:[function(require,module,exports){"use strict";module.exports=function(){var symbol;if(typeof Symbol!=="function")return false;symbol=Symbol("test symbol");try{String(symbol)}catch(e){return false}if(typeof Symbol.iterator==="symbol")return true;if(typeof Symbol.isConcatSpreadable!=="object")return false;if(typeof Symbol.isRegExp!=="object")return false;if(typeof Symbol.iterator!=="object")return false;if(typeof Symbol.toPrimitive!=="object")return false;if(typeof Symbol.toStringTag!=="object")return false;if(typeof Symbol.unscopables!=="object")return false;return true}},{}],6:[function(require,module,exports){"use strict";var assign=require("es5-ext/object/assign"),normalizeOpts=require("es5-ext/object/normalize-options"),isCallable=require("es5-ext/object/is-callable"),contains=require("es5-ext/string/#/contains"),d;d=module.exports=function(dscr,value){var c,e,w,options,desc;if(arguments.length<2||typeof dscr!=="string"){options=value;value=dscr;dscr=null}else{options=arguments[2]}if(dscr==null){c=w=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e");w=contains.call(dscr,"w")}desc={value:value,configurable:c,enumerable:e,writable:w};return!options?desc:assign(normalizeOpts(options),desc)};d.gs=function(dscr,get,set){var c,e,options,desc;if(typeof dscr!=="string"){options=set;set=get;get=dscr;dscr=null}else{options=arguments[3]}if(get==null){get=undefined}else if(!isCallable(get)){options=get;get=set=undefined}else if(set==null){set=undefined}else if(!isCallable(set)){options=set;set=undefined}if(dscr==null){c=true;e=false}else{c=contains.call(dscr,"c");e=contains.call(dscr,"e")}desc={get:get,set:set,configurable:c,enumerable:e};return!options?desc:assign(normalizeOpts(options),desc)}},{"es5-ext/object/assign":8,"es5-ext/object/is-callable":11,"es5-ext/object/normalize-options":15,"es5-ext/string/#/contains":17}],7:[function(require,module,exports){"use strict";module.exports=new Function("return this")()},{}],8:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.assign:require("./shim")},{"./is-implemented":9,"./shim":10}],9:[function(require,module,exports){"use strict";module.exports=function(){var assign=Object.assign,obj;if(typeof assign!=="function")return false;obj={foo:"raz"};assign(obj,{bar:"dwa"},{trzy:"trzy"});return obj.foo+obj.bar+obj.trzy==="razdwatrzy"}},{}],10:[function(require,module,exports){"use strict";var keys=require("../keys"),value=require("../valid-value"),max=Math.max;module.exports=function(dest,src){var error,i,l=max(arguments.length,2),assign;dest=Object(value(dest));assign=function(key){try{dest[key]=src[key]}catch(e){if(!error)error=e}};for(i=1;i<l;++i){src=arguments[i];keys(src).forEach(assign)}if(error!==undefined)throw error;return dest}},{"../keys":12,"../valid-value":16}],11:[function(require,module,exports){"use strict";module.exports=function(obj){return typeof obj==="function"}},{}],12:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.keys:require("./shim")},{"./is-implemented":13,"./shim":14}],13:[function(require,module,exports){"use strict";module.exports=function(){try{Object.keys("primitive");return true}catch(e){return false}}},{}],14:[function(require,module,exports){"use strict";var keys=Object.keys;module.exports=function(object){return keys(object==null?object:Object(object))}},{}],15:[function(require,module,exports){"use strict";var assign=require("./assign"),forEach=Array.prototype.forEach,create=Object.create,getPrototypeOf=Object.getPrototypeOf,process;process=function(src,obj){var proto=getPrototypeOf(src);return assign(proto?process(proto,obj):obj,src)};module.exports=function(options){var result=create(null);forEach.call(arguments,function(options){if(options==null)return;process(Object(options),result)});return result}},{"./assign":8}],16:[function(require,module,exports){"use strict";module.exports=function(value){if(value==null)throw new TypeError("Cannot use null or undefined");return value}},{}],17:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?String.prototype.contains:require("./shim")},{"./is-implemented":18,"./shim":19}],18:[function(require,module,exports){"use strict";var str="razdwatrzy";module.exports=function(){if(typeof str.contains!=="function")return false;return str.contains("dwa")===true&&str.contains("foo")===false}},{}],19:[function(require,module,exports){"use strict";var indexOf=String.prototype.indexOf;module.exports=function(searchString){return indexOf.call(this,searchString,arguments[1])>-1}},{}],20:[function(require,module,exports){"use strict";var d=require("d"),create=Object.create,defineProperties=Object.defineProperties,generateName,Symbol;generateName=function(){var created=create(null);return function(desc){var postfix=0;while(created[desc+(postfix||"")])++postfix;desc+=postfix||"";created[desc]=true;return"@@"+desc}}();module.exports=Symbol=function(description){var symbol;if(this instanceof Symbol){throw new TypeError("TypeError: Symbol is not a constructor")}symbol=create(Symbol.prototype);description=description===undefined?"":String(description);return defineProperties(symbol,{__description__:d("",description),__name__:d("",generateName(description))})};Object.defineProperties(Symbol,{create:d("",Symbol("create")),hasInstance:d("",Symbol("hasInstance")),isConcatSpreadable:d("",Symbol("isConcatSpreadable")),isRegExp:d("",Symbol("isRegExp")),iterator:d("",Symbol("iterator")),toPrimitive:d("",Symbol("toPrimitive")),toStringTag:d("",Symbol("toStringTag")),unscopables:d("",Symbol("unscopables"))});defineProperties(Symbol.prototype,{properToString:d(function(){return"Symbol ("+this.__description__+")"}),toString:d("",function(){return this.__name__})});Object.defineProperty(Symbol.prototype,Symbol.toPrimitive,d("",function(hint){throw new TypeError("Conversion of symbol objects is not allowed")}));Object.defineProperty(Symbol.prototype,Symbol.toStringTag,d("c","Symbol"))},{d:6}],21:[function(require,module,exports){"use strict";module.exports=require("./lib/core.js");require("./lib/done.js");require("./lib/es6-extensions.js");require("./lib/node-extensions.js")},{"./lib/core.js":22,"./lib/done.js":23,"./lib/es6-extensions.js":24,"./lib/node-extensions.js":25}],22:[function(require,module,exports){"use strict";var asap=require("asap");module.exports=Promise;function Promise(fn){if(typeof this!=="object")throw new TypeError("Promises must be constructed via new");if(typeof fn!=="function")throw new TypeError("not a function");var state=null;var value=null;var deferreds=[];var self=this;this.then=function(onFulfilled,onRejected){return new self.constructor(function(resolve,reject){handle(new Handler(onFulfilled,onRejected,resolve,reject))})};function handle(deferred){if(state===null){deferreds.push(deferred);return}asap(function(){var cb=state?deferred.onFulfilled:deferred.onRejected;if(cb===null){(state?deferred.resolve:deferred.reject)(value);return}var ret;try{ret=cb(value)}catch(e){deferred.reject(e);return}deferred.resolve(ret)})}function resolve(newValue){try{if(newValue===self)throw new TypeError("A promise cannot be resolved with itself.");if(newValue&&(typeof newValue==="object"||typeof newValue==="function")){var then=newValue.then;if(typeof then==="function"){doResolve(then.bind(newValue),resolve,reject);return}}state=true;value=newValue;finale()}catch(e){reject(e)}}function reject(newValue){state=false;value=newValue;finale()}function finale(){for(var i=0,len=deferreds.length;i<len;i++)handle(deferreds[i]);deferreds=null}doResolve(fn,resolve,reject)}function Handler(onFulfilled,onRejected,resolve,reject){this.onFulfilled=typeof onFulfilled==="function"?onFulfilled:null;this.onRejected=typeof onRejected==="function"?onRejected:null;this.resolve=resolve;this.reject=reject}function doResolve(fn,onFulfilled,onRejected){var done=false;try{fn(function(value){if(done)return;done=true;onFulfilled(value)},function(reason){if(done)return;done=true;onRejected(reason)})}catch(ex){if(done)return;done=true;onRejected(ex)}}},{asap:26}],23:[function(require,module,exports){"use strict";var Promise=require("./core.js");var asap=require("asap");module.exports=Promise;Promise.prototype.done=function(onFulfilled,onRejected){var self=arguments.length?this.then.apply(this,arguments):this;self.then(null,function(err){asap(function(){throw err})})}},{"./core.js":22,asap:26}],24:[function(require,module,exports){"use strict";var Promise=require("./core.js");var asap=require("asap");module.exports=Promise;function ValuePromise(value){this.then=function(onFulfilled){if(typeof onFulfilled!=="function")return this;return new Promise(function(resolve,reject){asap(function(){try{resolve(onFulfilled(value))}catch(ex){reject(ex)}})})}}ValuePromise.prototype=Promise.prototype;var TRUE=new ValuePromise(true);var FALSE=new ValuePromise(false);var NULL=new ValuePromise(null);var UNDEFINED=new ValuePromise(undefined);var ZERO=new ValuePromise(0);var EMPTYSTRING=new ValuePromise("");Promise.resolve=function(value){if(value instanceof Promise)return value;if(value===null)return NULL;if(value===undefined)return UNDEFINED;if(value===true)return TRUE;if(value===false)return FALSE;if(value===0)return ZERO;if(value==="")return EMPTYSTRING;if(typeof value==="object"||typeof value==="function"){try{var then=value.then;if(typeof then==="function"){return new Promise(then.bind(value))}}catch(ex){return new Promise(function(resolve,reject){reject(ex)})}}return new ValuePromise(value)};Promise.all=function(arr){var args=Array.prototype.slice.call(arr);return new Promise(function(resolve,reject){if(args.length===0)return resolve([]);var remaining=args.length;function res(i,val){try{if(val&&(typeof val==="object"||typeof val==="function")){var then=val.then;if(typeof then==="function"){then.call(val,function(val){res(i,val)},reject);return}}args[i]=val;if(--remaining===0){resolve(args)}}catch(ex){reject(ex)}}for(var i=0;i<args.length;i++){res(i,args[i])}})};Promise.reject=function(value){return new Promise(function(resolve,reject){reject(value)})};Promise.race=function(values){return new Promise(function(resolve,reject){values.forEach(function(value){Promise.resolve(value).then(resolve,reject)})})};Promise.prototype["catch"]=function(onRejected){return this.then(null,onRejected)}},{"./core.js":22,asap:26}],25:[function(require,module,exports){"use strict";var Promise=require("./core.js");var asap=require("asap");module.exports=Promise;Promise.denodeify=function(fn,argumentCount){argumentCount=argumentCount||Infinity;return function(){var self=this;var args=Array.prototype.slice.call(arguments);return new Promise(function(resolve,reject){while(args.length&&args.length>argumentCount){args.pop()}args.push(function(err,res){if(err)reject(err);else resolve(res)});fn.apply(self,args)})}};Promise.nodeify=function(fn){return function(){var args=Array.prototype.slice.call(arguments);var callback=typeof args[args.length-1]==="function"?args.pop():null;var ctx=this;try{return fn.apply(this,arguments).nodeify(callback,ctx)}catch(ex){if(callback===null||typeof callback=="undefined"){return new Promise(function(resolve,reject){reject(ex)})}else{asap(function(){callback.call(ctx,ex)})}}}};Promise.prototype.nodeify=function(callback,ctx){if(typeof callback!="function")return this;this.then(function(value){asap(function(){callback.call(ctx,null,value)})},function(err){asap(function(){callback.call(ctx,err)})})}},{"./core.js":22,asap:26}],26:[function(require,module,exports){(function(process){var head={task:void 0,next:null};var tail=head;var flushing=false;var requestFlush=void 0;var isNodeJS=false;function flush(){while(head.next){head=head.next;var task=head.task;head.task=void 0;var domain=head.domain;if(domain){head.domain=void 0;domain.enter()}try{task()}catch(e){if(isNodeJS){if(domain){domain.exit()}setTimeout(flush,0);if(domain){domain.enter()}throw e}else{setTimeout(function(){throw e},0)}}if(domain){domain.exit()}}flushing=false}if(typeof process!=="undefined"&&process.nextTick){isNodeJS=true;requestFlush=function(){process.nextTick(flush)}}else if(typeof setImmediate==="function"){if(typeof window!=="undefined"){requestFlush=setImmediate.bind(window,flush)}else{requestFlush=function(){setImmediate(flush)}}}else if(typeof MessageChannel!=="undefined"){var channel=new MessageChannel;channel.port1.onmessage=flush;requestFlush=function(){channel.port2.postMessage(0)}}else{requestFlush=function(){setTimeout(flush,0)}}function asap(task){tail=tail.next={task:task,domain:isNodeJS&&process.domain,next:null};if(!flushing){flushing=true;requestFlush()}}module.exports=asap}).call(this,require("_process"))},{_process:2}],27:[function(require,module,exports){!function(){var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";if(typeof Promise==="undefined")try{Promise=require("promise")}catch(ignored){}if(typeof regeneratorRuntime==="object"){return}var runtime=regeneratorRuntime=typeof exports==="undefined"?{}:exports;function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])}runtime.wrap=wrap;var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}var Gp=Generator.prototype;var GFp=GeneratorFunction.prototype=Object.create(Function.prototype);GFp.constructor=GeneratorFunction;GFp.prototype=Gp;Gp.constructor=GFp;if(GeneratorFunction.name!=="GeneratorFunction"){GeneratorFunction.name="GeneratorFunction"}if(GeneratorFunction.name!=="GeneratorFunction"){throw new Error("GeneratorFunction renamed?")}runtime.isGeneratorFunction=function(genFun){var ctor=genFun&&genFun.constructor;return ctor?GeneratorFunction.name===ctor.name:false};runtime.mark=function(genFun){genFun.__proto__=GFp;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator.throw);function step(arg){try{var info=this(arg);var value=info.value}catch(error){return reject(error)}if(info.done){resolve(value)}else{Promise.resolve(value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){throw new Error("Generator has already finished")}while(true){var delegate=context.delegate;if(delegate){try{var info=delegate.iterator[method](arg);method="next";arg=undefined}catch(uncaught){context.delegate=null;method="throw";arg=uncaught;continue}if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;try{var value=innerFn.call(self,context);state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:value,done:context.done};if(value===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}catch(thrown){state=GenStateCompleted;if(method==="next"){context.dispatchException(thrown)}else{arg=thrown}}}}generator.next=invoke.bind(generator,"next");generator.throw=invoke.bind(generator,"throw");generator.return=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){var iterator=iterable;if(iteratorSymbol in iterable){iterator=iterable[iteratorSymbol]()}else if(!isNaN(iterable.length)){var i=-1;iterator=function next(){while(++i<iterable.length){if(i in iterable){next.value=iterable[i];next.done=false;return next}}next.done=true;return next};iterator.next=iterator}return iterator}runtime.values=values;Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}()},{promise:21}]},{},[1]);
app/javascript/mastodon/features/notifications/containers/column_settings_container.js
res-ac/mstdn.res.ac
import { connect } from 'react-redux'; import { defineMessages, injectIntl } from 'react-intl'; import ColumnSettings from '../components/column_settings'; import { changeSetting } from '../../../actions/settings'; import { clearNotifications } from '../../../actions/notifications'; import { changeAlerts as changePushNotifications } from '../../../actions/push_notifications'; import { openModal } from '../../../actions/modal'; const messages = defineMessages({ clearMessage: { id: 'notifications.clear_confirmation', defaultMessage: 'Are you sure you want to permanently clear all your notifications?' }, clearConfirm: { id: 'notifications.clear', defaultMessage: 'Clear notifications' }, }); const mapStateToProps = state => ({ settings: state.getIn(['settings', 'notifications']), pushSettings: state.get('push_notifications'), }); const mapDispatchToProps = (dispatch, { intl }) => ({ onChange (path, checked) { if (path[0] === 'push') { dispatch(changePushNotifications(path.slice(1), checked)); } else { dispatch(changeSetting(['notifications', ...path], checked)); } }, onClear () { dispatch(openModal('CONFIRM', { message: intl.formatMessage(messages.clearMessage), confirm: intl.formatMessage(messages.clearConfirm), onConfirm: () => dispatch(clearNotifications()), })); }, }); export default injectIntl(connect(mapStateToProps, mapDispatchToProps)(ColumnSettings));
src/levelindex.js
JohnCrash/voxel
import React from 'react'; import ReactDOM from 'react-dom'; import Level from './level'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; function App(){ let route = window.location.hash.substr(1); console.log(`load level "${route}"`); return <MuiThemeProvider> <Level level={route}/> </MuiThemeProvider>; } function render(){ ReactDOM.render(<App />,document.getElementById('root')); } window.addEventListener('hashchange', render); render();
app/components/containers/Overlay.js
JobCompare/jc-ui
import React from 'react'; import PropTypes from 'prop-types'; import TypeChecker from '../../../utils/TypeChecker'; import OverlayController from '../../../utils/OverlayController'; // TODO: tutorial on how to get out of Overlay class Overlay extends React.Component { constructor() { super(); this.hide = this.hide.bind(this); } hide(event) { const { onClick } = this.props; OverlayController.hide(this.element); if (!TypeChecker.isUndefined(onClick)) { onClick(event); } } render() { const { isVisible } = this.props; const attributes = { ...this.props, onClick: this.hide, className: `overlay ${isVisible ? 'overlay-show' : 'overlay-hide'}`, }; if (!TypeChecker.isUndefined(attributes.isVisible)) { delete attributes.isVisible; } return ( <div {...attributes} ref={(element) => { this.element = element; }}> { this.props.children } </div> ); } } Overlay.propTypes = { onClick: PropTypes.func, isVisible: PropTypes.bool, }; export default Overlay;
src/svg-icons/hardware/tablet-android.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareTabletAndroid = (props) => ( <SvgIcon {...props}> <path d="M18 0H6C4.34 0 3 1.34 3 3v18c0 1.66 1.34 3 3 3h12c1.66 0 3-1.34 3-3V3c0-1.66-1.34-3-3-3zm-4 22h-4v-1h4v1zm5.25-3H4.75V3h14.5v16z"/> </SvgIcon> ); HardwareTabletAndroid = pure(HardwareTabletAndroid); HardwareTabletAndroid.displayName = 'HardwareTabletAndroid'; HardwareTabletAndroid.muiName = 'SvgIcon'; export default HardwareTabletAndroid;