target
stringlengths 5
300
| feat_repo_name
stringlengths 6
76
| text
stringlengths 26
1.05M
|
---|---|---|
client/components/footer.js | LivenUp/livenup | import React, { Component } from 'react';
export default class Footer extends Component {
render() {
return (
<footer className="footer">
<div className="col-md-12">
<div className="footer-container">
<span>LivenUp </span>
<a href="https://github.com/LivenUp/livenup" target="_blank"><i className="fa fa-github"></i></a>
<span className="footer-elements">Genevieve Kolve </span>
<a href="https://github.com/genevieve314" target="_blank"><i className="fa fa-github"></i></a>
<a href="https://www.linkedin.com/in/genevievekolve" target="_blank"><i className="fa fa-linkedin"></i></a>
<span className="footer-elements">Erik McGarruaugh </span>
<a href="https://github.com/erikmcgarraugh" target="_blank"><i className="fa fa-github"></i></a>
<a href="https://www.linkedin.com/in/charlesmeredith1" target="_blank"><i className="fa fa-linkedin"></i></a>
<span className="footer-elements">Charles Meredith </span>
<a href="https://github.com/chas3m" target="_blank"><i className="fa fa-github"></i></a>
<a href="https://www.linkedin.com/in/charlesmeredith1" target="_blank"><i className="fa fa-linkedin"></i></a>
<span className="footer-elements">John Michelin </span>
<a href="https://github.com/jmichelin" target="_blank"><i className="fa fa-github"></i></a>
<a href="https://www.linkedin.com/in/charlesmeredith1" target="_blank"><i className="fa fa-linkedin"></i></a>
<span className="footer-elements">Ryan Reynolds </span>
<a href="https://github.com/reynoldsryan" target="_blank"><i className="fa fa-github"></i></a>
<a href="https://www.linkedin.com/in/ryan-reynolds-8140963b" target="_blank"><i className="fa fa-linkedin"></i></a>
</div>
</div>
</footer>
)
}
}
/*
<footer class="mdl-mini-footer">
<div class="mdl-mini-footer__left-section">
<div class="mdl-logo">
LinkedIn
</div>
<ul class="mdl-mini-footer__link-list">
<li><img href='https://www.linkedin.com/in/ryanscottreynolds' src='' /></li>
<li><a href="#">Privacy and Terms</a></li>
<li><a href="#">User Agreement</a></li>
</ul>
</div>
<div class="mdl-mini-footer__right-section">
</div>
</footer>;
}
}
*/
|
app/webroot/js/jquery-1.11.0.min.js | bazocc4/tokomaju | /*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,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=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.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},n.extend=n.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||n.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&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.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(l.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&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},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=s(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:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.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=s(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),n.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||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=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)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(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 mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(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 typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.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},z=b?function(a,b){if(a===b)return j=!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===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.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=db.selectors={cacheLength:50,createPseudo:fb,match:V,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(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===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]||db.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]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(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(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.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+" ").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(),t=!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&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&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]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)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&&(t&&((l[s]||(l[s]={}))[a]=[u,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()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(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),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?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===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.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 X.test(a.nodeName)},input:function(a){return W.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:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(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]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[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?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;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=[u,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[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(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 sb(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 tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(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?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.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]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(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}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(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&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.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){n.each(b,function(b,c){var d=n.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&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.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},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.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?n.extend(a,d):d}},e={};return d.pipe=d.then,n.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&&n.isFunction(a.promise)?e:0,g=1===f?a:n.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]&&n.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 I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.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()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f
}}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.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=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.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 n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.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=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(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},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.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?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.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]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.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||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.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)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.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=((n.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?n(c,this).index(i)>=0:n.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[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),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||z,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!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.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]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._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 n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.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=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.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,n(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=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={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:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._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++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.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)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.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),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).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=xb(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=xb(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?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.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 n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(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,n.cleanData(vb(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,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.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+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.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 Mb(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=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.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 Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.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 Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(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+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.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=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.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=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)
},a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,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||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.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,n.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 gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.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=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.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],bc.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]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.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 lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),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:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.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(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.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)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._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=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.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)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.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})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.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=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.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||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.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}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.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 n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={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}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.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||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.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=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.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(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.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(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._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(vc," ").indexOf(b)>=0)return!0;return!1}}),n.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){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.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 wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.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||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.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 Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.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 Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(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 Qc(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}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,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":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.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=Dc.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||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.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]?", "+Kc+"; 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=Nc(Jc,k,b,v)){v.readyState=1,h&&m.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=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.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&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(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(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;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 Yc[g],b=void 0,f.onreadystatechange=n.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=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.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 ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.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,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.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,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(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"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.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?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n}); |
src/Info/BRCApproved/index.js | NERC-CEH/irecord-app | import React from 'react';
import AppHeader from 'Components/Header';
import { IonList, IonLabel, IonItem, IonPage } from '@ionic/react';
import AppMain from 'Components/Main';
import './styles.scss';
import './BRC_approved_logo.png';
export default () => (
<IonPage>
<AppHeader title={t('Help')} />
<AppMain id="help">
<img src="/images/BRC_approved_logo.png" className="brc-approved-logo" />
<IonList lines="none">
<IonItem>
<IonLabel class="ion-text-wrap">
{t(
'Wherever you see this logo on a biological recording app you can be assured that the data you submit will be: made available to experts for quality assurance; made available for conservation and research and preserved for long-term use.'
)}
</IonLabel>
</IonItem>
</IonList>
<IonList lines="none">
<IonItem lines="inset">
<IonLabel class="ion-text-wrap">
<b>{t('This logo indicates that your data is')}:</b>
</IonLabel>
</IonItem>
<IonItem>
<IonLabel class="ion-text-wrap">
{t(
'Sent to the Biological Record Centre’s data warehouse linked to the iRecord system where it accessible to you as the recorder, to an expert community of verifiers and other users of iRecord'
)}
.
</IonLabel>
</IonItem>
<IonItem>
<IonLabel class="ion-text-wrap">
{t(
'Quality assured data is passed onto Local Environmental Records Centres, National Recording Schemes and to the NBN Atlas'
)}
.
</IonLabel>
</IonItem>
</IonList>
<IonList lines="none">
<IonItem lines="inset">
<IonLabel class="ion-text-wrap">
<b>{t('About BRC')}</b>
</IonLabel>
</IonItem>
<IonItem>
{' '}
<IonLabel class="ion-text-wrap">
The{' '}
<a href="http://www.brc.ac.uk" rel="external">
Biological Records Centre
</a>{' '}
(BRC),{' '}
{t(
'established in 1964, is a national focus in the UK for terrestrial and freshwater species recording. BRC works closely with the voluntary recording community, principally through support of national recording schemes and societies. BRC is supported by the Joint Nature Conservation Committee (JNCC) and the UK Centre for Ecology & Hydrology (UKCEH). The work of BRC is a major component of the National Biodiversity Network (NBN)'
)}
.
</IonLabel>
</IonItem>
</IonList>
<IonList lines="none">
<IonItem lines="inset">
<IonLabel class="ion-text-wrap">
<b>{t('Which app should I use?')}</b>
</IonLabel>
</IonItem>
<IonItem>
<IonLabel class="ion-text-wrap">
{t('You might have noticed that several of')}{' '}
<a href="http://www.brc.ac.uk/apps" rel="external">
{t('BRC apps')}
</a>{' '}
{t(
'feature some of the same species? We have introduced the BRC Approved logo to signify that data from our apps all go to the same place. Therefore, you are free to choose which app you use to record a given species. All records will be sent to the same place, treated in the same way and will meet the established standards required by the Biological Record Centre'
)}
.
</IonLabel>
</IonItem>
</IonList>
</AppMain>
</IonPage>
);
|
src/components/Header/Header.js | tlin108/chaf | /**
* 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 React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Header.css';
import Link from '../Link';
import Navigation from '../Navigation';
import logoUrl from './logo-small.png';
import logoUrl2x from './[email protected]';
class Header extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<Navigation />
<Link className={s.brand} to="/">
<img src={logoUrl} srcSet={`${logoUrl2x} 2x`} width="38" height="38" alt="React" />
<span className={s.brandTxt}>Your Company</span>
</Link>
<div className={s.banner}>
<h1 className={s.bannerTitle}>React</h1>
<p className={s.bannerDesc}>Complex web apps made easy</p>
</div>
</div>
</div>
);
}
}
export default withStyles(s)(Header);
|
CompositeUi/src/views/component/Form.js | kreta/kreta | /*
* This file is part of the Kreta package.
*
* (c) Beñat Espiña <[email protected]>
* (c) Gorka Laucirica <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import './../../scss/components/_form.scss';
import React from 'react';
const Form = props => {
const {children, ...otherProps} = props;
return (
<form className="form" {...otherProps}>
{children}
</form>
);
};
export default Form;
|
ajax/libs/react-data-grid/0.12.7/react-data-grid-with-addons.min.js | brix/cdnjs | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.ReactDataGrid=t(require("react")):e.ReactDataGrid=t(e.React)}(this,function(e){return function(e){function t(s){if(r[s])return r[s].exports;var o=r[s]={exports:{},id:s,loaded:!1};return e[s].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){e.exports=r(44),e.exports.Editors=r(51),e.exports.Formatters=r(53),e.exports.Toolbar=r(54)},function(t,r,s){t.exports=e},function(e,t,r){var s=r(1),o={name:s.PropTypes.string.isRequired,key:s.PropTypes.string.isRequired,width:s.PropTypes.number.isRequired};e.exports=o},function(e,t,r){function s(){for(var e,t="",r=0;r<arguments.length;r++)if(e=arguments[r])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+s.apply(null,e);else if("object"==typeof e)for(var o in e)e.hasOwnProperty(o)&&e[o]&&(t+=" "+o);return t.substr(1)}var o,n;"undefined"!=typeof e&&e.exports&&(e.exports=s),o=[],n=function(){return s}.apply(t,o),!(void 0!==n&&(e.exports=n))},function(e,t,r){(function(t){"use strict";function s(e,r){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?l(!e.ref,"You are calling cloneWithProps() on a child with a ref. This is dangerous because you're creating a new child which will not be added as a ref to its parent."):null);var s=n.mergeProps(r,e.props);return!s.hasOwnProperty(a)&&e.props.hasOwnProperty(a)&&(s.children=e.props.children),o.createElement(e.type,s)}var o=r(21),n=r(22),i=r(25),l=r(8),a=i({children:null});e.exports=s}).call(t,r(6))},function(e,t,r){function s(e){return function(){return e}}function o(){}o.thatReturns=s,o.thatReturnsFalse=s(!1),o.thatReturnsTrue=s(!0),o.thatReturnsNull=s(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},e.exports=o},function(e,t,r){function s(){if(!l){l=!0;for(var e,t=i.length;t;){e=i,i=[];for(var r=-1;++r<t;)e[r]();t=i.length}l=!1}}function o(){}var n=e.exports={},i=[],l=!1;n.nextTick=function(e){i.push(e),l||setTimeout(s,0)},n.title="browser",n.browser=!0,n.env={},n.argv=[],n.version="",n.versions={},n.on=o,n.addListener=o,n.once=o,n.off=o,n.removeListener=o,n.removeAllListeners=o,n.emit=o,n.binding=function(e){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(e){throw new Error("process.chdir is not supported")},n.umask=function(){return 0}},function(e,t,r){"use strict";var s=(r(1),{propTypes:{},onKeyDown:function(e){if(this.isCtrlKeyHeldDown(e))this.checkAndCall("onPressKeyWithCtrl",e);else if(this.isKeyIdentified(e.key)){var t="onPress"+e.key;this.checkAndCall(t,e)}else this.isKeyPrintable(e.keyCode)&&this.checkAndCall("onPressChar",e)},isKeyPrintable:function(e){var t=e>47&&58>e||32==e||13==e||e>64&&91>e||e>95&&112>e||e>185&&193>e||e>218&&223>e;return t},isKeyIdentified:function(e){return"Unidentified"!==e},isCtrlKeyHeldDown:function(e){return e.ctrlKey===!0&&"Control"!==e.key},checkAndCall:function(e,t){"function"==typeof this[e]&&this[e](t)}});e.exports=s},function(e,t,r){(function(t){"use strict";var s=r(5),o=s;"production"!==t.env.NODE_ENV&&(o=function(e,t){for(var r=[],s=2,o=arguments.length;o>s;s++)r.push(arguments[s]);if(void 0===t)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(!e){var n=0;console.warn("Warning: "+t.replace(/%s/g,function(){return r[n++]}))}}),e.exports=o}).call(t,r(6))},function(e,t,r){"use strict";function s(e){var t,r,s,o=0,n=e.totalWidth,l=[],a=e.columns.map(i);for(t=0,r=a.length;r>t;t++)s=a[t],s.width?(/^([0-9]+)%$/.exec(s.width.toString())&&(s.width=Math.floor(s.width/100*e.totalWidth)),n-=s.width,o+=s.width):l.push(s);for(t=0,r=l.length;r>t;t++)s=l[t],s.width=0>=n?e.minColumnWidth:Math.floor(n/l.length),o+=s.width;var p=0;for(t=0,r=a.length;r>t;t++)s=a[t],s.left=p,p+=s.width;return{columns:a,width:o,totalWidth:e.totalWidth,minColumnWidth:e.minColumnWidth}}function o(e,t,r){var o=e.columns[t];e=i(e),e.columns=e.columns.slice(0);var n=i(o);return n.width=Math.max(r,e.minColumnWidth),e.columns.splice(t,1,n),s(e)}function n(e,t,r){var s,o,n,i={},l={};if(e.length!==t.length)return!1;for(s=0,o=e.length;o>s;s++)n=e[s],i[n.key]=n;for(s=0,o=t.length;o>s;s++){n=t[s],l[n.key]=n;var a=i[n.key];if(void 0===a||!r(a,n))return!1}for(s=0,o=e.length;o>s;s++){n=e[s];var p=l[n.key];if(void 0===p)return!1}return!0}var i=r(12),l=(r(1).isValidElement,r(27));e.exports={calculate:s,resizeColumn:o,sameColumn:l,sameColumns:n}},function(e,t,r){"use strict";var s=r(1),o=r(5),n=r(12),i={metricsComputator:s.PropTypes.object},l={childContextTypes:i,getChildContext:function(){return{metricsComputator:this}},getMetricImpl:function(e){return this._DOMMetrics.metrics[e].value},registerMetricsImpl:function(e,t){var r={},s=this._DOMMetrics;for(var o in t){if(void 0!==s.metrics[o])throw new Error("DOM metric "+o+" is already defined");s.metrics[o]={component:e,computator:t[o].bind(e)},r[o]=this.getMetricImpl.bind(null,o)}return-1===s.components.indexOf(e)&&s.components.push(e),r},unregisterMetricsFor:function(e){var t=this._DOMMetrics,r=t.components.indexOf(e);if(r>-1){t.components.splice(r,1);var s,o={};for(s in t.metrics)t.metrics[s].component===e&&(o[s]=!0);for(s in o)delete t.metrics[s]}},updateMetrics:function(){var e=this._DOMMetrics,t=!1;for(var r in e.metrics){var s=e.metrics[r].computator();s!==e.metrics[r].value&&(t=!0),e.metrics[r].value=s}if(t)for(var o=0,n=e.components.length;n>o;o++)e.components[o].metricsUpdated&&e.components[o].metricsUpdated()},componentWillMount:function(){this._DOMMetrics={metrics:{},components:[]}},componentDidMount:function(){window.addEventListener?window.addEventListener("resize",this.updateMetrics):window.attachEvent("resize",this.updateMetrics),this.updateMetrics()},componentWillUnmount:function(){window.removeEventListener("resize",this.updateMetrics)}},a={contextTypes:i,componentWillMount:function(){if(this.DOMMetrics){this._DOMMetricsDefs=n(this.DOMMetrics),this.DOMMetrics={};for(var e in this._DOMMetricsDefs)this.DOMMetrics[e]=o}},componentDidMount:function(){this.DOMMetrics&&(this.DOMMetrics=this.registerMetrics(this._DOMMetricsDefs))},componentWillUnmount:function(){return this.registerMetricsImpl?void(this.hasOwnProperty("DOMMetrics")&&delete this.DOMMetrics):this.context.metricsComputator.unregisterMetricsFor(this)},registerMetrics:function(e){return this.registerMetricsImpl?this.registerMetricsImpl(this,e):this.context.metricsComputator.registerMetricsImpl(this,e)},getMetric:function(e){return this.getMetricImpl?this.getMetricImpl(e):this.context.metricsComputator.getMetricImpl(e)}};e.exports={MetricsComputatorMixin:l,MetricsMixin:a}},function(e,t,r){"use strict";var s=r(1),o=r(3),n=r(17),i=(r(4),r(9)),l=s.createClass({displayName:"Row",propTypes:{height:s.PropTypes.number.isRequired,columns:s.PropTypes.array.isRequired,row:s.PropTypes.object.isRequired,cellRenderer:s.PropTypes.func,isSelected:s.PropTypes.bool,idx:s.PropTypes.number.isRequired,expandedRows:s.PropTypes.arrayOf(s.PropTypes.object)},render:function(){var e=o("react-grid-Row","react-grid-Row--${this.props.idx % 2 === 0 ? 'even' : 'odd'}"),t={height:this.getRowHeight(this.props),overflow:"hidden"},r=this.getCells();return s.createElement("div",s.__spread({},this.props,{className:e,style:t,onDragEnter:this.handleDragEnter}),s.isValidElement(this.props.row)?this.props.row:r)},getCells:function(){for(var e=[],t=[],r=0,o=this.props.columns.length;o>r;r++){var n=this.props.columns[r],i=this.props.cellRenderer,l=s.createElement(i,{ref:r,key:r,idx:r,rowIdx:this.props.idx,value:this.getCellValue(n.key||r),column:n,height:this.getRowHeight(),formatter:n.formatter,cellMetaData:this.props.cellMetaData,rowData:this.props.row});n.locked?t.push(l):e.push(l)}return e.concat(t)},getRowHeight:function(){var e=this.props.expandedRows||null;if(e&&this.props.key){var t=e[this.props.key]||null;if(t)return t.height}return this.props.height},getCellValue:function(e){if("select-row"===e)return this.props.isSelected;var t=this.props.row[e];return t?t:""},getDefaultProps:function(){return{cellRenderer:n,isSelected:!1,height:35}},setScrollLeft:function(e){for(var t=0,r=this.props.columns.length;r>t;t++)this.props.columns[t].locked&&this.refs[t].setScrollLeft(e)},doesRowContainSelectedCell:function(e){var t=e.cellMetaData.selected;return t&&t.rowIdx===e.idx?!0:!1},willRowBeDraggedOver:function(e){var t=e.cellMetaData.dragged;return null!=t&&(t.rowIdx||t.complete===!0)},hasRowBeenCopied:function(){var e=this.props.cellMetaData.copied;return null!=e&&e.rowIdx===this.props.idx},shouldComponentUpdate:function(e){return!i.sameColumns(this.props.columns,e.columns,i.sameColumn)||this.doesRowContainSelectedCell(this.props)||this.doesRowContainSelectedCell(e)||this.willRowBeDraggedOver(e)||e.row!==this.props.row||this.hasRowBeenCopied()||e.height!==this.props.height},handleDragEnter:function(){var e=this.props.cellMetaData.handleDragEnterRow;e&&e(this.props.idx)}});e.exports=l},function(e,t,r){"use strict";function s(e){var t={};for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t}e.exports=s},function(e,t,r){"use strict";function s(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=Object.assign||function(e,t){for(var r,o,n=s(e),i=1;i<arguments.length;i++){r=arguments[i],o=Object.keys(Object(r));for(var l=0;l<o.length;l++)n[o[l]]=r[o[l]]}return n}},function(e,t,r){function s(e,t){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var r=Object(e),s=Object.prototype.hasOwnProperty,o=1;o<arguments.length;o++){var n=arguments[o];if(null!=n){var i=Object(n);for(var l in i)s.call(i,l)&&(r[l]=i[l])}}return r}e.exports=s},function(e,t,r){"use strict";function s(e,t){if(e===t)return!0;var r;for(r in e)if(e.hasOwnProperty(r)&&(!t.hasOwnProperty(r)||e[r]!==t[r]))return!1;for(r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}e.exports=s},function(e,t,r){"use strict";var s=function(e){var t={};return e&&"[object Function]"===t.toString.call(e)};e.exports=s},function(e,t,r){"use strict";var s=r(1),o=r(3),n=r(4),i=r(43),l=r(2),a=r(16),p=r(35),u=s.createClass({displayName:"Cell",propTypes:{rowIdx:s.PropTypes.number.isRequired,idx:s.PropTypes.number.isRequired,selected:s.PropTypes.shape({idx:s.PropTypes.number.isRequired}),tabIndex:s.PropTypes.number,ref:s.PropTypes.string,column:s.PropTypes.shape(l).isRequired,value:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number,s.PropTypes.object,s.PropTypes.bool]).isRequired,isExpanded:s.PropTypes.bool,cellMetaData:s.PropTypes.shape(p).isRequired,handleDragStart:s.PropTypes.func,className:s.PropTypes.string,rowData:s.PropTypes.object.isRequired},getDefaultProps:function(){return{tabIndex:-1,ref:"cell",isExpanded:!1}},componentDidMount:function(){this.checkFocus()},componentDidUpdate:function(e,t){this.checkFocus();var r=this.props.cellMetaData.dragged;r&&r.complete===!0&&this.props.cellMetaData.handleTerminateDrag()},shouldComponentUpdate:function(e,t){return this.props.column.width!==e.column.width||this.props.column.left!==e.column.left||this.props.value!==e.value||this.props.height!==e.height||this.props.rowIdx!==e.rowIdx||this.isCellSelectionChanging(e)||this.isDraggedCellChanging(e)},getStyle:function(){var e={position:"absolute",width:this.props.column.width,height:this.props.height,left:this.props.column.left};return e},render:function(){var e=this.getStyle(),t=this.getCellClass(),r=this.renderCellContent({value:this.props.value,column:this.props.column,rowIdx:this.props.rowIdx,isExpanded:this.props.isExpanded});return s.createElement("div",s.__spread({},this.props,{className:t,style:e,onClick:this.onCellClick,onDoubleClick:this.onCellDoubleClick}),r,s.createElement("div",{className:"drag-handle",draggable:"true"}))},renderCellContent:function(e){var t,r=this.getFormatter();return s.isValidElement(r)?(e.dependentValues=this.getFormatterDependencies(),t=n(r,e)):t=a(r)?s.createElement(r,{value:this.props.value,dependentValues:this.getFormatterDependencies()}):s.createElement(c,{value:this.props.value}),s.createElement("div",{className:"react-grid-Cell__value"},t," ",this.props.cellControls)},isSelected:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:e.selected&&e.selected.rowIdx===this.props.rowIdx&&e.selected.idx===this.props.idx},isActive:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:this.isSelected()&&e.selected.active===!0},isCellSelectionChanging:function(e){var t=this.props.cellMetaData;if(null==t||null==t.selected)return!1;var r=e.cellMetaData.selected;return t.selected&&r?this.props.idx===r.idx||this.props.idx===t.selected.idx:!0},getFormatter:function(){var e=this.props.column;return this.isActive()?s.createElement(i,{rowData:this.props.rowData,rowIdx:this.props.rowIdx,idx:this.props.idx,cellMetaData:this.props.cellMetaData,column:e,height:this.props.height}):this.props.column.formatter},getFormatterDependencies:function(){this.props.column.ItemId;return"function"==typeof this.props.column.getRowMetaData?this.props.column.getRowMetaData(this.props.rowData,this.props.column):void 0},onCellClick:function(e){e&&"function"==typeof e.preventDefault&&e.preventDefault(),e&&"function"==typeof e.stopPropagation&&e.stopPropagation();var t=this.props.cellMetaData;null!=t&&null!=t.onCellClick&&t.onCellClick({rowIdx:this.props.rowIdx,idx:this.props.idx})},onCellDoubleClick:function(e){e&&"function"==typeof e.preventDefault&&e.preventDefault(),e&&"function"==typeof e.stopPropagation&&e.stopPropagation();var t=this.props.cellMetaData;null!=t&&null!=t.onCellDoubleClick&&t.onCellDoubleClick({rowIdx:this.props.rowIdx,idx:this.props.idx})},checkFocus:function(){this.isSelected()&&!this.isActive()&&this.getDOMNode().focus()},getCellClass:function(){var e=o(this.props.column.cellClass,"react-grid-Cell",this.props.className,this.props.column.locked?"react-grid-Cell--locked":null),t=o({selected:this.isSelected()&&!this.isActive(),editing:this.isActive(),copied:this.isCopied(),"active-drag-cell":this.isSelected()||this.isDraggedOver(),"is-dragged-over-up":this.isDraggedOverUpwards(),"is-dragged-over-down":this.isDraggedOverDownwards(),"was-dragged-over":this.wasDraggedOver()});return e+" "+t},setScrollLeft:function(e){var t=this;if(t.isMounted()){var r=this.getDOMNode(),s="translate3d("+e+"px, 0px, 0px)";r.style.webkitTransform=s,r.style.transform=s}},isCopied:function(){var e=this.props.cellMetaData.copied;return e&&e.rowIdx===this.props.rowIdx&&e.idx===this.props.idx},isDraggedOver:function(){var e=this.props.cellMetaData.dragged;return e&&e.overRowIdx===this.props.rowIdx&&e.idx===this.props.idx},wasDraggedOver:function(){var e=this.props.cellMetaData.dragged;return e&&(e.overRowIdx<this.props.rowIdx&&this.props.rowIdx<e.rowIdx||e.overRowIdx>this.props.rowIdx&&this.props.rowIdx>e.rowIdx)&&e.idx===this.props.idx},isDraggedCellChanging:function(e){var t,r=this.props.cellMetaData.dragged,s=e.cellMetaData.dragged;return r?t=s&&this.props.idx===s.idx||r&&this.props.idx===r.idx:!1},isDraggedOverUpwards:function(){var e=this.props.cellMetaData.dragged;return!this.isSelected()&&this.isDraggedOver()&&this.props.rowIdx<e.rowIdx},isDraggedOverDownwards:function(){var e=this.props.cellMetaData.dragged;return!this.isSelected()&&this.isDraggedOver()&&this.props.rowIdx>e.rowIdx}}),c=s.createClass({displayName:"SimpleCellFormatter",propTypes:{value:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number,s.PropTypes.object,s.PropTypes.bool]).isRequired},render:function(){return s.createElement("span",null,this.props.value)}});e.exports=u},function(e,t,r){"use strict";var s=r(1),o=(r(7),r(2)),n=s.createClass({displayName:"SimpleTextEditor",propTypes:{value:s.PropTypes.any.isRequired,onBlur:s.PropTypes.func.isRequired,column:s.PropTypes.shape(o).isRequired},getValue:function(){var e={};return e[this.props.column.key]=this.refs.input.getDOMNode().value,e},getInputNode:function(){return this.getDOMNode()},render:function(){return s.createElement("input",{ref:"input",type:"text",onBlur:this.props.onBlur,className:"form-control",defaultValue:this.props.value})}});e.exports=n},function(e,t,r){"use strict";var s=r(14),o={current:{},withContext:function(e,t){var r,n=o.current;o.current=s({},n,e);try{r=t()}finally{o.current=n}return r}};e.exports=o},function(e,t,r){"use strict";var s={current:null};e.exports=s},function(e,t,r){(function(t){"use strict";function s(e,r){Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:function(){return this._store?this._store[r]:null},set:function(e){"production"!==t.env.NODE_ENV?l(!1,"Don't set the "+r+" property of the component. Mutate the existing props object instead."):null,this._store[r]=e}})}function o(e){try{var t={props:!0};for(var r in t)s(e,r);p=!0}catch(o){}}var n=r(19),i=r(20),l=r(8),a={key:!0,ref:!0},p=!1,u=function(e,r,s,o,n,i){return this.type=e,this.key=r,this.ref=s,this._owner=o,this._context=n,"production"!==t.env.NODE_ENV&&(this._store={validated:!1,props:i},p)?void Object.freeze(this):void(this.props=i)};u.prototype={_isReactElement:!0},"production"!==t.env.NODE_ENV&&o(u.prototype),u.createElement=function(e,r,s){var o,p={},c=null,h=null;if(null!=r){h=void 0===r.ref?null:r.ref,"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?l(null!==r.key,"createElement(...): Encountered component with a `key` of null. In a future version, this will be treated as equivalent to the string 'null'; instead, provide an explicit key or use undefined."):null),c=null==r.key?null:""+r.key;for(o in r)r.hasOwnProperty(o)&&!a.hasOwnProperty(o)&&(p[o]=r[o])}var d=arguments.length-2;if(1===d)p.children=s;else if(d>1){for(var f=Array(d),m=0;d>m;m++)f[m]=arguments[m+2];p.children=f}if(e&&e.defaultProps){var g=e.defaultProps;for(o in g)"undefined"==typeof p[o]&&(p[o]=g[o])}return new u(e,c,h,i.current,n.current,p)},u.createFactory=function(e){var t=u.createElement.bind(null,e);return t.type=e,t},u.cloneAndReplaceProps=function(e,r){var s=new u(e.type,e.key,e.ref,e._owner,e._context,r);return"production"!==t.env.NODE_ENV&&(s._store.validated=e._store.validated),s},u.isValidElement=function(e){var t=!(!e||!e._isReactElement);return t},e.exports=u}).call(t,r(6))},function(e,t,r){(function(t){"use strict";function s(e){return function(t,r,s){t[r]=t.hasOwnProperty(r)?e(t[r],s):s}}function o(e,t){for(var r in t)if(t.hasOwnProperty(r)){var s=h[r];s&&h.hasOwnProperty(r)?s(e,r,t[r]):e.hasOwnProperty(r)||(e[r]=t[r])}return e}var n=r(14),i=r(5),l=r(23),a=r(24),p=r(8),u=!1,c=s(function(e,t){return n({},t,e)}),h={children:i,className:s(a),style:c},d={TransferStrategies:h,mergeProps:function(e,t){return o(n({},e),t)},Mixin:{transferPropsTo:function(e){return"production"!==t.env.NODE_ENV?l(e._owner===this,"%s: You can't call transferPropsTo() on a component that you don't own, %s. This usually means you are calling transferPropsTo() on a component passed in as props or children.",this.constructor.displayName,"string"==typeof e.type?e.type:e.type.displayName):l(e._owner===this),"production"!==t.env.NODE_ENV&&(u||(u=!0,"production"!==t.env.NODE_ENV?p(!1,"transferPropsTo is deprecated. See http://fb.me/react-transferpropsto for more information."):null)),o(e.props,this.props),e}}};e.exports=d}).call(t,r(6))},function(e,t,r){(function(t){"use strict";var r=function(e,r,s,o,n,i,l,a){if("production"!==t.env.NODE_ENV&&void 0===r)throw new Error("invariant requires an error message argument");if(!e){var p;if(void 0===r)p=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var u=[s,o,n,i,l,a],c=0;p=new Error("Invariant Violation: "+r.replace(/%s/g,function(){return u[c++]}))}throw p.framesToPop=1,p}};e.exports=r}).call(t,r(6))},function(e,t,r){"use strict";function s(e){e||(e="");var t,r=arguments.length;if(r>1)for(var s=1;r>s;s++)t=arguments[s],t&&(e=(e?e+" ":"")+t);return e}e.exports=s},function(e,t,r){var s=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};e.exports=s},function(e,t,r){"use strict";var s=r(1),o=r(3),n=s.PropTypes,i=r(4),l=r(15),a=r(5),p=r(37),u=r(11),c=r(2),h=s.createClass({displayName:"Canvas",mixins:[p],propTypes:{rowRenderer:n.oneOfType([n.func,n.element]),rowHeight:n.number.isRequired,height:n.number.isRequired,displayStart:n.number.isRequired,displayEnd:n.number.isRequired,rowsCount:n.number.isRequired,rowGetter:n.oneOfType([n.func.isRequired,n.array.isRequired]),onRows:n.func,columns:n.arrayOf(s.PropTypes.shape(c)).isRequired},render:function(){var e=this.state.displayStart,t=this.state.displayEnd,r=this.props.rowHeight,n=this.props.rowsCount,i=this.getRows(e,t).map(function(t,s){return this.renderRow({key:e+s,ref:s,idx:e+s,row:t,height:r,columns:this.props.columns,isSelected:this.isRowSelected(e+s),expandedRows:this.props.expandedRows,cellMetaData:this.props.cellMetaData})}.bind(this));this._currentRowsLength=i.length,e>0&&i.unshift(this.renderPlaceholder("top",e*r)),n-t>0&&i.push(this.renderPlaceholder("bottom",(n-t)*r));var l={position:"absolute",top:0,left:0,overflowX:"auto",overflowY:"scroll",width:this.props.totalWidth,height:this.props.height,transform:"translate3d(0, 0, 0)"};return s.createElement("div",{style:l,onScroll:this.onScroll,className:o("react-grid-Canvas",this.props.className,{opaque:this.props.cellMetaData.selected&&this.props.cellMetaData.selected.active})},s.createElement("div",{style:{width:this.props.width,overflow:"hidden"}},i))},renderRow:function(e){var t=this.props.rowRenderer;return"function"==typeof t?s.createElement(t,s.__spread({},e)):s.isValidElement(this.props.rowRenderer)?i(this.props.rowRenderer,e):void 0},renderPlaceholder:function(e,t){return s.createElement("div",{key:e,style:{height:t}},this.props.columns.map(function(e,t){return s.createElement("div",{style:{width:e.width},key:t})}))},getDefaultProps:function(){return{rowRenderer:u,onRows:a}},isRowSelected:function(e){return this.props.selectedRows&&this.props.selectedRows[e]===!0},_currentRowsLength:0,_currentRowsRange:{start:0,end:0},_scroll:{scrollTop:0,scrollLeft:0},getInitialState:function(){return{shouldUpdate:!0,displayStart:this.props.displayStart,displayEnd:this.props.displayEnd}},componentWillMount:function(){this._currentRowsLength=0,this._currentRowsRange={start:0,end:0},this._scroll={scrollTop:0,scrollLeft:0}},componentDidMount:function(){this.onRows()},componentDidUpdate:function(e){this._scroll!=={start:0,end:0}&&this.setScrollLeft(this._scroll.scrollLeft),this.onRows()},componentWillUnmount:function(){this._currentRowsLength=0,this._currentRowsRange={start:0,end:0},this._scroll={scrollTop:0,scrollLeft:0}},componentWillReceiveProps:function(e){e.rowsCount>this.props.rowsCount&&(this.getDOMNode().scrollTop=e.rowsCount*this.props.rowHeight);var t=!(e.visibleStart>this.state.displayStart&&e.visibleEnd<this.state.displayEnd&&e.rowsCount===this.props.rowsCount&&e.rowHeight===this.props.rowHeight&&e.columns===this.props.columns&&e.width===this.props.width&&l(e.style,this.props.style));this.setState(t?{shouldUpdate:!0,displayStart:e.displayStart,displayEnd:e.displayEnd}:{shouldUpdate:!1})},shouldComponentUpdate:function(e,t){return!t||t.shouldUpdate},onRows:function(){this._currentRowsRange!=={start:0,end:0}&&(this.props.onRows(this._currentRowsRange),this._currentRowsRange={start:0,end:0})},getRows:function(e,t){if(this._currentRowsRange={start:e,end:t},Array.isArray(this.props.rowGetter))return this.props.rowGetter.slice(e,t);for(var r=[],s=e;t>s;s++)r.push(this.props.rowGetter(s));return r},setScrollLeft:function(e){if(0!==this._currentRowsLength)for(var t=0,r=this._currentRowsLength;r>t;t++)this.refs[t]&&this.refs[t].setScrollLeft(e)},getScroll:function(){var e=this.getDOMNode(),t=e.scrollTop,r=e.scrollLeft;return{scrollTop:t,scrollLeft:r}},onScroll:function(e){this.appendScrollShim();var t=e.target,r=t.scrollTop,s=t.scrollLeft,o={scrollTop:r,scrollLeft:s};this._scroll=o,this.props.onScroll(o)}});e.exports=h},function(e,t,r){var s=r(1).isValidElement;e.exports=function(e,t){var r;for(r in e)if(e.hasOwnProperty(r)){if("function"==typeof e[r]&&"function"==typeof t[r]||s(e[r])&&s(t[r]))continue;if(!t.hasOwnProperty(r)||e[r]!==t[r])return!1}for(r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}},function(e,t,r){function s(){"use strict"}var o=r(9),n=r(10);Object.assign=r(13);var i=r(1).PropTypes;e.exports={mixins:[n.MetricsMixin],propTypes:{columns:i.arrayOf(s),minColumnWidth:i.number,columnEquality:i.func},DOMMetrics:{gridWidth:function(){return this.getDOMNode().offsetWidth-2}},getDefaultProps:function(){return{minColumnWidth:80,columnEquality:o.sameColumn}},getInitialState:function(){return this.getColumnMetricsType(this.props,!0)},componentWillReceiveProps:function(e){if(e.columns)if(o.sameColumns(this.props.columns,e.columns,this.props.columnEquality)){var t=this.adjustColumnWidths(e);this.setState({columns:t})}else{var r=this.getColumnMetricsType(e);r.columns=this.adjustColumnWidths(r.columns),this.setState(r)}},adjustColumnWidths:function(e){var t={};this.state.columns.columns.forEach(function(e){t[e.key]={width:e.width,left:e.left}});var r=Object.assign(this.state.columns,{columns:e.columns.map(function(e){return Object.assign(e,t[e.key])})});return r},getColumnMetricsType:function(e,t){var r=t?t:this.DOMMetrics.gridWidth();return{columns:o.calculate({columns:e.columns,totalWidth:r,minColumnWidth:e.minColumnWidth}),gridWidth:r}},metricsUpdated:function(){this.setState(this.getColumnMetricsType(this.props))},onColumnResize:function(e,t){var r=o.resizeColumn(this.state.columns,e,t);this.setState({columns:r})}}},function(e,t,r){"use strict";var s=r(1),o=s.PropTypes,n=r(5),i=s.createClass({displayName:"Draggable",propTypes:{onDragStart:o.func,onDragEnd:o.func,onDrag:o.func,component:o.oneOfType([o.func,o.constructor])},render:function(){this.props.component;return s.createElement("div",s.__spread({},this.props,{onMouseDown:this.onMouseDown}))},getDefaultProps:function(){return{onDragStart:n.thatReturnsTrue,onDragEnd:n,onDrag:n}},getInitialState:function(){return{drag:null}},onMouseDown:function(e){var t=this.props.onDragStart(e);(null!==t||0===e.button)&&(window.addEventListener("mouseup",this.onMouseUp),window.addEventListener("mousemove",this.onMouseMove),this.setState({drag:t}))},onMouseMove:function(e){null!==this.state.drag&&(e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault(),this.props.onDrag(e))},onMouseUp:function(e){this.cleanUp(),this.props.onDragEnd(e,this.state.drag),this.setState({drag:null})},componentWillUnmount:function(){this.cleanUp()},cleanUp:function(){window.removeEventListener("mouseup",this.onMouseUp),window.removeEventListener("mousemove",this.onMouseMove)}});e.exports=i},function(e,t,r){"use strict";var s=r(1),o=s.PropTypes,n=r(32),i=r(38),l=r(10),a=r(31),p=r(28),u=r(2),c=s.createClass({displayName:"Grid",mixins:[a,p,l.MetricsComputatorMixin],propTypes:{rowGetter:o.oneOfType([o.array,o.func]).isRequired,columns:o.arrayOf(s.PropTypes.shape(u)).isRequired,minHeight:o.number,headerRows:o.oneOfType([o.array,o.func]),rowHeight:o.number,rowRenderer:o.func,expandedRows:o.oneOfType([o.array,o.func]),selectedRows:o.oneOfType([o.array,o.func]),rowsCount:o.number,onRows:o.func,sortColumn:s.PropTypes.string.isRequired,sortDirection:s.PropTypes.oneOf(["ASC","DESC","NONE"]),rowOffsetHeight:o.number.isRequired,onViewportKeydown:o.func.isRequired,onViewportDragStart:o.func.isRequired,onViewportDragEnd:o.func.isRequired,onViewportDoubleClick:o.func.isRequired},getStyle:function(){return{overflow:"hidden",outline:0,position:"relative",minHeight:this.props.minHeight}},render:function(){var e=this.props.headerRows||[{ref:"row"}];return s.createElement("div",s.__spread({},this.props,{style:this.getStyle(),className:"react-grid-Grid"}),s.createElement(n,{ref:"header",columns:this.state.columns,onColumnResize:this.onColumnResize,height:this.props.rowHeight,totalWidth:this.DOMMetrics.gridWidth(),headerRows:e,sortColumn:this.props.sortColumn,sortDirection:this.props.sortDirection}),s.createElement("div",{ref:"viewPortContainer",onKeyDown:this.props.onViewportKeydown,onDoubleClick:this.props.onViewportDoubleClick,onDragStart:this.props.onViewportDragStart,onDragEnd:this.props.onViewportDragEnd},s.createElement(i,{ref:"viewport",width:this.state.columns.width,rowHeight:this.props.rowHeight,rowRenderer:this.props.rowRenderer,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,selectedRows:this.props.selectedRows,expandedRows:this.props.expandedRows,columns:this.state.columns,totalWidth:this.DOMMetrics.gridWidth(),onScroll:this.onScroll,onRows:this.props.onRows,cellMetaData:this.props.cellMetaData,rowOffsetHeight:this.props.rowOffsetHeight||this.props.rowHeight*e.length,minHeight:this.props.minHeight})))},getDefaultProps:function(){return{rowHeight:35,minHeight:350}}});e.exports=c},function(e,t,r){e.exports={componentDidMount:function(){this._scrollLeft=this.refs.viewport.getScroll().scrollLeft,this._onScroll()},componentDidUpdate:function(){this._onScroll()},componentWillMount:function(){this._scrollLeft=void 0},componentWillUnmount:function(){this._scrollLeft=void 0},onScroll:function(e){this._scrollLeft!==e.scrollLeft&&(this._scrollLeft=e.scrollLeft,this._onScroll())},_onScroll:function(){void 0!==this._scrollLeft&&(this.refs.header.setScrollLeft(this._scrollLeft),this.refs.viewport.setScrollLeft(this._scrollLeft))}}},function(e,t,r){"use strict";var s=r(1),o=r(3),n=r(12),i=r(9),l=r(34),a=s.createClass({displayName:"Header",propTypes:{columns:s.PropTypes.shape({width:s.PropTypes.number.isRequired}).isRequired,totalWidth:s.PropTypes.number,height:s.PropTypes.number.isRequired,headerRows:s.PropTypes.array.isRequired},render:function(){var e=(this.state.resizing||this.props,o({"react-grid-Header":!0,"react-grid-Header--resizing":!!this.state.resizing})),t=this.getHeaderRows();return s.createElement("div",s.__spread({},this.props,{style:this.getStyle(),className:e}),t)},shouldComponentUpdate:function(e,t){var r=!i.sameColumns(this.props.columns.columns,e.columns.columns,i.sameColumn)||this.props.totalWidth!=e.totalWidth||this.props.headerRows.length!=e.headerRows.length||this.state.resizing!=t.resizing||this.props.sortColumn!=e.sortColumn||this.props.sortDirection!=e.sortDirection;return r},getHeaderRows:function(){var e=this.state.resizing||this.props,t=[];return this.props.headerRows.forEach(function(r,o){var n={position:"absolute",top:this.props.height*o,left:0,width:this.props.totalWidth,overflow:"hidden"};t.push(s.createElement(l,{key:r.ref,ref:r.ref,style:n,onColumnResize:this.onColumnResize,onColumnResizeEnd:this.onColumnResizeEnd,width:e.columns.width,height:r.height||this.props.height,columns:e.columns.columns,resizing:e.column,headerCellRenderer:r.headerCellRenderer}))}.bind(this)),t},getInitialState:function(){return{resizing:null}},componentWillReceiveProps:function(e){this.setState({resizing:null})},onColumnResize:function(e,t){var r=this.state.resizing||this.props,s=this.getColumnPosition(e);if(null!=s){var o={columns:n(r.columns)};o.columns=i.resizeColumn(o.columns,s,t),o.columns.totalWidth<r.columns.totalWidth&&(o.columns.totalWidth=r.columns.totalWidth),o.column=o.columns.columns[s],this.setState({resizing:o})}},getColumnPosition:function(e){var t=this.state.resizing||this.props,r=-1;return t.columns.columns.forEach(function(t,s){var o="key";t[o]===e[o]&&(r=s)}),-1===r?null:r},onColumnResizeEnd:function(e,t){var r=this.getColumnPosition(e);null!==r&&this.props.onColumnResize&&this.props.onColumnResize(r,t||e.width)},setScrollLeft:function(e){var t=this.refs.row.getDOMNode();t.scrollLeft=e,this.refs.row.setScrollLeft(e)},getStyle:function(){return{position:"relative",
height:this.props.height*this.props.headerRows.length,overflow:"hidden"}}});e.exports=a},function(e,t,r){"use strict";function s(e){return o.createElement("div",{className:"widget-HeaderCell__value"},e.column.name)}var o=r(1),n=r(3),i=r(4),l=o.PropTypes,a=r(2),p=r(36),u=o.createClass({displayName:"HeaderCell",propTypes:{renderer:l.oneOfType([l.func,l.element]).isRequired,column:l.shape(a).isRequired,onResize:l.func.isRequired,height:l.number.isRequired,onResizeEnd:l.func.isRequired},render:function(){var e;this.props.column.resizable&&(e=o.createElement(p,{onDrag:this.onDrag,onDragStart:this.onDragStart,onDragEnd:this.onDragEnd}));var t=n({"react-grid-HeaderCell":!0,"react-grid-HeaderCell--resizing":this.state.resizing,"react-grid-HeaderCell--locked":this.props.column.locked});t=n(t,this.props.className);var r=this.getCell();return o.createElement("div",{className:t,style:this.getStyle()},r,{resizeHandle:e})},getCell:function(){return o.isValidElement(this.props.renderer)?i(this.props.renderer,{column:this.props.column}):this.props.renderer({column:this.props.column})},getDefaultProps:function(){return{renderer:s}},getInitialState:function(){return{resizing:!1}},setScrollLeft:function(e){var t=this.getDOMNode();t.style.webkitTransform="translate3d("+e+"px, 0px, 0px)",t.style.transform="translate3d("+e+"px, 0px, 0px)"},getStyle:function(){return{width:this.props.column.width,left:this.props.column.left,display:"inline-block",position:"absolute",overflow:"hidden",height:this.props.height,margin:0,textOverflow:"ellipsis",whiteSpace:"nowrap"}},onDragStart:function(){this.setState({resizing:!0})},onDrag:function(e){var t=this.props.onResize||null;if(t){var r=this.getWidthFromMouseEvent(e);r>0&&t(this.props.column,r)}},onDragEnd:function(e){var t=this.getWidthFromMouseEvent(e);this.props.onResizeEnd(this.props.column,t),this.setState({resizing:!1})},getWidthFromMouseEvent:function(e){var t=e.pageX,r=this.getDOMNode().getBoundingClientRect().left;return t-r}});e.exports=u},function(e,t,r){"use strict";var s=r(1),o=s.PropTypes,n=r(15),i=r(33),l=r(45),a=r(2),p={overflow:s.PropTypes.string,width:o.oneOfType([o.number,o.string]),height:s.PropTypes.number,position:s.PropTypes.string},u=s.createClass({displayName:"HeaderRow",propTypes:{width:o.oneOfType([o.number,o.string]),height:o.number.isRequired,columns:o.arrayOf(s.PropTypes.shape(a)).isRequired,onColumnResize:o.func,style:o.shape(p)},render:function(){var e={width:this.props.width?this.props.width+l():"100%",height:this.props.height,whiteSpace:"nowrap",overflowX:"hidden",overflowY:"hidden"},t=this.getCells();return s.createElement("div",s.__spread({},this.props,{className:"react-grid-HeaderRow"}),s.createElement("div",{style:e},t))},getCells:function(){for(var e=[],t=[],r=0,o=this.props.columns.length;o>r;r++){var n=this.props.columns[r],l=s.createElement(i,{ref:r,key:r,height:this.props.height,column:n,renderer:this.props.headerCellRenderer||n.headerRenderer||this.props.cellRenderer,resizing:this.props.resizing===n,onResize:this.props.onColumnResize,onResizeEnd:this.props.onColumnResizeEnd});n.locked?t.push(l):e.push(l)}return e.concat(t)},setScrollLeft:function(e){for(var t=0,r=this.props.columns.length;r>t;t++)this.props.columns[t].locked&&this.refs[t].setScrollLeft(e)},shouldComponentUpdate:function(e){return e.width!==this.props.width||e.height!==this.props.height||e.columns!==this.props.columns||!n(e.style,this.props.style)},getStyle:function(){return{overflow:"hidden",width:"100%",height:this.props.height,position:"absolute"}}});e.exports=u},function(e,t,r){var s=r(1).PropTypes;e.exports={selected:s.object.isRequired,copied:s.object,dragged:s.object,onCellClick:s.func.isRequired}},function(e,t,r){var s=r(1),o=(r(3),r(29)),n=(r(4),s.PropTypes,s.createClass({displayName:"ResizeHandle",style:{position:"absolute",top:0,right:0,width:6,height:"100%"},render:function(){return s.createElement(o,s.__spread({},this.props,{className:"react-grid-HeaderCell__resizeHandle",style:this.style}))}}));e.exports=n},function(e,t,r){"use strict";var s={appendScrollShim:function(){if(!this._scrollShim){var e=this._scrollShimSize(),t=document.createElement("div");t.classList?t.classList.add("react-grid-ScrollShim"):t.className+=" react-grid-ScrollShim",t.style.position="absolute",t.style.top=0,t.style.left=0,t.style.width=e.width+"px",t.style.height=e.height+"px",this.getDOMNode().appendChild(t),this._scrollShim=t}this._scheduleRemoveScrollShim()},_scrollShimSize:function(){return{width:this.props.width,height:this.props.length*this.props.rowHeight}},_scheduleRemoveScrollShim:function(){this._scheduleRemoveScrollShimTimer&&clearTimeout(this._scheduleRemoveScrollShimTimer),this._scheduleRemoveScrollShimTimer=setTimeout(this._removeScrollShim,200)},_removeScrollShim:function(){this._scrollShim&&(this._scrollShim.parentNode.removeChild(this._scrollShim),this._scrollShim=void 0)}};e.exports=s},function(e,t,r){"use strict";var s=r(1),o=r(26),n=s.PropTypes,i=r(39),l=s.createClass({displayName:"Viewport",mixins:[i],propTypes:{rowOffsetHeight:n.number.isRequired,totalWidth:n.number.isRequired,columns:n.shape({width:n.number.isRequired,columns:n.array.isRequired}),rowGetter:n.oneOfType([n.array,n.func]).isRequired,selectedRows:n.array,expandedRows:n.array,rowRenderer:n.func,rowsCount:n.number.isRequired,rowHeight:n.number.isRequired,onRows:n.func,onScroll:n.func,minHeight:n.number},render:function(){var e={padding:0,bottom:0,left:0,right:0,overflow:"hidden",position:"absolute",top:this.props.rowOffsetHeight};return s.createElement("div",{className:"react-grid-Viewport",style:e},s.createElement(o,{ref:"canvas",totalWidth:this.props.totalWidth,width:this.props.columns.width,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,selectedRows:this.props.selectedRows,expandedRows:this.props.expandedRows,columns:this.props.columns.columns,rowRenderer:this.props.rowRenderer,visibleStart:this.state.visibleStart,visibleEnd:this.state.visibleEnd,displayStart:this.state.displayStart,displayEnd:this.state.displayEnd,cellMetaData:this.props.cellMetaData,height:this.state.height,rowHeight:this.props.rowHeight,onScroll:this.onScroll,onRows:this.props.onRows}))},getScroll:function(){return this.refs.canvas.getScroll()},onScroll:function(e){this.updateScroll(e.scrollTop,e.scrollLeft,this.state.height,this.props.rowHeight,this.props.rowsCount),this.props.onScroll&&this.props.onScroll({scrollTop:e.scrollTop,scrollLeft:e.scrollLeft})},setScrollLeft:function(e){this.refs.canvas.setScrollLeft(e)}});e.exports=l},function(e,t,r){var s=r(1),o=r(10),n=(r(46),s.PropTypes,Math.min),i=Math.max,l=Math.floor,a=Math.ceil;e.exports={mixins:[o.MetricsMixin],DOMMetrics:{viewportHeight:function(){return this.getDOMNode().offsetHeight}},propTypes:{rowHeight:s.PropTypes.number,rowsCount:s.PropTypes.number.isRequired},getDefaultProps:function(){return{rowHeight:30}},getInitialState:function(){return this.getGridState(this.props)},getGridState:function(e){var t=a(e.minHeight/e.rowHeight),r=n(2*t,e.rowsCount);return{displayStart:0,displayEnd:r,height:e.minHeight,scrollTop:0,scrollLeft:0}},updateScroll:function(e,t,r,s,o){var p=a(r/s),u=l(e/s),c=n(u+p,o),h=i(0,u-2*p),d=n(u+2*p,o),f={visibleStart:u,visibleEnd:c,displayStart:h,displayEnd:d,height:r,scrollTop:e,scrollLeft:t};this.setState(f)},metricsUpdated:function(){var e=this.DOMMetrics.viewportHeight();e&&this.updateScroll(this.state.scrollTop,this.state.scrollLeft,e,this.props.rowHeight,this.props.rowsCount)},componentWillReceiveProps:function(e){this.props.rowHeight!==e.rowHeight?this.setState(this.getGridState(e)):this.props.rowsCount!==e.rowsCount&&this.updateScroll(this.state.scrollTop,this.state.scrollLeft,this.state.height,e.rowHeight,e.rowsCount)}}},function(e,t,r){"use strict";var s=r(1),o=r(2),n=s.createClass({displayName:"FilterableHeaderCell",propTypes:{onChange:s.PropTypes.func.isRequired,column:s.PropTypes.shape(o).isRequired},getInitialState:function(){return{filterTerm:""}},handleChange:function(e){e.preventDefault(),e.stopPropagation();var t=e.target.value;this.setState({filterTerm:t}),this.props.onChange({filterTerm:t,columnKey:this.props.column.key})},componentDidUpdate:function(e){var t=this.getDOMNode();t&&t.focus()},render:function(){return s.createElement("div",null,s.createElement("div",{className:"form-group"},s.createElement(this.renderInput,null)))},renderInput:function(){return this.props.column.filterable===!1?s.createElement("span",null):s.createElement("input",{type:"text",className:"form-control input-sm",placeholder:"Search",value:this.state.filterTerm,onChange:this.handleChange})}});e.exports=n},function(e,t,r){"use strict";var s=r(1),o=(r(3),r(2),{ASC:"ASC",DESC:"DESC",NONE:"NONE"}),n=s.createClass({displayName:"SortableHeaderCell",propTypes:{columnKey:s.PropTypes.string.isRequired,onSort:s.PropTypes.func.isRequired,sortDirection:s.PropTypes.oneOf(["ASC","DESC","NONE"])},onClick:function(){var e;switch(this.props.sortDirection){case null:case void 0:case o.NONE:e=o.ASC;break;case o.ASC:e=o.DESC;break;case o.DESC:e=o.NONE}this.props.onSort(this.props.columnKey,e)},getSortByText:function(){var e={ASC:"9650",DESC:"9660",NONE:""};return String.fromCharCode(e[this.props.sortDirection])},render:function(){return s.createElement("div",{onClick:this.onClick,style:{cursor:"pointer"}},this.props.column.name,s.createElement("span",{className:"pull-right"},this.getSortByText()))}});e.exports=n},function(e,t,r){"use strict";var s=r(1),o=s.createClass({displayName:"CheckBoxEditor",PropTypes:{value:s.PropTypes.bool.isRequired,rowIdx:s.PropTypes.number.isRequired},render:function(){return s.createElement("input",{className:"react-grid-CheckBox",type:"checkbox",checked:this.props.value,onChange:this.handleChange})},handleChange:function(e){this.props.column.onRowSelect(this.props.rowIdx)},shouldComponentUpdate:function(e,t){return this.props.value!=e.value}});e.exports=o},function(e,t,r){"use strict";var s=r(1),o=r(3),n=r(7),i=r(18),l=r(16),a=(r(4),s.createClass({displayName:"EditorContainer",mixins:[n],propTypes:{rowData:s.PropTypes.object.isRequired,value:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number,s.PropTypes.object,s.PropTypes.bool]).isRequired,cellMetaData:s.PropTypes.shape({selected:s.PropTypes.object.isRequired,copied:s.PropTypes.object,dragged:s.PropTypes.object,onCellClick:s.PropTypes.func,onCellDoubleClick:s.PropTypes.func}).isRequired,column:s.PropTypes.object.isRequired,height:s.PropTypes.number.isRequired},getInitialState:function(){return{isInvalid:!1}},componentWillMount:function(){this.validateEditor()},componentDidMount:function(){var e=this.getInputNode();void 0!==e&&(this.setTextInputFocus(),this.getEditor().disableContainerStyles||(e.className+=" editor-main",e.style.height=this.props.height-1+"px"))},validateEditor:function(){this.props.column.editor},createEditor:function(){var e={ref:"editor",name:"editor",column:this.props.column,value:this.getInitialValue(),onCommit:this.commit,rowMetaData:this.getRowMetaData(),height:this.props.height,onBlur:this.commit,onOverrideKeyDown:this.onKeyDown},t=this.props.column.editor;return t&&s.isValidElement(t)?s.addons.cloneWithProps(t,e):s.createElement(i,{ref:"editor",column:this.props.column,onBlur:this.commit,value:this.getInitialValue(),rowMetaData:this.getRowMetaData()})},getRowMetaData:function(){this.props.column.ItemId;return"function"==typeof this.props.column.getRowMetaData?this.props.column.getRowMetaData(this.props.rowData,this.props.column):void 0},onPressEnter:function(e){e.stopPropagation(),e.preventDefault(),this.commit({key:"Enter"})},onPressTab:function(e){e.stopPropagation(),e.preventDefault(),this.commit({key:"Tab"})},onPressEscape:function(e){e.stopPropagation(),e.preventDefault(),this.props.cellMetaData.onCommitCancel()},onPressArrowDown:function(e){this.editorHasResults()&&(e.stopPropagation(),e.preventDefault())},onPressArrowUp:function(e){this.editorHasResults()&&(e.stopPropagation(),e.preventDefault())},onPressArrowLeft:function(e){this.isCaretAtBeginningOfInput()||e.stopPropagation()},onPressArrowRight:function(e){this.isCaretAtEndOfInput()||e.stopPropagation()},editorHasResults:function(){return"SELECT"===this.getEditor().getInputNode().tagName?!0:l(this.getEditor().hasResults)?this.getEditor().hasResults():!1},getEditor:function(){return this.refs.editor},commit:function(e){var t=this.getEditor().getValue();if(this.isNewValueValid(t)){var r=this.props.column.key;this.props.cellMetaData.onCommit({cellKey:r,rowIdx:this.props.rowIdx,updated:t,key:e.key})}},isNewValueValid:function(e){if(l(this.validate)){var t=this.validate(e);return this.setState({isInvalid:!t}),t}return!0},getInputNode:function(){return this.getEditor().getInputNode()},getInitialValue:function(){var e=this.props.cellMetaData.selected,t=e.initialKeyCode;if("Delete"===t||"Backspace"===t)return"";if("Enter"===t)return this.props.value;var r=t?String.fromCharCode(t):this.props.value;return r},getContainerClass:function(){return o({"has-error":this.state.isInvalid===!0})},renderStatusIcon:function(){return this.state.isInvalid===!0?s.createElement("span",{className:"glyphicon glyphicon-remove form-control-feedback"}):void 0},render:function(){return s.createElement("div",{className:this.getContainerClass(),onKeyDown:this.onKeyDown},this.createEditor(),this.renderStatusIcon())},setCaretAtEndOfInput:function(){var e=this.getInputNode(),t=e.value.length;if(e.setSelectionRange)e.setSelectionRange(t,t);else if(e.createTextRange){var r=e.createTextRange();r.moveStart("character",t),r.collapse(),r.select()}},isCaretAtBeginningOfInput:function(){var e=this.getInputNode();return 0===e.selectionStart},isCaretAtEndOfInput:function(){var e=this.getInputNode();return e.selectionStart===e.value.length},setTextInputFocus:function(){var e=this.props.cellMetaData.selected,t=e.initialKeyCode,r=this.getInputNode();r.focus(),"INPUT"===r.tagName&&(this.isKeyPrintable(t)?r.select():(r.focus(),this.setCaretAtEndOfInput(),r.select()))}}));e.exports=a},function(e,t,r){"use strict";var s=r(1),o=(s.PropTypes,r(30)),n=(r(11),r(2)),i=r(7),l=r(42),a=r(41),p=r(40),u=r(4);Object.assign||(Object.assign=r(13));var c={ASC:"ASC",DESC:"DESC",NONE:"NONE"},h=s.createClass({displayName:"ReactDataGrid",propTypes:{rowHeight:s.PropTypes.number.isRequired,minHeight:s.PropTypes.number.isRequired,enableRowSelect:s.PropTypes.bool,onRowUpdated:s.PropTypes.func,rowGetter:s.PropTypes.func.isRequired,rowsCount:s.PropTypes.number.isRequired,toolbar:s.PropTypes.element,enableCellSelect:s.PropTypes.bool,columns:s.PropTypes.arrayOf(s.PropTypes.shape(n)).isRequired,onFilter:s.PropTypes.func,onCellCopyPaste:s.PropTypes.func,onCellsDragged:s.PropTypes.func,onAddFilter:s.PropTypes.func},mixins:[i],getDefaultProps:function(){return{enableCellSelect:!1,tabIndex:-1,ref:"cell",rowHeight:35,enableRowSelect:!1,minHeight:350}},getInitialState:function(){var e={selectedRows:[],copied:null,expandedRows:[],canFilter:!1,columnFilters:{},sortDirection:null,sortColumn:null,dragged:null};return e.selected=this.props.enableCellSelect?{rowIdx:0,idx:0}:{rowIdx:-1,idx:-1},e},componentWillReceiveProps:function(e){e.rowsCount===this.props.rowsCount+1&&this.onAfterAddRow(e.rowsCount+1)},render:function(){var e={selected:this.state.selected,dragged:this.state.dragged,onCellClick:this.onCellClick,onCellDoubleClick:this.onCellDoubleClick,onCommit:this.onCellCommit,onCommitCancel:this.setInactive,copied:this.state.copied,handleDragEnterRow:this.handleDragEnter,handleTerminateDrag:this.handleTerminateDrag},t=this.renderToolbar();return s.createElement("div",{className:"react-grid-Container"},t,s.createElement("div",{className:"react-grid-Main"},s.createElement(o,s.__spread({ref:"base"},this.props,{headerRows:this.getHeaderRows(),columns:this.getColumns(),rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,cellMetaData:e,selectedRows:this.state.selectedRows,expandedRows:this.state.expandedRows,rowOffsetHeight:this.getRowOffsetHeight(),sortColumn:this.state.sortColumn,sortDirection:this.state.sortDirection,minHeight:this.props.minHeight,onViewportKeydown:this.onKeyDown,onViewportDragStart:this.onDragStart,onViewportDragEnd:this.handleDragEnd,onViewportDoubleClick:this.onViewportDoubleClick}))))},renderToolbar:function(){var e=this.props.toolbar;return s.isValidElement(e)?u(e,{onToggleFilter:this.onToggleFilter,numberOfRows:this.props.rowsCount}):void 0},onSelect:function(e){if(this.props.enableCellSelect)if(this.state.selected.rowIdx===e.rowIdx&&this.state.selected.idx===e.idx&&this.state.selected.active===!0);else{var t=e.idx,r=e.rowIdx;t>=0&&r>=0&&t<this.getColumns().length&&r<this.props.rowsCount&&this.setState({selected:e})}},onCellClick:function(e){this.onSelect({rowIdx:e.rowIdx,idx:e.idx})},onCellDoubleClick:function(e){this.onSelect({rowIdx:e.rowIdx,idx:e.idx}),this.setActive("Enter")},onViewportDoubleClick:function(e){this.setActive()},onPressArrowUp:function(e){this.moveSelectedCell(e,-1,0)},onPressArrowDown:function(e){this.moveSelectedCell(e,1,0)},onPressArrowLeft:function(e){this.moveSelectedCell(e,0,-1)},onPressArrowRight:function(e){this.moveSelectedCell(e,0,1)},onPressTab:function(e){this.moveSelectedCell(e,0,1)},onPressEnter:function(e){this.setActive(e.key)},onPressDelete:function(e){this.setActive(e.key)},onPressEscape:function(e){this.setInactive(e.key)},onPressBackspace:function(e){this.setActive(e.key)},onPressChar:function(e){this.isKeyPrintable(e.keyCode)&&this.setActive(e.keyCode)},onPressKeyWithCtrl:function(e){var t={KeyCode_c:"99",KeyCode_C:"67",KeyCode_V:"86",KeyCode_v:"118"},r=this.state.selected.idx;if(this.canEdit(r))if(e.keyCode===t.KeyCode_c||e.keyCode===t.KeyCode_C){var s=this.getSelectedValue();this.handleCopy({value:s})}else(e.keyCode===t.KeyCode_v||e.keyCode===t.KeyCode_V)&&this.handlePaste()},onDragStart:function(e){var t=this.getSelectedValue();this.handleDragStart({idx:this.state.selected.idx,rowIdx:this.state.selected.rowIdx,value:t})},moveSelectedCell:function(e,t,r){e.stopPropagation(),e.preventDefault();var s=this.state.selected.rowIdx+t,o=this.state.selected.idx+r;this.onSelect({idx:o,rowIdx:s})},getSelectedValue:function(){var e=this.state.selected.rowIdx,t=this.state.selected.idx,r=this.props.enableRowSelect?1:0,s=this.props.columns[t-r].key;return this.props.rowGetter(e)[s]},setActive:function(e){var t=this.state.selected.rowIdx,r=this.state.selected.idx;if(this.canEdit(r)&&!this.isActive()){var s=Object.assign(this.state.selected,{idx:r,rowIdx:t,active:!0,initialKeyCode:e});this.setState({selected:s})}},setInactive:function(){var e=this.state.selected.rowIdx,t=this.state.selected.idx;if(this.canEdit(t)&&this.isActive()){var r=Object.assign(this.state.selected,{idx:t,rowIdx:e,active:!1});this.setState({selected:r})}},canEdit:function(e){return this.props.enableCellSelect===!0&&(null!=this.props.columns[e].editor||this.props.columns[e].editable)},isActive:function(){return this.state.selected.active===!0},onCellCommit:function(e){var t=Object.assign({},this.state.selected);t.active=!1,"Tab"===e.keyCode&&(t.idx+=1);var r=this.state.expandedRows;this.setState({selected:t,expandedRows:r}),this.props.onRowUpdated(e)},getColumns:function(){var e=this.getDecoratedColumns(this.props.columns);return this.props.enableRowSelect&&e.unshift({key:"select-row",name:"",formatter:s.createElement(l,null),onRowSelect:this.handleRowSelect,filterable:!1,headerRenderer:s.createElement("input",{type:"checkbox",onChange:this.handleCheckboxChange}),width:60,locked:!0}),e},handleCheckboxChange:function(e){var t;t=e.currentTarget instanceof HTMLInputElement&&e.currentTarget.checked===!0?!0:!1;for(var r=[],s=0;s<this.props.rowsCount;s++)r.push(t);this.setState({selectedRows:r})},handleRowSelect:function(e){var t=this.state.selectedRows;t[e]=null==t[e]||0==t[e]?!0:!1,this.setState({selectedRows:t})},onAfterAddRow:function(e){this.setState({selected:{idx:1,rowIdx:e-2}})},onToggleFilter:function(){this.setState({canFilter:!this.state.canFilter})},getHeaderRows:function(){var e=[{ref:"row",height:this.props.rowHeight}];return this.state.canFilter===!0&&e.push({ref:"filterRow",headerCellRenderer:s.createElement(p,{onChange:this.props.onAddFilter,column:this.props.column}),height:45}),e},getRowOffsetHeight:function(){var e=0;return this.getHeaderRows().forEach(function(t){return e+=parseFloat(t.height,10)}),e},getDecoratedColumns:function(e){return this.props.columns.map(function(e){var t=Object.assign({},e);if(t.sortable){var r=this.state.sortColumn===t.key?this.state.sortDirection:c.NONE;t.headerRenderer=s.createElement(a,{columnKey:t.key,onSort:this.handleSort,sortDirection:r})}return t},this)},handleSort:function(e,t){this.setState({sortDirection:t,sortColumn:e}),this.props.onGridSort(e,t)},copyPasteEnabled:function(){return null!==this.props.onCellCopyPaste},handleCopy:function(e){if(this.copyPasteEnabled()){var t=e.value,r=this.state.selected,s={idx:r.idx,rowIdx:r.rowIdx};this.setState({textToCopy:t,copied:s})}},handlePaste:function(){if(this.copyPasteEnabled()){var e=this.state.selected,t=this.getColumns()[e.idx].key;this.props.onCellCopyPaste&&this.props.onCellCopyPaste({cellKey:t,rowIdx:e.rowIdx,value:this.state.textToCopy,fromRow:this.state.copied.rowIdx,toRow:e.rowIdx}),this.setState({copied:null})}},dragEnabled:function(){return null!==this.props.onCellsDragged},handleDragStart:function(e){if(this.dragEnabled()){var t=e.idx,r=e.rowIdx;t>=0&&r>=0&&t<this.getColumns().length&&r<this.props.rowsCount&&this.setState({dragged:e})}},handleDragEnter:function(e){if(this.dragEnabled()){var t=(this.state.selected,this.state.dragged);t.overRowIdx=e,this.setState({dragged:t})}},handleDragEnd:function(){if(this.dragEnabled()){var e,t,r=this.state.selected,s=this.state.dragged,o=this.getColumns()[this.state.selected.idx].key;e=r.rowIdx<s.overRowIdx?r.rowIdx:s.overRowIdx,t=r.rowIdx>s.overRowIdx?r.rowIdx:s.overRowIdx,this.props.onCellsDragged&&this.props.onCellsDragged({cellKey:o,fromRow:e,toRow:t,value:s.value}),this.setState({dragged:{complete:!0}})}},handleTerminateDrag:function(){this.dragEnabled()&&this.setState({dragged:null})}});e.exports=h},function(e,t,r){"use strict";function s(){if(void 0===o){var e=document.createElement("div");e.style.width="50px",e.style.height="50px",e.style.overflowY="scroll",e.style.position="absolute",e.style.top="-200px",e.style.left="-200px";var t=document.createElement("div");t.style.height="100px",t.style.width="100%",e.appendChild(t),document.body.appendChild(e);var r=e.clientWidth,s=t.clientWidth;document.body.removeChild(e),o=r-s}return o}var o;e.exports=s},function(e,t,r){"use strict";function s(){var e=window.innerWidth,t=window.innerHeight;return e&&t||(e=document.documentElement.clientWidth,t=document.documentElement.clientHeight),e&&t||(e=document.body.clientWidth,t=document.body.clientHeight),{width:e,height:t}}e.exports=s},function(e,t,r){"use strict";var s=r(1),o=r(48),n=(r(7),r(2)),i=s.PropTypes.shape({id:s.PropTypes.required,title:s.PropTypes.string}),l=s.createClass({displayName:"AutoCompleteEditor",propTypes:{onCommit:s.PropTypes.func.isRequired,options:s.PropTypes.arrayOf(i).isRequired,label:s.PropTypes.any,value:s.PropTypes.any.isRequired,valueParams:s.PropTypes.arrayOf(s.PropTypes.string),column:s.PropTypes.shape(n).isRequired,resultIdentifier:s.PropTypes.string,search:s.PropTypes.string,height:s.PropTypes.string,onKeyDown:s.PropTypes.func.isRequired},getDefaultProps:function(){return{label:"title",resultIdentifier:"id"}},getValue:function(){var e,t={};return this.hasResults()&&this.isFocusedOnSuggestion()?(e=this.getLabel(this.refs.autoComplete.state.focusedValue),this.props.valueParams&&(e=this.constuctValueFromParams(this.refs.autoComplete.state.focusedValue,this.props.valueParams))):e=this.refs.autoComplete.state.searchTerm,t[this.props.column.key]=e,t},getInputNode:function(){return this.getDOMNode().getElementsByTagName("input")[0]},render:function(){return s.createElement("div",{height:this.props.height,onKeyDown:this.props.onKeyDown},s.createElement(o,{search:this.props.search,ref:"autoComplete",label:this.props.label,resultIdentifier:this.props.resultIdentifier,options:this.props.options,value:{title:this.props.value}}))},hasResults:function(){return this.refs.autoComplete.state.results.length>0},isFocusedOnSuggestion:function(){var e=this.refs.autoComplete;return null!=e.state.focusedValue},getLabel:function(e){var t=this.props.label;return"function"==typeof t?t(e):"string"==typeof t?e[t]:void 0},constuctValueFromParams:function(e,t){if(!t)return"";for(var r=[],s=0,o=t.length;o>s;s++)r.push(e[t[s]]);return r.join("|")}});e.exports=l},function(e,t,r){!function(t,s){e.exports=s(r(1))}(this,function(e){return function(e){function t(s){if(r[s])return r[s].exports;var o=r[s]={exports:{},id:s,loaded:!1};return e[s].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";function s(e,t,r){if(!e)return r(null,[]);t=new RegExp(t,"i");for(var s=[],o=0,n=e.length;n>o;o++)t.exec(e[o].title)&&s.push(e[o]);r(null,s)}var o=r(1),n=r(2),i=o.createClass({displayName:"Autocomplete",propTypes:{options:o.PropTypes.any,search:o.PropTypes.func,resultRenderer:o.PropTypes.oneOfType([o.PropTypes.component,o.PropTypes.func]),value:o.PropTypes.object,onChange:o.PropTypes.func,onError:o.PropTypes.func},getDefaultProps:function(){return{search:s}},getInitialState:function(){var e=this.props.searchTerm?this.props.searchTerm:this.props.value?this.props.value.title:"";return{results:[],showResults:!1,showResultsInProgress:!1,searchTerm:e,focusedValue:null}},getResultIdentifier:function(e){return void 0===this.props.resultIdentifier?e.id:e[this.props.resultIdentifier]},render:function(){var e=n(this.props.className,"react-autocomplete-Autocomplete",this.state.showResults?"react-autocomplete-Autocomplete--resultsShown":void 0),t={position:"relative",outline:"none"};return o.createElement("div",{tabIndex:"1",className:e,onFocus:this.onFocus,onBlur:this.onBlur,style:t},o.createElement("input",{ref:"search",className:"react-autocomplete-Autocomplete__search",style:{width:"100%"},onClick:this.showAllResults,onChange:this.onQueryChange,onFocus:this.showAllResults,onBlur:this.onQueryBlur,onKeyDown:this.onQueryKeyDown,value:this.state.searchTerm}),o.createElement(l,{className:"react-autocomplete-Autocomplete__results",onSelect:this.onValueChange,onFocus:this.onValueFocus,results:this.state.results,focusedValue:this.state.focusedValue,show:this.state.showResults,renderer:this.props.resultRenderer,label:this.props.label,resultIdentifier:this.props.resultIdentifier}))},componentWillReceiveProps:function(e){var t=e.searchTerm?e.searchTerm:e.value?e.value.title:"";this.setState({searchTerm:t})},componentWillMount:function(){this.blurTimer=null},showResults:function(e){this.setState({showResultsInProgress:!0}),this.props.search(this.props.options,e.trim(),this.onSearchComplete)},showAllResults:function(){this.state.showResultsInProgress||this.state.showResults||this.showResults("")},onValueChange:function(e){var t={value:e,showResults:!1};e&&(t.searchTerm=e.title),this.setState(t),this.props.onChange&&this.props.onChange(e)},onSearchComplete:function(e,t){if(e){if(!this.props.onError)throw e;this.props.onError(e)}this.setState({showResultsInProgress:!1,showResults:!0,results:t})},onValueFocus:function(e){this.setState({focusedValue:e})},onQueryChange:function(e){var t=e.target.value;this.setState({searchTerm:t,focusedValue:null}),this.showResults(t)},onFocus:function(){this.blurTimer&&(clearTimeout(this.blurTimer),this.blurTimer=null),this.refs.search.getDOMNode().focus()},onBlur:function(){this.blurTimer=setTimeout(function(){this.isMounted()&&this.setState({showResults:!1})}.bind(this),100)},onQueryKeyDown:function(e){if("Enter"===e.key)e.preventDefault(),this.state.focusedValue&&this.onValueChange(this.state.focusedValue);else if("ArrowUp"===e.key&&this.state.showResults){e.preventDefault();var t=Math.max(this.focusedValueIndex()-1,0);this.setState({focusedValue:this.state.results[t]})}else if("ArrowDown"===e.key)if(e.preventDefault(),this.state.showResults){var r=Math.min(this.focusedValueIndex()+(this.state.showResults?1:0),this.state.results.length-1);this.setState({showResults:!0,focusedValue:this.state.results[r]})}else this.showAllResults()},focusedValueIndex:function(){if(!this.state.focusedValue)return-1;for(var e=0,t=this.state.results.length;t>e;e++)if(this.getResultIdentifier(this.state.results[e])===this.getResultIdentifier(this.state.focusedValue))return e;return-1}}),l=o.createClass({displayName:"Results",getResultIdentifier:function(e){if(void 0===this.props.resultIdentifier){if(!e.id)throw"id property not found on result. You must specify a resultIdentifier and pass as props to autocomplete component";return e.id}return e[this.props.resultIdentifier]},render:function(){var e={display:this.props.show?"block":"none",position:"absolute",listStyleType:"none"},t=this.props,r=t.className,s=function(e,t){var r={},s=Object.prototype.hasOwnProperty;if(null==e)throw new TypeError;for(var o in e)s.call(e,o)&&!s.call(t,o)&&(r[o]=e[o]);return r}(t,{className:1});return o.createElement("ul",o.__spread({},s,{style:e,className:r+" react-autocomplete-Results"}),this.props.results.map(this.renderResult))},renderResult:function(e){var t=this.props.focusedValue&&this.getResultIdentifier(this.props.focusedValue)===this.getResultIdentifier(e),r=this.props.renderer||a;return r({ref:t?"focused":void 0,key:this.getResultIdentifier(e),result:e,focused:t,onMouseEnter:this.onMouseEnterResult,onClick:this.props.onSelect,label:this.props.label})},componentDidUpdate:function(){this.scrollToFocused()},componentDidMount:function(){this.scrollToFocused()},componentWillMount:function(){this.ignoreFocus=!1},scrollToFocused:function(){var e=this.refs&&this.refs.focused;if(e){var t=this.getDOMNode(),r=t.scrollTop,s=t.offsetHeight,o=e.getDOMNode(),n=o.offsetTop,i=n+o.offsetHeight;r>n?(this.ignoreFocus=!0,t.scrollTop=n):i-r>s&&(this.ignoreFocus=!0,t.scrollTop=i-s)}},onMouseEnterResult:function(e,t){if(this.ignoreFocus)this.ignoreFocus=!1;else{var r=this.getDOMNode(),s=r.scrollTop,o=r.offsetHeight,n=e.target,i=n.offsetTop,l=i+n.offsetHeight;l>s&&s+o>i&&this.props.onFocus(t)}}}),a=o.createClass({displayName:"Result",getDefaultProps:function(){return{label:function(e){return e.title}}},getLabel:function(e){return"function"==typeof this.props.label?this.props.label(e):"string"==typeof this.props.label?e[this.props.label]:void 0},render:function(){var e=n({"react-autocomplete-Result":!0,"react-autocomplete-Result--active":this.props.focused});return o.createElement("li",{style:{listStyleType:"none"},className:e,onClick:this.onClick,onMouseEnter:this.onMouseEnter},o.createElement("a",null,this.getLabel(this.props.result)))},onClick:function(){this.props.onClick(this.props.result)},onMouseEnter:function(e){this.props.onMouseEnter&&this.props.onMouseEnter(e,this.props.result)},shouldComponentUpdate:function(e){return e.result.id!==this.props.result.id||e.focused!==this.props.focused}});e.exports=i},function(t,r,s){t.exports=e},function(e,t,r){function s(){for(var e,t="",r=0;r<arguments.length;r++)if(e=arguments[r])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+s.apply(null,e);else if("object"==typeof e)for(var o in e)e.hasOwnProperty(o)&&e[o]&&(t+=" "+o);return t.substr(1)}"undefined"!=typeof e&&e.exports&&(e.exports=s)}])})},function(e,t,r){"use strict";var s=r(1),o=r(47),n=s.createClass({displayName:"AutoCompleteAsyncEditor",propTypes:{cacheResults:s.PropTypes.bool,column:s.PropTypes.object,rowMetaData:s.PropTypes.object,height:s.PropTypes.string,label:s.PropTypes.string,onCommit:s.PropTypes.func,onKeyDown:s.PropTypes.func,resultIdentifier:s.PropTypes.string,searchSourceArgs:s.PropTypes.array,searchUrl:s.PropTypes.func,value:s.PropTypes.string,valueParams:s.PropTypes.arrayOf(s.PropTypes.string)},getDefaultProps:function(){
return{label:"title"}},getSearchParams:function(){var e=this.props.rowMetaData,t=this.props.searchSourceArgs.map(function(t){if(null==e[t])throw"Cannot find Search Source Paramater "+t+" in rowMetaData. You must add an entry for this in models/GridColumn.js";return e[t]});return t},getInputNode:function(){return this.getDOMNode().getElementsByTagName("input")[0]},getValue:function(){return this.refs.autocomplete.getValue()},hasResults:function(){return this.refs.autocomplete.hasResults()},_searchRemote:function(e,t,r){var s=this.getSearchParams();s.push(this._onXHRSuccess.bind(null,r,t)),this.props.searchUrl.apply(this,s)},_onXHRSuccess:function(e,t,r,s,o){e(null,this._filterData(r,t))},_onXHRError:function(e,t,r,s){e(s)},_filterData:function(e,t){for(var r=new RegExp(t,"i"),s=[],o=0,n=e.length;n>o;o++)r.exec(e[o][this.props.label])&&s.push(e[o]);return s.slice(0,100)},render:function(){var e,t=this.props.column.formatter;return e="function"==typeof t&&"function"==typeof t.format?t.format(this.props.value):this.props.value,s.createElement(o,s.__spread({ref:"autocomplete"},this.props,{options:[],search:this._searchRemote,value:e}))}});e.exports=n},function(e,t,r){"use strict";var s=r(1),o=r(2),n=s.createClass({displayName:"DropDownEditor",propTypes:{options:s.PropTypes.arrayOf(s.PropTypes.string).isRequired,value:s.PropTypes.string.isRequired,onCommit:s.PropTypes.func.isRequired,column:s.PropTypes.shape(o).isRequired},getStyle:function(){return{width:"100%"}},render:function(){return s.createElement("select",{ref:"select",style:this.getStyle(),defaultValue:this.props.value,onChange:this.onChange,onClick:this.onClick,onDoubleClick:this.onDoubleClick},this.renderOptions())},renderOptions:function(){var e=[];return this.props.options.forEach(function(t){e.push(s.createElement("option",{key:t,value:t},t))},this),e},getValue:function(){var e={};return e[this.props.column.key]=this.refs.select.getDOMNode().value,e},getInputNode:function(){return this.refs.select.getDOMNode()},onChange:function(){this.props.onCommit({key:"Enter"})},onClick:function(e){e.stopPropagation(),e.preventDefault(),this.getInputNode().focus()},onDoubleClick:function(e){e.stopPropagation(),e.preventDefault(),this.getInputNode().focus()}});e.exports=n},function(e,t,r){var s={AutoComplete:r(47),DropDownEditor:r(50),SimpleTextEditor:r(18),AutoCompleteAsync:r(49)};e.exports=s},function(e,t,r){var s=r(1),o={},n={},i=s.createClass({displayName:"ImageFormatter",propTypes:{src:s.PropTypes.string.isRequired},getInitialState:function(){return{ready:!1}},componentWillMount:function(){this._load(this.props.src)},componentWillReceiveProps:function(e){e.src!==this.props.src&&(this.setState({src:null}),this._load(e.src))},render:function(){var e=this.state.src?{backgroundImage:"url("+this.state.src+")"}:void 0;return s.createElement("div",{className:"react-grid-image",style:e})},_load:function(e){if(n[e])return void this.setState({src:e});if(o[e])return void o[e].push(this._onLoad);o[e]=[this._onLoad];var t=new Image;t.onload=function(){o[e].forEach(function(t){t(e)}),delete o[e],t.onload=null,e=void 0},t.src=e},_onLoad:function(e){this.isMounted()&&e===this.props.src&&this.setState({src:e})}});e.exports=i},function(e,t,r){var s=r(52),o={ImageFormatter:s};e.exports=o},function(e,t,r){"use strict";var s=r(1),o=(r(11),s.createClass({displayName:"Toolbar",propTypes:{onAddRow:s.PropTypes.func,onToggleFilter:s.PropTypes.func.isRequired,enableFilter:s.PropTypes.bool,numberOfRows:s.PropTypes.number.isRequired},onAddRow:function(){null!==this.props.onAddRow&&this.props.onAddRow instanceof Function&&this.props.onAddRow({newRowIndex:this.props.numberOfRows})},getDefaultProps:function(){return{enableAddRow:!0}},renderAddRowButton:function(){return this.props.onAddRow?s.createElement("button",{type:"button",className:"btn",onClick:this.onAddRow},"Add Row"):void 0},renderToggleFilterButton:function(){return this.props.enableFilter?s.createElement("button",{type:"button",className:"btn",onClick:this.props.onToggleFilter},"Filter Rows"):void 0},render:function(){return s.createElement("div",{className:"react-grid-Toolbar"},s.createElement("div",{className:"tools"},this.renderAddRowButton(),this.renderToggleFilterButton()))}}));e.exports=o}])}); |
src/components/logged_in_navigation/components/notifications/index.js | aredotna/ervell | import axios from 'axios'
import React from 'react'
import Backbone from 'backbone'
import sharify from 'sharify'
import NotificationsBadgeView from 'components/logged_in_navigation/components/notifications/view.coffee'
import { mountWithApolloProvider } from 'v2/apollo'
import unmount from 'v2/util/unmount'
import Overlay from 'v2/components/UI/Overlay'
import NotificationsDropdown from 'v2/components/NotificationsDropdown'
const { API_URL, CURRENT_USER } = sharify.data
const STATE = {
isOpened: false,
}
const OverlaidNotificationsDropdown = ({ targetEl, onClose, onCompleted }) => (
<Overlay
onClose={onClose}
targetEl={() => targetEl}
alignToY="bottom"
alignToX="right"
anchorY="top"
anchorX="right"
offsetY={0}
offsetX={10}
>
<NotificationsDropdown onCompleted={onCompleted} />
</Overlay>
)
export default targetEl => {
if (!targetEl) return
// Setup legacy view for badge
const badgeState = new Backbone.Model({ unread_count: 0 })
axios({
method: 'GET',
url: `${API_URL}/notifications/unread_count`,
headers: { 'X-AUTH-TOKEN': CURRENT_USER.authentication_token },
}).then(({ data: { unread_count } }) => {
badgeState.set('unread_count', unread_count)
const badgeView = new NotificationsBadgeView({
el: targetEl,
state: badgeState,
})
badgeView.render()
})
const markAsRead = () => {
badgeState.set('unread_count', 0)
return axios({
method: 'POST',
url: `${API_URL}/notifications/clear`,
headers: { 'X-AUTH-TOKEN': CURRENT_USER.authentication_token },
})
}
// Setup click/rendering for NotificaionsDropdown
const notificationsEl = document.createElement('div')
const close = () => {
unmount(notificationsEl)
notificationsEl.parentNode &&
notificationsEl.parentNode.removeChild(notificationsEl)
setTimeout(() => (STATE.isOpened = false), 0)
}
targetEl.addEventListener('click', e => {
e.preventDefault()
if (STATE.isOpened) return
mountWithApolloProvider(
OverlaidNotificationsDropdown,
{
targetEl,
onClose: close,
onCompleted: markAsRead,
},
notificationsEl
)
STATE.isOpened = true
})
}
|
ajax/libs/analytics.js/1.3.6/analytics.js | suy/cdnjs | ;(function(){
/**
* Require the given path.
*
* @param {String} path
* @return {Object} exports
* @api public
*/
function require(path, parent, orig) {
var resolved = require.resolve(path);
// lookup failed
if (null == resolved) {
orig = orig || path;
parent = parent || 'root';
var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
err.path = orig;
err.parent = parent;
err.require = true;
throw err;
}
var module = require.modules[resolved];
// perform real require()
// by invoking the module's
// registered function
if (!module._resolving && !module.exports) {
var mod = {};
mod.exports = {};
mod.client = mod.component = true;
module._resolving = true;
module.call(this, mod.exports, require.relative(resolved), mod);
delete module._resolving;
module.exports = mod.exports;
}
return module.exports;
}
/**
* Registered modules.
*/
require.modules = {};
/**
* Registered aliases.
*/
require.aliases = {};
/**
* Resolve `path`.
*
* Lookup:
*
* - PATH/index.js
* - PATH.js
* - PATH
*
* @param {String} path
* @return {String} path or null
* @api private
*/
require.resolve = function(path) {
if (path.charAt(0) === '/') path = path.slice(1);
var paths = [
path,
path + '.js',
path + '.json',
path + '/index.js',
path + '/index.json'
];
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
if (require.modules.hasOwnProperty(path)) return path;
if (require.aliases.hasOwnProperty(path)) return require.aliases[path];
}
};
/**
* Normalize `path` relative to the current path.
*
* @param {String} curr
* @param {String} path
* @return {String}
* @api private
*/
require.normalize = function(curr, path) {
var segs = [];
if ('.' != path.charAt(0)) return path;
curr = curr.split('/');
path = path.split('/');
for (var i = 0; i < path.length; ++i) {
if ('..' == path[i]) {
curr.pop();
} else if ('.' != path[i] && '' != path[i]) {
segs.push(path[i]);
}
}
return curr.concat(segs).join('/');
};
/**
* Register module at `path` with callback `definition`.
*
* @param {String} path
* @param {Function} definition
* @api private
*/
require.register = function(path, definition) {
require.modules[path] = definition;
};
/**
* Alias a module definition.
*
* @param {String} from
* @param {String} to
* @api private
*/
require.alias = function(from, to) {
if (!require.modules.hasOwnProperty(from)) {
throw new Error('Failed to alias "' + from + '", it does not exist');
}
require.aliases[to] = from;
};
/**
* Return a require function relative to the `parent` path.
*
* @param {String} parent
* @return {Function}
* @api private
*/
require.relative = function(parent) {
var p = require.normalize(parent, '..');
/**
* lastIndexOf helper.
*/
function lastIndexOf(arr, obj) {
var i = arr.length;
while (i--) {
if (arr[i] === obj) return i;
}
return -1;
}
/**
* The relative require() itself.
*/
function localRequire(path) {
var resolved = localRequire.resolve(path);
return require(resolved, parent, path);
}
/**
* Resolve relative to the parent.
*/
localRequire.resolve = function(path) {
var c = path.charAt(0);
if ('/' == c) return path.slice(1);
if ('.' == c) return require.normalize(p, path);
// resolve deps by returning
// the dep in the nearest "deps"
// directory
var segs = parent.split('/');
var i = lastIndexOf(segs, 'deps') + 1;
if (!i) i = 0;
path = segs.slice(0, i + 1).join('/') + '/deps/' + path;
return path;
};
/**
* Check if module is defined at `path`.
*/
localRequire.exists = function(path) {
return require.modules.hasOwnProperty(localRequire.resolve(path));
};
return localRequire;
};
require.register("avetisk-defaults/index.js", function(exports, require, module){
'use strict';
/**
* Merge default values.
*
* @param {Object} dest
* @param {Object} defaults
* @return {Object}
* @api public
*/
var defaults = function (dest, src, recursive) {
for (var prop in src) {
if (recursive && dest[prop] instanceof Object && src[prop] instanceof Object) {
dest[prop] = defaults(dest[prop], src[prop], true);
} else if (! (prop in dest)) {
dest[prop] = src[prop];
}
}
return dest;
};
/**
* Expose `defaults`.
*/
module.exports = defaults;
});
require.register("component-type/index.js", function(exports, require, module){
/**
* toString ref.
*/
var toString = Object.prototype.toString;
/**
* Return the type of `val`.
*
* @param {Mixed} val
* @return {String}
* @api public
*/
module.exports = function(val){
switch (toString.call(val)) {
case '[object Function]': return 'function';
case '[object Date]': return 'date';
case '[object RegExp]': return 'regexp';
case '[object Arguments]': return 'arguments';
case '[object Array]': return 'array';
case '[object String]': return 'string';
}
if (val === null) return 'null';
if (val === undefined) return 'undefined';
if (val && val.nodeType === 1) return 'element';
if (val === Object(val)) return 'object';
return typeof val;
};
});
require.register("component-clone/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var type;
try {
type = require('type');
} catch(e){
type = require('type-component');
}
/**
* Module exports.
*/
module.exports = clone;
/**
* Clones objects.
*
* @param {Mixed} any object
* @api public
*/
function clone(obj){
switch (type(obj)) {
case 'object':
var copy = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = clone(obj[key]);
}
}
return copy;
case 'array':
var copy = new Array(obj.length);
for (var i = 0, l = obj.length; i < l; i++) {
copy[i] = clone(obj[i]);
}
return copy;
case 'regexp':
// from millermedeiros/amd-utils - MIT
var flags = '';
flags += obj.multiline ? 'm' : '';
flags += obj.global ? 'g' : '';
flags += obj.ignoreCase ? 'i' : '';
return new RegExp(obj.source, flags);
case 'date':
return new Date(obj.getTime());
default: // string, number, boolean, …
return obj;
}
}
});
require.register("component-cookie/index.js", function(exports, require, module){
/**
* Encode.
*/
var encode = encodeURIComponent;
/**
* Decode.
*/
var decode = decodeURIComponent;
/**
* Set or get cookie `name` with `value` and `options` object.
*
* @param {String} name
* @param {String} value
* @param {Object} options
* @return {Mixed}
* @api public
*/
module.exports = function(name, value, options){
switch (arguments.length) {
case 3:
case 2:
return set(name, value, options);
case 1:
return get(name);
default:
return all();
}
};
/**
* Set cookie `name` to `value`.
*
* @param {String} name
* @param {String} value
* @param {Object} options
* @api private
*/
function set(name, value, options) {
options = options || {};
var str = encode(name) + '=' + encode(value);
if (null == value) options.maxage = -1;
if (options.maxage) {
options.expires = new Date(+new Date + options.maxage);
}
if (options.path) str += '; path=' + options.path;
if (options.domain) str += '; domain=' + options.domain;
if (options.expires) str += '; expires=' + options.expires.toGMTString();
if (options.secure) str += '; secure';
document.cookie = str;
}
/**
* Return all cookies.
*
* @return {Object}
* @api private
*/
function all() {
return parse(document.cookie);
}
/**
* Get cookie `name`.
*
* @param {String} name
* @return {String}
* @api private
*/
function get(name) {
return all()[name];
}
/**
* Parse cookie `str`.
*
* @param {String} str
* @return {Object}
* @api private
*/
function parse(str) {
var obj = {};
var pairs = str.split(/ *; */);
var pair;
if ('' == pairs[0]) return obj;
for (var i = 0; i < pairs.length; ++i) {
pair = pairs[i].split('=');
obj[decode(pair[0])] = decode(pair[1]);
}
return obj;
}
});
require.register("component-each/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var type = require('type');
/**
* HOP reference.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Iterate the given `obj` and invoke `fn(val, i)`.
*
* @param {String|Array|Object} obj
* @param {Function} fn
* @api public
*/
module.exports = function(obj, fn){
switch (type(obj)) {
case 'array':
return array(obj, fn);
case 'object':
if ('number' == typeof obj.length) return array(obj, fn);
return object(obj, fn);
case 'string':
return string(obj, fn);
}
};
/**
* Iterate string chars.
*
* @param {String} obj
* @param {Function} fn
* @api private
*/
function string(obj, fn) {
for (var i = 0; i < obj.length; ++i) {
fn(obj.charAt(i), i);
}
}
/**
* Iterate object keys.
*
* @param {Object} obj
* @param {Function} fn
* @api private
*/
function object(obj, fn) {
for (var key in obj) {
if (has.call(obj, key)) {
fn(key, obj[key]);
}
}
}
/**
* Iterate array-ish.
*
* @param {Array|Object} obj
* @param {Function} fn
* @api private
*/
function array(obj, fn) {
for (var i = 0; i < obj.length; ++i) {
fn(obj[i], i);
}
}
});
require.register("component-indexof/index.js", function(exports, require, module){
module.exports = function(arr, obj){
if (arr.indexOf) return arr.indexOf(obj);
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === obj) return i;
}
return -1;
};
});
require.register("component-emitter/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var index = require('indexof');
/**
* 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);
}
fn._off = on;
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 i = index(callbacks, fn._off || fn);
if (~i) callbacks.splice(i, 1);
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;
};
});
require.register("component-event/index.js", function(exports, require, module){
/**
* Bind `el` event `type` to `fn`.
*
* @param {Element} el
* @param {String} type
* @param {Function} fn
* @param {Boolean} capture
* @return {Function}
* @api public
*/
exports.bind = function(el, type, fn, capture){
if (el.addEventListener) {
el.addEventListener(type, fn, capture || false);
} else {
el.attachEvent('on' + type, fn);
}
return fn;
};
/**
* Unbind `el` event `type`'s callback `fn`.
*
* @param {Element} el
* @param {String} type
* @param {Function} fn
* @param {Boolean} capture
* @return {Function}
* @api public
*/
exports.unbind = function(el, type, fn, capture){
if (el.removeEventListener) {
el.removeEventListener(type, fn, capture || false);
} else {
el.detachEvent('on' + type, fn);
}
return fn;
};
});
require.register("component-inherit/index.js", function(exports, require, module){
module.exports = function(a, b){
var fn = function(){};
fn.prototype = b.prototype;
a.prototype = new fn;
a.prototype.constructor = a;
};
});
require.register("component-object/index.js", function(exports, require, module){
/**
* HOP ref.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Return own keys in `obj`.
*
* @param {Object} obj
* @return {Array}
* @api public
*/
exports.keys = Object.keys || function(obj){
var keys = [];
for (var key in obj) {
if (has.call(obj, key)) {
keys.push(key);
}
}
return keys;
};
/**
* Return own values in `obj`.
*
* @param {Object} obj
* @return {Array}
* @api public
*/
exports.values = function(obj){
var vals = [];
for (var key in obj) {
if (has.call(obj, key)) {
vals.push(obj[key]);
}
}
return vals;
};
/**
* Merge `b` into `a`.
*
* @param {Object} a
* @param {Object} b
* @return {Object} a
* @api public
*/
exports.merge = function(a, b){
for (var key in b) {
if (has.call(b, key)) {
a[key] = b[key];
}
}
return a;
};
/**
* Return length of `obj`.
*
* @param {Object} obj
* @return {Number}
* @api public
*/
exports.length = function(obj){
return exports.keys(obj).length;
};
/**
* Check if `obj` is empty.
*
* @param {Object} obj
* @return {Boolean}
* @api public
*/
exports.isEmpty = function(obj){
return 0 == exports.length(obj);
};
});
require.register("component-trim/index.js", function(exports, require, module){
exports = module.exports = trim;
function trim(str){
if (str.trim) return str.trim();
return str.replace(/^\s*|\s*$/g, '');
}
exports.left = function(str){
if (str.trimLeft) return str.trimLeft();
return str.replace(/^\s*/, '');
};
exports.right = function(str){
if (str.trimRight) return str.trimRight();
return str.replace(/\s*$/, '');
};
});
require.register("component-querystring/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var trim = require('trim');
/**
* Parse the given query `str`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(str){
if ('string' != typeof str) return {};
str = trim(str);
if ('' == str) return {};
var obj = {};
var pairs = str.split('&');
for (var i = 0; i < pairs.length; i++) {
var parts = pairs[i].split('=');
obj[parts[0]] = null == parts[1]
? ''
: decodeURIComponent(parts[1]);
}
return obj;
};
/**
* Stringify the given `obj`.
*
* @param {Object} obj
* @return {String}
* @api public
*/
exports.stringify = function(obj){
if (!obj) return '';
var pairs = [];
for (var key in obj) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
return pairs.join('&');
};
});
require.register("component-url/index.js", function(exports, require, module){
/**
* Parse the given `url`.
*
* @param {String} str
* @return {Object}
* @api public
*/
exports.parse = function(url){
var a = document.createElement('a');
a.href = url;
return {
href: a.href,
host: a.host,
port: a.port,
hash: a.hash,
hostname: a.hostname,
pathname: a.pathname,
protocol: a.protocol,
search: a.search,
query: a.search.slice(1)
}
};
/**
* Check if `url` is absolute.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isAbsolute = function(url){
if (0 == url.indexOf('//')) return true;
if (~url.indexOf('://')) return true;
return false;
};
/**
* Check if `url` is relative.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isRelative = function(url){
return ! exports.isAbsolute(url);
};
/**
* Check if `url` is cross domain.
*
* @param {String} url
* @return {Boolean}
* @api public
*/
exports.isCrossDomain = function(url){
url = exports.parse(url);
return url.hostname != location.hostname
|| url.port != location.port
|| url.protocol != location.protocol;
};
});
require.register("component-bind/index.js", function(exports, require, module){
/**
* 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)));
}
};
});
require.register("segmentio-bind-all/index.js", function(exports, require, module){
try {
var bind = require('bind');
var type = require('type');
} catch (e) {
var bind = require('bind-component');
var type = require('type-component');
}
module.exports = function (obj) {
for (var key in obj) {
var val = obj[key];
if (type(val) === 'function') obj[key] = bind(obj, obj[key]);
}
return obj;
};
});
require.register("ianstormtaylor-bind/index.js", function(exports, require, module){
try {
var bind = require('bind');
} catch (e) {
var bind = require('bind-component');
}
var bindAll = require('bind-all');
/**
* Expose `bind`.
*/
module.exports = exports = bind;
/**
* Expose `bindAll`.
*/
exports.all = bindAll;
/**
* Expose `bindMethods`.
*/
exports.methods = bindMethods;
/**
* Bind `methods` on `obj` to always be called with the `obj` as context.
*
* @param {Object} obj
* @param {String} methods...
*/
function bindMethods (obj, methods) {
methods = [].slice.call(arguments, 1);
for (var i = 0, method; method = methods[i]; i++) {
obj[method] = bind(obj, obj[method]);
}
return obj;
}
});
require.register("timoxley-next-tick/index.js", function(exports, require, module){
"use strict"
if (typeof setImmediate == 'function') {
module.exports = function(f){ setImmediate(f) }
}
// legacy node.js
else if (typeof process != 'undefined' && typeof process.nextTick == 'function') {
module.exports = process.nextTick
}
// fallback for other environments / postMessage behaves badly on IE8
else if (typeof window == 'undefined' || window.ActiveXObject || !window.postMessage) {
module.exports = function(f){ setTimeout(f) };
} else {
var q = [];
window.addEventListener('message', function(){
var i = 0;
while (i < q.length) {
try { q[i++](); }
catch (e) {
q = q.slice(i);
window.postMessage('tic!', '*');
throw e;
}
}
q.length = 0;
}, true);
module.exports = function(fn){
if (!q.length) window.postMessage('tic!', '*');
q.push(fn);
}
}
});
require.register("ianstormtaylor-callback/index.js", function(exports, require, module){
var next = require('next-tick');
/**
* Expose `callback`.
*/
module.exports = callback;
/**
* Call an `fn` back synchronously if it exists.
*
* @param {Function} fn
*/
function callback (fn) {
if ('function' === typeof fn) fn();
}
/**
* Call an `fn` back asynchronously if it exists. If `wait` is ommitted, the
* `fn` will be called on next tick.
*
* @param {Function} fn
* @param {Number} wait (optional)
*/
callback.async = function (fn, wait) {
if ('function' !== typeof fn) return;
if (!wait) return next(fn);
setTimeout(fn, wait);
};
/**
* Symmetry.
*/
callback.sync = callback;
});
require.register("ianstormtaylor-is-empty/index.js", function(exports, require, module){
/**
* Expose `isEmpty`.
*/
module.exports = isEmpty;
/**
* Has.
*/
var has = Object.prototype.hasOwnProperty;
/**
* Test whether a value is "empty".
*
* @param {Mixed} val
* @return {Boolean}
*/
function isEmpty (val) {
if (null == val) return true;
if ('number' == typeof val) return 0 === val;
if (undefined !== val.length) return 0 === val.length;
for (var key in val) if (has.call(val, key)) return false;
return true;
}
});
require.register("ianstormtaylor-is/index.js", function(exports, require, module){
var isEmpty = require('is-empty');
try {
var typeOf = require('type');
} catch (e) {
var typeOf = require('component-type');
}
/**
* Types.
*/
var types = [
'arguments',
'array',
'boolean',
'date',
'element',
'function',
'null',
'number',
'object',
'regexp',
'string',
'undefined'
];
/**
* Expose type checkers.
*
* @param {Mixed} value
* @return {Boolean}
*/
for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type);
/**
* Add alias for `function` for old browsers.
*/
exports.fn = exports['function'];
/**
* Expose `empty` check.
*/
exports.empty = isEmpty;
/**
* Expose `nan` check.
*/
exports.nan = function (val) {
return exports.number(val) && val != val;
};
/**
* Generate a type checker.
*
* @param {String} type
* @return {Function}
*/
function generate (type) {
return function (value) {
return type === typeOf(value);
};
}
});
require.register("segmentio-after/index.js", function(exports, require, module){
module.exports = function after (times, func) {
// After 0, really?
if (times <= 0) return func();
// That's more like it.
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
});
require.register("yields-slug/index.js", function(exports, require, module){
/**
* Generate a slug from the given `str`.
*
* example:
*
* generate('foo bar');
* // > foo-bar
*
* @param {String} str
* @param {Object} options
* @config {String|RegExp} [replace] characters to replace, defaulted to `/[^a-z0-9]/g`
* @config {String} [separator] separator to insert, defaulted to `-`
* @return {String}
*/
module.exports = function (str, options) {
options || (options = {});
return str.toLowerCase()
.replace(options.replace || /[^a-z0-9]/g, ' ')
.replace(/^ +| +$/g, '')
.replace(/ +/g, options.separator || '-')
};
});
require.register("segmentio-analytics.js-integration/lib/index.js", function(exports, require, module){
var bind = require('bind');
var callback = require('callback');
var clone = require('clone');
var debug = require('debug');
var defaults = require('defaults');
var protos = require('./protos');
var slug = require('slug');
var statics = require('./statics');
/**
* Expose `createIntegration`.
*/
module.exports = createIntegration;
/**
* Create a new Integration constructor.
*
* @param {String} name
*/
function createIntegration (name) {
/**
* Initialize a new `Integration`.
*
* @param {Object} options
*/
function Integration (options) {
this.debug = debug('analytics:integration:' + slug(name));
this.options = defaults(clone(options) || {}, this.defaults);
this._queue = [];
this.once('ready', bind(this, this.flush));
Integration.emit('construct', this);
this._wrapInitialize();
this._wrapLoad();
this._wrapPage();
this._wrapTrack();
}
Integration.prototype.defaults = {};
Integration.prototype.globals = [];
Integration.prototype.name = name;
for (var key in statics) Integration[key] = statics[key];
for (var key in protos) Integration.prototype[key] = protos[key];
return Integration;
}
});
require.register("segmentio-analytics.js-integration/lib/protos.js", function(exports, require, module){
var after = require('after');
var callback = require('callback');
var Emitter = require('emitter');
var tick = require('next-tick');
var events = require('./events');
/**
* Mixin emitter.
*/
Emitter(exports);
/**
* Initialize.
*/
exports.initialize = function () {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
* @api private
*/
exports.loaded = function () {
return false;
};
/**
* Load.
*
* @param {Function} cb
*/
exports.load = function (cb) {
callback.async(cb);
};
/**
* Page.
*
* @param {Page} page
*/
exports.page = function(page){};
/**
* Track.
*
* @param {Track} track
*/
exports.track = function(track){};
/**
* Invoke a `method` that may or may not exist on the prototype with `args`,
* queueing or not depending on whether the integration is "ready". Don't
* trust the method call, since it contains integration party code.
*
* @param {String} method
* @param {Mixed} args...
* @api private
*/
exports.invoke = function (method) {
if (!this[method]) return;
var args = [].slice.call(arguments, 1);
if (!this._ready) return this.queue(method, args);
try {
this.debug('%s with %o', method, args);
this[method].apply(this, args);
} catch (e) {
this.debug('error %o calling %s with %o', e, method, args);
}
};
/**
* Queue a `method` with `args`. If the integration assumes an initial
* pageview, then let the first call to `page` pass through.
*
* @param {String} method
* @param {Array} args
* @api private
*/
exports.queue = function (method, args) {
if ('page' == method && this._assumesPageview && !this._initialized) {
return this.page.apply(this, args);
}
this._queue.push({ method: method, args: args });
};
/**
* Flush the internal queue.
*
* @api private
*/
exports.flush = function () {
this._ready = true;
var call;
while (call = this._queue.shift()) this[call.method].apply(this, call.args);
};
/**
* Reset the integration, removing its global variables.
*
* @api private
*/
exports.reset = function () {
for (var i = 0, key; key = this.globals[i]; i++) window[key] = undefined;
};
/**
* Wrap the initialize method in an exists check, so we don't have to do it for
* every single integration.
*
* @api private
*/
exports._wrapInitialize = function () {
var initialize = this.initialize;
this.initialize = function () {
this.debug('initialize');
this._initialized = true;
initialize.apply(this, arguments);
this.emit('initialize');
var self = this;
if (this._readyOnInitialize) {
tick(function () {
self.emit('ready');
});
}
};
if (this._assumesPageview) this.initialize = after(2, this.initialize);
};
/**
* Wrap the load method in `debug` calls, so every integration gets them
* automatically.
*
* @api private
*/
exports._wrapLoad = function () {
var load = this.load;
this.load = function (callback) {
var self = this;
this.debug('loading');
if (this.loaded()) {
this.debug('already loaded');
tick(function () {
if (self._readyOnLoad) self.emit('ready');
callback && callback();
});
return;
}
load.call(this, function (err, e) {
self.debug('loaded');
self.emit('load');
if (self._readyOnLoad) self.emit('ready');
callback && callback(err, e);
});
};
};
/**
* Wrap the page method to call `initialize` instead if the integration assumes
* a pageview.
*
* @api private
*/
exports._wrapPage = function () {
var page = this.page;
this.page = function () {
if (this._assumesPageview && !this._initialized) {
return this.initialize({
category: arguments[0],
name: arguments[1],
properties: arguments[2],
options: arguments[3]
});
}
page.apply(this, arguments);
};
};
/**
* Wrap the track method to call other ecommerce methods if
* available depending on the `track.event()`.
*
* @api private
*/
exports._wrapTrack = function(){
var t = this.track;
this.track = function(track){
var event = track.event();
var called;
for (var method in events) {
var regexp = events[method];
if (!this[method]) continue;
if (!regexp.test(event)) continue;
this[method].apply(this, arguments);
called = true;
break;
}
if (!called) t.apply(this, arguments);
};
};
});
require.register("segmentio-analytics.js-integration/lib/events.js", function(exports, require, module){
/**
* Expose `events`
*/
module.exports = {
removedProduct: /removed product/i,
viewedProduct: /viewed product/i,
addedProduct: /added product/i,
completedOrder: /completed order/i
};
});
require.register("segmentio-analytics.js-integration/lib/statics.js", function(exports, require, module){
var after = require('after');
var Emitter = require('emitter');
/**
* Mixin emitter.
*/
Emitter(exports);
/**
* Add a new option to the integration by `key` with default `value`.
*
* @param {String} key
* @param {Mixed} value
* @return {Integration}
*/
exports.option = function (key, value) {
this.prototype.defaults[key] = value;
return this;
};
/**
* Register a new global variable `key` owned by the integration, which will be
* used to test whether the integration is already on the page.
*
* @param {String} global
* @return {Integration}
*/
exports.global = function (key) {
this.prototype.globals.push(key);
return this;
};
/**
* Mark the integration as assuming an initial pageview, so to defer loading
* the script until the first `page` call, noop the first `initialize`.
*
* @return {Integration}
*/
exports.assumesPageview = function () {
this.prototype._assumesPageview = true;
return this;
};
/**
* Mark the integration as being "ready" once `load` is called.
*
* @return {Integration}
*/
exports.readyOnLoad = function () {
this.prototype._readyOnLoad = true;
return this;
};
/**
* Mark the integration as being "ready" once `load` is called.
*
* @return {Integration}
*/
exports.readyOnInitialize = function () {
this.prototype._readyOnInitialize = true;
return this;
};
});
require.register("component-domify/index.js", function(exports, require, module){
/**
* Expose `parse`.
*/
module.exports = parse;
/**
* Wrap map from jquery.
*/
var map = {
legend: [1, '<fieldset>', '</fieldset>'],
tr: [2, '<table><tbody>', '</tbody></table>'],
col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
_default: [0, '', '']
};
map.td =
map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
map.option =
map.optgroup = [1, '<select multiple="multiple">', '</select>'];
map.thead =
map.tbody =
map.colgroup =
map.caption =
map.tfoot = [1, '<table>', '</table>'];
map.text =
map.circle =
map.ellipse =
map.line =
map.path =
map.polygon =
map.polyline =
map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>'];
/**
* Parse `html` and return the children.
*
* @param {String} html
* @return {Array}
* @api private
*/
function parse(html) {
if ('string' != typeof html) throw new TypeError('String expected');
html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace
// tag name
var m = /<([\w:]+)/.exec(html);
if (!m) return document.createTextNode(html);
var tag = m[1];
// body support
if (tag == 'body') {
var el = document.createElement('html');
el.innerHTML = html;
return el.removeChild(el.lastChild);
}
// wrap map
var wrap = map[tag] || map._default;
var depth = wrap[0];
var prefix = wrap[1];
var suffix = wrap[2];
var el = document.createElement('div');
el.innerHTML = prefix + html + suffix;
while (depth--) el = el.lastChild;
// one element
if (el.firstChild == el.lastChild) {
return el.removeChild(el.firstChild);
}
// several elements
var fragment = document.createDocumentFragment();
while (el.firstChild) {
fragment.appendChild(el.removeChild(el.firstChild));
}
return fragment;
}
});
require.register("component-once/index.js", function(exports, require, module){
/**
* Identifier.
*/
var n = 0;
/**
* Global.
*/
var global = (function(){ return this })();
/**
* Make `fn` callable only once.
*
* @param {Function} fn
* @return {Function}
* @api public
*/
module.exports = function(fn) {
var id = n++;
function once(){
// no receiver
if (this == global) {
if (once.called) return;
once.called = true;
return fn.apply(this, arguments);
}
// receiver
var key = '__called_' + id + '__';
if (this[key]) return;
this[key] = true;
return fn.apply(this, arguments);
}
return once;
};
});
require.register("segmentio-alias/index.js", function(exports, require, module){
var type = require('type');
try {
var clone = require('clone');
} catch (e) {
var clone = require('clone-component');
}
/**
* Expose `alias`.
*/
module.exports = alias;
/**
* Alias an `object`.
*
* @param {Object} obj
* @param {Mixed} method
*/
function alias (obj, method) {
switch (type(method)) {
case 'object': return aliasByDictionary(clone(obj), method);
case 'function': return aliasByFunction(clone(obj), method);
}
}
/**
* Convert the keys in an `obj` using a dictionary of `aliases`.
*
* @param {Object} obj
* @param {Object} aliases
*/
function aliasByDictionary (obj, aliases) {
for (var key in aliases) {
if (undefined === obj[key]) continue;
obj[aliases[key]] = obj[key];
delete obj[key];
}
return obj;
}
/**
* Convert the keys in an `obj` using a `convert` function.
*
* @param {Object} obj
* @param {Function} convert
*/
function aliasByFunction (obj, convert) {
// have to create another object so that ie8 won't infinite loop on keys
var output = {};
for (var key in obj) output[convert(key)] = obj[key];
return output;
}
});
require.register("segmentio-convert-dates/index.js", function(exports, require, module){
var is = require('is');
try {
var clone = require('clone');
} catch (e) {
var clone = require('clone-component');
}
/**
* Expose `convertDates`.
*/
module.exports = convertDates;
/**
* Recursively convert an `obj`'s dates to new values.
*
* @param {Object} obj
* @param {Function} convert
* @return {Object}
*/
function convertDates (obj, convert) {
obj = clone(obj);
for (var key in obj) {
var val = obj[key];
if (is.date(val)) obj[key] = convert(val);
if (is.object(val)) obj[key] = convertDates(val, convert);
}
return obj;
}
});
require.register("segmentio-global-queue/index.js", function(exports, require, module){
/**
* Expose `generate`.
*/
module.exports = generate;
/**
* Generate a global queue pushing method with `name`.
*
* @param {String} name
* @param {Object} options
* @property {Boolean} wrap
* @return {Function}
*/
function generate (name, options) {
options = options || {};
return function (args) {
args = [].slice.call(arguments);
window[name] || (window[name] = []);
options.wrap === false
? window[name].push.apply(window[name], args)
: window[name].push(args);
};
}
});
require.register("segmentio-load-date/index.js", function(exports, require, module){
/*
* Load date.
*
* For reference: http://www.html5rocks.com/en/tutorials/webperformance/basics/
*/
var time = new Date()
, perf = window.performance;
if (perf && perf.timing && perf.timing.responseEnd) {
time = new Date(perf.timing.responseEnd);
}
module.exports = time;
});
require.register("segmentio-load-script/index.js", function(exports, require, module){
var type = require('type');
module.exports = function loadScript (options, callback) {
if (!options) throw new Error('Cant load nothing...');
// Allow for the simplest case, just passing a `src` string.
if (type(options) === 'string') options = { src : options };
var https = document.location.protocol === 'https:' ||
document.location.protocol === 'chrome-extension:';
// If you use protocol relative URLs, third-party scripts like Google
// Analytics break when testing with `file:` so this fixes that.
if (options.src && options.src.indexOf('//') === 0) {
options.src = https ? 'https:' + options.src : 'http:' + options.src;
}
// Allow them to pass in different URLs depending on the protocol.
if (https && options.https) options.src = options.https;
else if (!https && options.http) options.src = options.http;
// Make the `<script>` element and insert it before the first script on the
// page, which is guaranteed to exist since this Javascript is running.
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = options.src;
var firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(script, firstScript);
// If we have a callback, attach event handlers, even in IE. Based off of
// the Third-Party Javascript script loading example:
// https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html
if (callback && type(callback) === 'function') {
if (script.addEventListener) {
script.addEventListener('load', function (event) {
callback(null, event);
}, false);
script.addEventListener('error', function (event) {
callback(new Error('Failed to load the script.'), event);
}, false);
} else if (script.attachEvent) {
script.attachEvent('onreadystatechange', function (event) {
if (/complete|loaded/.test(script.readyState)) {
callback(null, event);
}
});
}
}
// Return the script element in case they want to do anything special, like
// give it an ID or attributes.
return script;
};
});
require.register("segmentio-on-body/index.js", function(exports, require, module){
var each = require('each');
/**
* Cache whether `<body>` exists.
*/
var body = false;
/**
* Callbacks to call when the body exists.
*/
var callbacks = [];
/**
* Export a way to add handlers to be invoked once the body exists.
*
* @param {Function} callback A function to call when the body exists.
*/
module.exports = function onBody (callback) {
if (body) {
call(callback);
} else {
callbacks.push(callback);
}
};
/**
* Set an interval to check for `document.body`.
*/
var interval = setInterval(function () {
if (!document.body) return;
body = true;
each(callbacks, call);
clearInterval(interval);
}, 5);
/**
* Call a callback, passing it the body.
*
* @param {Function} callback The callback to call.
*/
function call (callback) {
callback(document.body);
}
});
require.register("segmentio-on-error/index.js", function(exports, require, module){
/**
* Expose `onError`.
*/
module.exports = onError;
/**
* Callbacks.
*/
var callbacks = [];
/**
* Preserve existing handler.
*/
if ('function' == typeof window.onerror) callbacks.push(window.onerror);
/**
* Bind to `window.onerror`.
*/
window.onerror = handler;
/**
* Error handler.
*/
function handler () {
for (var i = 0, fn; fn = callbacks[i]; i++) fn.apply(this, arguments);
}
/**
* Call a `fn` on `window.onerror`.
*
* @param {Function} fn
*/
function onError (fn) {
callbacks.push(fn);
if (window.onerror != handler) {
callbacks.push(window.onerror);
window.onerror = handler;
}
}
});
require.register("segmentio-to-iso-string/index.js", function(exports, require, module){
/**
* Expose `toIsoString`.
*/
module.exports = toIsoString;
/**
* Turn a `date` into an ISO string.
*
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
*
* @param {Date} date
* @return {String}
*/
function toIsoString (date) {
return date.getUTCFullYear()
+ '-' + pad(date.getUTCMonth() + 1)
+ '-' + pad(date.getUTCDate())
+ 'T' + pad(date.getUTCHours())
+ ':' + pad(date.getUTCMinutes())
+ ':' + pad(date.getUTCSeconds())
+ '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5)
+ 'Z';
}
/**
* Pad a `number` with a ten's place zero.
*
* @param {Number} number
* @return {String}
*/
function pad (number) {
var n = number.toString();
return n.length === 1 ? '0' + n : n;
}
});
require.register("segmentio-to-unix-timestamp/index.js", function(exports, require, module){
/**
* Expose `toUnixTimestamp`.
*/
module.exports = toUnixTimestamp;
/**
* Convert a `date` into a Unix timestamp.
*
* @param {Date}
* @return {Number}
*/
function toUnixTimestamp (date) {
return Math.floor(date.getTime() / 1000);
}
});
require.register("segmentio-use-https/index.js", function(exports, require, module){
/**
* Protocol.
*/
module.exports = function (url) {
switch (arguments.length) {
case 0: return check();
case 1: return transform(url);
}
};
/**
* Transform a protocol-relative `url` to the use the proper protocol.
*
* @param {String} url
* @return {String}
*/
function transform (url) {
return check() ? 'https:' + url : 'http:' + url;
}
/**
* Check whether `https:` be used for loading scripts.
*
* @return {Boolean}
*/
function check () {
return (
location.protocol == 'https:' ||
location.protocol == 'chrome-extension:'
);
}
});
require.register("visionmedia-batch/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
try {
var EventEmitter = require('events').EventEmitter;
} catch (err) {
var Emitter = require('emitter');
}
/**
* Noop.
*/
function noop(){}
/**
* Expose `Batch`.
*/
module.exports = Batch;
/**
* Create a new Batch.
*/
function Batch() {
if (!(this instanceof Batch)) return new Batch;
this.fns = [];
this.concurrency(Infinity);
this.throws(true);
for (var i = 0, len = arguments.length; i < len; ++i) {
this.push(arguments[i]);
}
}
/**
* Inherit from `EventEmitter.prototype`.
*/
if (EventEmitter) {
Batch.prototype.__proto__ = EventEmitter.prototype;
} else {
Emitter(Batch.prototype);
}
/**
* Set concurrency to `n`.
*
* @param {Number} n
* @return {Batch}
* @api public
*/
Batch.prototype.concurrency = function(n){
this.n = n;
return this;
};
/**
* Queue a function.
*
* @param {Function} fn
* @return {Batch}
* @api public
*/
Batch.prototype.push = function(fn){
this.fns.push(fn);
return this;
};
/**
* Set wether Batch will or will not throw up.
*
* @param {Boolean} throws
* @return {Batch}
* @api public
*/
Batch.prototype.throws = function(throws) {
this.e = !!throws;
return this;
};
/**
* Execute all queued functions in parallel,
* executing `cb(err, results)`.
*
* @param {Function} cb
* @return {Batch}
* @api public
*/
Batch.prototype.end = function(cb){
var self = this
, total = this.fns.length
, pending = total
, results = []
, errors = []
, cb = cb || noop
, fns = this.fns
, max = this.n
, throws = this.e
, index = 0
, done;
// empty
if (!fns.length) return cb(null, results);
// process
function next() {
var i = index++;
var fn = fns[i];
if (!fn) return;
var start = new Date;
try {
fn(callback);
} catch (err) {
callback(err);
}
function callback(err, res){
if (done) return;
if (err && throws) return done = true, cb(err);
var complete = total - pending + 1;
var end = new Date;
results[i] = res;
errors[i] = err;
self.emit('progress', {
index: i,
value: res,
error: err,
pending: pending,
total: total,
complete: complete,
percent: complete / total * 100 | 0,
start: start,
end: end,
duration: end - start
});
if (--pending) next()
else if(!throws) cb(errors, results);
else cb(null, results);
}
}
// concurrency
for (var i = 0; i < fns.length; i++) {
if (i == max) break;
next();
}
return this;
};
});
require.register("segmentio-substitute/index.js", function(exports, require, module){
/**
* Expose `substitute`
*/
module.exports = substitute;
/**
* Substitute `:prop` with the given `obj` in `str`
*
* @param {String} str
* @param {Object} obj
* @param {RegExp} expr
* @return {String}
* @api public
*/
function substitute(str, obj, expr){
if (!obj) throw new TypeError('expected an object');
expr = expr || /:(\w+)/g;
return str.replace(expr, function(_, prop){
return null != obj[prop]
? obj[prop]
: _;
});
}
});
require.register("segmentio-load-pixel/index.js", function(exports, require, module){
/**
* Module dependencies.
*/
var stringify = require('querystring').stringify;
var sub = require('substitute');
/**
* Factory function to create a pixel loader.
*
* @param {String} path
* @return {Function}
* @api public
*/
module.exports = function(path){
return function(query, obj, fn){
if ('function' == typeof obj) fn = obj, obj = {};
obj = obj || {};
fn = fn || function(){};
var url = sub(path, obj);
var img = new Image;
img.onerror = error(fn, 'failed to load pixel', img);
img.onload = function(){ fn(); };
query = stringify(query);
if (query) query = '?' + query;
img.src = url + query;
img.width = 1;
img.height = 1;
return img;
};
};
/**
* Create an error handler.
*
* @param {Fucntion} fn
* @param {String} message
* @param {Image} img
* @return {Function}
* @api private
*/
function error(fn, message, img){
return function(e){
e = e || window.event;
var err = new Error(message);
err.event = e;
err.source = img;
fn(err);
};
}
});
require.register("segmentio-analytics.js-integrations/index.js", function(exports, require, module){
var integrations = require('./lib/slugs');
var each = require('each');
/**
* Expose the integrations, using their own `name` from their `prototype`.
*/
each(integrations, function (slug) {
var plugin = require('./lib/' + slug);
var name = plugin.Integration.prototype.name;
exports[name] = plugin;
});
});
require.register("segmentio-analytics.js-integrations/lib/adroll.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(AdRoll);
user = analytics.user(); // store for later
};
/**
* Expose `AdRoll` integration.
*/
var AdRoll = exports.Integration = integration('AdRoll')
.assumesPageview()
.readyOnLoad()
.global('__adroll_loaded')
.global('adroll_adv_id')
.global('adroll_pix_id')
.global('adroll_custom_data')
.option('advId', '')
.option('pixId', '');
/**
* Initialize.
*
* http://support.adroll.com/getting-started-in-4-easy-steps/#step-one
* http://support.adroll.com/enhanced-conversion-tracking/
*
* @param {Object} page
*/
AdRoll.prototype.initialize = function (page) {
window.adroll_adv_id = this.options.advId;
window.adroll_pix_id = this.options.pixId;
if (user.id()) window.adroll_custom_data = { USER_ID: user.id() };
window.__adroll_loaded = true;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
AdRoll.prototype.loaded = function () {
return window.__adroll;
};
/**
* Load the AdRoll library.
*
* @param {Function} callback
*/
AdRoll.prototype.load = function (callback) {
load({
http: 'http://a.adroll.com/j/roundtrip.js',
https: 'https://s.adroll.com/j/roundtrip.js'
}, callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/adwords.js", function(exports, require, module){
var load = require('load-pixel')('//www.googleadservices.com/pagead/conversion/:id');
var integration = require('integration');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(AdWords);
};
/**
* Expose `load`.
*/
exports.load = load;
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `AdWords`
*/
var AdWords = exports.Integration = integration('AdWords')
.readyOnInitialize()
.option('conversionId', '')
.option('events', {});
/**
* Track.
*
* @param {Track}
*/
AdWords.prototype.track = function(track){
var id = this.options.conversionId;
var events = this.options.events;
var event = track.event();
if (!has.call(events, event)) return;
return exports.load({
value: track.revenue() || 0,
label: events[event],
script: 0
}, { id: id });
};
});
require.register("segmentio-analytics.js-integrations/lib/amplitude.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Amplitude);
};
/**
* Expose `Amplitude` integration.
*/
var Amplitude = exports.Integration = integration('Amplitude')
.assumesPageview()
.readyOnInitialize()
.global('amplitude')
.option('apiKey', '')
.option('trackAllPages', false)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* https://github.com/amplitude/Amplitude-Javascript
*
* @param {Object} page
*/
Amplitude.prototype.initialize = function (page) {
(function(e,t){var r=e.amplitude||{}; r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)));};} var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName"]; for(var c=0;c<s.length;c++){i(s[c]);}e.amplitude=r;})(window,document);
window.amplitude.init(this.options.apiKey);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Amplitude.prototype.loaded = function () {
return !! (window.amplitude && window.amplitude.options);
};
/**
* Load the Amplitude library.
*
* @param {Function} callback
*/
Amplitude.prototype.load = function (callback) {
load('https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.0-min.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Amplitude.prototype.page = function (page) {
var properties = page.properties();
var category = page.category();
var name = page.fullName();
var opts = this.options;
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Identify.
*
* @param {Facade} identify
*/
Amplitude.prototype.identify = function (identify) {
var id = identify.userId();
var traits = identify.traits();
if (id) window.amplitude.setUserId(id);
if (traits) window.amplitude.setGlobalUserProperties(traits);
};
/**
* Track.
*
* @param {Track} event
*/
Amplitude.prototype.track = function (track) {
var props = track.properties();
var event = track.event();
window.amplitude.logEvent(event, props);
};
});
require.register("segmentio-analytics.js-integrations/lib/awesm.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Awesm);
user = analytics.user(); // store for later
};
/**
* Expose `Awesm` integration.
*/
var Awesm = exports.Integration = integration('awe.sm')
.assumesPageview()
.readyOnLoad()
.global('AWESM')
.option('apiKey', '')
.option('events', {});
/**
* Initialize.
*
* http://developers.awe.sm/guides/javascript/
*
* @param {Object} page
*/
Awesm.prototype.initialize = function (page) {
window.AWESM = { api_key: this.options.apiKey };
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Awesm.prototype.loaded = function () {
return !! window.AWESM._exists;
};
/**
* Load.
*
* @param {Function} callback
*/
Awesm.prototype.load = function (callback) {
var key = this.options.apiKey;
load('//widgets.awe.sm/v3/widgets.js?key=' + key + '&async=true', callback);
};
/**
* Track.
*
* @param {Track} track
*/
Awesm.prototype.track = function (track) {
var event = track.event();
var goal = this.options.events[event];
if (!goal) return;
window.AWESM.convert(goal, track.cents(), null, user.id());
};
});
require.register("segmentio-analytics.js-integrations/lib/awesomatic.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var load = require('load-script');
var noop = function(){};
var onBody = require('on-body');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Awesomatic);
user = analytics.user(); // store for later
};
/**
* Expose `Awesomatic` integration.
*/
var Awesomatic = exports.Integration = integration('Awesomatic')
.assumesPageview()
.global('Awesomatic')
.global('AwesomaticSettings')
.global('AwsmSetup')
.global('AwsmTmp')
.option('appId', '');
/**
* Initialize.
*
* @param {Object} page
*/
Awesomatic.prototype.initialize = function (page) {
var self = this;
var id = user.id();
var options = user.traits();
options.appId = this.options.appId;
if (id) options.user_id = id;
this.load(function () {
window.Awesomatic.initialize(options, function () {
self.emit('ready'); // need to wait for initialize to callback
});
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Awesomatic.prototype.loaded = function () {
return is.object(window.Awesomatic);
};
/**
* Load the Awesomatic library.
*
* @param {Function} callback
*/
Awesomatic.prototype.load = function (callback) {
var url = 'https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js';
load(url, callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/bing-ads.js", function(exports, require, module){
var integration = require('integration');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Bing);
};
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `Bing`
*/
var Bing = exports.Integration = integration('Bing Ads')
.readyOnInitialize()
.option('siteId', '')
.option('domainId', '')
.option('goals', {});
/**
* Track.
*
* @param {Track} track
*/
Bing.prototype.track = function(track){
var goals = this.options.goals;
var traits = track.traits();
var event = track.event();
if (!has.call(goals, event)) return;
var goal = goals[event];
return exports.load(goal, track.revenue(), this.options);
};
/**
* Load conversion.
*
* @param {Mixed} goal
* @param {Number} revenue
* @param {String} currency
* @return {IFrame}
* @api private
*/
exports.load = function(goal, revenue, options){
var iframe = document.createElement('iframe');
iframe.src = '//flex.msn.com/mstag/tag/' + options.siteId
+ '/analytics.html'
+ '?domainId=' + options.domainId
+ '&revenue=' + revenue || 0
+ '&actionid=' + goal;
+ '&dedup=1'
+ '&type=1'
iframe.width = 1;
iframe.height = 1;
return iframe;
};
});
require.register("segmentio-analytics.js-integrations/lib/bronto.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var Track = require('facade').Track;
var load = require('load-script');
var each = require('each');
/**
* Expose plugin.
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Bronto);
};
/**
* Expose `Bronto` integration.
*/
var Bronto = exports.Integration = integration('Bronto')
.readyOnLoad()
.global('__bta')
.option('siteId', '')
.option('host', '');
/**
* Initialize.
*
* http://bronto.com/product-blog/features/using-conversion-tracking-private-domain#.Ut_Vk2T8KqB
* http://bronto.com/product-blog/features/javascript-conversion-tracking-setup-and-reporting#.Ut_VhmT8KqB
*
* @param {Object} page
*/
Bronto.prototype.initialize = function(page){
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Bronto.prototype.loaded = function(){
return this.bta;
};
/**
* Load the Bronto library.
*
* @param {Function} fn
*/
Bronto.prototype.load = function(fn){
var self = this;
load('//p.bm23.com/bta.js', function(err){
if (err) return fn(err);
var opts = self.options;
self.bta = new window.__bta(opts.siteId);
if (opts.host) self.bta.setHost(opts.host);
fn();
});
};
/**
* Track.
*
* @param {Track} event
*/
Bronto.prototype.track = function(track){
var revenue = track.revenue();
var event = track.event();
var type = 'number' == typeof revenue ? '$' : 't';
this.bta.addConversionLegacy(type, event, revenue);
};
/**
* Completed order.
*
* @param {Track} track
* @api private
*/
Bronto.prototype.completedOrder = function(track){
var products = track.products();
var props = track.properties();
var items = [];
// items
each(products, function(product){
var track = new Track({ properties: product });
items.push({
item_id: track.id() || track.sku(),
desc: product.description || track.name(),
quantity: track.quantity(),
amount: track.price(),
});
});
// add conversion
this.bta.addConversion({
order_id: track.orderId(),
date: props.date || new Date,
items: items
});
};
});
require.register("segmentio-analytics.js-integrations/lib/bugherd.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(BugHerd);
};
/**
* Expose `BugHerd` integration.
*/
var BugHerd = exports.Integration = integration('BugHerd')
.assumesPageview()
.readyOnLoad()
.global('BugHerdConfig')
.global('_bugHerd')
.option('apiKey', '')
.option('showFeedbackTab', true);
/**
* Initialize.
*
* http://support.bugherd.com/home
*
* @param {Object} page
*/
BugHerd.prototype.initialize = function (page) {
window.BugHerdConfig = { feedback: { hide: !this.options.showFeedbackTab }};
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
BugHerd.prototype.loaded = function () {
return !! window._bugHerd;
};
/**
* Load the BugHerd library.
*
* @param {Function} callback
*/
BugHerd.prototype.load = function (callback) {
load('//www.bugherd.com/sidebarv2.js?apikey=' + this.options.apiKey, callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/bugsnag.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var extend = require('extend');
var load = require('load-script');
var onError = require('on-error');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Bugsnag);
};
/**
* Expose `Bugsnag` integration.
*/
var Bugsnag = exports.Integration = integration('Bugsnag')
.readyOnLoad()
.global('Bugsnag')
.option('apiKey', '');
/**
* Initialize.
*
* https://bugsnag.com/docs/notifiers/js
*
* @param {Object} page
*/
Bugsnag.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Bugsnag.prototype.loaded = function () {
return is.object(window.Bugsnag);
};
/**
* Load.
*
* @param {Function} callback (optional)
*/
Bugsnag.prototype.load = function (callback) {
var apiKey = this.options.apiKey;
load('//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js', function(err){
if (err) return callback(err);
window.Bugsnag.apiKey = apiKey;
callback();
});
};
/**
* Identify.
*
* @param {Identify} identify
*/
Bugsnag.prototype.identify = function (identify) {
window.Bugsnag.metaData = window.Bugsnag.metaData || {};
extend(window.Bugsnag.metaData, identify.traits());
};
});
require.register("segmentio-analytics.js-integrations/lib/chartbeat.js", function(exports, require, module){
var integration = require('integration');
var onBody = require('on-body');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Chartbeat);
};
/**
* Expose `Chartbeat` integration.
*/
var Chartbeat = exports.Integration = integration('Chartbeat')
.assumesPageview()
.readyOnLoad()
.global('_sf_async_config')
.global('_sf_endpt')
.global('pSUPERFLY')
.option('domain', '')
.option('uid', null);
/**
* Initialize.
*
* http://chartbeat.com/docs/configuration_variables/
*
* @param {Object} page
*/
Chartbeat.prototype.initialize = function (page) {
window._sf_async_config = this.options;
onBody(function () {
window._sf_endpt = new Date().getTime();
});
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Chartbeat.prototype.loaded = function () {
return !! window.pSUPERFLY;
};
/**
* Load the Chartbeat library.
*
* http://chartbeat.com/docs/adding_the_code/
*
* @param {Function} callback
*/
Chartbeat.prototype.load = function (callback) {
load({
https: 'https://a248.e.akamai.net/chartbeat.download.akamai.com/102508/js/chartbeat.js',
http: 'http://static.chartbeat.com/js/chartbeat.js'
}, callback);
};
/**
* Page.
*
* http://chartbeat.com/docs/handling_virtual_page_changes/
*
* @param {Page} page
*/
Chartbeat.prototype.page = function (page) {
var props = page.properties();
var name = page.fullName();
window.pSUPERFLY.virtualPage(props.path, name || props.title);
};
});
require.register("segmentio-analytics.js-integrations/lib/churnbee.js", function(exports, require, module){
/**
* Module dependencies.
*/
var push = require('global-queue')('_cbq');
var integration = require('integration');
var load = require('load-script');
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Supported events
*/
var supported = {
activation: true,
changePlan: true,
register: true,
refund: true,
charge: true,
cancel: true,
login: true,
};
/**
* Expose plugin.
*/
module.exports = exports = function(analytics){
analytics.addIntegration(ChurnBee);
};
/**
* Expose `ChurnBee` integration.
*/
var ChurnBee = exports.Integration = integration('ChurnBee')
.readyOnInitialize()
.global('_cbq')
.global('ChurnBee')
.option('events', {})
.option('apiKey', '');
/**
* Initialize.
*
* https://churnbee.com/docs
*
* @param {Object} page
*/
ChurnBee.prototype.initialize = function(page){
push('_setApiKey', this.options.apiKey);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
ChurnBee.prototype.loaded = function(){
return !! window.ChurnBee;
};
/**
* Load the ChurnBee library.
*
* @param {Function} fn
*/
ChurnBee.prototype.load = function(fn){
load('//api.churnbee.com/cb.js', fn);
};
/**
* Track.
*
* @param {Track} event
*/
ChurnBee.prototype.track = function(track){
var events = this.options.events;
var event = track.event();
if (has.call(events, event)) event = events[event];
if (true != supported[event]) return;
push(event, track.properties({ revenue: 'amount' }));
};
});
require.register("segmentio-analytics.js-integrations/lib/clicktale.js", function(exports, require, module){
var date = require('load-date');
var domify = require('domify');
var each = require('each');
var integration = require('integration');
var is = require('is');
var useHttps = require('use-https');
var load = require('load-script');
var onBody = require('on-body');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(ClickTale);
};
/**
* Expose `ClickTale` integration.
*/
var ClickTale = exports.Integration = integration('ClickTale')
.assumesPageview()
.readyOnLoad()
.global('WRInitTime')
.global('ClickTale')
.global('ClickTaleSetUID')
.global('ClickTaleField')
.global('ClickTaleEvent')
.option('httpCdnUrl', 'http://s.clicktale.net/WRe0.js')
.option('httpsCdnUrl', '')
.option('projectId', '')
.option('recordingRatio', 0.01)
.option('partitionId', '');
/**
* Initialize.
*
* http://wiki.clicktale.com/Article/JavaScript_API
*
* @param {Object} page
*/
ClickTale.prototype.initialize = function (page) {
var options = this.options;
window.WRInitTime = date.getTime();
onBody(function (body) {
body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'));
});
this.load(function () {
window.ClickTale(options.projectId, options.recordingRatio, options.partitionId);
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
ClickTale.prototype.loaded = function () {
return is.fn(window.ClickTale);
};
/**
* Load the ClickTale library.
*
* @param {Function} callback
*/
ClickTale.prototype.load = function (callback) {
var http = this.options.httpCdnUrl;
var https = this.options.httpsCdnUrl;
if (useHttps() && !https) return this.debug('https option required');
load({ http: http, https: https }, callback);
};
/**
* Identify.
*
* http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleSetUID
* http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleField
*
* @param {Identify} identify
*/
ClickTale.prototype.identify = function (identify) {
var id = identify.userId();
window.ClickTaleSetUID(id);
each(identify.traits(), function (key, value) {
window.ClickTaleField(key, value);
});
};
/**
* Track.
*
* http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleEvent
*
* @param {Track} track
*/
ClickTale.prototype.track = function (track) {
window.ClickTaleEvent(track.event());
};
});
require.register("segmentio-analytics.js-integrations/lib/clicky.js", function(exports, require, module){
var Identify = require('facade').Identify;
var extend = require('extend');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Clicky);
user = analytics.user(); // store for later
};
/**
* Expose `Clicky` integration.
*/
var Clicky = exports.Integration = integration('Clicky')
.assumesPageview()
.readyOnLoad()
.global('clicky')
.global('clicky_site_ids')
.global('clicky_custom')
.option('siteId', null);
/**
* Initialize.
*
* http://clicky.com/help/customization
*
* @param {Object} page
*/
Clicky.prototype.initialize = function (page) {
window.clicky_site_ids = window.clicky_site_ids || [this.options.siteId];
this.identify(new Identify({
userId: user.id(),
traits: user.traits()
}));
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Clicky.prototype.loaded = function () {
return is.object(window.clicky);
};
/**
* Load the Clicky library.
*
* @param {Function} callback
*/
Clicky.prototype.load = function (callback) {
load('//static.getclicky.com/js', callback);
};
/**
* Page.
*
* http://clicky.com/help/customization#/help/custom/manual
*
* @param {Page} page
*/
Clicky.prototype.page = function (page) {
var properties = page.properties();
var category = page.category();
var name = page.fullName();
window.clicky.log(properties.path, name || properties.title);
};
/**
* Identify.
*
* @param {Identify} id (optional)
*/
Clicky.prototype.identify = function (identify) {
window.clicky_custom = window.clicky_custom || {};
window.clicky_custom.session = window.clicky_custom.session || {};
extend(window.clicky_custom.session, identify.traits());
};
/**
* Track.
*
* http://clicky.com/help/customization#/help/custom/manual
*
* @param {Track} event
*/
Clicky.prototype.track = function (track) {
window.clicky.goal(track.event(), track.revenue());
};
});
require.register("segmentio-analytics.js-integrations/lib/comscore.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Comscore);
};
/**
* Expose `Comscore` integration.
*/
var Comscore = exports.Integration = integration('comScore')
.assumesPageview()
.readyOnLoad()
.global('_comscore')
.global('COMSCORE')
.option('c1', '2')
.option('c2', '');
/**
* Initialize.
*
* @param {Object} page
*/
Comscore.prototype.initialize = function (page) {
window._comscore = window._comscore || [this.options];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Comscore.prototype.loaded = function () {
return !! window.COMSCORE;
};
/**
* Load.
*
* @param {Function} callback
*/
Comscore.prototype.load = function (callback) {
load({
http: 'http://b.scorecardresearch.com/beacon.js',
https: 'https://sb.scorecardresearch.com/beacon.js'
}, callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/crazy-egg.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(CrazyEgg);
};
/**
* Expose `CrazyEgg` integration.
*/
var CrazyEgg = exports.Integration = integration('Crazy Egg')
.assumesPageview()
.readyOnLoad()
.global('CE2')
.option('accountNumber', '');
/**
* Initialize.
*
* @param {Object} page
*/
CrazyEgg.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
CrazyEgg.prototype.loaded = function () {
return !! window.CE2;
};
/**
* Load the Crazy Egg library.
*
* @param {Function} callback
*/
CrazyEgg.prototype.load = function (callback) {
var number = this.options.accountNumber;
var path = number.slice(0,4) + '/' + number.slice(4);
var cache = Math.floor(new Date().getTime()/3600000);
var url = '//dnn506yrbagrg.cloudfront.net/pages/scripts/' + path + '.js?' + cache;
load(url, callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/curebit.js", function(exports, require, module){
var push = require('global-queue')('_curebitq');
var Identify = require('facade').Identify;
var integration = require('integration');
var Track = require('facade').Track;
var iso = require('to-iso-string');
var load = require('load-script');
var extend = require('extend');
var clone = require('clone');
var each = require('each');
/**
* User reference
*/
var user;
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Curebit);
user = analytics.user();
};
/**
* Expose `Curebit` integration
*/
var Curebit = exports.Integration = integration('Curebit')
.readyOnInitialize()
.global('_curebitq')
.global('curebit')
.option('siteId', '')
.option('iframeWidth', 0)
.option('iframeHeight', 0)
.option('iframeBorder', 0)
.option('iframeId', '')
.option('responsive', true)
.option('device', '')
.option('server', 'https://www.curebit.com');
/**
* Initialize
*
* @param {Object} page
*/
Curebit.prototype.initialize = function(){
push('init', {
site_id: this.options.siteId,
server: this.options.server
});
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Curebit.prototype.loaded = function(){
return !! window.curebit;
};
/**
* Load
*
* @param {Function} fn
* @api private
*/
Curebit.prototype.load = function(fn){
load('//d2jjzw81hqbuqv.cloudfront.net/assets/api/all-0.6.js', fn);
};
/**
* Identify.
*
* http://www.curebit.com/docs/affiliate/registration
*
* @param {Identify} identify
* @api public
*/
Curebit.prototype.identify = function(identify){
push('register_affiliate', {
responsive: this.options.responsive,
device: this.options.device,
iframe: {
width: this.options.iframeWidth,
height: this.options.iframeHeight,
id: this.options.iframeId,
frameborder: this.options.iframeBorder
},
affiliate_member: {
email: identify.email(),
first_name: identify.firstName(),
last_name: identify.lastName(),
customer_id: identify.userId()
},
});
};
/**
* Completed order
*
* https://www.curebit.com/docs/ecommerce/custom
*
* @param {Track} track
* @api private
*/
Curebit.prototype.completedOrder = function(track){
var orderId = track.orderId();
var products = track.products();
var props = track.properties();
var items = [];
// identify
var identify = new Identify({
traits: user.traits(),
userId: user.id()
});
// items
each(products, function(product){
var track = new Track({ properties: product });
items.push({
product_id: track.id() || track.sku(),
quantity: track.quantity(),
image_url: product.image,
price: track.price(),
title: track.name(),
url: product.url,
});
});
// transaction
push('register_purchase', {
order_date: iso(props.date || new Date),
order_number: orderId,
coupon_code: track.coupon(),
subtotal: track.total(),
customer_id: identify.userId(),
first_name: identify.firstName(),
last_name: identify.lastName(),
email: identify.email(),
items: items
});
};
});
require.register("segmentio-analytics.js-integrations/lib/customerio.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var convertDates = require('convert-dates');
var Identify = require('facade').Identify;
var integration = require('integration');
var load = require('load-script');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Customerio);
user = analytics.user(); // store for later
};
/**
* Expose `Customerio` integration.
*/
var Customerio = exports.Integration = integration('Customer.io')
.assumesPageview()
.readyOnInitialize()
.global('_cio')
.option('siteId', '');
/**
* Initialize.
*
* http://customer.io/docs/api/javascript.html
*
* @param {Object} page
*/
Customerio.prototype.initialize = function (page) {
window._cio = window._cio || [];
(function() {var a,b,c; a = function (f) {return function () {window._cio.push([f].concat(Array.prototype.slice.call(arguments,0))); }; }; b = ['identify', 'track']; for (c = 0; c < b.length; c++) {window._cio[b[c]] = a(b[c]); } })();
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Customerio.prototype.loaded = function () {
return !! (window._cio && window._cio.pageHasLoaded);
};
/**
* Load.
*
* @param {Function} callback
*/
Customerio.prototype.load = function (callback) {
var script = load('https://assets.customer.io/assets/track.js', callback);
script.id = 'cio-tracker';
script.setAttribute('data-site-id', this.options.siteId);
};
/**
* Identify.
*
* http://customer.io/docs/api/javascript.html#section-Identify_customers
*
* @param {Identify} identify
*/
Customerio.prototype.identify = function (identify) {
if (!identify.userId()) return this.debug('user id required');
var traits = identify.traits({ created: 'created_at' });
traits = convertDates(traits, convertDate);
window._cio.identify(traits);
};
/**
* Group.
*
* @param {Group} group
*/
Customerio.prototype.group = function (group) {
var traits = group.traits();
traits = alias(traits, function (trait) {
return 'Group ' + trait;
});
this.identify(new Identify({
userId: user.id(),
traits: traits
}));
};
/**
* Track.
*
* http://customer.io/docs/api/javascript.html#section-Track_a_custom_event
*
* @param {Track} track
*/
Customerio.prototype.track = function (track) {
var properties = track.properties();
properties = convertDates(properties, convertDate);
window._cio.track(track.event(), properties);
};
/**
* Convert a date to the format Customer.io supports.
*
* @param {Date} date
* @return {Number}
*/
function convertDate (date) {
return Math.floor(date.getTime() / 1000);
}
});
require.register("segmentio-analytics.js-integrations/lib/drip.js", function(exports, require, module){
var alias = require('alias');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
var push = require('global-queue')('_dcq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Drip);
};
/**
* Expose `Drip` integration.
*/
var Drip = exports.Integration = integration('Drip')
.assumesPageview()
.readyOnLoad()
.global('dc')
.global('_dcq')
.global('_dcs')
.option('account', '');
/**
* Initialize.
*
* @param {Object} page
*/
Drip.prototype.initialize = function (page) {
window._dcq = window._dcq || [];
window._dcs = window._dcs || {};
window._dcs.account = this.options.account;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Drip.prototype.loaded = function () {
return is.object(window.dc);
};
/**
* Load.
*
* @param {Function} callback
*/
Drip.prototype.load = function (callback) {
load('//tag.getdrip.com/' + this.options.account + '.js', callback);
};
/**
* Track.
*
* @param {Track} track
*/
Drip.prototype.track = function (track) {
var props = track.properties();
var cents = Math.round(track.cents());
props.action = track.event();
if (cents) props.value = cents;
delete props.revenue;
push('track', props);
};
});
require.register("segmentio-analytics.js-integrations/lib/errorception.js", function(exports, require, module){
var callback = require('callback');
var extend = require('extend');
var integration = require('integration');
var load = require('load-script');
var onError = require('on-error');
var push = require('global-queue')('_errs');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Errorception);
};
/**
* Expose `Errorception` integration.
*/
var Errorception = exports.Integration = integration('Errorception')
.assumesPageview()
.readyOnInitialize()
.global('_errs')
.option('projectId', '')
.option('meta', true);
/**
* Initialize.
*
* https://github.com/amplitude/Errorception-Javascript
*
* @param {Object} page
*/
Errorception.prototype.initialize = function (page) {
window._errs = window._errs || [this.options.projectId];
onError(push);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Errorception.prototype.loaded = function () {
return !! (window._errs && window._errs.push !== Array.prototype.push);
};
/**
* Load the Errorception library.
*
* @param {Function} callback
*/
Errorception.prototype.load = function (callback) {
load('//beacon.errorception.com/' + this.options.projectId + '.js', callback);
};
/**
* Identify.
*
* http://blog.errorception.com/2012/11/capture-custom-data-with-your-errors.html
*
* @param {Object} identify
*/
Errorception.prototype.identify = function (identify) {
if (!this.options.meta) return;
var traits = identify.traits();
window._errs = window._errs || [];
window._errs.meta = window._errs.meta || {};
extend(window._errs.meta, traits);
};
});
require.register("segmentio-analytics.js-integrations/lib/evergage.js", function(exports, require, module){
var each = require('each');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_aaq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Evergage);
};
/**
* Expose `Evergage` integration.integration.
*/
var Evergage = exports.Integration = integration('Evergage')
.assumesPageview()
.readyOnInitialize()
.global('_aaq')
.option('account', '')
.option('dataset', '');
/**
* Initialize.
*
* @param {Object} page
*/
Evergage.prototype.initialize = function (page) {
var account = this.options.account;
var dataset = this.options.dataset;
window._aaq = window._aaq || [];
push('setEvergageAccount', account);
push('setDataset', dataset);
push('setUseSiteConfig', true);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Evergage.prototype.loaded = function () {
return !! (window._aaq && window._aaq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Evergage.prototype.load = function (callback) {
var account = this.options.account;
var dataset = this.options.dataset;
var url = '//cdn.evergage.com/beacon/' + account + '/' + dataset + '/scripts/evergage.min.js';
load(url, callback);
};
/**
* Page.
*
* @param {Page} page
*/
Evergage.prototype.page = function (page) {
var props = page.properties();
var name = page.name();
if (name) push('namePage', name);
each(props, function(key, value) {
push('setCustomField', key, value, 'page');
});
window.Evergage.init(true);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Evergage.prototype.identify = function (identify) {
var id = identify.userId();
if (!id) return;
push('setUser', id);
var traits = identify.traits({
email: 'userEmail',
name: 'userName'
});;
each(traits, function (key, value) {
push('setUserField', key, value, 'page');
});
};
/**
* Group.
*
* @param {Group} group
*/
Evergage.prototype.group = function (group) {
var props = group.traits();
var id = group.groupId();
if (!id) return;
push('setCompany', id);
each(props, function(key, value) {
push('setAccountField', key, value, 'page');
});
};
/**
* Track.
*
* @param {Track} track
*/
Evergage.prototype.track = function (track) {
push('trackAction', track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/facebook-ads.js", function(exports, require, module){
var load = require('load-pixel')('//www.facebook.com/offsite_event.php');
var integration = require('integration');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Facebook);
};
/**
* Expose `load`.
*/
exports.load = load;
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `Facebook`
*/
var Facebook = exports.Integration = integration('Facebook Ads')
.readyOnInitialize()
.option('currency', 'USD')
.option('events', {});
/**
* Track.
*
* @param {Track} track
*/
Facebook.prototype.track = function(track){
var events = this.options.events;
var traits = track.traits();
var event = track.event();
if (!has.call(events, event)) return;
return exports.load({
currency: this.options.currency,
value: track.revenue() || 0,
id: events[event]
});
};
});
require.register("segmentio-analytics.js-integrations/lib/foxmetrics.js", function(exports, require, module){
var push = require('global-queue')('_fxm');
var integration = require('integration');
var Track = require('facade').Track;
var callback = require('callback');
var load = require('load-script');
var each = require('each');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(FoxMetrics);
};
/**
* Expose `FoxMetrics` integration.
*/
var FoxMetrics = exports.Integration = integration('FoxMetrics')
.assumesPageview()
.readyOnInitialize()
.global('_fxm')
.option('appId', '');
/**
* Initialize.
*
* http://foxmetrics.com/documentation/apijavascript
*
* @param {Object} page
*/
FoxMetrics.prototype.initialize = function(page){
window._fxm = window._fxm || [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
FoxMetrics.prototype.loaded = function(){
return !! (window._fxm && window._fxm.appId);
};
/**
* Load the FoxMetrics library.
*
* @param {Function} callback
*/
FoxMetrics.prototype.load = function(callback){
var id = this.options.appId;
load('//d35tca7vmefkrc.cloudfront.net/scripts/' + id + '.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
FoxMetrics.prototype.page = function(page){
var properties = page.proxy('properties');
var category = page.category();
var name = page.name();
this._category = category; // store for later
push(
'_fxm.pages.view',
properties.title, // title
name, // name
category, // category
properties.url, // url
properties.referrer // referrer
);
};
/**
* Identify.
*
* @param {Identify} identify
*/
FoxMetrics.prototype.identify = function(identify){
var id = identify.userId();
if (!id) return;
push(
'_fxm.visitor.profile',
id, // user id
identify.firstName(), // first name
identify.lastName(), // last name
identify.email(), // email
identify.address(), // address
undefined, // social
undefined, // partners
identify.traits() // attributes
);
};
/**
* Track.
*
* @param {Track} track
*/
FoxMetrics.prototype.track = function(track){
var props = track.properties();
var category = this._category || props.category;
push(track.event(), category, props);
};
/**
* Viewed product.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.viewedProduct = function(track){
ecommerce('productview', track);
};
/**
* Removed product.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.removedProduct = function(track){
ecommerce('removecartitem', track);
};
/**
* Added product.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.addedProduct = function(track){
ecommerce('cartitem', track);
};
/**
* Completed Order.
*
* @param {Track} track
* @api private
*/
FoxMetrics.prototype.completedOrder = function(track){
var orderId = track.orderId();
// transaction
push('_fxm.ecommerce.order'
, orderId
, track.subtotal()
, track.shipping()
, track.tax()
, track.city()
, track.state()
, track.zip()
, track.quantity());
// items
each(track.products(), function(product){
var track = new Track({ properties: product });
ecommerce('purchaseitem', track, [
track.quantity(),
track.price(),
orderId
]);
});
};
/**
* Track ecommerce `event` with `track`
* with optional `arr` to append.
*
* @param {String} event
* @param {Track} track
* @param {Array} arr
* @api private
*/
function ecommerce(event, track, arr){
push.apply(null, [
'_fxm.ecommerce.' + event,
track.id() || track.sku(),
track.name(),
track.category()
].concat(arr || []));
};
});
require.register("segmentio-analytics.js-integrations/lib/gauges.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_gauges');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Gauges);
};
/**
* Expose `Gauges` integration.
*/
var Gauges = exports.Integration = integration('Gauges')
.assumesPageview()
.readyOnInitialize()
.global('_gauges')
.option('siteId', '');
/**
* Initialize Gauges.
*
* http://get.gaug.es/documentation/tracking/
*
* @param {Object} page
*/
Gauges.prototype.initialize = function (page) {
window._gauges = window._gauges || [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Gauges.prototype.loaded = function () {
return !! (window._gauges && window._gauges.push !== Array.prototype.push);
};
/**
* Load the Gauges library.
*
* @param {Function} callback
*/
Gauges.prototype.load = function (callback) {
var id = this.options.siteId;
var script = load('//secure.gaug.es/track.js', callback);
script.id = 'gauges-tracker';
script.setAttribute('data-site-id', id);
};
/**
* Page.
*
* @param {Page} page
*/
Gauges.prototype.page = function (page) {
push('track');
};
});
require.register("segmentio-analytics.js-integrations/lib/get-satisfaction.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
var onBody = require('on-body');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(GetSatisfaction);
};
/**
* Expose `GetSatisfaction` integration.
*/
var GetSatisfaction = exports.Integration = integration('Get Satisfaction')
.assumesPageview()
.readyOnLoad()
.global('GSFN')
.option('widgetId', '');
/**
* Initialize.
*
* https://console.getsatisfaction.com/start/101022?signup=true#engage
*
* @param {Object} page
*/
GetSatisfaction.prototype.initialize = function (page) {
var widget = this.options.widgetId;
var div = document.createElement('div');
var id = div.id = 'getsat-widget-' + widget;
onBody(function (body) { body.appendChild(div); });
// usually the snippet is sync, so wait for it before initializing the tab
this.load(function () {
window.GSFN.loadWidget(widget, { containerId: id });
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
GetSatisfaction.prototype.loaded = function () {
return !! window.GSFN;
};
/**
* Load the Get Satisfaction library.
*
* @param {Function} callback
*/
GetSatisfaction.prototype.load = function (callback) {
load('https://loader.engage.gsfn.us/loader.js', callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/google-analytics.js", function(exports, require, module){
var callback = require('callback');
var canonical = require('canonical');
var each = require('each');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
var push = require('global-queue')('_gaq');
var Track = require('facade').Track;
var type = require('type');
var url = require('url');
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(GA);
user = analytics.user();
};
/**
* Expose `GA` integration.
*
* http://support.google.com/analytics/bin/answer.py?hl=en&answer=2558867
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration#_gat.GA_Tracker_._setSiteSpeedSampleRate
*/
var GA = exports.Integration = integration('Google Analytics')
.readyOnLoad()
.global('ga')
.global('gaplugins')
.global('_gaq')
.global('GoogleAnalyticsObject')
.option('anonymizeIp', false)
.option('classic', false)
.option('domain', 'none')
.option('doubleClick', false)
.option('enhancedLinkAttribution', false)
.option('ignoreReferrer', null)
.option('includeSearch', false)
.option('siteSpeedSampleRate', null)
.option('trackingId', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
.option('sendUserId', false);
/**
* When in "classic" mode, on `construct` swap all of the method to point to
* their classic counterparts.
*/
GA.on('construct', function (integration) {
if (!integration.options.classic) return;
integration.initialize = integration.initializeClassic;
integration.load = integration.loadClassic;
integration.loaded = integration.loadedClassic;
integration.page = integration.pageClassic;
integration.track = integration.trackClassic;
integration.completedOrder = integration.completedOrderClassic;
});
/**
* Initialize.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced
*/
GA.prototype.initialize = function () {
var opts = this.options;
// setup the tracker globals
window.GoogleAnalyticsObject = 'ga';
window.ga = window.ga || function () {
window.ga.q = window.ga.q || [];
window.ga.q.push(arguments);
};
window.ga.l = new Date().getTime();
window.ga('create', opts.trackingId, {
cookieDomain: opts.domain || GA.prototype.defaults.domain, // to protect against empty string
siteSpeedSampleRate: opts.siteSpeedSampleRate,
allowLinker: true
});
// send global id
if (this.options.sendUserId && user.id()) {
window.ga('set', '&uid', user.id());
}
// anonymize after initializing, otherwise a warning is shown
// in google analytics debugger
if (opts.anonymizeIp) window.ga('set', 'anonymizeIp', true);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
GA.prototype.loaded = function () {
return !! window.gaplugins;
};
/**
* Load the Google Analytics library.
*
* @param {Function} callback
*/
GA.prototype.load = function (callback) {
load('//www.google-analytics.com/analytics.js', callback);
};
/**
* Page.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/pages
*
* @param {Page} page
*/
GA.prototype.page = function (page) {
var category = page.category();
var props = page.properties();
var name = page.fullName();
var track;
this._category = category; // store for later
window.ga('send', 'pageview', {
page: path(props, this.options),
title: name || props.title,
location: props.url
});
// categorized pages
if (category && this.options.trackCategorizedPages) {
track = page.track(category);
this.track(track, { noninteraction: true });
}
// named pages
if (name && this.options.trackNamedPages) {
track = page.track(name);
this.track(track, { noninteraction: true });
}
};
/**
* Track.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/events
* https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference
*
* @param {Track} event
*/
GA.prototype.track = function (track, options) {
var opts = options || track.options(this.name);
var props = track.properties();
var revenue = track.revenue();
var event = track.event();
window.ga('send', 'event', {
eventAction: event,
eventCategory: this._category || props.category || 'All',
eventLabel: props.label,
eventValue: formatValue(props.value || revenue),
nonInteraction: props.noninteraction || opts.noninteraction
});
};
/**
* Completed order.
*
* https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce
*
* @param {Track} track
* @api private
*/
GA.prototype.completedOrder = function(track){
var orderId = track.orderId();
var products = track.products();
var props = track.properties();
// orderId is required.
if (!orderId) return;
// require ecommerce
if (!this.ecommerce) {
window.ga('require', 'ecommerce', 'ecommerce.js');
this.ecommerce = true;
}
// add transaction
window.ga('ecommerce:addTransaction', {
affiliation: props.affiliation,
shipping: track.shipping(),
revenue: track.total(),
tax: track.tax(),
id: orderId
});
// add products
each(products, function(product){
var track = new Track({ properties: product });
window.ga('ecommerce:addItem', {
category: track.category(),
quantity: track.quantity(),
price: track.price(),
name: track.name(),
sku: track.sku(),
id: orderId
});
});
// send
window.ga('ecommerce:send');
};
/**
* Initialize (classic).
*
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration
*/
GA.prototype.initializeClassic = function () {
var opts = this.options;
var anonymize = opts.anonymizeIp;
var db = opts.doubleClick;
var domain = opts.domain;
var enhanced = opts.enhancedLinkAttribution;
var ignore = opts.ignoreReferrer;
var sample = opts.siteSpeedSampleRate;
window._gaq = window._gaq || [];
push('_setAccount', opts.trackingId);
push('_setAllowLinker', true);
if (anonymize) push('_gat._anonymizeIp');
if (domain) push('_setDomainName', domain);
if (sample) push('_setSiteSpeedSampleRate', sample);
if (enhanced) {
var protocol = 'https:' === document.location.protocol ? 'https:' : 'http:';
var pluginUrl = protocol + '//www.google-analytics.com/plugins/ga/inpage_linkid.js';
push('_require', 'inpage_linkid', pluginUrl);
}
if (ignore) {
if (!is.array(ignore)) ignore = [ignore];
each(ignore, function (domain) {
push('_addIgnoredRef', domain);
});
}
this.load();
};
/**
* Loaded? (classic)
*
* @return {Boolean}
*/
GA.prototype.loadedClassic = function () {
return !! (window._gaq && window._gaq.push !== Array.prototype.push);
};
/**
* Load the classic Google Analytics library.
*
* @param {Function} callback
*/
GA.prototype.loadClassic = function (callback) {
if (this.options.doubleClick) {
load('//stats.g.doubleclick.net/dc.js', callback);
} else {
load({
http: 'http://www.google-analytics.com/ga.js',
https: 'https://ssl.google-analytics.com/ga.js'
}, callback);
}
};
/**
* Page (classic).
*
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration
*
* @param {Page} page
*/
GA.prototype.pageClassic = function (page) {
var opts = page.options(this.name);
var category = page.category();
var props = page.properties();
var name = page.fullName();
var track;
push('_trackPageview', path(props, this.options));
// categorized pages
if (category && this.options.trackCategorizedPages) {
track = page.track(category);
this.track(track, { noninteraction: true });
}
// named pages
if (name && this.options.trackNamedPages) {
track = page.track(name);
this.track(track, { noninteraction: true });
}
};
/**
* Track (classic).
*
* https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking
*
* @param {Track} track
*/
GA.prototype.trackClassic = function (track, options) {
var opts = options || track.options(this.name);
var props = track.properties();
var revenue = track.revenue();
var event = track.event();
var category = this._category || props.category || 'All';
var label = props.label;
var value = formatValue(revenue || props.value);
var noninteraction = props.noninteraction || opts.noninteraction;
push('_trackEvent', category, event, label, value, noninteraction);
};
/**
* Completed order.
*
* https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce
*
* @param {Track} track
* @api private
*/
GA.prototype.completedOrderClassic = function(track){
var orderId = track.orderId();
var products = track.products() || [];
var props = track.properties();
// required
if (!orderId) return;
// add transaction
push('_addTrans'
, orderId
, props.affiliation
, track.total()
, track.tax()
, track.shipping()
, track.city()
, track.state()
, track.country());
// add items
each(products, function(product){
var track = new Track({ properties: product });
push('_addItem'
, orderId
, track.sku()
, track.name()
, track.category()
, track.price()
, track.quantity());
})
// send
push('_trackTrans');
};
/**
* Return the path based on `properties` and `options`.
*
* @param {Object} properties
* @param {Object} options
*/
function path (properties, options) {
if (!properties) return;
var str = properties.path;
if (options.includeSearch && properties.search) str += properties.search;
return str;
}
/**
* Format the value property to Google's liking.
*
* @param {Number} value
* @return {Number}
*/
function formatValue (value) {
if (!value || value < 0) return 0;
return Math.round(value);
}
});
require.register("segmentio-analytics.js-integrations/lib/google-tag-manager.js", function(exports, require, module){
var push = require('global-queue')('dataLayer', { wrap: false });
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(GTM);
};
/**
* Expose `GTM`
*/
var GTM = exports.Integration = integration('Google Tag Manager')
.assumesPageview()
.readyOnLoad()
.global('dataLayer')
.global('google_tag_manager')
.option('containerId', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true)
/**
* Initialize
*
* https://developers.google.com/tag-manager
*
* @param {Object} page
*/
GTM.prototype.initialize = function(){
this.load();
};
/**
* Loaded
*
* @return {Boolean}
*/
GTM.prototype.loaded = function(){
return !! (window.dataLayer && [].push != window.dataLayer.push);
};
/**
* Load.
*
* @param {Function} fn
*/
GTM.prototype.load = function(fn){
var id = this.options.containerId;
push({ 'gtm.start': +new Date, event: 'gtm.js' });
load('//www.googletagmanager.com/gtm.js?id=' + id + '&l=dataLayer', fn);
};
/**
* Page.
*
* @param {Page} page
* @api public
*/
GTM.prototype.page = function(page){
var category = page.category();
var props = page.properties();
var name = page.fullName();
var opts = this.options;
var track;
// all
if (opts.trackAllPages) {
this.track(page.track());
}
// categorized
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Track.
*
* https://developers.google.com/tag-manager/devguide#events
*
* @param {Track} track
* @api public
*/
GTM.prototype.track = function(track){
var props = track.properties();
props.event = track.event();
push(props);
};
});
require.register("segmentio-analytics.js-integrations/lib/gosquared.js", function(exports, require, module){
var Identify = require('facade').Identify;
var Track = require('facade').Track;
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var onBody = require('on-body');
var each = require('each');
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(GoSquared);
user = analytics.user(); // store reference for later
};
/**
* Expose `GoSquared` integration.
*/
var GoSquared = exports.Integration = integration('GoSquared')
.assumesPageview()
.readyOnLoad()
.global('_gs')
.option('siteToken', '')
.option('anonymizeIP', false)
.option('cookieDomain', null)
.option('useCookies', true)
.option('trackHash', false)
.option('trackLocal', false)
.option('trackParams', true);
/**
* Initialize.
*
* https://www.gosquared.com/developer/tracker
* Options: https://www.gosquared.com/developer/tracker/configuration
*
* @param {Object} page
*/
GoSquared.prototype.initialize = function (page) {
var self = this;
var options = this.options;
push(options.siteToken);
each(options, function(name, value){
if ('siteToken' == name) return;
if (null == value) return;
push('set', name, value);
});
self.identify(new Identify({
traits: user.traits(),
userId: user.id()
}));
self.load();
};
/**
* Loaded? (checks if the tracker version is set)
*
* @return {Boolean}
*/
GoSquared.prototype.loaded = function () {
return !! (window._gs && window._gs.v);
};
/**
* Load the GoSquared library.
*
* @param {Function} callback
*/
GoSquared.prototype.load = function (callback) {
load('//d1l6p2sc9645hc.cloudfront.net/tracker.js', callback);
};
/**
* Page.
*
* https://www.gosquared.com/developer/tracker/pageviews
*
* @param {Page} page
*/
GoSquared.prototype.page = function (page) {
var props = page.properties();
var name = page.fullName();
push('track', props.path, name || props.title)
};
/**
* Identify.
*
* https://www.gosquared.com/developer/tracker/tagging
*
* @param {Identify} identify
*/
GoSquared.prototype.identify = function (identify) {
var traits = identify.traits({ userId: 'userID' });
var username = identify.username();
var email = identify.email();
var id = identify.userId();
if (id) push('set', 'visitorID', id);
var name = email || username || id;
if (name) push('set', 'visitorName', name);
push('set', 'visitor', traits);
};
/**
* Track.
*
* https://www.gosquared.com/developer/tracker/events
*
* @param {Track} track
*/
GoSquared.prototype.track = function (track) {
push('event', track.event(), track.properties());
};
/**
* Checked out.
*
* @param {Track} track
* @api private
*/
GoSquared.prototype.completedOrder = function(track){
var products = track.products();
var items = [];
each(products, function(product){
var track = new Track({ properties: product });
items.push({
category: track.category(),
quantity: track.quantity(),
price: track.price(),
name: track.name(),
});
})
push('transaction', track.orderId(), {
revenue: track.total(),
track: true
}, items);
};
/**
* Push to `_gs.q`.
*
* @param {...} args
* @api private
*/
function push(){
var _gs = window._gs = window._gs || function(){
(_gs.q = _gs.q || []).push(arguments);
};
_gs.apply(null, arguments);
}
});
require.register("segmentio-analytics.js-integrations/lib/heap.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Heap);
};
/**
* Expose `Heap` integration.
*/
var Heap = exports.Integration = integration('Heap')
.assumesPageview()
.readyOnInitialize()
.global('heap')
.global('_heapid')
.option('apiKey', '');
/**
* Initialize.
*
* https://heapanalytics.com/docs#installWeb
*
* @param {Object} page
*/
Heap.prototype.initialize = function (page) {
window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)));};},e=["identify","track"];for(var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f]);};
window.heap.load(this.options.apiKey);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Heap.prototype.loaded = function () {
return (window.heap && window.heap.appid);
};
/**
* Load the Heap library.
*
* @param {Function} callback
*/
Heap.prototype.load = function (callback) {
load('//d36lvucg9kzous.cloudfront.net', callback);
};
/**
* Identify.
*
* https://heapanalytics.com/docs#identify
*
* @param {Identify} identify
*/
Heap.prototype.identify = function (identify) {
var traits = identify.traits();
var username = identify.username();
var id = identify.userId();
var handle = username || id;
if (handle) traits.handle = handle;
delete traits.username;
window.heap.identify(traits);
};
/**
* Track.
*
* https://heapanalytics.com/docs#track
*
* @param {Track} track
*/
Heap.prototype.track = function (track) {
window.heap.track(track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/hittail.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(HitTail);
};
/**
* Expose `HitTail` integration.
*/
var HitTail = exports.Integration = integration('HitTail')
.assumesPageview()
.readyOnLoad()
.global('htk')
.option('siteId', '');
/**
* Initialize.
*
* @param {Object} page
*/
HitTail.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
HitTail.prototype.loaded = function () {
return is.fn(window.htk);
};
/**
* Load the HitTail library.
*
* @param {Function} callback
*/
HitTail.prototype.load = function (callback) {
var id = this.options.siteId;
load('//' + id + '.hittail.com/mlt.js', callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/hubspot.js", function(exports, require, module){
var callback = require('callback');
var convert = require('convert-dates');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_hsq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(HubSpot);
};
/**
* Expose `HubSpot` integration.
*/
var HubSpot = exports.Integration = integration('HubSpot')
.assumesPageview()
.readyOnInitialize()
.global('_hsq')
.option('portalId', null);
/**
* Initialize.
*
* @param {Object} page
*/
HubSpot.prototype.initialize = function (page) {
window._hsq = [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
HubSpot.prototype.loaded = function () {
return !! (window._hsq && window._hsq.push !== Array.prototype.push);
};
/**
* Load the HubSpot library.
*
* @param {Function} fn
*/
HubSpot.prototype.load = function (fn) {
if (document.getElementById('hs-analytics')) return callback.async(fn);
var id = this.options.portalId;
var cache = Math.ceil(new Date() / 300000) * 300000;
var url = 'https://js.hs-analytics.net/analytics/' + cache + '/' + id + '.js';
var script = load(url, fn);
script.id = 'hs-analytics';
};
/**
* Page.
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
HubSpot.prototype.page = function (page) {
push('_trackPageview');
};
/**
* Identify.
*
* @param {Identify} identify
*/
HubSpot.prototype.identify = function (identify) {
if (!identify.email()) return;
var traits = identify.traits();
traits = convertDates(traits);
push('identify', traits);
};
/**
* Track.
*
* @param {Track} track
*/
HubSpot.prototype.track = function (track) {
var props = track.properties();
props = convertDates(props);
push('trackEvent', track.event(), props);
};
/**
* Convert all the dates in the HubSpot properties to millisecond times
*
* @param {Object} properties
*/
function convertDates (properties) {
return convert(properties, function (date) { return date.getTime(); });
}
});
require.register("segmentio-analytics.js-integrations/lib/improvely.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Improvely);
};
/**
* Expose `Improvely` integration.
*/
var Improvely = exports.Integration = integration('Improvely')
.assumesPageview()
.readyOnInitialize()
.global('_improvely')
.global('improvely')
.option('domain', '')
.option('projectId', null);
/**
* Initialize.
*
* http://www.improvely.com/docs/landing-page-code
*
* @param {Object} page
*/
Improvely.prototype.initialize = function (page) {
window._improvely = [];
window.improvely = {init: function (e, t) { window._improvely.push(["init", e, t]); }, goal: function (e) { window._improvely.push(["goal", e]); }, label: function (e) { window._improvely.push(["label", e]); } };
var domain = this.options.domain;
var id = this.options.projectId;
window.improvely.init(domain, id);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Improvely.prototype.loaded = function () {
return !! (window.improvely && window.improvely.identify);
};
/**
* Load the Improvely library.
*
* @param {Function} callback
*/
Improvely.prototype.load = function (callback) {
var domain = this.options.domain;
load('//' + domain + '.iljmp.com/improvely.js', callback);
};
/**
* Identify.
*
* http://www.improvely.com/docs/labeling-visitors
*
* @param {Identify} identify
*/
Improvely.prototype.identify = function (identify) {
var id = identify.userId();
if (id) window.improvely.label(id);
};
/**
* Track.
*
* http://www.improvely.com/docs/conversion-code
*
* @param {Track} track
*/
Improvely.prototype.track = function (track) {
var props = track.properties({ revenue: 'amount' });
props.type = track.event();
window.improvely.goal(props);
};
});
require.register("segmentio-analytics.js-integrations/lib/inspectlet.js", function(exports, require, module){
var integration = require('integration');
var alias = require('alias');
var clone = require('clone');
var load = require('load-script');
var push = require('global-queue')('__insp');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Inspectlet);
};
/**
* Expose `Inspectlet` integration.
*/
var Inspectlet = exports.Integration = integration('Inspectlet')
.assumesPageview()
.readyOnLoad()
.global('__insp')
.global('__insp_')
.option('wid', '');
/**
* Initialize.
*
* https://www.inspectlet.com/dashboard/embedcode/1492461759/initial
*
* @param {Object} page
*/
Inspectlet.prototype.initialize = function (page) {
push('wid', this.options.wid);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Inspectlet.prototype.loaded = function () {
return !! window.__insp_;
};
/**
* Load the Inspectlet library.
*
* @param {Function} callback
*/
Inspectlet.prototype.load = function (callback) {
load('//www.inspectlet.com/inspectlet.js', callback);
};
/**
* Track.
*
* http://www.inspectlet.com/docs/tags
*
* @param {Track} track
*/
Inspectlet.prototype.track = function (track) {
push('tagSession', track.event());
};
});
require.register("segmentio-analytics.js-integrations/lib/intercom.js", function(exports, require, module){
var alias = require('alias');
var convertDates = require('convert-dates');
var integration = require('integration');
var each = require('each');
var is = require('is');
var isEmail = require('is-email');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Intercom);
};
/**
* Expose `Intercom` integration.
*/
var Intercom = exports.Integration = integration('Intercom')
.assumesPageview()
.readyOnLoad()
.global('Intercom')
.option('activator', '#IntercomDefaultWidget')
.option('appId', '')
.option('inbox', false);
/**
* Initialize.
*
* http://docs.intercom.io/
* http://docs.intercom.io/#IntercomJS
*
* @param {Object} page
*/
Intercom.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Intercom.prototype.loaded = function () {
return is.fn(window.Intercom);
};
/**
* Load the Intercom library.
*
* @param {Function} callback
*/
Intercom.prototype.load = function (callback) {
load('https://static.intercomcdn.com/intercom.v1.js', callback);
};
/**
* Identify.
*
* http://docs.intercom.io/#IntercomJS
*
* @param {Identify} identify
*/
Intercom.prototype.identify = function (identify) {
var traits = identify.traits({ userId: 'user_id' });
var opts = identify.options(this.name);
var companyCreated = identify.companyCreated();
var created = identify.created();
var email = identify.email();
var name = identify.name();
var id = identify.userId();
if (!id && !traits.email) return; // one is required
traits.app_id = this.options.appId;
// name
if (name) traits.name = name;
// handle dates
if (companyCreated) traits.company.created = companyCreated;
if (created) traits.created = created;
// convert dates
traits = convertDates(traits, formatDate);
traits = alias(traits, { created: 'created_at'});
// company
if (traits.company) {
traits.company = alias(traits.company, { created: 'created_at' });
}
// handle options
if (opts.increments) traits.increments = opts.increments;
if (opts.userHash) traits.user_hash = opts.userHash;
if (opts.user_hash) traits.user_hash = opts.user_hash;
if (this.options.inbox) {
traits.widget = {
activator: this.options.activator
};
}
var method = this._id !== id ? 'boot': 'update';
this._id = id; // cache for next time
window.Intercom(method, traits);
};
/**
* Group.
*
* @param {Group} group
*/
Intercom.prototype.group = function (group) {
var props = group.properties();
var id = group.groupId();
if (id) props.id = id;
window.Intercom('update', { company: props });
};
/**
* Track.
*
* @param {Track} track
*/
Intercom.prototype.track = function(track){
window.Intercom('trackUserEvent', track.event(), track.traits());
};
/**
* Format a date to Intercom's liking.
*
* @param {Date} date
* @return {Number}
*/
function formatDate (date) {
return Math.floor(date / 1000);
}
});
require.register("segmentio-analytics.js-integrations/lib/keen-io.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Keen);
};
/**
* Expose `Keen IO` integration.
*/
var Keen = exports.Integration = integration('Keen IO')
.readyOnInitialize()
.global('Keen')
.option('projectId', '')
.option('readKey', '')
.option('writeKey', '')
.option('trackNamedPages', true)
.option('trackAllPages', false)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* https://keen.io/docs/
*/
Keen.prototype.initialize = function () {
var options = this.options;
window.Keen = window.Keen||{configure:function(e){this._cf=e;},addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i]);},setGlobalProperties:function(e){this._gp=e;},onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e);}};
window.Keen.configure({
projectId: options.projectId,
writeKey: options.writeKey,
readKey: options.readKey
});
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Keen.prototype.loaded = function () {
return !! (window.Keen && window.Keen.Base64);
};
/**
* Load the Keen IO library.
*
* @param {Function} callback
*/
Keen.prototype.load = function (callback) {
load('//dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Keen.prototype.page = function (page) {
var category = page.category();
var props = page.properties();
var name = page.fullName();
var opts = this.options;
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Identify.
*
* TODO: migrate from old `userId` to simpler `id`
*
* @param {Identify} identify
*/
Keen.prototype.identify = function (identify) {
var traits = identify.traits();
var id = identify.userId();
var user = {};
if (id) user.userId = id;
if (traits) user.traits = traits;
window.Keen.setGlobalProperties(function() {
return { user: user };
});
};
/**
* Track.
*
* @param {Track} track
*/
Keen.prototype.track = function (track) {
window.Keen.addEvent(track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/kissmetrics.js", function(exports, require, module){
var alias = require('alias');
var Batch = require('batch');
var callback = require('callback');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
var push = require('global-queue')('_kmq');
var Track = require('facade').Track;
var each = require('each');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(KISSmetrics);
};
/**
* Expose `KISSmetrics` integration.
*/
var KISSmetrics = exports.Integration = integration('KISSmetrics')
.assumesPageview()
.readyOnInitialize()
.global('_kmq')
.global('KM')
.global('_kmil')
.option('apiKey', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* http://support.kissmetrics.com/apis/javascript
*
* @param {Object} page
*/
KISSmetrics.prototype.initialize = function (page) {
window._kmq = [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
KISSmetrics.prototype.loaded = function () {
return is.object(window.KM);
};
/**
* Load.
*
* @param {Function} callback
*/
KISSmetrics.prototype.load = function (callback) {
var key = this.options.apiKey;
var useless = '//i.kissmetrics.com/i.js';
var library = '//doug1izaerwt3.cloudfront.net/' + key + '.1.js';
new Batch()
.push(function (done) { load(useless, done); }) // :)
.push(function (done) { load(library, done); })
.end(callback);
};
/**
* Page.
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
KISSmetrics.prototype.page = function (page) {
var category = page.category();
var name = page.fullName();
var opts = this.options;
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Identify.
*
* @param {Identify} identify
*/
KISSmetrics.prototype.identify = function (identify) {
var traits = identify.traits();
var id = identify.userId();
if (id) push('identify', id);
if (traits) push('set', traits);
};
/**
* Track.
*
* @param {Track} track
*/
KISSmetrics.prototype.track = function (track) {
var props = track.properties({ revenue: 'Billing Amount' });
push('record', track.event(), props);
};
/**
* Alias.
*
* @param {Alias} to
*/
KISSmetrics.prototype.alias = function (alias) {
push('alias', alias.to(), alias.from());
};
/**
* Viewed product.
*
* @param {Track} track
* @api private
*/
KISSmetrics.prototype.viewedProduct = function(track){
push('record', 'Product Viewed', toProduct(track));
};
/**
* Product added.
*
* @param {Track} track
* @api private
*/
KISSmetrics.prototype.addedProduct = function(track){
push('record', 'Product Added', toProduct(track));
};
/**
* Completed order.
*
* @param {Track} track
* @api private
*/
KISSmetrics.prototype.completedOrder = function(track){
var orderId = track.orderId();
var products = track.products();
// transaction
push('record', 'Purchased', {
'Order ID': track.orderId(),
'Order Total': track.total()
});
// items
window._kmq.push(function(){
var km = window.KM;
each(products, function(product, i){
var track = new Track({ properties: product });
var item = toProduct(track);
item['Order ID'] = orderId;
item._t = km.ts() + i;
item._d = 1;
km.set(item);
});
});
};
/**
* Get a product from the given `track`.
*
* @param {Track} track
* @return {Object}
* @api private
*/
function toProduct(track){
return {
Quantity: track.quantity(),
Price: track.price(),
Name: track.name(),
SKU: track.sku()
};
}
});
require.register("segmentio-analytics.js-integrations/lib/klaviyo.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_learnq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Klaviyo);
};
/**
* Expose `Klaviyo` integration.
*/
var Klaviyo = exports.Integration = integration('Klaviyo')
.assumesPageview()
.readyOnInitialize()
.global('_learnq')
.option('apiKey', '');
/**
* Initialize.
*
* https://www.klaviyo.com/docs/getting-started
*
* @param {Object} page
*/
Klaviyo.prototype.initialize = function (page) {
push('account', this.options.apiKey);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Klaviyo.prototype.loaded = function () {
return !! (window._learnq && window._learnq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Klaviyo.prototype.load = function (callback) {
load('//a.klaviyo.com/media/js/learnmarklet.js', callback);
};
/**
* Trait aliases.
*/
var aliases = {
id: '$id',
email: '$email',
firstName: '$first_name',
lastName: '$last_name',
phone: '$phone_number',
title: '$title'
};
/**
* Identify.
*
* @param {Identify} identify
*/
Klaviyo.prototype.identify = function (identify) {
var traits = identify.traits(aliases);
if (!traits.$id && !traits.$email) return;
push('identify', traits);
};
/**
* Group.
*
* @param {Group} group
*/
Klaviyo.prototype.group = function (group) {
var props = group.properties();
if (!props.name) return;
push('identify', { $organization: props.name });
};
/**
* Track.
*
* @param {Track} track
*/
Klaviyo.prototype.track = function (track) {
push('track', track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/leadlander.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(LeadLander);
};
/**
* Expose `LeadLander` integration.
*/
var LeadLander = exports.Integration = integration('LeadLander')
.assumesPageview()
.readyOnLoad()
.global('llactid')
.global('trackalyzer')
.option('accountId', null);
/**
* Initialize.
*
* @param {Object} page
*/
LeadLander.prototype.initialize = function (page) {
window.llactid = this.options.accountId;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
LeadLander.prototype.loaded = function () {
return !! window.trackalyzer;
};
/**
* Load.
*
* @param {Function} callback
*/
LeadLander.prototype.load = function (callback) {
load('http://t6.trackalyzer.com/trackalyze-nodoc.js', callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/livechat.js", function(exports, require, module){
var each = require('each');
var integration = require('integration');
var load = require('load-script');
var clone = require('clone');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(LiveChat);
};
/**
* Expose `LiveChat` integration.
*/
var LiveChat = exports.Integration = integration('LiveChat')
.assumesPageview()
.readyOnLoad()
.global('__lc')
.option('group', 0)
.option('license', '');
/**
* Initialize.
*
* http://www.livechatinc.com/api/javascript-api
*
* @param {Object} page
*/
LiveChat.prototype.initialize = function (page) {
window.__lc = clone(this.options);
this.isLoaded = false;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
LiveChat.prototype.loaded = function () {
return this.isLoaded;
};
/**
* Load.
*
* @param {Function} callback
*/
LiveChat.prototype.load = function (callback) {
var self = this;
load('//cdn.livechatinc.com/tracking.js', function(err){
if (err) return callback(err);
self.isLoaded = true;
callback();
});
};
/**
* Identify.
*
* @param {Identify} identify
*/
LiveChat.prototype.identify = function (identify) {
var traits = identify.traits({ userId: 'User ID' });
window.LC_API.set_custom_variables(convert(traits));
};
/**
* Convert a traits object into the format LiveChat requires.
*
* @param {Object} traits
* @return {Array}
*/
function convert (traits) {
var arr = [];
each(traits, function (key, value) {
arr.push({ name: key, value: value });
});
return arr;
}
});
require.register("segmentio-analytics.js-integrations/lib/lucky-orange.js", function(exports, require, module){
var Identify = require('facade').Identify;
var integration = require('integration');
var load = require('load-script');
/**
* User ref
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(LuckyOrange);
user = analytics.user();
};
/**
* Expose `LuckyOrange` integration.
*/
var LuckyOrange = exports.Integration = integration('Lucky Orange')
.assumesPageview()
.readyOnLoad()
.global('_loq')
.global('__wtw_watcher_added')
.global('__wtw_lucky_site_id')
.global('__wtw_lucky_is_segment_io')
.global('__wtw_custom_user_data')
.option('siteId', null);
/**
* Initialize.
*
* @param {Object} page
*/
LuckyOrange.prototype.initialize = function (page) {
window._loq || (window._loq = []);
window.__wtw_lucky_site_id = this.options.siteId;
this.identify(new Identify({
traits: user.traits(),
userId: user.id()
}));
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
LuckyOrange.prototype.loaded = function () {
return !! window.__wtw_watcher_added;
};
/**
* Load.
*
* @param {Function} callback
*/
LuckyOrange.prototype.load = function (callback) {
var cache = Math.floor(new Date().getTime() / 60000);
load({
http: 'http://www.luckyorange.com/w.js?' + cache,
https: 'https://ssl.luckyorange.com/w.js?' + cache
}, callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
LuckyOrange.prototype.identify = function (identify) {
var traits = window.__wtw_custom_user_data = identify.traits();
var email = identify.email();
var name = identify.name();
if (name) traits.name = name;
if (email) traits.email = email;
};
});
require.register("segmentio-analytics.js-integrations/lib/lytics.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Lytics);
};
/**
* Expose `Lytics` integration.
*/
var Lytics = exports.Integration = integration('Lytics')
.readyOnInitialize()
.global('jstag')
.option('cid', '')
.option('cookie', 'seerid')
.option('delay', 2000)
.option('sessionTimeout', 1800)
.option('url', '//c.lytics.io');
/**
* Options aliases.
*/
var aliases = {
sessionTimeout: 'sessecs'
};
/**
* Initialize.
*
* http://admin.lytics.io/doc#jstag
*
* @param {Object} page
*/
Lytics.prototype.initialize = function (page) {
var options = alias(this.options, aliases);
window.jstag = (function () {var t = {_q: [], _c: options, ts: (new Date()).getTime() }; t.send = function() {this._q.push([ 'ready', 'send', Array.prototype.slice.call(arguments) ]); return this; }; return t; })();
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Lytics.prototype.loaded = function () {
return !! (window.jstag && window.jstag.bind);
};
/**
* Load the Lytics library.
*
* @param {Function} callback
*/
Lytics.prototype.load = function (callback) {
load('//c.lytics.io/static/io.min.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Lytics.prototype.page = function (page) {
window.jstag.send(page.properties());
};
/**
* Idenfity.
*
* @param {Identify} identify
*/
Lytics.prototype.identify = function (identify) {
var traits = identify.traits({ userId: '_uid' });
window.jstag.send(traits);
};
/**
* Track.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Lytics.prototype.track = function (track) {
var props = track.properties();
props._e = track.event();
window.jstag.send(props);
};
});
require.register("segmentio-analytics.js-integrations/lib/mixpanel.js", function(exports, require, module){
var alias = require('alias');
var clone = require('clone');
var dates = require('convert-dates');
var integration = require('integration');
var iso = require('to-iso-string');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Mixpanel);
};
/**
* Expose `Mixpanel` integration.
*/
var Mixpanel = exports.Integration = integration('Mixpanel')
.readyOnLoad()
.global('mixpanel')
.option('cookieName', '')
.option('nameTag', true)
.option('pageview', false)
.option('people', false)
.option('token', '')
.option('trackAllPages', false)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Options aliases.
*/
var optionsAliases = {
cookieName: 'cookie_name'
};
/**
* Initialize.
*
* https://mixpanel.com/help/reference/javascript#installing
* https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.init
*/
Mixpanel.prototype.initialize = function () {
(function (c, a) {window.mixpanel = a; var b, d, h, e; a._i = []; a.init = function (b, c, f) {function d(a, b) {var c = b.split('.'); 2 == c.length && (a = a[c[0]], b = c[1]); a[b] = function () {a.push([b].concat(Array.prototype.slice.call(arguments, 0))); }; } var g = a; 'undefined' !== typeof f ? g = a[f] = [] : f = 'mixpanel'; g.people = g.people || []; h = ['disable', 'track', 'track_pageview', 'track_links', 'track_forms', 'register', 'register_once', 'unregister', 'identify', 'alias', 'name_tag', 'set_config', 'people.set', 'people.increment', 'people.track_charge', 'people.append']; for (e = 0; e < h.length; e++) d(g, h[e]); a._i.push([b, c, f]); }; a.__SV = 1.2; })(document, window.mixpanel || []);
var options = alias(this.options, optionsAliases);
window.mixpanel.init(options.token, options);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Mixpanel.prototype.loaded = function () {
return !! (window.mixpanel && window.mixpanel.config);
};
/**
* Load.
*
* @param {Function} callback
*/
Mixpanel.prototype.load = function (callback) {
load('//cdn.mxpnl.com/libs/mixpanel-2.2.min.js', callback);
};
/**
* Page.
*
* https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.track_pageview
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Mixpanel.prototype.page = function (page) {
var category = page.category();
var name = page.fullName();
var opts = this.options;
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Trait aliases.
*/
var traitAliases = {
created: '$created',
email: '$email',
firstName: '$first_name',
lastName: '$last_name',
lastSeen: '$last_seen',
name: '$name',
username: '$username',
phone: '$phone'
};
/**
* Identify.
*
* https://mixpanel.com/help/reference/javascript#super-properties
* https://mixpanel.com/help/reference/javascript#user-identity
* https://mixpanel.com/help/reference/javascript#storing-user-profiles
*
* @param {Identify} identify
*/
Mixpanel.prototype.identify = function (identify) {
var username = identify.username();
var email = identify.email();
var id = identify.userId();
// id
if (id) window.mixpanel.identify(id);
// name tag
var nametag = email || username || id;
if (nametag) window.mixpanel.name_tag(nametag);
// traits
traits = identify.traits(traitAliases);
window.mixpanel.register(traits);
if (this.options.people) window.mixpanel.people.set(traits);
};
/**
* Track.
*
* https://mixpanel.com/help/reference/javascript#sending-events
* https://mixpanel.com/help/reference/javascript#tracking-revenue
*
* @param {Track} track
*/
Mixpanel.prototype.track = function (track) {
var props = track.properties();
var revenue = track.revenue();
props = dates(props, iso);
window.mixpanel.track(track.event(), props);
if (revenue && this.options.people) {
window.mixpanel.people.track_charge(revenue);
}
};
/**
* Alias.
*
* https://mixpanel.com/help/reference/javascript#user-identity
* https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.alias
*
* @param {Alias} alias
*/
Mixpanel.prototype.alias = function (alias) {
var mp = window.mixpanel;
var to = alias.to();
if (mp.get_distinct_id && mp.get_distinct_id() === to) return;
// HACK: internal mixpanel API to ensure we don't overwrite
if (mp.get_property && mp.get_property('$people_distinct_id') === to) return;
// although undocumented, mixpanel takes an optional original id
mp.alias(to, alias.from());
};
});
require.register("segmentio-analytics.js-integrations/lib/mojn.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var load = require('load-script');
var is = require('is');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Mojn);
};
/**
* Expose `Mojn`
*/
var Mojn = exports.Integration = integration('Mojn')
.option('customerCode', '')
.global('_agTrack')
.readyOnInitialize();
/**
* Initialize.
*
* @param {Object} page
*/
Mojn.prototype.initialize = function(){
window._agTrack = window._agTrack || [];
window._agTrack.push({ cid: this.options.customerCode });
this.load();
};
/**
* Load the Mojn script.
*
* @param {Function} fn
*/
Mojn.prototype.load = function(fn) {
load('https://track.idtargeting.com/' + this.options.customerCode + '/track.js', fn);
};
/**
* Loaded?
*
* @return {Boolean}
*/
Mojn.prototype.loaded = function () {
return is.object(window._agTrack);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Mojn.prototype.identify = function(identify) {
var email = identify.email();
if (!email) return;
var img = new Image();
img.src = '//matcher.idtargeting.com/analytics.gif?cid=' + this.options.customerCode + '&_mjnctid='+email;
img.width = 1;
img.height = 1;
return img;
};
/**
* Track.
*
* @param {Track} event
*/
Mojn.prototype.track = function(track) {
var properties = track.properties();
var revenue = properties.revenue;
var currency = properties.currency || '';
var conv = currency + revenue;
if (!revenue) return;
window._agTrack.push({ conv: conv });
return conv;
};
});
require.register("segmentio-analytics.js-integrations/lib/mouseflow.js", function(exports, require, module){
var push = require('global-queue')('_mfq');
var integration = require('integration');
var load = require('load-script');
var each = require('each');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(Mouseflow);
};
/**
* Expose `Mouseflow`
*/
var Mouseflow = exports.Integration = integration('Mouseflow')
.assumesPageview()
.readyOnLoad()
.global('mouseflow')
.global('_mfq')
.option('apiKey', '')
.option('mouseflowHtmlDelay', 0);
/**
* Iniitalize
*
* @param {Object} page
*/
Mouseflow.prototype.initialize = function(page){
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Mouseflow.prototype.loaded = function(){
return !! (window._mfq && [].push != window._mfq.push);
};
/**
* Load mouseflow.
*
* @param {Function} fn
*/
Mouseflow.prototype.load = function(fn){
var apiKey = this.options.apiKey;
window.mouseflowHtmlDelay = this.options.mouseflowHtmlDelay;
load('//cdn.mouseflow.com/projects/' + apiKey + '.js', fn);
};
/**
* Page.
*
* //mouseflow.zendesk.com/entries/22528817-Single-page-websites
*
* @param {Page} page
*/
Mouseflow.prototype.page = function(page){
if (!window.mouseflow) return;
if ('function' != typeof mouseflow.newPageView) return;
mouseflow.newPageView();
};
/**
* Identify.
*
* //mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging
*
* @param {Identify} identify
*/
Mouseflow.prototype.identify = function(identify){
set(identify.traits());
};
/**
* Track.
*
* //mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging
*
* @param {Track} track
*/
Mouseflow.prototype.track = function(track){
var props = track.properties();
props.event = track.event();
set(props);
};
/**
* Push the given `hash`.
*
* @param {Object} hash
*/
function set(hash){
each(hash, function(k, v){
push('setVariable', k, v);
});
}
});
require.register("segmentio-analytics.js-integrations/lib/mousestats.js", function(exports, require, module){
var each = require('each');
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(MouseStats);
};
/**
* Expose `MouseStats` integration.
*/
var MouseStats = exports.Integration = integration('MouseStats')
.assumesPageview()
.readyOnLoad()
.global('msaa')
.option('accountNumber', '');
/**
* Initialize.
*
* http://www.mousestats.com/docs/pages/allpages
*
* @param {Object} page
*/
MouseStats.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
MouseStats.prototype.loaded = function () {
return is.fn(window.msaa);
};
/**
* Load.
*
* @param {Function} callback
*/
MouseStats.prototype.load = function (callback) {
var number = this.options.accountNumber;
var path = number.slice(0,1) + '/' + number.slice(1,2) + '/' + number;
var cache = Math.floor(new Date().getTime() / 60000);
var partial = '.mousestats.com/js/' + path + '.js?' + cache;
var http = 'http://www2' + partial;
var https = 'https://ssl' + partial;
load({ http: http, https: https }, callback);
};
/**
* Identify.
*
* http://www.mousestats.com/docs/wiki/7/how-to-add-custom-data-to-visitor-playbacks
*
* @param {Identify} identify
*/
MouseStats.prototype.identify = function (identify) {
each(identify.traits(), function (key, value) {
window.MouseStatsVisitorPlaybacks.customVariable(key, value);
});
};
});
require.register("segmentio-analytics.js-integrations/lib/olark.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var https = require('use-https');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Olark);
};
/**
* Expose `Olark` integration.
*/
var Olark = exports.Integration = integration('Olark')
.assumesPageview()
.readyOnInitialize()
.global('olark')
.option('identify', true)
.option('page', true)
.option('siteId', '')
.option('track', false);
/**
* Initialize.
*
* http://www.olark.com/documentation
*
* @param {Object} page
*/
Olark.prototype.initialize = function (page) {
window.olark||(function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i,' onl' + 'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()})({loader: "static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});
window.olark.identify(this.options.siteId);
// keep track of the widget's open state
var self = this;
box('onExpand', function () { self._open = true; });
box('onShrink', function () { self._open = false; });
};
/**
* Page.
*
* @param {Page} page
*/
Olark.prototype.page = function (page) {
if (!this.options.page || !this._open) return;
var props = page.properties();
var name = page.fullName();
if (!name && !props.url) return;
var msg = name ? name.toLowerCase() + ' page' : props.url;
chat('sendNotificationToOperator', {
body: 'looking at ' + msg // lowercase since olark does
});
};
/**
* Identify.
*
* @param {String} id (optional)
* @param {Object} traits (optional)
* @param {Object} options (optional)
*/
Olark.prototype.identify = function (identify) {
if (!this.options.identify) return;
var username = identify.username();
var traits = identify.traits();
var id = identify.userId();
var email = identify.email();
var phone = identify.phone();
var name = identify.name()
|| identify.firstName();
visitor('updateCustomFields', traits);
if (email) visitor('updateEmailAddress', { emailAddress: email });
if (phone) visitor('updatePhoneNumber', { phoneNumber: phone });
// figure out best name
if (name) visitor('updateFullName', { fullName: name });
// figure out best nickname
var nickname = name || email || username || id;
if (name && email) nickname += ' (' + email + ')';
if (nickname) chat('updateVisitorNickname', { snippet: nickname });
};
/**
* Track.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Olark.prototype.track = function (track) {
if (!this.options.track || !this._open) return;
chat('sendNotificationToOperator', {
body: 'visitor triggered "' + track.event() + '"' // lowercase since olark does
});
};
/**
* Helper method for Olark box API calls.
*
* @param {String} action
* @param {Object} value
*/
function box (action, value) {
window.olark('api.box.' + action, value);
}
/**
* Helper method for Olark visitor API calls.
*
* @param {String} action
* @param {Object} value
*/
function visitor (action, value) {
window.olark('api.visitor.' + action, value);
}
/**
* Helper method for Olark chat API calls.
*
* @param {String} action
* @param {Object} value
*/
function chat (action, value) {
window.olark('api.chat.' + action, value);
}
});
require.register("segmentio-analytics.js-integrations/lib/optimizely.js", function(exports, require, module){
var bind = require('bind');
var callback = require('callback');
var each = require('each');
var integration = require('integration');
var push = require('global-queue')('optimizely');
var tick = require('next-tick');
/**
* Analytics reference.
*/
var analytics;
/**
* Expose plugin.
*/
module.exports = exports = function (ajs) {
ajs.addIntegration(Optimizely);
analytics = ajs; // store for later
};
/**
* Expose `Optimizely` integration.
*/
var Optimizely = exports.Integration = integration('Optimizely')
.readyOnInitialize()
.option('variations', true)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* https://www.optimizely.com/docs/api#function-calls
*/
Optimizely.prototype.initialize = function () {
if (this.options.variations) tick(this.replay);
};
/**
* Track.
*
* https://www.optimizely.com/docs/api#track-event
*
* @param {Track} track
*/
Optimizely.prototype.track = function (track) {
var props = track.properties();
if (props.revenue) props.revenue *= 100;
push('trackEvent', track.event(), props);
};
/**
* Page.
*
* https://www.optimizely.com/docs/api#track-event
*
* @param {Page} page
*/
Optimizely.prototype.page = function (page) {
var category = page.category();
var name = page.fullName();
var opts = this.options;
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
};
/**
* Replay experiment data as traits to other enabled providers.
*
* https://www.optimizely.com/docs/api#data-object
*/
Optimizely.prototype.replay = function () {
if (!window.optimizely) return; // in case the snippet isnt on the page
var data = window.optimizely.data;
if (!data) return;
var experiments = data.experiments;
var map = data.state.variationNamesMap;
var traits = {};
each(map, function (experimentId, variation) {
var experiment = experiments[experimentId].name;
traits['Experiment: ' + experiment] = variation;
});
analytics.identify(traits);
};
});
require.register("segmentio-analytics.js-integrations/lib/perfect-audience.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(PerfectAudience);
};
/**
* Expose `PerfectAudience` integration.
*/
var PerfectAudience = exports.Integration = integration('Perfect Audience')
.assumesPageview()
.readyOnLoad()
.global('_pa')
.option('siteId', '');
/**
* Initialize.
*
* https://www.perfectaudience.com/docs#javascript_api_autoopen
*
* @param {Object} page
*/
PerfectAudience.prototype.initialize = function (page) {
window._pa = window._pa || {};
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
PerfectAudience.prototype.loaded = function () {
return !! (window._pa && window._pa.track);
};
/**
* Load.
*
* @param {Function} callback
*/
PerfectAudience.prototype.load = function (callback) {
var id = this.options.siteId;
load('//tag.perfectaudience.com/serve/' + id + '.js', callback);
};
/**
* Track.
*
* @param {Track} event
*/
PerfectAudience.prototype.track = function (track) {
window._pa.track(track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/pingdom.js", function(exports, require, module){
var date = require('load-date');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_prum');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Pingdom);
};
/**
* Expose `Pingdom` integration.
*/
var Pingdom = exports.Integration = integration('Pingdom')
.assumesPageview()
.readyOnLoad()
.global('_prum')
.option('id', '');
/**
* Initialize.
*
* @param {Object} page
*/
Pingdom.prototype.initialize = function (page) {
window._prum = window._prum || [];
push('id', this.options.id);
push('mark', 'firstbyte', date.getTime());
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Pingdom.prototype.loaded = function () {
return !! (window._prum && window._prum.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Pingdom.prototype.load = function (callback) {
load('//rum-static.pingdom.net/prum.min.js', callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/preact.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var convertDates = require('convert-dates');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_lnq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Preact);
};
/**
* Expose `Preact` integration.
*/
var Preact = exports.Integration = integration('Preact')
.assumesPageview()
.readyOnInitialize()
.global('_lnq')
.option('projectCode', '');
/**
* Initialize.
*
* http://www.preact.io/api/javascript
*
* @param {Object} page
*/
Preact.prototype.initialize = function (page) {
window._lnq = window._lnq || [];
push('_setCode', this.options.projectCode);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Preact.prototype.loaded = function () {
return !! (window._lnq && window._lnq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Preact.prototype.load = function (callback) {
load('//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js', callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Preact.prototype.identify = function (identify) {
if (!identify.userId()) return;
var traits = identify.traits({ created: 'created_at' });
traits = convertDates(traits, convertDate);
push('_setPersonData', {
name: identify.name(),
email: identify.email(),
uid: identify.userId(),
properties: traits
});
};
/**
* Group.
*
* @param {String} id
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Preact.prototype.group = function (group) {
if (!group.groupId()) return;
push('_setAccount', group.traits());
};
/**
* Track.
*
* @param {Track} track
*/
Preact.prototype.track = function (track) {
var props = track.properties();
var revenue = track.revenue();
var event = track.event();
var special = { name: event };
if (revenue) {
special.revenue = revenue * 100;
delete props.revenue;
}
if (props.note) {
special.note = props.note;
delete props.note;
}
push('_logEvent', special, props);
};
/**
* Convert a `date` to a format Preact supports.
*
* @param {Date} date
* @return {Number}
*/
function convertDate (date) {
return Math.floor(date / 1000);
}
});
require.register("segmentio-analytics.js-integrations/lib/qualaroo.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_kiq');
var Facade = require('facade');
var Identify = Facade.Identify;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Qualaroo);
};
/**
* Expose `Qualaroo` integration.
*/
var Qualaroo = exports.Integration = integration('Qualaroo')
.assumesPageview()
.readyOnInitialize()
.global('_kiq')
.option('customerId', '')
.option('siteToken', '')
.option('track', false);
/**
* Initialize.
*
* @param {Object} page
*/
Qualaroo.prototype.initialize = function (page) {
window._kiq = window._kiq || [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Qualaroo.prototype.loaded = function () {
return !! (window._kiq && window._kiq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Qualaroo.prototype.load = function (callback) {
var token = this.options.siteToken;
var id = this.options.customerId;
load('//s3.amazonaws.com/ki.js/' + id + '/' + token + '.js', callback);
};
/**
* Identify.
*
* http://help.qualaroo.com/customer/portal/articles/731085-identify-survey-nudge-takers
* http://help.qualaroo.com/customer/portal/articles/731091-set-additional-user-properties
*
* @param {Identify} identify
*/
Qualaroo.prototype.identify = function (identify) {
var traits = identify.traits();
var id = identify.userId();
var email = identify.email();
if (email) id = email;
if (id) push('identify', id);
if (traits) push('set', traits);
};
/**
* Track.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
*/
Qualaroo.prototype.track = function (track) {
if (!this.options.track) return;
var event = track.event();
var traits = {};
traits['Triggered: ' + event] = true;
this.identify(new Identify({ traits: traits }));
};
});
require.register("segmentio-analytics.js-integrations/lib/quantcast.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_qevents', { wrap: false });
/**
* User reference.
*/
var user;
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Quantcast);
user = analytics.user(); // store for later
};
/**
* Expose `Quantcast` integration.
*/
var Quantcast = exports.Integration = integration('Quantcast')
.assumesPageview()
.readyOnInitialize()
.global('_qevents')
.global('__qc')
.option('pCode', null)
.option('labelPages', false);
/**
* Initialize.
*
* https://www.quantcast.com/learning-center/guides/using-the-quantcast-asynchronous-tag/
* https://www.quantcast.com/help/cross-platform-audience-measurement-guide/
*
* @param {Object} page
*/
Quantcast.prototype.initialize = function (page) {
page = page || {};
window._qevents = window._qevents || [];
var opts = this.options;
var settings = { qacct: opts.pCode };
if (user.id()) settings.uid = user.id();
push(settings);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Quantcast.prototype.loaded = function () {
return !! window.__qc;
};
/**
* Load.
*
* @param {Function} callback
*/
Quantcast.prototype.load = function (callback) {
load({
http: 'http://edge.quantserve.com/quant.js',
https: 'https://secure.quantserve.com/quant.js'
}, callback);
};
/**
* Page.
*
* https://cloudup.com/cBRRFAfq6mf
*
* @param {Page} page
*/
Quantcast.prototype.page = function (page) {
var settings = {
event: 'refresh',
qacct: this.options.pCode,
};
if (user.id()) settings.uid = user.id();
push(settings);
};
/**
* Identify.
*
* https://www.quantcast.com/help/cross-platform-audience-measurement-guide/
*
* @param {String} id (optional)
*/
Quantcast.prototype.identify = function (identify) {
// edit the initial quantcast settings
var id = identify.userId();
if (id) window._qevents[0].uid = id;
};
/**
* Track.
*
* https://cloudup.com/cBRRFAfq6mf
*
* @param {Track} track
*/
Quantcast.prototype.track = function (track) {
var settings = {
event: 'click',
qacct: this.options.pCode
};
if (user.id()) settings.uid = user.id();
push(settings);
};
});
require.register("segmentio-analytics.js-integrations/lib/rollbar.js", function(exports, require, module){
var callback = require('callback');
var clone = require('clone');
var extend = require('extend');
var integration = require('integration');
var load = require('load-script');
var onError = require('on-error');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Rollbar);
};
/**
* Expose `Rollbar` integration.
*/
var Rollbar = exports.Integration = integration('Rollbar')
.readyOnInitialize()
.assumesPageview()
.global('_rollbar')
.option('accessToken', '')
.option('identify', true);
/**
* Initialize.
*
* https://rollbar.com/docs/notifier/rollbar.js/
*
* @param {Object} page
*/
Rollbar.prototype.initialize = function (page) {
var options = this.options;
window._rollbar = window._rollbar || window._ratchet || [options.accessToken, options];
onError(function() { window._rollbar.push.apply(window._rollbar, arguments); });
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Rollbar.prototype.loaded = function () {
return !! (window._rollbar && window._rollbar.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Rollbar.prototype.load = function (callback) {
load('//d37gvrvc0wt4s1.cloudfront.net/js/1/rollbar.min.js', callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Rollbar.prototype.identify = function (identify) {
if (!this.options.identify) return;
var traits = identify.traits();
var rollbar = window._rollbar;
var params = rollbar.shift
? rollbar[1] = rollbar[1] || {}
: rollbar.extraParams = rollbar.extraParams || {};
params.person = params.person || {};
extend(params.person, traits);
};
});
require.register("segmentio-analytics.js-integrations/lib/saasquatch.js", function(exports, require, module){
/**
* Module dependencies.
*/
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function(analytics){
analytics.addIntegration(SaaSquatch);
};
/**
* Expose `SaaSquatch` integration.
*/
var SaaSquatch = exports.Integration = integration('SaaSquatch')
.readyOnInitialize()
.option('tenantAlias', '')
.global('_sqh');
/**
* Initialize
*
* @param {Page} page
*/
SaaSquatch.prototype.initialize = function(page){};
/**
* Loaded?
*
* @return {Boolean}
*/
SaaSquatch.prototype.loaded = function(){
return window._sqh && window._sqh.push != [].push;
};
/**
* Load the SaaSquatch library.
*
* @param {Function} fn
*/
SaaSquatch.prototype.load = function(fn){
load('//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js', fn);
};
/**
* Identify.
*
* @param {Facade} identify
*/
SaaSquatch.prototype.identify = function(identify){
var sqh = window._sqh = window._sqh || [];
var accountId = identify.proxy('traits.accountId');
var image = identify.proxy('traits.referralImage');
var opts = identify.options(this.name);
var id = identify.userId();
var email = identify.email();
if (!(id || email)) return;
if (this.called) return;
var init = {
tenant_alias: this.options.tenantAlias,
first_name: identify.firstName(),
last_name: identify.lastName(),
user_image: identify.avatar(),
email: email,
user_id: id,
};
if (accountId) init.account_id = accountId;
if (opts.checksum) init.checksum = opts.checksum;
if (image) init.fb_share_image = image;
sqh.push(['init', init]);
this.called = true;
this.load();
};
});
require.register("segmentio-analytics.js-integrations/lib/sentry.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Sentry);
};
/**
* Expose `Sentry` integration.
*/
var Sentry = exports.Integration = integration('Sentry')
.readyOnLoad()
.global('Raven')
.option('config', '');
/**
* Initialize.
*
* http://raven-js.readthedocs.org/en/latest/config/index.html
*/
Sentry.prototype.initialize = function () {
var config = this.options.config;
this.load(function () {
// for now, raven basically requires `install` to be called
// https://github.com/getsentry/raven-js/blob/master/src/raven.js#L113
window.Raven.config(config).install();
});
};
/**
* Loaded?
*
* @return {Boolean}
*/
Sentry.prototype.loaded = function () {
return is.object(window.Raven);
};
/**
* Load.
*
* @param {Function} callback
*/
Sentry.prototype.load = function (callback) {
load('//cdn.ravenjs.com/1.1.10/native/raven.min.js', callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Sentry.prototype.identify = function (identify) {
window.Raven.setUser(identify.traits());
};
});
require.register("segmentio-analytics.js-integrations/lib/snapengage.js", function(exports, require, module){
var integration = require('integration');
var is = require('is');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(SnapEngage);
};
/**
* Expose `SnapEngage` integration.
*/
var SnapEngage = exports.Integration = integration('SnapEngage')
.assumesPageview()
.readyOnLoad()
.global('SnapABug')
.option('apiKey', '');
/**
* Initialize.
*
* http://help.snapengage.com/installation-guide-getting-started-in-a-snap/
*
* @param {Object} page
*/
SnapEngage.prototype.initialize = function (page) {
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
SnapEngage.prototype.loaded = function () {
return is.object(window.SnapABug);
};
/**
* Load.
*
* @param {Function} callback
*/
SnapEngage.prototype.load = function (callback) {
var key = this.options.apiKey;
var url = '//commondatastorage.googleapis.com/code.snapengage.com/js/' + key + '.js';
load(url, callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
SnapEngage.prototype.identify = function (identify) {
var email = identify.email();
if (!email) return;
window.SnapABug.setUserEmail(email);
};
});
require.register("segmentio-analytics.js-integrations/lib/spinnakr.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Spinnakr);
};
/**
* Expose `Spinnakr` integration.
*/
var Spinnakr = exports.Integration = integration('Spinnakr')
.assumesPageview()
.readyOnLoad()
.global('_spinnakr_site_id')
.global('_spinnakr')
.option('siteId', '');
/**
* Initialize.
*
* @param {Object} page
*/
Spinnakr.prototype.initialize = function (page) {
window._spinnakr_site_id = this.options.siteId;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Spinnakr.prototype.loaded = function () {
return !! window._spinnakr;
};
/**
* Load.
*
* @param {Function} callback
*/
Spinnakr.prototype.load = function (callback) {
load('//d3ojzyhbolvoi5.cloudfront.net/js/so.js', callback);
};
});
require.register("segmentio-analytics.js-integrations/lib/tapstream.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var slug = require('slug');
var push = require('global-queue')('_tsq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Tapstream);
};
/**
* Expose `Tapstream` integration.
*/
var Tapstream = exports.Integration = integration('Tapstream')
.assumesPageview()
.readyOnInitialize()
.global('_tsq')
.option('accountName', '')
.option('trackAllPages', true)
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Initialize.
*
* @param {Object} page
*/
Tapstream.prototype.initialize = function (page) {
window._tsq = window._tsq || [];
push('setAccountName', this.options.accountName);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Tapstream.prototype.loaded = function () {
return !! (window._tsq && window._tsq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Tapstream.prototype.load = function (callback) {
load('//cdn.tapstream.com/static/js/tapstream.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Tapstream.prototype.page = function (page) {
var category = page.category();
var opts = this.options;
var name = page.fullName();
// all pages
if (opts.trackAllPages) {
this.track(page.track());
}
// named pages
if (name && opts.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && opts.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Track.
*
* @param {Track} track
*/
Tapstream.prototype.track = function (track) {
var props = track.properties();
push('fireHit', slug(track.event()), [props.url]); // needs events as slugs
};
});
require.register("segmentio-analytics.js-integrations/lib/trakio.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var clone = require('clone');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Trakio);
};
/**
* Expose `Trakio` integration.
*/
var Trakio = exports.Integration = integration('trak.io')
.assumesPageview()
.readyOnInitialize()
.global('trak')
.option('token', '')
.option('trackNamedPages', true)
.option('trackCategorizedPages', true);
/**
* Options aliases.
*/
var optionsAliases = {
initialPageview: 'auto_track_page_view'
};
/**
* Initialize.
*
* https://docs.trak.io
*
* @param {Object} page
*/
Trakio.prototype.initialize = function (page) {
var self = this;
var options = this.options;
window.trak = window.trak || [];
window.trak.io = window.trak.io || {};
window.trak.io.load = function(e) {self.load(); var r = function(e) {return function() {window.trak.push([e].concat(Array.prototype.slice.call(arguments,0))); }; } ,i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"]; for (var s=0;s<i.length;s++) window.trak.io[i[s]]=r(i[s]); window.trak.io.initialize.apply(window.trak.io,arguments); };
window.trak.io.load(options.token, alias(options, optionsAliases));
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Trakio.prototype.loaded = function () {
return !! (window.trak && window.trak.loaded);
};
/**
* Load the trak.io library.
*
* @param {Function} callback
*/
Trakio.prototype.load = function (callback) {
load('//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js', callback);
};
/**
* Page.
*
* @param {Page} page
*/
Trakio.prototype.page = function (page) {
var category = page.category();
var props = page.properties();
var name = page.fullName();
window.trak.io.page_view(props.path, name || props.title);
// named pages
if (name && this.options.trackNamedPages) {
this.track(page.track(name));
}
// categorized pages
if (category && this.options.trackCategorizedPages) {
this.track(page.track(category));
}
};
/**
* Trait aliases.
*
* http://docs.trak.io/properties.html#special
*/
var traitAliases = {
avatar: 'avatar_url',
firstName: 'first_name',
lastName: 'last_name'
};
/**
* Identify.
*
* @param {Identify} identify
*/
Trakio.prototype.identify = function (identify) {
var traits = identify.traits(traitAliases);
var id = identify.userId();
if (id) {
window.trak.io.identify(id, traits);
} else {
window.trak.io.identify(traits);
}
};
/**
* Group.
*
* @param {String} id (optional)
* @param {Object} properties (optional)
* @param {Object} options (optional)
*
* TODO: add group
* TODO: add `trait.company/organization` from trak.io docs http://docs.trak.io/properties.html#special
*/
/**
* Track.
*
* @param {Track} track
*/
Trakio.prototype.track = function (track) {
window.trak.io.track(track.event(), track.properties());
};
/**
* Alias.
*
* @param {Alias} alias
*/
Trakio.prototype.alias = function (alias) {
if (!window.trak.io.distinct_id) return;
var from = alias.from();
var to = alias.to();
if (to === window.trak.io.distinct_id()) return;
if (from) {
window.trak.io.alias(from, to);
} else {
window.trak.io.alias(to);
}
};
});
require.register("segmentio-analytics.js-integrations/lib/twitter-ads.js", function(exports, require, module){
var pixel = require('load-pixel')('//analytics.twitter.com/i/adsct');
var integration = require('integration');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(TwitterAds);
};
/**
* Expose `load`
*/
exports.load = pixel;
/**
* HOP
*/
var has = Object.prototype.hasOwnProperty;
/**
* Expose `TwitterAds`
*/
var TwitterAds = exports.Integration = integration('Twitter Ads')
.readyOnInitialize()
.option('events', {});
/**
* Track.
*
* @param {Track} track
*/
TwitterAds.prototype.track = function(track){
var events = this.options.events;
var event = track.event();
if (!has.call(events, event)) return;
return exports.load({
txn_id: events[event],
p_id: 'Twitter'
});
};
});
require.register("segmentio-analytics.js-integrations/lib/usercycle.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_uc');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Usercycle);
};
/**
* Expose `Usercycle` integration.
*/
var Usercycle = exports.Integration = integration('USERcycle')
.assumesPageview()
.readyOnInitialize()
.global('_uc')
.option('key', '');
/**
* Initialize.
*
* http://docs.usercycle.com/javascript_api
*
* @param {Object} page
*/
Usercycle.prototype.initialize = function (page) {
push('_key', this.options.key);
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Usercycle.prototype.loaded = function () {
return !! (window._uc && window._uc.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Usercycle.prototype.load = function (callback) {
load('//api.usercycle.com/javascripts/track.js', callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Usercycle.prototype.identify = function (identify) {
var traits = identify.traits();
var id = identify.userId();
if (id) push('uid', id);
// there's a special `came_back` event used for retention and traits
push('action', 'came_back', traits);
};
/**
* Track.
*
* @param {Track} track
*/
Usercycle.prototype.track = function (track) {
push('action', track.event(), track.properties({
revenue: 'revenue_amount'
}));
};
});
require.register("segmentio-analytics.js-integrations/lib/userfox.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var convertDates = require('convert-dates');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_ufq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Userfox);
};
/**
* Expose `Userfox` integration.
*/
var Userfox = exports.Integration = integration('userfox')
.assumesPageview()
.readyOnInitialize()
.global('_ufq')
.option('clientId', '');
/**
* Initialize.
*
* https://www.userfox.com/docs/
*
* @param {Object} page
*/
Userfox.prototype.initialize = function (page) {
window._ufq = [];
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Userfox.prototype.loaded = function () {
return !! (window._ufq && window._ufq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Userfox.prototype.load = function (callback) {
load('//d2y71mjhnajxcg.cloudfront.net/js/userfox-stable.js', callback);
};
/**
* Identify.
*
* https://www.userfox.com/docs/#custom-data
*
* @param {Identify} identify
*/
Userfox.prototype.identify = function (identify) {
var traits = identify.traits({ created: 'signup_date' });
var email = identify.email();
if (!email) return;
// initialize the library with the email now that we have it
push('init', {
clientId: this.options.clientId,
email: email
});
traits = convertDates(traits, formatDate);
push('track', traits);
};
/**
* Convert a `date` to a format userfox supports.
*
* @param {Date} date
* @return {String}
*/
function formatDate (date) {
return Math.round(date.getTime() / 1000).toString();
}
});
require.register("segmentio-analytics.js-integrations/lib/uservoice.js", function(exports, require, module){
var alias = require('alias');
var callback = require('callback');
var clone = require('clone');
var convertDates = require('convert-dates');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('UserVoice');
var unix = require('to-unix-timestamp');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(UserVoice);
};
/**
* Expose `UserVoice` integration.
*/
var UserVoice = exports.Integration = integration('UserVoice')
.assumesPageview()
.readyOnInitialize()
.global('UserVoice')
.global('showClassicWidget')
.option('apiKey', '')
.option('classic', false)
.option('forumId', null)
.option('showWidget', true)
.option('mode', 'contact')
.option('accentColor', '#448dd6')
.option('smartvote', true)
.option('trigger', null)
.option('triggerPosition', 'bottom-right')
.option('triggerColor', '#ffffff')
.option('triggerBackgroundColor', 'rgba(46, 49, 51, 0.6)')
// BACKWARDS COMPATIBILITY: classic options
.option('classicMode', 'full')
.option('primaryColor', '#cc6d00')
.option('linkColor', '#007dbf')
.option('defaultMode', 'support')
.option('tabLabel', 'Feedback & Support')
.option('tabColor', '#cc6d00')
.option('tabPosition', 'middle-right')
.option('tabInverted', false);
/**
* When in "classic" mode, on `construct` swap all of the method to point to
* their classic counterparts.
*/
UserVoice.on('construct', function (integration) {
if (!integration.options.classic) return;
integration.group = undefined;
integration.identify = integration.identifyClassic;
integration.initialize = integration.initializeClassic;
});
/**
* Initialize.
*
* @param {Object} page
*/
UserVoice.prototype.initialize = function (page) {
var options = this.options;
var opts = formatOptions(options);
push('set', opts);
push('autoprompt', {});
if (options.showWidget) {
options.trigger
? push('addTrigger', options.trigger, opts)
: push('addTrigger', opts);
}
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
UserVoice.prototype.loaded = function () {
return !! (window.UserVoice && window.UserVoice.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
UserVoice.prototype.load = function (callback) {
var key = this.options.apiKey;
load('//widget.uservoice.com/' + key + '.js', callback);
};
/**
* Identify.
*
* @param {Identify} identify
*/
UserVoice.prototype.identify = function (identify) {
var traits = identify.traits({ created: 'created_at' });
traits = convertDates(traits, unix);
push('identify', traits);
};
/**
* Group.
*
* @param {Group} group
*/
UserVoice.prototype.group = function (group) {
var traits = group.traits({ created: 'created_at' });
traits = convertDates(traits, unix);
push('identify', { account: traits });
};
/**
* Initialize (classic).
*
* @param {Object} options
* @param {Function} ready
*/
UserVoice.prototype.initializeClassic = function () {
var options = this.options;
window.showClassicWidget = showClassicWidget; // part of public api
if (options.showWidget) showClassicWidget('showTab', formatClassicOptions(options));
this.load();
};
/**
* Identify (classic).
*
* @param {Identify} identify
*/
UserVoice.prototype.identifyClassic = function (identify) {
push('setCustomFields', identify.traits());
};
/**
* Format the options for UserVoice.
*
* @param {Object} options
* @return {Object}
*/
function formatOptions (options) {
return alias(options, {
forumId: 'forum_id',
accentColor: 'accent_color',
smartvote: 'smartvote_enabled',
triggerColor: 'trigger_color',
triggerBackgroundColor: 'trigger_background_color',
triggerPosition: 'trigger_position'
});
}
/**
* Format the classic options for UserVoice.
*
* @param {Object} options
* @return {Object}
*/
function formatClassicOptions (options) {
return alias(options, {
forumId: 'forum_id',
classicMode: 'mode',
primaryColor: 'primary_color',
tabPosition: 'tab_position',
tabColor: 'tab_color',
linkColor: 'link_color',
defaultMode: 'default_mode',
tabLabel: 'tab_label',
tabInverted: 'tab_inverted'
});
}
/**
* Show the classic version of the UserVoice widget. This method is usually part
* of UserVoice classic's public API.
*
* @param {String} type ('showTab' or 'showLightbox')
* @param {Object} options (optional)
*/
function showClassicWidget (type, options) {
type = type || 'showLightbox';
push(type, 'classic_widget', options);
}
});
require.register("segmentio-analytics.js-integrations/lib/vero.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
var push = require('global-queue')('_veroq');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Vero);
};
/**
* Expose `Vero` integration.
*/
var Vero = exports.Integration = integration('Vero')
.assumesPageview()
.readyOnInitialize()
.global('_veroq')
.option('apiKey', '');
/**
* Initialize.
*
* https://github.com/getvero/vero-api/blob/master/sections/js.md
*
* @param {Object} page
*/
Vero.prototype.initialize = function (pgae) {
push('init', { api_key: this.options.apiKey });
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Vero.prototype.loaded = function () {
return !! (window._veroq && window._veroq.push !== Array.prototype.push);
};
/**
* Load.
*
* @param {Function} callback
*/
Vero.prototype.load = function (callback) {
load('//d3qxef4rp70elm.cloudfront.net/m.js', callback);
};
/**
* Identify.
*
* https://github.com/getvero/vero-api/blob/master/sections/js.md#user-identification
*
* @param {Identify} identify
*/
Vero.prototype.identify = function (identify) {
var traits = identify.traits();
var email = identify.email();
var id = identify.userId();
if (!id || !email) return; // both required
push('user', traits);
};
/**
* Track.
*
* https://github.com/getvero/vero-api/blob/master/sections/js.md#tracking-events
*
* @param {Track} track
*/
Vero.prototype.track = function (track) {
push('track', track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js", function(exports, require, module){
var callback = require('callback');
var each = require('each');
var integration = require('integration');
var tick = require('next-tick');
/**
* Analytics reference.
*/
var analytics;
/**
* Expose plugin.
*/
module.exports = exports = function (ajs) {
ajs.addIntegration(VWO);
analytics = ajs;
};
/**
* Expose `VWO` integration.
*/
var VWO = exports.Integration = integration('Visual Website Optimizer')
.readyOnInitialize()
.option('replay', true);
/**
* Initialize.
*
* http://v2.visualwebsiteoptimizer.com/tools/get_tracking_code.php
*/
VWO.prototype.initialize = function () {
if (this.options.replay) this.replay();
};
/**
* Replay the experiments the user has seen as traits to all other integrations.
* Wait for the next tick to replay so that the `analytics` object and all of
* the integrations are fully initialized.
*/
VWO.prototype.replay = function () {
tick(function () {
experiments(function (err, traits) {
if (traits) analytics.identify(traits);
});
});
};
/**
* Get dictionary of experiment keys and variations.
*
* http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/
*
* @param {Function} callback
* @return {Object}
*/
function experiments (callback) {
enqueue(function () {
var data = {};
var ids = window._vwo_exp_ids;
if (!ids) return callback();
each(ids, function (id) {
var name = variation(id);
if (name) data['Experiment: ' + id] = name;
});
callback(null, data);
});
}
/**
* Add a `fn` to the VWO queue, creating one if it doesn't exist.
*
* @param {Function} fn
*/
function enqueue (fn) {
window._vis_opt_queue = window._vis_opt_queue || [];
window._vis_opt_queue.push(fn);
}
/**
* Get the chosen variation's name from an experiment `id`.
*
* http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/
*
* @param {String} id
* @return {String}
*/
function variation (id) {
var experiments = window._vwo_exp;
if (!experiments) return null;
var experiment = experiments[id];
var variationId = experiment.combination_chosen;
return variationId ? experiment.comb_n[variationId] : null;
}
});
require.register("segmentio-analytics.js-integrations/lib/webengage.js", function(exports, require, module){
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin
*/
module.exports = exports = function(analytics){
analytics.addIntegration(WebEngage);
};
/**
* Expose `WebEngage` integration
*/
var WebEngage = exports.Integration = integration('WebEngage')
.assumesPageview()
.readyOnLoad()
.global('_weq')
.global('webengage')
.option('widgetVersion', '4.0')
.option('licenseCode', '');
/**
* Initialize.
*
* @param {Object} page
*/
WebEngage.prototype.initialize = function(page){
var _weq = window._weq = window._weq || {};
_weq['webengage.licenseCode'] = this.options.licenseCode;
_weq['webengage.widgetVersion'] = this.options.widgetVersion;
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
WebEngage.prototype.loaded = function(){
return !! window.webengage;
};
/**
* Load
*
* @param {Function} fn
*/
WebEngage.prototype.load = function(fn){
var path = '/js/widget/webengage-min-v-4.0.js';
load({
https: 'https://ssl.widgets.webengage.com' + path,
http: 'http://cdn.widgets.webengage.com' + path
}, fn);
};
});
require.register("segmentio-analytics.js-integrations/lib/woopra.js", function(exports, require, module){
var each = require('each');
var extend = require('extend');
var integration = require('integration');
var isEmail = require('is-email');
var load = require('load-script');
var type = require('type');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Woopra);
};
/**
* Expose `Woopra` integration.
*/
var Woopra = exports.Integration = integration('Woopra')
.readyOnLoad()
.global('woopra')
.option('domain', '');
/**
* Initialize.
*
* http://www.woopra.com/docs/setup/javascript-tracking/
*
* @param {Object} page
*/
Woopra.prototype.initialize = function (page) {
(function () {var i, s, z, w = window, d = document, a = arguments, q = 'script', f = ['config', 'track', 'identify', 'visit', 'push', 'call'], c = function () {var i, self = this; self._e = []; for (i = 0; i < f.length; i++) {(function (f) {self[f] = function () {self._e.push([f].concat(Array.prototype.slice.call(arguments, 0))); return self; }; })(f[i]); } }; w._w = w._w || {}; for (i = 0; i < a.length; i++) { w._w[a[i]] = w[a[i]] = w[a[i]] || new c(); } })('woopra');
window.woopra.config({ domain: this.options.domain });
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Woopra.prototype.loaded = function () {
return !! (window.woopra && window.woopra.loaded);
};
/**
* Load.
*
* @param {Function} callback
*/
Woopra.prototype.load = function (callback) {
load('//static.woopra.com/js/w.js', callback);
};
/**
* Page.
*
* @param {String} category (optional)
*/
Woopra.prototype.page = function (page) {
var props = page.properties();
var name = page.fullName();
if (name) props.title = name;
window.woopra.track('pv', props);
};
/**
* Identify.
*
* @param {Identify} identify
*/
Woopra.prototype.identify = function (identify) {
window.woopra.identify(identify.traits()).push(); // `push` sends it off async
};
/**
* Track.
*
* @param {Track} track
*/
Woopra.prototype.track = function (track) {
window.woopra.track(track.event(), track.properties());
};
});
require.register("segmentio-analytics.js-integrations/lib/yandex-metrica.js", function(exports, require, module){
var callback = require('callback');
var integration = require('integration');
var load = require('load-script');
/**
* Expose plugin.
*/
module.exports = exports = function (analytics) {
analytics.addIntegration(Yandex);
};
/**
* Expose `Yandex` integration.
*/
var Yandex = exports.Integration = integration('Yandex Metrica')
.assumesPageview()
.readyOnInitialize()
.global('yandex_metrika_callbacks')
.global('Ya')
.option('counterId', null);
/**
* Initialize.
*
* http://api.yandex.com/metrika/
* https://metrica.yandex.com/22522351?step=2#tab=code
*
* @param {Object} page
*/
Yandex.prototype.initialize = function (page) {
var id = this.options.counterId;
push(function () {
window['yaCounter' + id] = new window.Ya.Metrika({ id: id });
});
this.load();
};
/**
* Loaded?
*
* @return {Boolean}
*/
Yandex.prototype.loaded = function () {
return !! (window.Ya && window.Ya.Metrika);
};
/**
* Load.
*
* @param {Function} callback
*/
Yandex.prototype.load = function (callback) {
load('//mc.yandex.ru/metrika/watch.js', callback);
};
/**
* Push a new callback on the global Yandex queue.
*
* @param {Function} callback
*/
function push (callback) {
window.yandex_metrika_callbacks = window.yandex_metrika_callbacks || [];
window.yandex_metrika_callbacks.push(callback);
}
});
require.register("segmentio-canonical/index.js", function(exports, require, module){
module.exports = function canonical () {
var tags = document.getElementsByTagName('link');
for (var i = 0, tag; tag = tags[i]; i++) {
if ('canonical' == tag.getAttribute('rel')) return tag.getAttribute('href');
}
};
});
require.register("segmentio-extend/index.js", function(exports, require, module){
module.exports = function extend (object) {
// Takes an unlimited number of extenders.
var args = Array.prototype.slice.call(arguments, 1);
// For each extender, copy their properties on our object.
for (var i = 0, source; source = args[i]; i++) {
if (!source) continue;
for (var property in source) {
object[property] = source[property];
}
}
return object;
};
});
require.register("camshaft-require-component/index.js", function(exports, require, module){
/**
* Require a module with a fallback
*/
module.exports = function(parent) {
function require(name, fallback) {
try {
return parent(name);
}
catch (e) {
try {
return parent(fallback || name+"-component");
}
catch(e2) {
throw e;
}
}
};
// Merge the old properties
for (var key in parent) {
require[key] = parent[key];
}
return require;
};
});
require.register("ianstormtaylor-to-camel-case/index.js", function(exports, require, module){
var toSpace = require('to-space-case');
/**
* Expose `toCamelCase`.
*/
module.exports = toCamelCase;
/**
* Convert a `string` to camel case.
*
* @param {String} string
* @return {String}
*/
function toCamelCase (string) {
return toSpace(string).replace(/\s(\w)/g, function (matches, letter) {
return letter.toUpperCase();
});
}
});
require.register("ianstormtaylor-to-capital-case/index.js", function(exports, require, module){
var clean = require('to-no-case');
/**
* Expose `toCapitalCase`.
*/
module.exports = toCapitalCase;
/**
* Convert a `string` to capital case.
*
* @param {String} string
* @return {String}
*/
function toCapitalCase (string) {
return clean(string).replace(/(^|\s)(\w)/g, function (matches, previous, letter) {
return previous + letter.toUpperCase();
});
}
});
require.register("ianstormtaylor-to-constant-case/index.js", function(exports, require, module){
var snake = require('to-snake-case');
/**
* Expose `toConstantCase`.
*/
module.exports = toConstantCase;
/**
* Convert a `string` to constant case.
*
* @param {String} string
* @return {String}
*/
function toConstantCase (string) {
return snake(string).toUpperCase();
}
});
require.register("ianstormtaylor-to-dot-case/index.js", function(exports, require, module){
var toSpace = require('to-space-case');
/**
* Expose `toDotCase`.
*/
module.exports = toDotCase;
/**
* Convert a `string` to slug case.
*
* @param {String} string
* @return {String}
*/
function toDotCase (string) {
return toSpace(string).replace(/\s/g, '.');
}
});
require.register("ianstormtaylor-to-no-case/index.js", function(exports, require, module){
/**
* Expose `toNoCase`.
*/
module.exports = toNoCase;
/**
* Test whether a string is camel-case.
*/
var hasSpace = /\s/;
var hasCamel = /[a-z][A-Z]/;
var hasSeparator = /[\W_]/;
/**
* Remove any starting case from a `string`, like camel or snake, but keep
* spaces and punctuation that may be important otherwise.
*
* @param {String} string
* @return {String}
*/
function toNoCase (string) {
if (hasSpace.test(string)) return string.toLowerCase();
if (hasSeparator.test(string)) string = unseparate(string);
if (hasCamel.test(string)) string = uncamelize(string);
return string.toLowerCase();
}
/**
* Separator splitter.
*/
var separatorSplitter = /[\W_]+(.|$)/g;
/**
* Un-separate a `string`.
*
* @param {String} string
* @return {String}
*/
function unseparate (string) {
return string.replace(separatorSplitter, function (m, next) {
return next ? ' ' + next : '';
});
}
/**
* Camelcase splitter.
*/
var camelSplitter = /(.)([A-Z]+)/g;
/**
* Un-camelcase a `string`.
*
* @param {String} string
* @return {String}
*/
function uncamelize (string) {
return string.replace(camelSplitter, function (m, previous, uppers) {
return previous + ' ' + uppers.toLowerCase().split('').join(' ');
});
}
});
require.register("ianstormtaylor-to-pascal-case/index.js", function(exports, require, module){
var toSpace = require('to-space-case');
/**
* Expose `toPascalCase`.
*/
module.exports = toPascalCase;
/**
* Convert a `string` to pascal case.
*
* @param {String} string
* @return {String}
*/
function toPascalCase (string) {
return toSpace(string).replace(/(?:^|\s)(\w)/g, function (matches, letter) {
return letter.toUpperCase();
});
}
});
require.register("ianstormtaylor-to-sentence-case/index.js", function(exports, require, module){
var clean = require('to-no-case');
/**
* Expose `toSentenceCase`.
*/
module.exports = toSentenceCase;
/**
* Convert a `string` to camel case.
*
* @param {String} string
* @return {String}
*/
function toSentenceCase (string) {
return clean(string).replace(/[a-z]/i, function (letter) {
return letter.toUpperCase();
});
}
});
require.register("ianstormtaylor-to-slug-case/index.js", function(exports, require, module){
var toSpace = require('to-space-case');
/**
* Expose `toSlugCase`.
*/
module.exports = toSlugCase;
/**
* Convert a `string` to slug case.
*
* @param {String} string
* @return {String}
*/
function toSlugCase (string) {
return toSpace(string).replace(/\s/g, '-');
}
});
require.register("ianstormtaylor-to-snake-case/index.js", function(exports, require, module){
var toSpace = require('to-space-case');
/**
* Expose `toSnakeCase`.
*/
module.exports = toSnakeCase;
/**
* Convert a `string` to snake case.
*
* @param {String} string
* @return {String}
*/
function toSnakeCase (string) {
return toSpace(string).replace(/\s/g, '_');
}
});
require.register("ianstormtaylor-to-space-case/index.js", function(exports, require, module){
var clean = require('to-no-case');
/**
* Expose `toSpaceCase`.
*/
module.exports = toSpaceCase;
/**
* Convert a `string` to space case.
*
* @param {String} string
* @return {String}
*/
function toSpaceCase (string) {
return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) {
return match ? ' ' + match : '';
});
}
});
require.register("component-escape-regexp/index.js", function(exports, require, module){
/**
* Escape regexp special characters in `str`.
*
* @param {String} str
* @return {String}
* @api public
*/
module.exports = function(str){
return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g, '\\$1');
};
});
require.register("ianstormtaylor-map/index.js", function(exports, require, module){
var each = require('each');
/**
* Map an array or object.
*
* @param {Array|Object} obj
* @param {Function} iterator
* @return {Mixed}
*/
module.exports = function map (obj, iterator) {
var arr = [];
each(obj, function (o) {
arr.push(iterator.apply(null, arguments));
});
return arr;
};
});
require.register("ianstormtaylor-title-case-minors/index.js", function(exports, require, module){
module.exports = [
'a',
'an',
'and',
'as',
'at',
'but',
'by',
'en',
'for',
'from',
'how',
'if',
'in',
'neither',
'nor',
'of',
'on',
'only',
'onto',
'out',
'or',
'per',
'so',
'than',
'that',
'the',
'to',
'until',
'up',
'upon',
'v',
'v.',
'versus',
'vs',
'vs.',
'via',
'when',
'with',
'without',
'yet'
];
});
require.register("ianstormtaylor-to-title-case/index.js", function(exports, require, module){
var capital = require('to-capital-case')
, escape = require('escape-regexp')
, map = require('map')
, minors = require('title-case-minors');
/**
* Expose `toTitleCase`.
*/
module.exports = toTitleCase;
/**
* Minors.
*/
var escaped = map(minors, escape);
var minorMatcher = new RegExp('[^^]\\b(' + escaped.join('|') + ')\\b', 'ig');
var colonMatcher = /:\s*(\w)/g;
/**
* Convert a `string` to camel case.
*
* @param {String} string
* @return {String}
*/
function toTitleCase (string) {
return capital(string)
.replace(minorMatcher, function (minor) {
return minor.toLowerCase();
})
.replace(colonMatcher, function (letter) {
return letter.toUpperCase();
});
}
});
require.register("ianstormtaylor-case/lib/index.js", function(exports, require, module){
var cases = require('./cases');
/**
* Expose `determineCase`.
*/
module.exports = exports = determineCase;
/**
* Determine the case of a `string`.
*
* @param {String} string
* @return {String|Null}
*/
function determineCase (string) {
for (var key in cases) {
if (key == 'none') continue;
var convert = cases[key];
if (convert(string) == string) return key;
}
return null;
}
/**
* Define a case by `name` with a `convert` function.
*
* @param {String} name
* @param {Object} convert
*/
exports.add = function (name, convert) {
exports[name] = cases[name] = convert;
};
/**
* Add all the `cases`.
*/
for (var key in cases) {
exports.add(key, cases[key]);
}
});
require.register("ianstormtaylor-case/lib/cases.js", function(exports, require, module){
var camel = require('to-camel-case')
, capital = require('to-capital-case')
, constant = require('to-constant-case')
, dot = require('to-dot-case')
, none = require('to-no-case')
, pascal = require('to-pascal-case')
, sentence = require('to-sentence-case')
, slug = require('to-slug-case')
, snake = require('to-snake-case')
, space = require('to-space-case')
, title = require('to-title-case');
/**
* Camel.
*/
exports.camel = camel;
/**
* Pascal.
*/
exports.pascal = pascal;
/**
* Dot. Should precede lowercase.
*/
exports.dot = dot;
/**
* Slug. Should precede lowercase.
*/
exports.slug = slug;
/**
* Snake. Should precede lowercase.
*/
exports.snake = snake;
/**
* Space. Should precede lowercase.
*/
exports.space = space;
/**
* Constant. Should precede uppercase.
*/
exports.constant = constant;
/**
* Capital. Should precede sentence and title.
*/
exports.capital = capital;
/**
* Title.
*/
exports.title = title;
/**
* Sentence.
*/
exports.sentence = sentence;
/**
* Convert a `string` to lower case from camel, slug, etc. Different that the
* usual `toLowerCase` in that it will try to break apart the input first.
*
* @param {String} string
* @return {String}
*/
exports.lower = function (string) {
return none(string).toLowerCase();
};
/**
* Convert a `string` to upper case from camel, slug, etc. Different that the
* usual `toUpperCase` in that it will try to break apart the input first.
*
* @param {String} string
* @return {String}
*/
exports.upper = function (string) {
return none(string).toUpperCase();
};
/**
* Invert each character in a `string` from upper to lower and vice versa.
*
* @param {String} string
* @return {String}
*/
exports.inverse = function (string) {
for (var i = 0, char; char = string[i]; i++) {
if (!/[a-z]/i.test(char)) continue;
var upper = char.toUpperCase();
var lower = char.toLowerCase();
string[i] = char == upper ? lower : upper;
}
return string;
};
/**
* None.
*/
exports.none = none;
});
require.register("segmentio-obj-case/index.js", function(exports, require, module){
var Case = require('case');
var cases = [
Case.upper,
Case.lower,
Case.snake,
Case.pascal,
Case.camel,
Case.constant,
Case.title,
Case.capital,
Case.sentence
];
/**
* Module exports, export
*/
module.exports = module.exports.find = multiple(find);
/**
* Export the replacement function, return the modified object
*/
module.exports.replace = function (obj, key, val) {
multiple(replace).apply(this, arguments);
return obj;
};
/**
* Export the delete function, return the modified object
*/
module.exports.del = function (obj, key) {
multiple(del).apply(this, arguments);
return obj;
};
/**
* Compose applying the function to a nested key
*/
function multiple (fn) {
return function (obj, key, val) {
var keys = key.split('.');
if (keys.length === 0) return;
while (keys.length > 1) {
key = keys.shift();
obj = find(obj, key);
if (obj === null || obj === undefined) return;
}
key = keys.shift();
return fn(obj, key, val);
};
}
/**
* Find an object by its key
*
* find({ first_name : 'Calvin' }, 'firstName')
*/
function find (obj, key) {
for (var i = 0; i < cases.length; i++) {
var cased = cases[i](key);
if (obj.hasOwnProperty(cased)) return obj[cased];
}
}
/**
* Delete a value for a given key
*
* del({ a : 'b', x : 'y' }, 'X' }) -> { a : 'b' }
*/
function del (obj, key) {
for (var i = 0; i < cases.length; i++) {
var cased = cases[i](key);
if (obj.hasOwnProperty(cased)) delete obj[cased];
}
return obj;
}
/**
* Replace an objects existing value with a new one
*
* replace({ a : 'b' }, 'a', 'c') -> { a : 'c' }
*/
function replace (obj, key, val) {
for (var i = 0; i < cases.length; i++) {
var cased = cases[i](key);
if (obj.hasOwnProperty(cased)) obj[cased] = val;
}
return obj;
}
});
require.register("segmentio-facade/lib/index.js", function(exports, require, module){
var Facade = require('./facade');
/**
* Expose `Facade` facade.
*/
module.exports = Facade;
/**
* Expose specific-method facades.
*/
Facade.Alias = require('./alias');
Facade.Group = require('./group');
Facade.Identify = require('./identify');
Facade.Track = require('./track');
Facade.Page = require('./page');
});
require.register("segmentio-facade/lib/alias.js", function(exports, require, module){
var Facade = require('./facade');
var component = require('require-component')(require);
var inherit = component('inherit');
/**
* Expose `Alias` facade.
*/
module.exports = Alias;
/**
* Initialize a new `Alias` facade with a `dictionary` of arguments.
*
* @param {Object} dictionary
* @property {String} from
* @property {String} to
* @property {Object} options
*/
function Alias (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`.
*/
inherit(Alias, Facade);
/**
* Return type of facade.
*
* @return {String}
*/
Alias.prototype.action = function () {
return 'alias';
};
/**
* Setup some basic proxies.
*/
Alias.prototype.from = Facade.field('from');
Alias.prototype.to = Facade.field('to');
});
require.register("segmentio-facade/lib/facade.js", function(exports, require, module){
var component = require('require-component')(require);
var clone = component('clone');
var isEnabled = component('./is-enabled');
var objCase = component('obj-case');
/**
* Expose `Facade`.
*/
module.exports = Facade;
/**
* Initialize a new `Facade` with an `obj` of arguments.
*
* @param {Object} obj
*/
function Facade (obj) {
if (!obj.hasOwnProperty('timestamp')) obj.timestamp = new Date();
else obj.timestamp = new Date(obj.timestamp);
this.obj = obj;
}
/**
* Return a proxy function for a `field` that will attempt to first use methods,
* and fallback to accessing the underlying object directly. You can specify
* deeply nested fields too like:
*
* this.proxy('options.Librato');
*
* @param {String} field
*/
Facade.prototype.proxy = function (field) {
var fields = field.split('.');
field = fields.shift();
// Call a function at the beginning to take advantage of facaded fields
var obj = this[field] || this.field(field);
if (!obj) return obj;
if (typeof obj === 'function') obj = obj.call(this) || {};
if (fields.length === 0) return clone(obj);
obj = objCase(obj, fields.join('.'));
return clone(obj);
};
/**
* Directly access a specific `field` from the underlying object, returning a
* clone so outsiders don't mess with stuff.
*
* @param {String} field
* @return {Mixed}
*/
Facade.prototype.field = function (field) {
return clone(this.obj[field]);
};
/**
* Utility method to always proxy a particular `field`. You can specify deeply
* nested fields too like:
*
* Facade.proxy('options.Librato');
*
* @param {String} field
* @return {Function}
*/
Facade.proxy = function (field) {
return function () {
return this.proxy(field);
};
};
/**
* Utility method to directly access a `field`.
*
* @param {String} field
* @return {Function}
*/
Facade.field = function (field) {
return function () {
return this.field(field);
};
};
/**
* Get the basic json object of this facade.
*
* @return {Object}
*/
Facade.prototype.json = function () {
return clone(this.obj);
};
/**
* Get the options of a call (formerly called "context"). If you pass an
* integration name, it will get the options for that specific integration, or
* undefined if the integration is not enabled.
*
* @param {String} integration (optional)
* @return {Object or Null}
*/
Facade.prototype.options = function (integration) {
var options = clone(this.obj.options || this.obj.context) || {};
if (!integration) return clone(options);
if (!this.enabled(integration)) return;
options = options[integration] || objCase(options, integration) || {};
return typeof options === 'boolean' ? {} : clone(options);
};
/**
* Check whether an integration is enabled.
*
* @param {String} integration
* @return {Boolean}
*/
Facade.prototype.enabled = function (integration) {
var allEnabled = this.proxy('options.providers.all');
if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('options.all');
if (typeof allEnabled !== 'boolean') allEnabled = true;
var enabled = allEnabled && isEnabled(integration);
var options = this.options();
// If the integration is explicitly enabled or disabled, use that
// First, check options.providers for backwards compatibility
if (options.providers && options.providers.hasOwnProperty(integration)) {
enabled = options.providers[integration];
}
// Next, check for the integration's existence in 'options' to enable it.
// If the settings are a boolean, use that, otherwise it should be enabled.
if (options.hasOwnProperty(integration)) {
var settings = options[integration];
if (typeof settings === 'boolean') {
enabled = settings;
} else {
enabled = true;
}
}
return enabled ? true : false;
};
/**
* Get the `userAgent` option.
*
* @return {String}
*/
Facade.prototype.userAgent = function () {};
/**
* Check whether the user is active.
*
* @return {Boolean}
*/
Facade.prototype.active = function () {
var active = this.proxy('options.active');
if (active === null || active === undefined) active = true;
return active;
};
/**
* Setup some basic proxies.
*/
Facade.prototype.channel = Facade.field('channel');
Facade.prototype.timestamp = Facade.field('timestamp');
Facade.prototype.ip = Facade.proxy('options.ip');
});
require.register("segmentio-facade/lib/group.js", function(exports, require, module){
var Facade = require('./facade');
var component = require('require-component')(require);
var inherit = component('inherit');
var newDate = component('new-date');
/**
* Expose `Group` facade.
*/
module.exports = Group;
/**
* Initialize a new `Group` facade with a `dictionary` of arguments.
*
* @param {Object} dictionary
* @param {String} userId
* @param {String} groupId
* @param {Object} properties
* @param {Object} options
*/
function Group (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`
*/
inherit(Group, Facade);
/**
* Get the facade's action.
*/
Group.prototype.action = function () {
return 'group';
};
/**
* Setup some basic proxies.
*/
Group.prototype.groupId = Facade.field('groupId');
Group.prototype.userId = Facade.field('userId');
/**
* Get created or createdAt.
*
* @return {Date}
*/
Group.prototype.created = function(){
var created = this.proxy('traits.createdAt')
|| this.proxy('traits.created')
|| this.proxy('properties.createdAt')
|| this.proxy('properties.created');
if (created) return newDate(created);
};
/**
* Get the group's traits.
*
* @param {Object} aliases
* @return {Object}
*/
Group.prototype.traits = function (aliases) {
var ret = this.properties();
var id = this.groupId();
aliases = aliases || {};
if (id) ret.id = id;
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('traits.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return ret;
};
/**
* Get traits or properties.
*
* TODO: remove me
*
* @return {Object}
*/
Group.prototype.properties = function(){
return this.field('traits')
|| this.field('properties')
|| {};
};
});
require.register("segmentio-facade/lib/page.js", function(exports, require, module){
var component = require('require-component')(require);
var Facade = component('./facade');
var inherit = component('inherit');
var Track = require('./track');
/**
* Expose `Page` facade
*/
module.exports = Page;
/**
* Initialize new `Page` facade with `dictionary`.
*
* @param {Object} dictionary
* @param {String} category
* @param {String} name
* @param {Object} traits
* @param {Object} options
*/
function Page(dictionary){
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`
*/
inherit(Page, Facade);
/**
* Get the facade's action.
*
* @return {String}
*/
Page.prototype.action = function(){
return 'page';
};
/**
* Proxies
*/
Page.prototype.category = Facade.field('category');
Page.prototype.name = Facade.field('name');
/**
* Get the page properties mixing `category` and `name`.
*
* @return {Object}
*/
Page.prototype.properties = function(){
var props = this.field('properties') || {};
var category = this.category();
var name = this.name();
if (category) props.category = category;
if (name) props.name = name;
return props;
};
/**
* Get the page fullName.
*
* @return {String}
*/
Page.prototype.fullName = function(){
var category = this.category();
var name = this.name();
return name && category
? category + ' ' + name
: name;
};
/**
* Get event with `name`.
*
* @return {String}
*/
Page.prototype.event = function(name){
return name
? 'Viewed ' + name + ' Page'
: 'Loaded a Page';
};
/**
* Convert this Page to a Track facade with `name`.
*
* @param {String} name
* @return {Track}
*/
Page.prototype.track = function(name){
var props = this.properties();
return new Track({
event: this.event(name),
properties: props
});
};
});
require.register("segmentio-facade/lib/identify.js", function(exports, require, module){
var component = require('require-component')(require);
var clone = component('clone');
var Facade = component('./facade');
var inherit = component('inherit');
var isEmail = component('is-email');
var newDate = component('new-date');
var trim = component('trim');
/**
* Expose `Idenfity` facade.
*/
module.exports = Identify;
/**
* Initialize a new `Identify` facade with a `dictionary` of arguments.
*
* @param {Object} dictionary
* @param {String} userId
* @param {String} sessionId
* @param {Object} traits
* @param {Object} options
*/
function Identify (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`.
*/
inherit(Identify, Facade);
/**
* Get the facade's action.
*/
Identify.prototype.action = function () {
return 'identify';
};
/**
* Setup some basic proxies.
*/
Identify.prototype.userId = Facade.field('userId');
Identify.prototype.sessionId = Facade.field('sessionId');
/**
* Get the user's traits.
*
* @param {Object} aliases
* @return {Object}
*/
Identify.prototype.traits = function (aliases) {
var ret = this.field('traits') || {};
var id = this.userId();
aliases = aliases || {};
if (id) ret.id = id;
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('traits.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return ret;
};
/**
* Get the user's email, falling back to their user ID if it's a valid email.
*
* @return {String}
*/
Identify.prototype.email = function () {
var email = this.proxy('traits.email');
if (email) return email;
var userId = this.userId();
if (isEmail(userId)) return userId;
};
/**
* Get the user's created date, optionally looking for `createdAt` since lots of
* people do that instead.
*
* @return {Date or Undefined}
*/
Identify.prototype.created = function () {
var created = this.proxy('traits.created') || this.proxy('traits.createdAt');
if (created) return newDate(created);
};
/**
* Get the company created date.
*
* @return {Date or undefined}
*/
Identify.prototype.companyCreated = function(){
var created = this.proxy('traits.company.created')
|| this.proxy('traits.company.createdAt');
if (created) return newDate(created);
};
/**
* Get the user's name, optionally combining a first and last name if that's all
* that was provided.
*
* @return {String or Undefined}
*/
Identify.prototype.name = function () {
var name = this.proxy('traits.name');
if (typeof name === 'string') return trim(name);
var firstName = this.firstName();
var lastName = this.lastName();
if (firstName && lastName) return trim(firstName + ' ' + lastName);
};
/**
* Get the user's first name, optionally splitting it out of a single name if
* that's all that was provided.
*
* @return {String or Undefined}
*/
Identify.prototype.firstName = function () {
var firstName = this.proxy('traits.firstName');
if (typeof firstName === 'string') return trim(firstName);
var name = this.proxy('traits.name');
if (typeof name === 'string') return trim(name).split(' ')[0];
};
/**
* Get the user's last name, optionally splitting it out of a single name if
* that's all that was provided.
*
* @return {String or Undefined}
*/
Identify.prototype.lastName = function () {
var lastName = this.proxy('traits.lastName');
if (typeof lastName === 'string') return trim(lastName);
var name = this.proxy('traits.name');
if (typeof name !== 'string') return;
var space = trim(name).indexOf(' ');
if (space === -1) return;
return trim(name.substr(space + 1));
};
/**
* Get the user's unique id.
*
* @return {String or undefined}
*/
Identify.prototype.uid = function(){
return this.userId()
|| this.username()
|| this.email();
};
/**
* Get description.
*
* @return {String}
*/
Identify.prototype.description = function(){
return this.proxy('traits.description')
|| this.proxy('traits.background');
};
/**
* Setup sme basic "special" trait proxies.
*/
Identify.prototype.username = Facade.proxy('traits.username');
Identify.prototype.website = Facade.proxy('traits.website');
Identify.prototype.phone = Facade.proxy('traits.phone');
Identify.prototype.address = Facade.proxy('traits.address');
Identify.prototype.avatar = Facade.proxy('traits.avatar');
});
require.register("segmentio-facade/lib/is-enabled.js", function(exports, require, module){
/**
* A few integrations are disabled by default. They must be explicitly
* enabled by setting options[Provider] = true.
*/
var disabled = {
Salesforce: true,
Marketo: true
};
/**
* Check whether an integration should be enabled by default.
*
* @param {String} integration
* @return {Boolean}
*/
module.exports = function (integration) {
return ! disabled[integration];
};
});
require.register("segmentio-facade/lib/track.js", function(exports, require, module){
var component = require('require-component')(require);
var clone = component('clone');
var Facade = component('./facade');
var Identify = component('./identify');
var inherit = component('inherit');
var isEmail = component('is-email');
var traverse = component('isodate-traverse');
/**
* Expose `Track` facade.
*/
module.exports = Track;
/**
* Initialize a new `Track` facade with a `dictionary` of arguments.
*
* @param {object} dictionary
* @property {String} event
* @property {String} userId
* @property {String} sessionId
* @property {Object} properties
* @property {Object} options
*/
function Track (dictionary) {
Facade.call(this, dictionary);
}
/**
* Inherit from `Facade`.
*/
inherit(Track, Facade);
/**
* Return the facade's action.
*
* @return {String}
*/
Track.prototype.action = function () {
return 'track';
};
/**
* Setup some basic proxies.
*/
Track.prototype.userId = Facade.field('userId');
Track.prototype.sessionId = Facade.field('sessionId');
Track.prototype.event = Facade.field('event');
Track.prototype.value = Facade.proxy('properties.value');
/**
* Misc
*/
Track.prototype.category = Facade.proxy('properties.category');
Track.prototype.country = Facade.proxy('properties.country');
Track.prototype.state = Facade.proxy('properties.state');
Track.prototype.city = Facade.proxy('properties.city');
Track.prototype.zip = Facade.proxy('properties.zip');
/**
* Ecommerce
*/
Track.prototype.id = Facade.proxy('properties.id');
Track.prototype.sku = Facade.proxy('properties.sku');
Track.prototype.tax = Facade.proxy('properties.tax');
Track.prototype.name = Facade.proxy('properties.name');
Track.prototype.price = Facade.proxy('properties.price');
Track.prototype.total = Facade.proxy('properties.total');
Track.prototype.coupon = Facade.proxy('properties.coupon');
Track.prototype.orderId = Facade.proxy('properties.orderId');
Track.prototype.shipping = Facade.proxy('properties.shipping');
/**
* Get subtotal.
*
* @return {Number}
*/
Track.prototype.subtotal = function(){
var subtotal = this.obj.properties.subtotal;
var total = this.total();
var n;
if (subtotal) return subtotal;
if (!total) return 0;
if (n = this.tax()) total -= n;
if (n = this.shipping()) total -= n;
return total;
};
/**
* Get products.
*
* @return {Array}
*/
Track.prototype.products = function(){
var props = this.obj.properties || {};
return props.products || [];
};
/**
* Get quantity.
*
* @return {Number}
*/
Track.prototype.quantity = function(){
var props = this.obj.properties || {};
return props.quantity || 1;
};
/**
* Get currency.
*
* @return {String}
*/
Track.prototype.currency = function(){
var props = this.obj.properties || {};
return props.currency || 'USD';
};
/**
* BACKWARDS COMPATIBILITY: should probably re-examine where these come from.
*/
Track.prototype.referrer = Facade.proxy('properties.referrer');
Track.prototype.query = Facade.proxy('options.query');
/**
* Get the call's properties.
*
* @param {Object} aliases
* @return {Object}
*/
Track.prototype.properties = function (aliases) {
var ret = this.field('properties') || {};
aliases = aliases || {};
for (var alias in aliases) {
var value = null == this[alias]
? this.proxy('properties.' + alias)
: this[alias]();
if (null == value) continue;
ret[aliases[alias]] = value;
delete ret[alias];
}
return clone(traverse(ret));
};
/**
* Get the call's "super properties" which are just traits that have been
* passed in as if from an identify call.
*
* @return {Object}
*/
Track.prototype.traits = function () {
return this.proxy('options.traits') || {};
};
/**
* Get the call's username.
*
* @return {String or Undefined}
*/
Track.prototype.username = function () {
return this.proxy('traits.username') ||
this.proxy('properties.username') ||
this.userId() ||
this.sessionId();
};
/**
* Get the call's email, using an the user ID if it's a valid email.
*
* @return {String or Undefined}
*/
Track.prototype.email = function () {
var email = this.proxy('traits.email');
if (email) return email;
var userId = this.userId();
if (isEmail(userId)) return userId;
};
/**
* Get the call's revenue, parsing it from a string with an optional leading
* dollar sign.
*
* @return {String or Undefined}
*/
Track.prototype.revenue = function () {
var revenue = this.proxy('properties.revenue');
if (!revenue) return;
if (typeof revenue === 'number') return revenue;
if (typeof revenue !== 'string') return;
revenue = revenue.replace(/\$/g, '');
revenue = parseFloat(revenue);
if (!isNaN(revenue)) return revenue;
};
/**
* Get cents.
*
* @return {Number}
*/
Track.prototype.cents = function(){
var revenue = this.revenue();
return 'number' != typeof revenue
? this.value() || 0
: revenue * 100;
};
/**
* A utility to turn the pieces of a track call into an identify. Used for
* integrations with super properties or rate limits.
*
* TODO: remove me.
*
* @return {Facade}
*/
Track.prototype.identify = function () {
var json = this.json();
json.traits = this.traits();
return new Identify(json);
};
});
require.register("segmentio-is-email/index.js", function(exports, require, module){
/**
* Expose `isEmail`.
*/
module.exports = isEmail;
/**
* Email address matcher.
*/
var matcher = /.+\@.+\..+/;
/**
* Loosely validate an email address.
*
* @param {String} string
* @return {Boolean}
*/
function isEmail (string) {
return matcher.test(string);
}
});
require.register("segmentio-is-meta/index.js", function(exports, require, module){
module.exports = function isMeta (e) {
if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return true;
// Logic that handles checks for the middle mouse button, based
// on [jQuery](https://github.com/jquery/jquery/blob/master/src/event.js#L466).
var which = e.which, button = e.button;
if (!which && button !== undefined) {
return (!button & 1) && (!button & 2) && (button & 4);
} else if (which === 2) {
return true;
}
return false;
};
});
require.register("segmentio-isodate/index.js", function(exports, require, module){
/**
* Matcher, slightly modified from:
*
* https://github.com/csnover/js-iso8601/blob/lax/iso8601.js
*/
var matcher = /^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;
/**
* Convert an ISO date string to a date. Fallback to native `Date.parse`.
*
* https://github.com/csnover/js-iso8601/blob/lax/iso8601.js
*
* @param {String} iso
* @return {Date}
*/
exports.parse = function (iso) {
var numericKeys = [1, 5, 6, 7, 8, 11, 12];
var arr = matcher.exec(iso);
var offset = 0;
// fallback to native parsing
if (!arr) return new Date(iso);
// remove undefined values
for (var i = 0, val; val = numericKeys[i]; i++) {
arr[val] = parseInt(arr[val], 10) || 0;
}
// allow undefined days and months
arr[2] = parseInt(arr[2], 10) || 1;
arr[3] = parseInt(arr[3], 10) || 1;
// month is 0-11
arr[2]--;
// allow abitrary sub-second precision
if (arr[8]) arr[8] = (arr[8] + '00').substring(0, 3);
// apply timezone if one exists
if (arr[4] == ' ') {
offset = new Date().getTimezoneOffset();
} else if (arr[9] !== 'Z' && arr[10]) {
offset = arr[11] * 60 + arr[12];
if ('+' == arr[10]) offset = 0 - offset;
}
var millis = Date.UTC(arr[1], arr[2], arr[3], arr[5], arr[6] + offset, arr[7], arr[8]);
return new Date(millis);
};
/**
* Checks whether a `string` is an ISO date string. `strict` mode requires that
* the date string at least have a year, month and date.
*
* @param {String} string
* @param {Boolean} strict
* @return {Boolean}
*/
exports.is = function (string, strict) {
if (strict && false === /^\d{4}-\d{2}-\d{2}/.test(string)) return false;
return matcher.test(string);
};
});
require.register("segmentio-isodate-traverse/index.js", function(exports, require, module){
var is = require('is');
var isodate = require('isodate');
var each;
try {
each = require('each');
} catch (err) {
each = require('each-component');
}
/**
* Expose `traverse`.
*/
module.exports = traverse;
/**
* Traverse an object or array, and return a clone with all ISO strings parsed
* into Date objects.
*
* @param {Object} obj
* @return {Object}
*/
function traverse (input, strict) {
if (strict === undefined) strict = true;
if (is.object(input)) {
return object(input, strict);
} else if (is.array(input)) {
return array(input, strict);
}
}
/**
* Object traverser.
*
* @param {Object} obj
* @param {Boolean} strict
* @return {Object}
*/
function object (obj, strict) {
each(obj, function (key, val) {
if (isodate.is(val, strict)) {
obj[key] = isodate.parse(val);
} else if (is.object(val) || is.array(val)) {
traverse(val, strict);
}
});
return obj;
}
/**
* Array traverser.
*
* @param {Array} arr
* @param {Boolean} strict
* @return {Array}
*/
function array (arr, strict) {
each(arr, function (val, x) {
if (is.object(val)) {
traverse(val, strict);
} else if (isodate.is(val, strict)) {
arr[x] = isodate.parse(val);
}
});
return arr;
}
});
require.register("component-json-fallback/index.js", function(exports, require, module){
/*
json2.js
2014-02-04
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function () {
return this.valueOf();
};
}
var cx,
escapable,
gap,
indent,
meta,
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
module.exports = JSON;
});
require.register("segmentio-json/index.js", function(exports, require, module){
module.exports = 'undefined' == typeof JSON
? require('json-fallback')
: JSON;
});
require.register("segmentio-new-date/lib/index.js", function(exports, require, module){
var is = require('is');
var isodate = require('isodate');
var milliseconds = require('./milliseconds');
var seconds = require('./seconds');
/**
* Returns a new Javascript Date object, allowing a variety of extra input types
* over the native Date constructor.
*
* @param {Date|String|Number} val
*/
module.exports = function newDate (val) {
if (is.date(val)) return val;
if (is.number(val)) return new Date(toMs(val));
// date strings
if (isodate.is(val)) return isodate.parse(val);
if (milliseconds.is(val)) return milliseconds.parse(val);
if (seconds.is(val)) return seconds.parse(val);
// fallback to Date.parse
return new Date(val);
};
/**
* If the number passed val is seconds from the epoch, turn it into milliseconds.
* Milliseconds would be greater than 31557600000 (December 31, 1970).
*
* @param {Number} num
*/
function toMs (num) {
if (num < 31557600000) return num * 1000;
return num;
}
});
require.register("segmentio-new-date/lib/milliseconds.js", function(exports, require, module){
/**
* Matcher.
*/
var matcher = /\d{13}/;
/**
* Check whether a string is a millisecond date string.
*
* @param {String} string
* @return {Boolean}
*/
exports.is = function (string) {
return matcher.test(string);
};
/**
* Convert a millisecond string to a date.
*
* @param {String} millis
* @return {Date}
*/
exports.parse = function (millis) {
millis = parseInt(millis, 10);
return new Date(millis);
};
});
require.register("segmentio-new-date/lib/seconds.js", function(exports, require, module){
/**
* Matcher.
*/
var matcher = /\d{10}/;
/**
* Check whether a string is a second date string.
*
* @param {String} string
* @return {Boolean}
*/
exports.is = function (string) {
return matcher.test(string);
};
/**
* Convert a second string to a date.
*
* @param {String} seconds
* @return {Date}
*/
exports.parse = function (seconds) {
var millis = parseInt(seconds, 10) * 1000;
return new Date(millis);
};
});
require.register("segmentio-store.js/store.js", function(exports, require, module){
;(function(win){
var store = {},
doc = win.document,
localStorageName = 'localStorage',
namespace = '__storejs__',
storage
store.disabled = false
store.set = function(key, value) {}
store.get = function(key) {}
store.remove = function(key) {}
store.clear = function() {}
store.transact = function(key, defaultVal, transactionFn) {
var val = store.get(key)
if (transactionFn == null) {
transactionFn = defaultVal
defaultVal = null
}
if (typeof val == 'undefined') { val = defaultVal || {} }
transactionFn(val)
store.set(key, val)
}
store.getAll = function() {}
store.serialize = function(value) {
return JSON.stringify(value)
}
store.deserialize = function(value) {
if (typeof value != 'string') { return undefined }
try { return JSON.parse(value) }
catch(e) { return value || undefined }
}
// Functions to encapsulate questionable FireFox 3.6.13 behavior
// when about.config::dom.storage.enabled === false
// See https://github.com/marcuswestin/store.js/issues#issue/13
function isLocalStorageNameSupported() {
try { return (localStorageName in win && win[localStorageName]) }
catch(err) { return false }
}
if (isLocalStorageNameSupported()) {
storage = win[localStorageName]
store.set = function(key, val) {
if (val === undefined) { return store.remove(key) }
storage.setItem(key, store.serialize(val))
return val
}
store.get = function(key) { return store.deserialize(storage.getItem(key)) }
store.remove = function(key) { storage.removeItem(key) }
store.clear = function() { storage.clear() }
store.getAll = function() {
var ret = {}
for (var i=0; i<storage.length; ++i) {
var key = storage.key(i)
ret[key] = store.get(key)
}
return ret
}
} else if (doc.documentElement.addBehavior) {
var storageOwner,
storageContainer
// Since #userData storage applies only to specific paths, we need to
// somehow link our data to a specific path. We choose /favicon.ico
// as a pretty safe option, since all browsers already make a request to
// this URL anyway and being a 404 will not hurt us here. We wrap an
// iframe pointing to the favicon in an ActiveXObject(htmlfile) object
// (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
// since the iframe access rules appear to allow direct access and
// manipulation of the document element, even for a 404 page. This
// document can be used instead of the current document (which would
// have been limited to the current path) to perform #userData storage.
try {
storageContainer = new ActiveXObject('htmlfile')
storageContainer.open()
storageContainer.write('<s' + 'cript>document.w=window</s' + 'cript><iframe src="/favicon.ico"></iframe>')
storageContainer.close()
storageOwner = storageContainer.w.frames[0].document
storage = storageOwner.createElement('div')
} catch(e) {
// somehow ActiveXObject instantiation failed (perhaps some special
// security settings or otherwse), fall back to per-path storage
storage = doc.createElement('div')
storageOwner = doc.body
}
function withIEStorage(storeFunction) {
return function() {
var args = Array.prototype.slice.call(arguments, 0)
args.unshift(storage)
// See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
// and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
storageOwner.appendChild(storage)
storage.addBehavior('#default#userData')
storage.load(localStorageName)
var result = storeFunction.apply(store, args)
storageOwner.removeChild(storage)
return result
}
}
// In IE7, keys may not contain special chars. See all of https://github.com/marcuswestin/store.js/issues/40
var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g")
function ieKeyFix(key) {
return key.replace(forbiddenCharsRegex, '___')
}
store.set = withIEStorage(function(storage, key, val) {
key = ieKeyFix(key)
if (val === undefined) { return store.remove(key) }
storage.setAttribute(key, store.serialize(val))
storage.save(localStorageName)
return val
})
store.get = withIEStorage(function(storage, key) {
key = ieKeyFix(key)
return store.deserialize(storage.getAttribute(key))
})
store.remove = withIEStorage(function(storage, key) {
key = ieKeyFix(key)
storage.removeAttribute(key)
storage.save(localStorageName)
})
store.clear = withIEStorage(function(storage) {
var attributes = storage.XMLDocument.documentElement.attributes
storage.load(localStorageName)
for (var i=0, attr; attr=attributes[i]; i++) {
storage.removeAttribute(attr.name)
}
storage.save(localStorageName)
})
store.getAll = withIEStorage(function(storage) {
var attributes = storage.XMLDocument.documentElement.attributes
var ret = {}
for (var i=0, attr; attr=attributes[i]; ++i) {
var key = ieKeyFix(attr.name)
ret[attr.name] = store.deserialize(storage.getAttribute(key))
}
return ret
})
}
try {
store.set(namespace, namespace)
if (store.get(namespace) != namespace) { store.disabled = true }
store.remove(namespace)
} catch(e) {
store.disabled = true
}
store.enabled = !store.disabled
if (typeof module != 'undefined' && module.exports) { module.exports = store }
else if (typeof define === 'function' && define.amd) { define(store) }
else { win.store = store }
})(this.window || global);
});
require.register("segmentio-top-domain/index.js", function(exports, require, module){
var url = require('url');
// Official Grammar: http://tools.ietf.org/html/rfc883#page-56
// Look for tlds with up to 2-6 characters.
module.exports = function (urlStr) {
var host = url.parse(urlStr).hostname
, topLevel = host.match(/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i);
return topLevel ? topLevel[0] : host;
};
});
require.register("visionmedia-debug/index.js", function(exports, require, module){
if ('undefined' == typeof window) {
module.exports = require('./lib/debug');
} else {
module.exports = require('./debug');
}
});
require.register("visionmedia-debug/debug.js", function(exports, require, module){
/**
* Expose `debug()` as the module.
*/
module.exports = debug;
/**
* Create a debugger with the given `name`.
*
* @param {String} name
* @return {Type}
* @api public
*/
function debug(name) {
if (!debug.enabled(name)) return function(){};
return function(fmt){
fmt = coerce(fmt);
var curr = new Date;
var ms = curr - (debug[name] || curr);
debug[name] = curr;
fmt = name
+ ' '
+ fmt
+ ' +' + debug.humanize(ms);
// This hackery is required for IE8
// where `console.log` doesn't have 'apply'
window.console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
}
/**
* The currently active debug mode names.
*/
debug.names = [];
debug.skips = [];
/**
* Enables a debug mode by name. This can include modes
* separated by a colon and wildcards.
*
* @param {String} name
* @api public
*/
debug.enable = function(name) {
try {
localStorage.debug = name;
} catch(e){}
var split = (name || '').split(/[\s,]+/)
, len = split.length;
for (var i = 0; i < len; i++) {
name = split[i].replace('*', '.*?');
if (name[0] === '-') {
debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
}
else {
debug.names.push(new RegExp('^' + name + '$'));
}
}
};
/**
* Disable debug output.
*
* @api public
*/
debug.disable = function(){
debug.enable('');
};
/**
* Humanize the given `ms`.
*
* @param {Number} m
* @return {String}
* @api private
*/
debug.humanize = function(ms) {
var sec = 1000
, min = 60 * 1000
, hour = 60 * min;
if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
if (ms >= min) return (ms / min).toFixed(1) + 'm';
if (ms >= sec) return (ms / sec | 0) + 's';
return ms + 'ms';
};
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
debug.enabled = function(name) {
for (var i = 0, len = debug.skips.length; i < len; i++) {
if (debug.skips[i].test(name)) {
return false;
}
}
for (var i = 0, len = debug.names.length; i < len; i++) {
if (debug.names[i].test(name)) {
return true;
}
}
return false;
};
/**
* Coerce `val`.
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
// persist
try {
if (window.localStorage) debug.enable(localStorage.debug);
} catch(e){}
});
require.register("yields-prevent/index.js", function(exports, require, module){
/**
* prevent default on the given `e`.
*
* examples:
*
* anchor.onclick = prevent;
* anchor.onclick = function(e){
* if (something) return prevent(e);
* };
*
* @param {Event} e
*/
module.exports = function(e){
e = e || window.event
return e.preventDefault
? e.preventDefault()
: e.returnValue = false;
};
});
require.register("analytics/lib/index.js", function(exports, require, module){
/**
* Analytics.js
*
* (C) 2013 Segment.io Inc.
*/
var Analytics = require('./analytics');
var createIntegration = require('integration');
var each = require('each');
var Integrations = require('integrations');
/**
* Expose the `analytics` singleton.
*/
var analytics = module.exports = exports = new Analytics();
/**
* Expose require
*/
analytics.require = require;
/**
* Expose `VERSION`.
*/
exports.VERSION = '1.3.6';
/**
* Add integrations.
*/
each(Integrations, function (name, Integration) {
analytics.use(Integration);
});
});
require.register("analytics/lib/analytics.js", function(exports, require, module){
var after = require('after');
var bind = require('bind');
var callback = require('callback');
var canonical = require('canonical');
var clone = require('clone');
var cookie = require('./cookie');
var debug = require('debug');
var defaults = require('defaults');
var each = require('each');
var Emitter = require('emitter');
var group = require('./group');
var is = require('is');
var isEmail = require('is-email');
var isMeta = require('is-meta');
var newDate = require('new-date');
var on = require('event').bind;
var prevent = require('prevent');
var querystring = require('querystring');
var size = require('object').length;
var store = require('./store');
var url = require('url');
var user = require('./user');
var Facade = require('facade');
var Identify = Facade.Identify;
var Group = Facade.Group;
var Alias = Facade.Alias;
var Track = Facade.Track;
var Page = Facade.Page;
/**
* Expose `Analytics`.
*/
module.exports = Analytics;
/**
* Initialize a new `Analytics` instance.
*/
function Analytics () {
this.Integrations = {};
this._integrations = {};
this._readied = false;
this._timeout = 300;
this._user = user; // BACKWARDS COMPATIBILITY
bind.all(this);
var self = this;
this.on('initialize', function (settings, options) {
if (options.initialPageview) self.page();
});
this.on('initialize', function () {
self._parseQuery();
});
}
/**
* Event Emitter.
*/
Emitter(Analytics.prototype);
/**
* Use a `plugin`.
*
* @param {Function} plugin
* @return {Analytics}
*/
Analytics.prototype.use = function (plugin) {
plugin(this);
return this;
};
/**
* Define a new `Integration`.
*
* @param {Function} Integration
* @return {Analytics}
*/
Analytics.prototype.addIntegration = function (Integration) {
var name = Integration.prototype.name;
if (!name) throw new TypeError('attempted to add an invalid integration');
this.Integrations[name] = Integration;
return this;
};
/**
* Initialize with the given integration `settings` and `options`. Aliased to
* `init` for convenience.
*
* @param {Object} settings
* @param {Object} options (optional)
* @return {Analytics}
*/
Analytics.prototype.init =
Analytics.prototype.initialize = function (settings, options) {
settings = settings || {};
options = options || {};
this._options(options);
this._readied = false;
this._integrations = {};
// load user now that options are set
user.load();
group.load();
// clean unknown integrations from settings
var self = this;
each(settings, function (name) {
var Integration = self.Integrations[name];
if (!Integration) delete settings[name];
});
// make ready callback
var ready = after(size(settings), function () {
self._readied = true;
self.emit('ready');
});
// initialize integrations, passing ready
each(settings, function (name, opts) {
var Integration = self.Integrations[name];
if (options.initialPageview && opts.initialPageview === false) {
Integration.prototype.page = after(2, Integration.prototype.page);
}
var integration = new Integration(clone(opts));
integration.once('ready', ready);
integration.initialize();
self._integrations[name] = integration;
});
// backwards compat with angular plugin.
// TODO: remove
this.initialized = true;
this.emit('initialize', settings, options);
return this;
};
/**
* Identify a user by optional `id` and `traits`.
*
* @param {String} id (optional)
* @param {Object} traits (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.identify = function (id, traits, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(traits)) fn = traits, options = null, traits = null;
if (is.object(id)) options = traits, traits = id, id = user.id();
// clone traits before we manipulate so we don't do anything uncouth, and take
// from `user` so that we carryover anonymous traits
user.identify(id, traits);
id = user.id();
traits = user.traits();
this._invoke('identify', new Identify({
options: options,
traits: traits,
userId: id
}));
// emit
this.emit('identify', id, traits, options);
this._callback(fn);
return this;
};
/**
* Return the current user.
*
* @return {Object}
*/
Analytics.prototype.user = function () {
return user;
};
/**
* Identify a group by optional `id` and `traits`. Or, if no arguments are
* supplied, return the current group.
*
* @param {String} id (optional)
* @param {Object} traits (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics or Object}
*/
Analytics.prototype.group = function (id, traits, options, fn) {
if (0 === arguments.length) return group;
if (is.fn(options)) fn = options, options = null;
if (is.fn(traits)) fn = traits, options = null, traits = null;
if (is.object(id)) options = traits, traits = id, id = group.id();
// grab from group again to make sure we're taking from the source
group.identify(id, traits);
id = group.id();
traits = group.traits();
this._invoke('group', new Group({
options: options,
traits: traits,
groupId: id
}));
this.emit('group', id, traits, options);
this._callback(fn);
return this;
};
/**
* Track an `event` that a user has triggered with optional `properties`.
*
* @param {String} event
* @param {Object} properties (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.track = function (event, properties, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(properties)) fn = properties, options = null, properties = null;
this._invoke('track', new Track({
properties: properties,
options: options,
event: event
}));
this.emit('track', event, properties, options);
this._callback(fn);
return this;
};
/**
* Helper method to track an outbound link that would normally navigate away
* from the page before the analytics calls were sent.
*
* BACKWARDS COMPATIBILITY: aliased to `trackClick`.
*
* @param {Element or Array} links
* @param {String or Function} event
* @param {Object or Function} properties (optional)
* @return {Analytics}
*/
Analytics.prototype.trackClick =
Analytics.prototype.trackLink = function (links, event, properties) {
if (!links) return this;
if (is.element(links)) links = [links]; // always arrays, handles jquery
var self = this;
each(links, function (el) {
on(el, 'click', function (e) {
var ev = is.fn(event) ? event(el) : event;
var props = is.fn(properties) ? properties(el) : properties;
self.track(ev, props);
if (el.href && el.target !== '_blank' && !isMeta(e)) {
prevent(e);
self._callback(function () {
window.location.href = el.href;
});
}
});
});
return this;
};
/**
* Helper method to track an outbound form that would normally navigate away
* from the page before the analytics calls were sent.
*
* BACKWARDS COMPATIBILITY: aliased to `trackSubmit`.
*
* @param {Element or Array} forms
* @param {String or Function} event
* @param {Object or Function} properties (optional)
* @return {Analytics}
*/
Analytics.prototype.trackSubmit =
Analytics.prototype.trackForm = function (forms, event, properties) {
if (!forms) return this;
if (is.element(forms)) forms = [forms]; // always arrays, handles jquery
var self = this;
each(forms, function (el) {
function handler (e) {
prevent(e);
var ev = is.fn(event) ? event(el) : event;
var props = is.fn(properties) ? properties(el) : properties;
self.track(ev, props);
self._callback(function () {
el.submit();
});
}
// support the events happening through jQuery or Zepto instead of through
// the normal DOM API, since `el.submit` doesn't bubble up events...
var $ = window.jQuery || window.Zepto;
if ($) {
$(el).submit(handler);
} else {
on(el, 'submit', handler);
}
});
return this;
};
/**
* Trigger a pageview, labeling the current page with an optional `category`,
* `name` and `properties`.
*
* @param {String} category (optional)
* @param {String} name (optional)
* @param {Object or String} properties (or path) (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.page = function (category, name, properties, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(properties)) fn = properties, options = properties = null;
if (is.fn(name)) fn = name, options = properties = name = null;
if (is.object(category)) options = name, properties = category, name = category = null;
if (is.object(name)) options = properties, properties = name, name = null;
if (is.string(category) && !is.string(name)) name = category, category = null;
var defs = {
path: canonicalPath(),
referrer: document.referrer,
title: document.title,
url: canonicalUrl(),
search: location.search
};
if (name) defs.name = name;
if (category) defs.category = category;
properties = clone(properties) || {};
defaults(properties, defs);
this._invoke('page', new Page({
properties: properties,
category: category,
options: options,
name: name
}));
this.emit('page', category, name, properties, options);
this._callback(fn);
return this;
};
/**
* BACKWARDS COMPATIBILITY: convert an old `pageview` to a `page` call.
*
* @param {String} url (optional)
* @param {Object} options (optional)
* @return {Analytics}
* @api private
*/
Analytics.prototype.pageview = function (url, options) {
var properties = {};
if (url) properties.path = url;
this.page(properties);
return this;
};
/**
* Merge two previously unassociated user identities.
*
* @param {String} to
* @param {String} from (optional)
* @param {Object} options (optional)
* @param {Function} fn (optional)
* @return {Analytics}
*/
Analytics.prototype.alias = function (to, from, options, fn) {
if (is.fn(options)) fn = options, options = null;
if (is.fn(from)) fn = from, options = null, from = null;
if (is.object(from)) options = from, from = null;
this._invoke('alias', new Alias({
options: options,
from: from,
to: to
}));
this.emit('alias', to, from, options);
this._callback(fn);
return this;
};
/**
* Register a `fn` to be fired when all the analytics services are ready.
*
* @param {Function} fn
* @return {Analytics}
*/
Analytics.prototype.ready = function (fn) {
if (!is.fn(fn)) return this;
this._readied
? callback.async(fn)
: this.once('ready', fn);
return this;
};
/**
* Set the `timeout` (in milliseconds) used for callbacks.
*
* @param {Number} timeout
*/
Analytics.prototype.timeout = function (timeout) {
this._timeout = timeout;
};
/**
* Enable or disable debug.
*
* @param {String or Boolean} str
*/
Analytics.prototype.debug = function(str){
if (0 == arguments.length || str) {
debug.enable('analytics:' + (str || '*'));
} else {
debug.disable();
}
};
/**
* Apply options.
*
* @param {Object} options
* @return {Analytics}
* @api private
*/
Analytics.prototype._options = function (options) {
options = options || {};
cookie.options(options.cookie);
store.options(options.localStorage);
user.options(options.user);
group.options(options.group);
return this;
};
/**
* Callback a `fn` after our defined timeout period.
*
* @param {Function} fn
* @return {Analytics}
* @api private
*/
Analytics.prototype._callback = function (fn) {
callback.async(fn, this._timeout);
return this;
};
/**
* Call `method` with `facade` on all enabled integrations.
*
* @param {String} method
* @param {Facade} facade
* @return {Analytics}
* @api private
*/
Analytics.prototype._invoke = function (method, facade) {
var options = facade.options();
each(this._integrations, function (name, integration) {
if (!facade.enabled(name)) return;
integration.invoke.call(integration, method, facade);
});
return this;
};
/**
* Push `args`.
*
* @param {Array} args
* @api private
*/
Analytics.prototype.push = function(args){
var method = args.shift();
if (!this[method]) return;
this[method].apply(this, args);
};
/**
* Parse the query string for callable methods.
*
* @return {Analytics}
* @api private
*/
Analytics.prototype._parseQuery = function () {
// Identify and track any `ajs_uid` and `ajs_event` parameters in the URL.
var q = querystring.parse(window.location.search);
if (q.ajs_uid) this.identify(q.ajs_uid);
if (q.ajs_event) this.track(q.ajs_event);
return this;
};
/**
* Return the canonical path for the page.
*
* @return {String}
*/
function canonicalPath () {
var canon = canonical();
if (!canon) return window.location.pathname;
var parsed = url.parse(canon);
return parsed.pathname;
}
/**
* Return the canonical URL for the page, without the hash.
*
* @return {String}
*/
function canonicalUrl () {
var canon = canonical();
if (canon) return canon;
var url = window.location.href;
var i = url.indexOf('#');
return -1 == i ? url : url.slice(0, i);
}
});
require.register("analytics/lib/cookie.js", function(exports, require, module){
var bind = require('bind');
var cookie = require('cookie');
var clone = require('clone');
var defaults = require('defaults');
var json = require('json');
var topDomain = require('top-domain');
/**
* Initialize a new `Cookie` with `options`.
*
* @param {Object} options
*/
function Cookie (options) {
this.options(options);
}
/**
* Get or set the cookie options.
*
* @param {Object} options
* @field {Number} maxage (1 year)
* @field {String} domain
* @field {String} path
* @field {Boolean} secure
*/
Cookie.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options = options || {};
var domain = '.' + topDomain(window.location.href);
// localhost cookies are special: http://curl.haxx.se/rfc/cookie_spec.html
if (domain === '.localhost') domain = '';
defaults(options, {
maxage: 31536000000, // default to a year
path: '/',
domain: domain
});
this._options = options;
};
/**
* Set a `key` and `value` in our cookie.
*
* @param {String} key
* @param {Object} value
* @return {Boolean} saved
*/
Cookie.prototype.set = function (key, value) {
try {
value = json.stringify(value);
cookie(key, value, clone(this._options));
return true;
} catch (e) {
return false;
}
};
/**
* Get a value from our cookie by `key`.
*
* @param {String} key
* @return {Object} value
*/
Cookie.prototype.get = function (key) {
try {
var value = cookie(key);
value = value ? json.parse(value) : null;
return value;
} catch (e) {
return null;
}
};
/**
* Remove a value from our cookie by `key`.
*
* @param {String} key
* @return {Boolean} removed
*/
Cookie.prototype.remove = function (key) {
try {
cookie(key, null, clone(this._options));
return true;
} catch (e) {
return false;
}
};
/**
* Expose the cookie singleton.
*/
module.exports = bind.all(new Cookie());
/**
* Expose the `Cookie` constructor.
*/
module.exports.Cookie = Cookie;
});
require.register("analytics/lib/entity.js", function(exports, require, module){
var traverse = require('isodate-traverse');
var defaults = require('defaults');
var cookie = require('./cookie');
var store = require('./store');
var extend = require('extend');
var clone = require('clone');
/**
* Expose `Entity`
*/
module.exports = Entity;
/**
* Initialize new `Entity` with `options`.
*
* @param {Object} options
*/
function Entity(options){
this.options(options);
}
/**
* Get or set storage `options`.
*
* @param {Object} options
* @property {Object} cookie
* @property {Object} localStorage
* @property {Boolean} persist (default: `true`)
*/
Entity.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options || (options = {});
defaults(options, this.defaults || {});
this._options = options;
};
/**
* Get or set the entity's `id`.
*
* @param {String} id
*/
Entity.prototype.id = function (id) {
switch (arguments.length) {
case 0: return this._getId();
case 1: return this._setId(id);
}
};
/**
* Get the entity's id.
*
* @return {String}
*/
Entity.prototype._getId = function () {
var ret = this._options.persist
? cookie.get(this._options.cookie.key)
: this._id;
return ret === undefined ? null : ret;
};
/**
* Set the entity's `id`.
*
* @param {String} id
*/
Entity.prototype._setId = function (id) {
if (this._options.persist) {
cookie.set(this._options.cookie.key, id);
} else {
this._id = id;
}
};
/**
* Get or set the entity's `traits`.
*
* BACKWARDS COMPATIBILITY: aliased to `properties`
*
* @param {Object} traits
*/
Entity.prototype.properties =
Entity.prototype.traits = function (traits) {
switch (arguments.length) {
case 0: return this._getTraits();
case 1: return this._setTraits(traits);
}
};
/**
* Get the entity's traits. Always convert ISO date strings into real dates,
* since they aren't parsed back from local storage.
*
* @return {Object}
*/
Entity.prototype._getTraits = function () {
var ret = this._options.persist
? store.get(this._options.localStorage.key)
: this._traits;
return ret ? traverse(clone(ret)) : {};
};
/**
* Set the entity's `traits`.
*
* @param {Object} traits
*/
Entity.prototype._setTraits = function (traits) {
traits || (traits = {});
if (this._options.persist) {
store.set(this._options.localStorage.key, traits);
} else {
this._traits = traits;
}
};
/**
* Identify the entity with an `id` and `traits`. If we it's the same entity,
* extend the existing `traits` instead of overwriting.
*
* @param {String} id
* @param {Object} traits
*/
Entity.prototype.identify = function (id, traits) {
traits || (traits = {});
var current = this.id();
if (current === null || current === id) traits = extend(this.traits(), traits);
if (id) this.id(id);
this.debug('identify %o, %o', id, traits);
this.traits(traits);
this.save();
};
/**
* Save the entity to local storage and the cookie.
*
* @return {Boolean}
*/
Entity.prototype.save = function () {
if (!this._options.persist) return false;
cookie.set(this._options.cookie.key, this.id());
store.set(this._options.localStorage.key, this.traits());
return true;
};
/**
* Log the entity out, reseting `id` and `traits` to defaults.
*/
Entity.prototype.logout = function () {
this.id(null);
this.traits({});
cookie.remove(this._options.cookie.key);
store.remove(this._options.localStorage.key);
};
/**
* Reset all entity state, logging out and returning options to defaults.
*/
Entity.prototype.reset = function () {
this.logout();
this.options({});
};
/**
* Load saved entity `id` or `traits` from storage.
*/
Entity.prototype.load = function () {
this.id(cookie.get(this._options.cookie.key));
this.traits(store.get(this._options.localStorage.key));
};
});
require.register("analytics/lib/group.js", function(exports, require, module){
var debug = require('debug')('analytics:group');
var Entity = require('./entity');
var inherit = require('inherit');
var bind = require('bind');
/**
* Group defaults
*/
Group.defaults = {
persist: true,
cookie: {
key: 'ajs_group_id'
},
localStorage: {
key: 'ajs_group_properties'
}
};
/**
* Initialize a new `Group` with `options`.
*
* @param {Object} options
*/
function Group (options) {
this.defaults = Group.defaults;
this.debug = debug;
Entity.call(this, options);
}
/**
* Inherit `Entity`
*/
inherit(Group, Entity);
/**
* Expose the group singleton.
*/
module.exports = bind.all(new Group());
/**
* Expose the `Group` constructor.
*/
module.exports.Group = Group;
});
require.register("analytics/lib/store.js", function(exports, require, module){
var bind = require('bind');
var defaults = require('defaults');
var store = require('store');
/**
* Initialize a new `Store` with `options`.
*
* @param {Object} options
*/
function Store (options) {
this.options(options);
}
/**
* Set the `options` for the store.
*
* @param {Object} options
* @field {Boolean} enabled (true)
*/
Store.prototype.options = function (options) {
if (arguments.length === 0) return this._options;
options = options || {};
defaults(options, { enabled : true });
this.enabled = options.enabled && store.enabled;
this._options = options;
};
/**
* Set a `key` and `value` in local storage.
*
* @param {String} key
* @param {Object} value
*/
Store.prototype.set = function (key, value) {
if (!this.enabled) return false;
return store.set(key, value);
};
/**
* Get a value from local storage by `key`.
*
* @param {String} key
* @return {Object}
*/
Store.prototype.get = function (key) {
if (!this.enabled) return null;
return store.get(key);
};
/**
* Remove a value from local storage by `key`.
*
* @param {String} key
*/
Store.prototype.remove = function (key) {
if (!this.enabled) return false;
return store.remove(key);
};
/**
* Expose the store singleton.
*/
module.exports = bind.all(new Store());
/**
* Expose the `Store` constructor.
*/
module.exports.Store = Store;
});
require.register("analytics/lib/user.js", function(exports, require, module){
var debug = require('debug')('analytics:user');
var Entity = require('./entity');
var inherit = require('inherit');
var bind = require('bind');
var cookie = require('./cookie');
/**
* User defaults
*/
User.defaults = {
persist: true,
cookie: {
key: 'ajs_user_id',
oldKey: 'ajs_user'
},
localStorage: {
key: 'ajs_user_traits'
}
};
/**
* Initialize a new `User` with `options`.
*
* @param {Object} options
*/
function User (options) {
this.defaults = User.defaults;
this.debug = debug;
Entity.call(this, options);
}
/**
* Inherit `Entity`
*/
inherit(User, Entity);
/**
* Load saved user `id` or `traits` from storage.
*/
User.prototype.load = function () {
if (this._loadOldCookie()) return;
Entity.prototype.load.call(this);
};
/**
* BACKWARDS COMPATIBILITY: Load the old user from the cookie.
*
* @return {Boolean}
* @api private
*/
User.prototype._loadOldCookie = function () {
var user = cookie.get(this._options.cookie.oldKey);
if (!user) return false;
this.id(user.id);
this.traits(user.traits);
cookie.remove(this._options.cookie.oldKey);
return true;
};
/**
* Expose the user singleton.
*/
module.exports = bind.all(new User());
/**
* Expose the `User` constructor.
*/
module.exports.User = User;
});
require.register("segmentio-analytics.js-integrations/lib/slugs.json", function(exports, require, module){
module.exports = [
"adroll",
"adwords",
"amplitude",
"awesm",
"awesomatic",
"bing-ads",
"bronto",
"bugherd",
"bugsnag",
"chartbeat",
"churnbee",
"clicktale",
"clicky",
"comscore",
"crazy-egg",
"curebit",
"customerio",
"drip",
"errorception",
"evergage",
"facebook-ads",
"foxmetrics",
"gauges",
"get-satisfaction",
"google-analytics",
"google-tag-manager",
"gosquared",
"heap",
"hittail",
"hubspot",
"improvely",
"inspectlet",
"intercom",
"keen-io",
"kissmetrics",
"klaviyo",
"leadlander",
"livechat",
"lucky-orange",
"lytics",
"mixpanel",
"mojn",
"mouseflow",
"mousestats",
"olark",
"optimizely",
"perfect-audience",
"pingdom",
"preact",
"qualaroo",
"quantcast",
"rollbar",
"saasquatch",
"sentry",
"snapengage",
"spinnakr",
"tapstream",
"trakio",
"twitter-ads",
"usercycle",
"userfox",
"uservoice",
"vero",
"visual-website-optimizer",
"webengage",
"woopra",
"yandex-metrica"
]
});
require.alias("avetisk-defaults/index.js", "analytics/deps/defaults/index.js");
require.alias("avetisk-defaults/index.js", "defaults/index.js");
require.alias("component-clone/index.js", "analytics/deps/clone/index.js");
require.alias("component-clone/index.js", "clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-cookie/index.js", "analytics/deps/cookie/index.js");
require.alias("component-cookie/index.js", "cookie/index.js");
require.alias("component-each/index.js", "analytics/deps/each/index.js");
require.alias("component-each/index.js", "each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("component-emitter/index.js", "analytics/deps/emitter/index.js");
require.alias("component-emitter/index.js", "emitter/index.js");
require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js");
require.alias("component-event/index.js", "analytics/deps/event/index.js");
require.alias("component-event/index.js", "event/index.js");
require.alias("component-inherit/index.js", "analytics/deps/inherit/index.js");
require.alias("component-inherit/index.js", "inherit/index.js");
require.alias("component-object/index.js", "analytics/deps/object/index.js");
require.alias("component-object/index.js", "object/index.js");
require.alias("component-querystring/index.js", "analytics/deps/querystring/index.js");
require.alias("component-querystring/index.js", "querystring/index.js");
require.alias("component-trim/index.js", "component-querystring/deps/trim/index.js");
require.alias("component-url/index.js", "analytics/deps/url/index.js");
require.alias("component-url/index.js", "url/index.js");
require.alias("ianstormtaylor-bind/index.js", "analytics/deps/bind/index.js");
require.alias("ianstormtaylor-bind/index.js", "bind/index.js");
require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js");
require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js");
require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js");
require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js");
require.alias("ianstormtaylor-callback/index.js", "analytics/deps/callback/index.js");
require.alias("ianstormtaylor-callback/index.js", "callback/index.js");
require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js");
require.alias("ianstormtaylor-is/index.js", "analytics/deps/is/index.js");
require.alias("ianstormtaylor-is/index.js", "is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-after/index.js", "analytics/deps/after/index.js");
require.alias("segmentio-after/index.js", "after/index.js");
require.alias("segmentio-analytics.js-integration/lib/index.js", "analytics/deps/integration/lib/index.js");
require.alias("segmentio-analytics.js-integration/lib/protos.js", "analytics/deps/integration/lib/protos.js");
require.alias("segmentio-analytics.js-integration/lib/events.js", "analytics/deps/integration/lib/events.js");
require.alias("segmentio-analytics.js-integration/lib/statics.js", "analytics/deps/integration/lib/statics.js");
require.alias("segmentio-analytics.js-integration/lib/index.js", "analytics/deps/integration/index.js");
require.alias("segmentio-analytics.js-integration/lib/index.js", "integration/index.js");
require.alias("avetisk-defaults/index.js", "segmentio-analytics.js-integration/deps/defaults/index.js");
require.alias("component-clone/index.js", "segmentio-analytics.js-integration/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-emitter/index.js", "segmentio-analytics.js-integration/deps/emitter/index.js");
require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js");
require.alias("ianstormtaylor-bind/index.js", "segmentio-analytics.js-integration/deps/bind/index.js");
require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js");
require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js");
require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js");
require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js");
require.alias("ianstormtaylor-callback/index.js", "segmentio-analytics.js-integration/deps/callback/index.js");
require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js");
require.alias("segmentio-after/index.js", "segmentio-analytics.js-integration/deps/after/index.js");
require.alias("timoxley-next-tick/index.js", "segmentio-analytics.js-integration/deps/next-tick/index.js");
require.alias("yields-slug/index.js", "segmentio-analytics.js-integration/deps/slug/index.js");
require.alias("visionmedia-debug/index.js", "segmentio-analytics.js-integration/deps/debug/index.js");
require.alias("visionmedia-debug/debug.js", "segmentio-analytics.js-integration/deps/debug/debug.js");
require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integration/index.js");
require.alias("segmentio-analytics.js-integrations/index.js", "analytics/deps/integrations/index.js");
require.alias("segmentio-analytics.js-integrations/lib/adroll.js", "analytics/deps/integrations/lib/adroll.js");
require.alias("segmentio-analytics.js-integrations/lib/adwords.js", "analytics/deps/integrations/lib/adwords.js");
require.alias("segmentio-analytics.js-integrations/lib/amplitude.js", "analytics/deps/integrations/lib/amplitude.js");
require.alias("segmentio-analytics.js-integrations/lib/awesm.js", "analytics/deps/integrations/lib/awesm.js");
require.alias("segmentio-analytics.js-integrations/lib/awesomatic.js", "analytics/deps/integrations/lib/awesomatic.js");
require.alias("segmentio-analytics.js-integrations/lib/bing-ads.js", "analytics/deps/integrations/lib/bing-ads.js");
require.alias("segmentio-analytics.js-integrations/lib/bronto.js", "analytics/deps/integrations/lib/bronto.js");
require.alias("segmentio-analytics.js-integrations/lib/bugherd.js", "analytics/deps/integrations/lib/bugherd.js");
require.alias("segmentio-analytics.js-integrations/lib/bugsnag.js", "analytics/deps/integrations/lib/bugsnag.js");
require.alias("segmentio-analytics.js-integrations/lib/chartbeat.js", "analytics/deps/integrations/lib/chartbeat.js");
require.alias("segmentio-analytics.js-integrations/lib/churnbee.js", "analytics/deps/integrations/lib/churnbee.js");
require.alias("segmentio-analytics.js-integrations/lib/clicktale.js", "analytics/deps/integrations/lib/clicktale.js");
require.alias("segmentio-analytics.js-integrations/lib/clicky.js", "analytics/deps/integrations/lib/clicky.js");
require.alias("segmentio-analytics.js-integrations/lib/comscore.js", "analytics/deps/integrations/lib/comscore.js");
require.alias("segmentio-analytics.js-integrations/lib/crazy-egg.js", "analytics/deps/integrations/lib/crazy-egg.js");
require.alias("segmentio-analytics.js-integrations/lib/curebit.js", "analytics/deps/integrations/lib/curebit.js");
require.alias("segmentio-analytics.js-integrations/lib/customerio.js", "analytics/deps/integrations/lib/customerio.js");
require.alias("segmentio-analytics.js-integrations/lib/drip.js", "analytics/deps/integrations/lib/drip.js");
require.alias("segmentio-analytics.js-integrations/lib/errorception.js", "analytics/deps/integrations/lib/errorception.js");
require.alias("segmentio-analytics.js-integrations/lib/evergage.js", "analytics/deps/integrations/lib/evergage.js");
require.alias("segmentio-analytics.js-integrations/lib/facebook-ads.js", "analytics/deps/integrations/lib/facebook-ads.js");
require.alias("segmentio-analytics.js-integrations/lib/foxmetrics.js", "analytics/deps/integrations/lib/foxmetrics.js");
require.alias("segmentio-analytics.js-integrations/lib/gauges.js", "analytics/deps/integrations/lib/gauges.js");
require.alias("segmentio-analytics.js-integrations/lib/get-satisfaction.js", "analytics/deps/integrations/lib/get-satisfaction.js");
require.alias("segmentio-analytics.js-integrations/lib/google-analytics.js", "analytics/deps/integrations/lib/google-analytics.js");
require.alias("segmentio-analytics.js-integrations/lib/google-tag-manager.js", "analytics/deps/integrations/lib/google-tag-manager.js");
require.alias("segmentio-analytics.js-integrations/lib/gosquared.js", "analytics/deps/integrations/lib/gosquared.js");
require.alias("segmentio-analytics.js-integrations/lib/heap.js", "analytics/deps/integrations/lib/heap.js");
require.alias("segmentio-analytics.js-integrations/lib/hittail.js", "analytics/deps/integrations/lib/hittail.js");
require.alias("segmentio-analytics.js-integrations/lib/hubspot.js", "analytics/deps/integrations/lib/hubspot.js");
require.alias("segmentio-analytics.js-integrations/lib/improvely.js", "analytics/deps/integrations/lib/improvely.js");
require.alias("segmentio-analytics.js-integrations/lib/inspectlet.js", "analytics/deps/integrations/lib/inspectlet.js");
require.alias("segmentio-analytics.js-integrations/lib/intercom.js", "analytics/deps/integrations/lib/intercom.js");
require.alias("segmentio-analytics.js-integrations/lib/keen-io.js", "analytics/deps/integrations/lib/keen-io.js");
require.alias("segmentio-analytics.js-integrations/lib/kissmetrics.js", "analytics/deps/integrations/lib/kissmetrics.js");
require.alias("segmentio-analytics.js-integrations/lib/klaviyo.js", "analytics/deps/integrations/lib/klaviyo.js");
require.alias("segmentio-analytics.js-integrations/lib/leadlander.js", "analytics/deps/integrations/lib/leadlander.js");
require.alias("segmentio-analytics.js-integrations/lib/livechat.js", "analytics/deps/integrations/lib/livechat.js");
require.alias("segmentio-analytics.js-integrations/lib/lucky-orange.js", "analytics/deps/integrations/lib/lucky-orange.js");
require.alias("segmentio-analytics.js-integrations/lib/lytics.js", "analytics/deps/integrations/lib/lytics.js");
require.alias("segmentio-analytics.js-integrations/lib/mixpanel.js", "analytics/deps/integrations/lib/mixpanel.js");
require.alias("segmentio-analytics.js-integrations/lib/mojn.js", "analytics/deps/integrations/lib/mojn.js");
require.alias("segmentio-analytics.js-integrations/lib/mouseflow.js", "analytics/deps/integrations/lib/mouseflow.js");
require.alias("segmentio-analytics.js-integrations/lib/mousestats.js", "analytics/deps/integrations/lib/mousestats.js");
require.alias("segmentio-analytics.js-integrations/lib/olark.js", "analytics/deps/integrations/lib/olark.js");
require.alias("segmentio-analytics.js-integrations/lib/optimizely.js", "analytics/deps/integrations/lib/optimizely.js");
require.alias("segmentio-analytics.js-integrations/lib/perfect-audience.js", "analytics/deps/integrations/lib/perfect-audience.js");
require.alias("segmentio-analytics.js-integrations/lib/pingdom.js", "analytics/deps/integrations/lib/pingdom.js");
require.alias("segmentio-analytics.js-integrations/lib/preact.js", "analytics/deps/integrations/lib/preact.js");
require.alias("segmentio-analytics.js-integrations/lib/qualaroo.js", "analytics/deps/integrations/lib/qualaroo.js");
require.alias("segmentio-analytics.js-integrations/lib/quantcast.js", "analytics/deps/integrations/lib/quantcast.js");
require.alias("segmentio-analytics.js-integrations/lib/rollbar.js", "analytics/deps/integrations/lib/rollbar.js");
require.alias("segmentio-analytics.js-integrations/lib/saasquatch.js", "analytics/deps/integrations/lib/saasquatch.js");
require.alias("segmentio-analytics.js-integrations/lib/sentry.js", "analytics/deps/integrations/lib/sentry.js");
require.alias("segmentio-analytics.js-integrations/lib/snapengage.js", "analytics/deps/integrations/lib/snapengage.js");
require.alias("segmentio-analytics.js-integrations/lib/spinnakr.js", "analytics/deps/integrations/lib/spinnakr.js");
require.alias("segmentio-analytics.js-integrations/lib/tapstream.js", "analytics/deps/integrations/lib/tapstream.js");
require.alias("segmentio-analytics.js-integrations/lib/trakio.js", "analytics/deps/integrations/lib/trakio.js");
require.alias("segmentio-analytics.js-integrations/lib/twitter-ads.js", "analytics/deps/integrations/lib/twitter-ads.js");
require.alias("segmentio-analytics.js-integrations/lib/usercycle.js", "analytics/deps/integrations/lib/usercycle.js");
require.alias("segmentio-analytics.js-integrations/lib/userfox.js", "analytics/deps/integrations/lib/userfox.js");
require.alias("segmentio-analytics.js-integrations/lib/uservoice.js", "analytics/deps/integrations/lib/uservoice.js");
require.alias("segmentio-analytics.js-integrations/lib/vero.js", "analytics/deps/integrations/lib/vero.js");
require.alias("segmentio-analytics.js-integrations/lib/visual-website-optimizer.js", "analytics/deps/integrations/lib/visual-website-optimizer.js");
require.alias("segmentio-analytics.js-integrations/lib/webengage.js", "analytics/deps/integrations/lib/webengage.js");
require.alias("segmentio-analytics.js-integrations/lib/woopra.js", "analytics/deps/integrations/lib/woopra.js");
require.alias("segmentio-analytics.js-integrations/lib/yandex-metrica.js", "analytics/deps/integrations/lib/yandex-metrica.js");
require.alias("segmentio-analytics.js-integrations/index.js", "integrations/index.js");
require.alias("component-clone/index.js", "segmentio-analytics.js-integrations/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-domify/index.js", "segmentio-analytics.js-integrations/deps/domify/index.js");
require.alias("component-each/index.js", "segmentio-analytics.js-integrations/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("component-once/index.js", "segmentio-analytics.js-integrations/deps/once/index.js");
require.alias("component-type/index.js", "segmentio-analytics.js-integrations/deps/type/index.js");
require.alias("component-url/index.js", "segmentio-analytics.js-integrations/deps/url/index.js");
require.alias("ianstormtaylor-callback/index.js", "segmentio-analytics.js-integrations/deps/callback/index.js");
require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js");
require.alias("ianstormtaylor-bind/index.js", "segmentio-analytics.js-integrations/deps/bind/index.js");
require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js");
require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js");
require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js");
require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-analytics.js-integrations/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-alias/index.js", "segmentio-analytics.js-integrations/deps/alias/index.js");
require.alias("component-clone/index.js", "segmentio-alias/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-type/index.js", "segmentio-alias/deps/type/index.js");
require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integrations/deps/integration/lib/index.js");
require.alias("segmentio-analytics.js-integration/lib/protos.js", "segmentio-analytics.js-integrations/deps/integration/lib/protos.js");
require.alias("segmentio-analytics.js-integration/lib/events.js", "segmentio-analytics.js-integrations/deps/integration/lib/events.js");
require.alias("segmentio-analytics.js-integration/lib/statics.js", "segmentio-analytics.js-integrations/deps/integration/lib/statics.js");
require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integrations/deps/integration/index.js");
require.alias("avetisk-defaults/index.js", "segmentio-analytics.js-integration/deps/defaults/index.js");
require.alias("component-clone/index.js", "segmentio-analytics.js-integration/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-emitter/index.js", "segmentio-analytics.js-integration/deps/emitter/index.js");
require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js");
require.alias("ianstormtaylor-bind/index.js", "segmentio-analytics.js-integration/deps/bind/index.js");
require.alias("component-bind/index.js", "ianstormtaylor-bind/deps/bind/index.js");
require.alias("segmentio-bind-all/index.js", "ianstormtaylor-bind/deps/bind-all/index.js");
require.alias("component-bind/index.js", "segmentio-bind-all/deps/bind/index.js");
require.alias("component-type/index.js", "segmentio-bind-all/deps/type/index.js");
require.alias("ianstormtaylor-callback/index.js", "segmentio-analytics.js-integration/deps/callback/index.js");
require.alias("timoxley-next-tick/index.js", "ianstormtaylor-callback/deps/next-tick/index.js");
require.alias("segmentio-after/index.js", "segmentio-analytics.js-integration/deps/after/index.js");
require.alias("timoxley-next-tick/index.js", "segmentio-analytics.js-integration/deps/next-tick/index.js");
require.alias("yields-slug/index.js", "segmentio-analytics.js-integration/deps/slug/index.js");
require.alias("visionmedia-debug/index.js", "segmentio-analytics.js-integration/deps/debug/index.js");
require.alias("visionmedia-debug/debug.js", "segmentio-analytics.js-integration/deps/debug/debug.js");
require.alias("segmentio-analytics.js-integration/lib/index.js", "segmentio-analytics.js-integration/index.js");
require.alias("segmentio-canonical/index.js", "segmentio-analytics.js-integrations/deps/canonical/index.js");
require.alias("segmentio-convert-dates/index.js", "segmentio-analytics.js-integrations/deps/convert-dates/index.js");
require.alias("component-clone/index.js", "segmentio-convert-dates/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-convert-dates/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-extend/index.js", "segmentio-analytics.js-integrations/deps/extend/index.js");
require.alias("segmentio-facade/lib/index.js", "segmentio-analytics.js-integrations/deps/facade/lib/index.js");
require.alias("segmentio-facade/lib/alias.js", "segmentio-analytics.js-integrations/deps/facade/lib/alias.js");
require.alias("segmentio-facade/lib/facade.js", "segmentio-analytics.js-integrations/deps/facade/lib/facade.js");
require.alias("segmentio-facade/lib/group.js", "segmentio-analytics.js-integrations/deps/facade/lib/group.js");
require.alias("segmentio-facade/lib/page.js", "segmentio-analytics.js-integrations/deps/facade/lib/page.js");
require.alias("segmentio-facade/lib/identify.js", "segmentio-analytics.js-integrations/deps/facade/lib/identify.js");
require.alias("segmentio-facade/lib/is-enabled.js", "segmentio-analytics.js-integrations/deps/facade/lib/is-enabled.js");
require.alias("segmentio-facade/lib/track.js", "segmentio-analytics.js-integrations/deps/facade/lib/track.js");
require.alias("segmentio-facade/lib/index.js", "segmentio-analytics.js-integrations/deps/facade/index.js");
require.alias("camshaft-require-component/index.js", "segmentio-facade/deps/require-component/index.js");
require.alias("segmentio-isodate-traverse/index.js", "segmentio-facade/deps/isodate-traverse/index.js");
require.alias("component-each/index.js", "segmentio-isodate-traverse/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-isodate-traverse/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-isodate-traverse/deps/isodate/index.js");
require.alias("component-clone/index.js", "segmentio-facade/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-inherit/index.js", "segmentio-facade/deps/inherit/index.js");
require.alias("component-trim/index.js", "segmentio-facade/deps/trim/index.js");
require.alias("segmentio-is-email/index.js", "segmentio-facade/deps/is-email/index.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/lib/index.js");
require.alias("segmentio-new-date/lib/milliseconds.js", "segmentio-facade/deps/new-date/lib/milliseconds.js");
require.alias("segmentio-new-date/lib/seconds.js", "segmentio-facade/deps/new-date/lib/seconds.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-new-date/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-new-date/deps/isodate/index.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-new-date/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/lib/index.js");
require.alias("ianstormtaylor-case/lib/cases.js", "segmentio-obj-case/deps/case/lib/cases.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/index.js");
require.alias("ianstormtaylor-to-camel-case/index.js", "ianstormtaylor-case/deps/to-camel-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-camel-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-constant-case/index.js", "ianstormtaylor-case/deps/to-constant-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-to-constant-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-dot-case/index.js", "ianstormtaylor-case/deps/to-dot-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-dot-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-pascal-case/index.js", "ianstormtaylor-case/deps/to-pascal-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-pascal-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-sentence-case/index.js", "ianstormtaylor-case/deps/to-sentence-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-sentence-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-slug-case/index.js", "ianstormtaylor-case/deps/to-slug-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-slug-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-title-case/index.js", "ianstormtaylor-case/deps/to-title-case/index.js");
require.alias("component-escape-regexp/index.js", "ianstormtaylor-to-title-case/deps/escape-regexp/index.js");
require.alias("ianstormtaylor-map/index.js", "ianstormtaylor-to-title-case/deps/map/index.js");
require.alias("component-each/index.js", "ianstormtaylor-map/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-title-case-minors/index.js", "ianstormtaylor-to-title-case/deps/title-case-minors/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-to-title-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "ianstormtaylor-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-obj-case/index.js");
require.alias("segmentio-facade/lib/index.js", "segmentio-facade/index.js");
require.alias("segmentio-global-queue/index.js", "segmentio-analytics.js-integrations/deps/global-queue/index.js");
require.alias("segmentio-is-email/index.js", "segmentio-analytics.js-integrations/deps/is-email/index.js");
require.alias("segmentio-load-date/index.js", "segmentio-analytics.js-integrations/deps/load-date/index.js");
require.alias("segmentio-load-script/index.js", "segmentio-analytics.js-integrations/deps/load-script/index.js");
require.alias("component-type/index.js", "segmentio-load-script/deps/type/index.js");
require.alias("segmentio-on-body/index.js", "segmentio-analytics.js-integrations/deps/on-body/index.js");
require.alias("component-each/index.js", "segmentio-on-body/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("segmentio-on-error/index.js", "segmentio-analytics.js-integrations/deps/on-error/index.js");
require.alias("segmentio-to-iso-string/index.js", "segmentio-analytics.js-integrations/deps/to-iso-string/index.js");
require.alias("segmentio-to-unix-timestamp/index.js", "segmentio-analytics.js-integrations/deps/to-unix-timestamp/index.js");
require.alias("segmentio-use-https/index.js", "segmentio-analytics.js-integrations/deps/use-https/index.js");
require.alias("timoxley-next-tick/index.js", "segmentio-analytics.js-integrations/deps/next-tick/index.js");
require.alias("yields-slug/index.js", "segmentio-analytics.js-integrations/deps/slug/index.js");
require.alias("visionmedia-batch/index.js", "segmentio-analytics.js-integrations/deps/batch/index.js");
require.alias("component-emitter/index.js", "visionmedia-batch/deps/emitter/index.js");
require.alias("component-indexof/index.js", "component-emitter/deps/indexof/index.js");
require.alias("visionmedia-debug/index.js", "segmentio-analytics.js-integrations/deps/debug/index.js");
require.alias("visionmedia-debug/debug.js", "segmentio-analytics.js-integrations/deps/debug/debug.js");
require.alias("segmentio-load-pixel/index.js", "segmentio-analytics.js-integrations/deps/load-pixel/index.js");
require.alias("segmentio-load-pixel/index.js", "segmentio-analytics.js-integrations/deps/load-pixel/index.js");
require.alias("component-querystring/index.js", "segmentio-load-pixel/deps/querystring/index.js");
require.alias("component-trim/index.js", "component-querystring/deps/trim/index.js");
require.alias("segmentio-substitute/index.js", "segmentio-load-pixel/deps/substitute/index.js");
require.alias("segmentio-substitute/index.js", "segmentio-load-pixel/deps/substitute/index.js");
require.alias("segmentio-substitute/index.js", "segmentio-substitute/index.js");
require.alias("segmentio-load-pixel/index.js", "segmentio-load-pixel/index.js");
require.alias("segmentio-canonical/index.js", "analytics/deps/canonical/index.js");
require.alias("segmentio-canonical/index.js", "canonical/index.js");
require.alias("segmentio-extend/index.js", "analytics/deps/extend/index.js");
require.alias("segmentio-extend/index.js", "extend/index.js");
require.alias("segmentio-facade/lib/index.js", "analytics/deps/facade/lib/index.js");
require.alias("segmentio-facade/lib/alias.js", "analytics/deps/facade/lib/alias.js");
require.alias("segmentio-facade/lib/facade.js", "analytics/deps/facade/lib/facade.js");
require.alias("segmentio-facade/lib/group.js", "analytics/deps/facade/lib/group.js");
require.alias("segmentio-facade/lib/page.js", "analytics/deps/facade/lib/page.js");
require.alias("segmentio-facade/lib/identify.js", "analytics/deps/facade/lib/identify.js");
require.alias("segmentio-facade/lib/is-enabled.js", "analytics/deps/facade/lib/is-enabled.js");
require.alias("segmentio-facade/lib/track.js", "analytics/deps/facade/lib/track.js");
require.alias("segmentio-facade/lib/index.js", "analytics/deps/facade/index.js");
require.alias("segmentio-facade/lib/index.js", "facade/index.js");
require.alias("camshaft-require-component/index.js", "segmentio-facade/deps/require-component/index.js");
require.alias("segmentio-isodate-traverse/index.js", "segmentio-facade/deps/isodate-traverse/index.js");
require.alias("component-each/index.js", "segmentio-isodate-traverse/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-isodate-traverse/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-isodate-traverse/deps/isodate/index.js");
require.alias("component-clone/index.js", "segmentio-facade/deps/clone/index.js");
require.alias("component-type/index.js", "component-clone/deps/type/index.js");
require.alias("component-inherit/index.js", "segmentio-facade/deps/inherit/index.js");
require.alias("component-trim/index.js", "segmentio-facade/deps/trim/index.js");
require.alias("segmentio-is-email/index.js", "segmentio-facade/deps/is-email/index.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/lib/index.js");
require.alias("segmentio-new-date/lib/milliseconds.js", "segmentio-facade/deps/new-date/lib/milliseconds.js");
require.alias("segmentio-new-date/lib/seconds.js", "segmentio-facade/deps/new-date/lib/seconds.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-facade/deps/new-date/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-new-date/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-new-date/deps/isodate/index.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-new-date/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-facade/deps/obj-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/lib/index.js");
require.alias("ianstormtaylor-case/lib/cases.js", "segmentio-obj-case/deps/case/lib/cases.js");
require.alias("ianstormtaylor-case/lib/index.js", "segmentio-obj-case/deps/case/index.js");
require.alias("ianstormtaylor-to-camel-case/index.js", "ianstormtaylor-case/deps/to-camel-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-camel-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-constant-case/index.js", "ianstormtaylor-case/deps/to-constant-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-to-constant-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-dot-case/index.js", "ianstormtaylor-case/deps/to-dot-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-dot-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-pascal-case/index.js", "ianstormtaylor-case/deps/to-pascal-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-pascal-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-sentence-case/index.js", "ianstormtaylor-case/deps/to-sentence-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-sentence-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-slug-case/index.js", "ianstormtaylor-case/deps/to-slug-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-slug-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-snake-case/index.js", "ianstormtaylor-case/deps/to-snake-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-to-snake-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-space-case/index.js", "ianstormtaylor-case/deps/to-space-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-space-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-to-title-case/index.js", "ianstormtaylor-case/deps/to-title-case/index.js");
require.alias("component-escape-regexp/index.js", "ianstormtaylor-to-title-case/deps/escape-regexp/index.js");
require.alias("ianstormtaylor-map/index.js", "ianstormtaylor-to-title-case/deps/map/index.js");
require.alias("component-each/index.js", "ianstormtaylor-map/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-title-case-minors/index.js", "ianstormtaylor-to-title-case/deps/title-case-minors/index.js");
require.alias("ianstormtaylor-to-capital-case/index.js", "ianstormtaylor-to-title-case/deps/to-capital-case/index.js");
require.alias("ianstormtaylor-to-no-case/index.js", "ianstormtaylor-to-capital-case/deps/to-no-case/index.js");
require.alias("ianstormtaylor-case/lib/index.js", "ianstormtaylor-case/index.js");
require.alias("segmentio-obj-case/index.js", "segmentio-obj-case/index.js");
require.alias("segmentio-facade/lib/index.js", "segmentio-facade/index.js");
require.alias("segmentio-is-email/index.js", "analytics/deps/is-email/index.js");
require.alias("segmentio-is-email/index.js", "is-email/index.js");
require.alias("segmentio-is-meta/index.js", "analytics/deps/is-meta/index.js");
require.alias("segmentio-is-meta/index.js", "is-meta/index.js");
require.alias("segmentio-isodate-traverse/index.js", "analytics/deps/isodate-traverse/index.js");
require.alias("segmentio-isodate-traverse/index.js", "isodate-traverse/index.js");
require.alias("component-each/index.js", "segmentio-isodate-traverse/deps/each/index.js");
require.alias("component-type/index.js", "component-each/deps/type/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-isodate-traverse/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-isodate-traverse/deps/isodate/index.js");
require.alias("segmentio-json/index.js", "analytics/deps/json/index.js");
require.alias("segmentio-json/index.js", "json/index.js");
require.alias("component-json-fallback/index.js", "segmentio-json/deps/json-fallback/index.js");
require.alias("segmentio-new-date/lib/index.js", "analytics/deps/new-date/lib/index.js");
require.alias("segmentio-new-date/lib/milliseconds.js", "analytics/deps/new-date/lib/milliseconds.js");
require.alias("segmentio-new-date/lib/seconds.js", "analytics/deps/new-date/lib/seconds.js");
require.alias("segmentio-new-date/lib/index.js", "analytics/deps/new-date/index.js");
require.alias("segmentio-new-date/lib/index.js", "new-date/index.js");
require.alias("ianstormtaylor-is/index.js", "segmentio-new-date/deps/is/index.js");
require.alias("component-type/index.js", "ianstormtaylor-is/deps/type/index.js");
require.alias("ianstormtaylor-is-empty/index.js", "ianstormtaylor-is/deps/is-empty/index.js");
require.alias("segmentio-isodate/index.js", "segmentio-new-date/deps/isodate/index.js");
require.alias("segmentio-new-date/lib/index.js", "segmentio-new-date/index.js");
require.alias("segmentio-store.js/store.js", "analytics/deps/store/store.js");
require.alias("segmentio-store.js/store.js", "analytics/deps/store/index.js");
require.alias("segmentio-store.js/store.js", "store/index.js");
require.alias("segmentio-store.js/store.js", "segmentio-store.js/index.js");
require.alias("segmentio-top-domain/index.js", "analytics/deps/top-domain/index.js");
require.alias("segmentio-top-domain/index.js", "analytics/deps/top-domain/index.js");
require.alias("segmentio-top-domain/index.js", "top-domain/index.js");
require.alias("component-url/index.js", "segmentio-top-domain/deps/url/index.js");
require.alias("segmentio-top-domain/index.js", "segmentio-top-domain/index.js");
require.alias("visionmedia-debug/index.js", "analytics/deps/debug/index.js");
require.alias("visionmedia-debug/debug.js", "analytics/deps/debug/debug.js");
require.alias("visionmedia-debug/index.js", "debug/index.js");
require.alias("yields-prevent/index.js", "analytics/deps/prevent/index.js");
require.alias("yields-prevent/index.js", "prevent/index.js");
require.alias("analytics/lib/index.js", "analytics/index.js");if (typeof exports == "object") {
module.exports = require("analytics");
} else if (typeof define == "function" && define.amd) {
define([], function(){ return require("analytics"); });
} else {
this["analytics"] = require("analytics");
}})(); |
packages/react-scripts/fixtures/kitchensink/src/features/syntax/Generators.js | paweljedrzejczyk/create-react-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, { Component } from 'react';
import PropTypes from 'prop-types';
function* load(limit) {
let i = 1;
while (i <= limit) {
yield { id: i, name: i };
i++;
}
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
componentDidMount() {
const users = [];
for (let user of load(4)) {
users.push(user);
}
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-generators">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
ajax/libs/yasr/2.3.1/yasr.bundled.min.js | zimbatm/cdnjs | !function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.YASR=t()}}(function(){var t;return function e(t,n,r){function i(a,s){if(!n[a]){if(!t[a]){var l="function"==typeof require&&require;if(!s&&l)return l(a,!0);if(o)return o(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return i(n?n:e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;a<r.length;a++)i(r[a]);return i}({1:[function(t,e){e.exports=t("./main.js")},{"./main.js":32}],2:[function(e,n,r){(function(n,i,o){(function(n){"use strict";"function"==typeof t&&t.amd?t("datatables",["jquery"],n):"object"==typeof r?n(e("jquery")):jQuery&&!jQuery.fn.dataTable&&n(jQuery)})(function(t){"use strict";function e(n){var r,i,o="a aa ai ao as b fn i m o s ",a={};t.each(n,function(t){r=t.match(/^([^A-Z]+?)([A-Z])/);if(r&&-1!==o.indexOf(r[1]+" ")){i=t.replace(r[0],r[2].toLowerCase());a[i]=t;"o"===r[1]&&e(n[t])}});n._hungarianMap=a}function r(n,i,a){n._hungarianMap||e(n);var s;t.each(i,function(e){s=n._hungarianMap[e];if(s!==o&&(a||i[s]===o))if("o"===s.charAt(0)){i[s]||(i[s]={});t.extend(!0,i[s],i[e]);r(n[s],i[s],a)}else i[s]=i[e]})}function a(t){var e=$e.defaults.oLanguage,n=t.sZeroRecords;!t.sEmptyTable&&n&&"No data available in table"===e.sEmptyTable&&Oe(t,t,"sZeroRecords","sEmptyTable");!t.sLoadingRecords&&n&&"Loading..."===e.sLoadingRecords&&Oe(t,t,"sZeroRecords","sLoadingRecords");t.sInfoThousands&&(t.sThousands=t.sInfoThousands);var r=t.sDecimal;r&&Xe(r)}function s(t){yn(t,"ordering","bSort");yn(t,"orderMulti","bSortMulti");yn(t,"orderClasses","bSortClasses");yn(t,"orderCellsTop","bSortCellsTop");yn(t,"order","aaSorting");yn(t,"orderFixed","aaSortingFixed");yn(t,"paging","bPaginate");yn(t,"pagingType","sPaginationType");yn(t,"pageLength","iDisplayLength");yn(t,"searching","bFilter");var e=t.aoSearchCols;if(e)for(var n=0,i=e.length;i>n;n++)e[n]&&r($e.models.oSearch,e[n])}function l(t){yn(t,"orderable","bSortable");yn(t,"orderData","aDataSort");yn(t,"orderSequence","asSorting");yn(t,"orderDataType","sortDataType")}function u(e){var n=e.oBrowser,r=t("<div/>").css({position:"absolute",top:0,left:0,height:1,width:1,overflow:"hidden"}).append(t("<div/>").css({position:"absolute",top:1,left:1,width:100,overflow:"scroll"}).append(t('<div class="test"/>').css({width:"100%",height:10}))).appendTo("body"),i=r.find(".test");n.bScrollOversize=100===i[0].offsetWidth;n.bScrollbarLeft=1!==i.offset().left;r.remove()}function c(t,e,n,r,i,a){var s,l=r,u=!1;if(n!==o){s=n;u=!0}for(;l!==i;)if(t.hasOwnProperty(l)){s=u?e(s,t[l],l,t):t[l];u=!0;l+=a}return s}function f(e,n){var r=$e.defaults.column,o=e.aoColumns.length,a=t.extend({},$e.models.oColumn,r,{nTh:n?n:i.createElement("th"),sTitle:r.sTitle?r.sTitle:n?n.innerHTML:"",aDataSort:r.aDataSort?r.aDataSort:[o],mData:r.mData?r.mData:o,idx:o});e.aoColumns.push(a);var s=e.aoPreSearchCols;s[o]=t.extend({},$e.models.oSearch,s[o]);h(e,o,null)}function h(e,n,i){var a=e.aoColumns[n],s=e.oClasses,u=t(a.nTh);if(!a.sWidthOrig){a.sWidthOrig=u.attr("width")||null;var c=(u.attr("style")||"").match(/width:\s*(\d+[pxem%]+)/);c&&(a.sWidthOrig=c[1])}if(i!==o&&null!==i){l(i);r($e.defaults.column,i);i.mDataProp===o||i.mData||(i.mData=i.mDataProp);i.sType&&(a._sManualType=i.sType);i.className&&!i.sClass&&(i.sClass=i.className);t.extend(a,i);Oe(a,i,"sWidth","sWidthOrig");"number"==typeof i.iDataSort&&(a.aDataSort=[i.iDataSort]);Oe(a,i,"aDataSort")}var f=a.mData,h=M(f),d=a.mRender?M(a.mRender):null,p=function(t){return"string"==typeof t&&-1!==t.indexOf("@")};a._bAttrSrc=t.isPlainObject(f)&&(p(f.sort)||p(f.type)||p(f.filter));a.fnGetData=function(t,e,n){var r=h(t,e,o,n);return d&&e?d(r,e,t,n):r};a.fnSetData=function(t,e,n){return D(f)(t,e,n)};if(!e.oFeatures.bSort){a.bSortable=!1;u.addClass(s.sSortableNone)}var g=-1!==t.inArray("asc",a.asSorting),m=-1!==t.inArray("desc",a.asSorting);if(a.bSortable&&(g||m))if(g&&!m){a.sSortingClass=s.sSortableAsc;a.sSortingClassJUI=s.sSortJUIAscAllowed}else if(!g&&m){a.sSortingClass=s.sSortableDesc;a.sSortingClassJUI=s.sSortJUIDescAllowed}else{a.sSortingClass=s.sSortable;a.sSortingClassJUI=s.sSortJUI}else{a.sSortingClass=s.sSortableNone;a.sSortingClassJUI=""}}function d(t){if(t.oFeatures.bAutoWidth!==!1){var e=t.aoColumns;ye(t);for(var n=0,r=e.length;r>n;n++)e[n].nTh.style.width=e[n].sWidth}var i=t.oScroll;(""!==i.sY||""!==i.sX)&&me(t);ze(t,null,"column-sizing",[t])}function p(t,e){var n=v(t,"bVisible");return"number"==typeof n[e]?n[e]:null}function g(e,n){var r=v(e,"bVisible"),i=t.inArray(n,r);return-1!==i?i:null}function m(t){return v(t,"bVisible").length}function v(e,n){var r=[];t.map(e.aoColumns,function(t,e){t[n]&&r.push(e)});return r}function y(t){var e,n,r,i,a,s,l,u,c,f=t.aoColumns,h=t.aoData,d=$e.ext.type.detect;for(e=0,n=f.length;n>e;e++){l=f[e];c=[];if(!l.sType&&l._sManualType)l.sType=l._sManualType;else if(!l.sType){for(r=0,i=d.length;i>r;r++){for(a=0,s=h.length;s>a;a++){c[a]===o&&(c[a]=T(t,a,e,"type"));u=d[r](c[a],t);if(!u||"html"===u)break}if(u){l.sType=u;break}}l.sType||(l.sType="string")}}}function b(e,n,r,i){var a,s,l,u,c,h,d,p=e.aoColumns;if(n)for(a=n.length-1;a>=0;a--){d=n[a];var g=d.targets!==o?d.targets:d.aTargets;t.isArray(g)||(g=[g]);for(l=0,u=g.length;u>l;l++)if("number"==typeof g[l]&&g[l]>=0){for(;p.length<=g[l];)f(e);i(g[l],d)}else if("number"==typeof g[l]&&g[l]<0)i(p.length+g[l],d);else if("string"==typeof g[l])for(c=0,h=p.length;h>c;c++)("_all"==g[l]||t(p[c].nTh).hasClass(g[l]))&&i(c,d)}if(r)for(a=0,s=r.length;s>a;a++)i(a,r[a])}function x(e,n,r,i){var o=e.aoData.length,a=t.extend(!0,{},$e.models.oRow,{src:r?"dom":"data"});a._aData=n;e.aoData.push(a);for(var s=e.aoColumns,l=0,u=s.length;u>l;l++){r&&_(e,o,l,T(e,o,l));s[l].sType=null}e.aiDisplayMaster.push(o);(r||!e.oFeatures.bDeferRender)&&I(e,o,r,i);return o}function w(e,n){var r;n instanceof t||(n=t(n));return n.map(function(t,n){r=j(e,n);return x(e,r.data,n,r.cells)})}function S(t,e){return e._DT_RowIndex!==o?e._DT_RowIndex:null}function C(e,n,r){return t.inArray(r,e.aoData[n].anCells)}function T(t,e,n,r){var i=t.iDraw,a=t.aoColumns[n],s=t.aoData[e]._aData,l=a.sDefaultContent,u=a.fnGetData(s,r,{settings:t,row:e,col:n});if(u===o){if(t.iDrawError!=i&&null===l){He(t,0,"Requested unknown parameter "+("function"==typeof a.mData?"{function}":"'"+a.mData+"'")+" for row "+e,4);t.iDrawError=i}return l}if(u!==s&&null!==u||null===l){if("function"==typeof u)return u.call(s)}else u=l;return null===u&&"display"==r?"":u}function _(t,e,n,r){var i=t.aoColumns[n],o=t.aoData[e]._aData;i.fnSetData(o,r,{settings:t,row:e,col:n})}function k(e){return t.map(e.match(/(\\.|[^\.])+/g),function(t){return t.replace(/\\./g,".")})}function M(e){if(t.isPlainObject(e)){var n={};t.each(e,function(t,e){e&&(n[t]=M(e))});return function(t,e,r,i){var a=n[e]||n._;return a!==o?a(t,e,r,i):t}}if(null===e)return function(t){return t};if("function"==typeof e)return function(t,n,r,i){return e(t,n,r,i)};if("string"!=typeof e||-1===e.indexOf(".")&&-1===e.indexOf("[")&&-1===e.indexOf("("))return function(t){return t[e]};var r=function(t,e,n){var i,a,s,l;if(""!==n)for(var u=k(n),c=0,f=u.length;f>c;c++){i=u[c].match(bn);a=u[c].match(xn);if(i){u[c]=u[c].replace(bn,"");""!==u[c]&&(t=t[u[c]]);s=[];u.splice(0,c+1);l=u.join(".");for(var h=0,d=t.length;d>h;h++)s.push(r(t[h],e,l));var p=i[0].substring(1,i[0].length-1);t=""===p?s:s.join(p);break}if(a){u[c]=u[c].replace(xn,"");t=t[u[c]]()}else{if(null===t||t[u[c]]===o)return o;t=t[u[c]]}}return t};return function(t,n){return r(t,n,e)}}function D(e){if(t.isPlainObject(e))return D(e._);if(null===e)return function(){};if("function"==typeof e)return function(t,n,r){e(t,"set",n,r)};if("string"!=typeof e||-1===e.indexOf(".")&&-1===e.indexOf("[")&&-1===e.indexOf("("))return function(t,n){t[e]=n};var n=function(t,e,r){for(var i,a,s,l,u,c=k(r),f=c[c.length-1],h=0,d=c.length-1;d>h;h++){a=c[h].match(bn);s=c[h].match(xn);if(a){c[h]=c[h].replace(bn,"");t[c[h]]=[];i=c.slice();i.splice(0,h+1);u=i.join(".");for(var p=0,g=e.length;g>p;p++){l={};n(l,e[p],u);t[c[h]].push(l)}return}if(s){c[h]=c[h].replace(xn,"");t=t[c[h]](e)}(null===t[c[h]]||t[c[h]]===o)&&(t[c[h]]={});t=t[c[h]]}f.match(xn)?t=t[f.replace(xn,"")](e):t[f.replace(bn,"")]=e};return function(t,r){return n(t,r,e)}}function L(t){return dn(t.aoData,"_aData")}function A(t){t.aoData.length=0;t.aiDisplayMaster.length=0;t.aiDisplay.length=0}function N(t,e,n){for(var r=-1,i=0,a=t.length;a>i;i++)t[i]==e?r=i:t[i]>e&&t[i]--;-1!=r&&n===o&&t.splice(r,1)}function E(t,e,n,r){var i,a,s=t.aoData[e];if("dom"!==n&&(n&&"auto"!==n||"dom"!==s.src)){var l,u=s.anCells;if(u)for(i=0,a=u.length;a>i;i++){l=u[i];for(;l.childNodes.length;)l.removeChild(l.firstChild);u[i].innerHTML=T(t,e,i,"display")}}else s._aData=j(t,s).data;s._aSortData=null;s._aFilterData=null;var c=t.aoColumns;if(r!==o)c[r].sType=null;else for(i=0,a=c.length;a>i;i++)c[i].sType=null;P(s)}function j(e,n){var r,i,o,a,s=[],l=[],u=n.firstChild,c=0,f=e.aoColumns,h=function(t,e,n){if("string"==typeof t){var r=t.indexOf("@");if(-1!==r){var i=t.substring(r+1);o["@"+i]=n.getAttribute(i)}}},d=function(e){i=f[c];a=t.trim(e.innerHTML);if(i&&i._bAttrSrc){o={display:a};h(i.mData.sort,o,e);h(i.mData.type,o,e);h(i.mData.filter,o,e);s.push(o)}else s.push(a);c++};if(u)for(;u;){r=u.nodeName.toUpperCase();if("TD"==r||"TH"==r){d(u);l.push(u)}u=u.nextSibling}else{l=n.anCells;for(var p=0,g=l.length;g>p;p++)d(l[p])}return{data:s,cells:l}}function I(t,e,n,r){var o,a,s,l,u,c=t.aoData[e],f=c._aData,h=[];if(null===c.nTr){o=n||i.createElement("tr");c.nTr=o;c.anCells=h;o._DT_RowIndex=e;P(c);for(l=0,u=t.aoColumns.length;u>l;l++){s=t.aoColumns[l];a=n?r[l]:i.createElement(s.sCellType);h.push(a);(!n||s.mRender||s.mData!==l)&&(a.innerHTML=T(t,e,l,"display"));s.sClass&&(a.className+=" "+s.sClass);s.bVisible&&!n?o.appendChild(a):!s.bVisible&&n&&a.parentNode.removeChild(a);s.fnCreatedCell&&s.fnCreatedCell.call(t.oInstance,a,T(t,e,l),f,e,l)}ze(t,"aoRowCreatedCallback",null,[o,f,e])}c.nTr.setAttribute("role","row")}function P(e){var n=e.nTr,r=e._aData;if(n){r.DT_RowId&&(n.id=r.DT_RowId);if(r.DT_RowClass){var i=r.DT_RowClass.split(" ");e.__rowc=e.__rowc?vn(e.__rowc.concat(i)):i;t(n).removeClass(e.__rowc.join(" ")).addClass(r.DT_RowClass)}r.DT_RowData&&t(n).data(r.DT_RowData)}}function H(e){var n,r,i,o,a,s=e.nTHead,l=e.nTFoot,u=0===t("th, td",s).length,c=e.oClasses,f=e.aoColumns;u&&(o=t("<tr/>").appendTo(s));for(n=0,r=f.length;r>n;n++){a=f[n];i=t(a.nTh).addClass(a.sClass);u&&i.appendTo(o);if(e.oFeatures.bSort){i.addClass(a.sSortingClass);if(a.bSortable!==!1){i.attr("tabindex",e.iTabIndex).attr("aria-controls",e.sTableId);Ae(e,a.nTh,n)}}a.sTitle!=i.html()&&i.html(a.sTitle);Ue(e,"header")(e,i,a,c)}u&&z(e.aoHeader,s);t(s).find(">tr").attr("role","row");t(s).find(">tr>th, >tr>td").addClass(c.sHeaderTH);t(l).find(">tr>th, >tr>td").addClass(c.sFooterTH);if(null!==l){var h=e.aoFooter[0];for(n=0,r=h.length;r>n;n++){a=f[n];a.nTf=h[n].cell;a.sClass&&t(a.nTf).addClass(a.sClass)}}}function O(e,n,r){var i,a,s,l,u,c,f,h,d,p=[],g=[],m=e.aoColumns.length;if(n){r===o&&(r=!1);for(i=0,a=n.length;a>i;i++){p[i]=n[i].slice();p[i].nTr=n[i].nTr;for(s=m-1;s>=0;s--)e.aoColumns[s].bVisible||r||p[i].splice(s,1);g.push([])}for(i=0,a=p.length;a>i;i++){f=p[i].nTr;if(f)for(;c=f.firstChild;)f.removeChild(c);for(s=0,l=p[i].length;l>s;s++){h=1;d=1;if(g[i][s]===o){f.appendChild(p[i][s].cell);g[i][s]=1;for(;p[i+h]!==o&&p[i][s].cell==p[i+h][s].cell;){g[i+h][s]=1;h++}for(;p[i][s+d]!==o&&p[i][s].cell==p[i][s+d].cell;){for(u=0;h>u;u++)g[i+u][s+d]=1;d++}t(p[i][s].cell).attr("rowspan",h).attr("colspan",d)}}}}}function F(e){var n=ze(e,"aoPreDrawCallback","preDraw",[e]);if(-1===t.inArray(!1,n)){var r=[],i=0,a=e.asStripeClasses,s=a.length,l=(e.aoOpenRows.length,e.oLanguage),u=e.iInitDisplayStart,c="ssp"==Be(e),f=e.aiDisplay;e.bDrawing=!0;if(u!==o&&-1!==u){e._iDisplayStart=c?u:u>=e.fnRecordsDisplay()?0:u;e.iInitDisplayStart=-1}var h=e._iDisplayStart,d=e.fnDisplayEnd();if(e.bDeferLoading){e.bDeferLoading=!1;e.iDraw++;pe(e,!1)}else if(c){if(!e.bDestroying&&!B(e))return}else e.iDraw++;if(0!==f.length)for(var p=c?0:h,g=c?e.aoData.length:d,v=p;g>v;v++){var y=f[v],b=e.aoData[y];null===b.nTr&&I(e,y);var x=b.nTr;if(0!==s){var w=a[i%s];if(b._sRowStripe!=w){t(x).removeClass(b._sRowStripe).addClass(w);b._sRowStripe=w}}ze(e,"aoRowCallback",null,[x,b._aData,i,v]);r.push(x);i++}else{var S=l.sZeroRecords;1==e.iDraw&&"ajax"==Be(e)?S=l.sLoadingRecords:l.sEmptyTable&&0===e.fnRecordsTotal()&&(S=l.sEmptyTable);r[0]=t("<tr/>",{"class":s?a[0]:""}).append(t("<td />",{valign:"top",colSpan:m(e),"class":e.oClasses.sRowEmpty}).html(S))[0]}ze(e,"aoHeaderCallback","header",[t(e.nTHead).children("tr")[0],L(e),h,d,f]);ze(e,"aoFooterCallback","footer",[t(e.nTFoot).children("tr")[0],L(e),h,d,f]);var C=t(e.nTBody);C.children().detach();C.append(t(r));ze(e,"aoDrawCallback","draw",[e]);e.bSorted=!1;e.bFiltered=!1;e.bDrawing=!1}else pe(e,!1)}function R(t,e){var n=t.oFeatures,r=n.bSort,i=n.bFilter;r&&Me(t);i?Y(t,t.oPreviousSearch):t.aiDisplay=t.aiDisplayMaster.slice();e!==!0&&(t._iDisplayStart=0);t._drawHold=e;F(t);t._drawHold=!1}function W(e){var n=e.oClasses,r=t(e.nTable),i=t("<div/>").insertBefore(r),o=e.oFeatures,a=t("<div/>",{id:e.sTableId+"_wrapper","class":n.sWrapper+(e.nTFoot?"":" "+n.sNoFooter)});e.nHolding=i[0];e.nTableWrapper=a[0];e.nTableReinsertBefore=e.nTable.nextSibling;for(var s,l,u,c,f,h,d=e.sDom.split(""),p=0;p<d.length;p++){s=null;l=d[p];if("<"==l){u=t("<div/>")[0];c=d[p+1];if("'"==c||'"'==c){f="";h=2;for(;d[p+h]!=c;){f+=d[p+h];h++}"H"==f?f=n.sJUIHeader:"F"==f&&(f=n.sJUIFooter);if(-1!=f.indexOf(".")){var g=f.split(".");u.id=g[0].substr(1,g[0].length-1);u.className=g[1]}else"#"==f.charAt(0)?u.id=f.substr(1,f.length-1):u.className=f;p+=h}a.append(u);a=t(u)}else if(">"==l)a=a.parent();else if("l"==l&&o.bPaginate&&o.bLengthChange)s=ce(e);else if("f"==l&&o.bFilter)s=$(e);else if("r"==l&&o.bProcessing)s=de(e);else if("t"==l)s=ge(e);else if("i"==l&&o.bInfo)s=ie(e);else if("p"==l&&o.bPaginate)s=fe(e);else if(0!==$e.ext.feature.length)for(var m=$e.ext.feature,v=0,y=m.length;y>v;v++)if(l==m[v].cFeature){s=m[v].fnInit(e);break}if(s){var b=e.aanFeatures;b[l]||(b[l]=[]);b[l].push(s);a.append(s)}}i.replaceWith(a)}function z(e,n){var r,i,o,a,s,l,u,c,f,h,d,p=t(n).children("tr"),g=function(t,e,n){for(var r=t[e];r[n];)n++;return n};e.splice(0,e.length);for(o=0,l=p.length;l>o;o++)e.push([]);for(o=0,l=p.length;l>o;o++){r=p[o];c=0;i=r.firstChild;for(;i;){if("TD"==i.nodeName.toUpperCase()||"TH"==i.nodeName.toUpperCase()){f=1*i.getAttribute("colspan");h=1*i.getAttribute("rowspan");f=f&&0!==f&&1!==f?f:1;h=h&&0!==h&&1!==h?h:1;u=g(e,o,c);d=1===f?!0:!1;for(s=0;f>s;s++)for(a=0;h>a;a++){e[o+a][u+s]={cell:i,unique:d};e[o+a].nTr=r}}i=i.nextSibling}}}function q(t,e,n){var r=[];if(!n){n=t.aoHeader;if(e){n=[];z(n,e)}}for(var i=0,o=n.length;o>i;i++)for(var a=0,s=n[i].length;s>a;a++)!n[i][a].unique||r[a]&&t.bSortCellsTop||(r[a]=n[i][a].cell);return r}function U(e,n,r){ze(e,"aoServerParams","serverParams",[n]);if(n&&t.isArray(n)){var i={},o=/(.*?)\[\]$/;t.each(n,function(t,e){var n=e.name.match(o);if(n){var r=n[0];i[r]||(i[r]=[]);i[r].push(e.value)}else i[e.name]=e.value});n=i}var a,s=e.ajax,l=e.oInstance;if(t.isPlainObject(s)&&s.data){a=s.data;var u=t.isFunction(a)?a(n):a;n=t.isFunction(a)&&u?u:t.extend(!0,n,u);delete s.data}var c={data:n,success:function(t){var n=t.error||t.sError;n&&e.oApi._fnLog(e,0,n);e.json=t;ze(e,null,"xhr",[e,t]);r(t)},dataType:"json",cache:!1,type:e.sServerMethod,error:function(t,n){var r=e.oApi._fnLog;"parsererror"==n?r(e,0,"Invalid JSON response",1):4===t.readyState&&r(e,0,"Ajax error",7);pe(e,!1)}};e.oAjaxData=n;ze(e,null,"preXhr",[e,n]);if(e.fnServerData)e.fnServerData.call(l,e.sAjaxSource,t.map(n,function(t,e){return{name:e,value:t}}),r,e);else if(e.sAjaxSource||"string"==typeof s)e.jqXHR=t.ajax(t.extend(c,{url:s||e.sAjaxSource}));else if(t.isFunction(s))e.jqXHR=s.call(l,n,r,e);else{e.jqXHR=t.ajax(t.extend(c,s));s.data=a}}function B(t){if(t.bAjaxDataGet){t.iDraw++;pe(t,!0);U(t,V(t),function(e){X(t,e)});return!1}return!0}function V(e){var n,r,i,o,a=e.aoColumns,s=a.length,l=e.oFeatures,u=e.oPreviousSearch,c=e.aoPreSearchCols,f=[],h=ke(e),d=e._iDisplayStart,p=l.bPaginate!==!1?e._iDisplayLength:-1,g=function(t,e){f.push({name:t,value:e})};g("sEcho",e.iDraw);g("iColumns",s);g("sColumns",dn(a,"sName").join(","));g("iDisplayStart",d);g("iDisplayLength",p);var m={draw:e.iDraw,columns:[],order:[],start:d,length:p,search:{value:u.sSearch,regex:u.bRegex}};for(n=0;s>n;n++){i=a[n];o=c[n];r="function"==typeof i.mData?"function":i.mData;m.columns.push({data:r,name:i.sName,searchable:i.bSearchable,orderable:i.bSortable,search:{value:o.sSearch,regex:o.bRegex}});g("mDataProp_"+n,r);if(l.bFilter){g("sSearch_"+n,o.sSearch);g("bRegex_"+n,o.bRegex);g("bSearchable_"+n,i.bSearchable)}l.bSort&&g("bSortable_"+n,i.bSortable)}if(l.bFilter){g("sSearch",u.sSearch);g("bRegex",u.bRegex)}if(l.bSort){t.each(h,function(t,e){m.order.push({column:e.col,dir:e.dir});g("iSortCol_"+t,e.col);g("sSortDir_"+t,e.dir)});g("iSortingCols",h.length)}var v=$e.ext.legacy.ajax;return null===v?e.sAjaxSource?f:m:v?f:m}function X(t,e){var n=function(t,n){return e[t]!==o?e[t]:e[n]},r=n("sEcho","draw"),i=n("iTotalRecords","recordsTotal"),a=n("iTotalDisplayRecords","recordsFiltered");if(r){if(1*r<t.iDraw)return;t.iDraw=1*r}A(t);t._iRecordsTotal=parseInt(i,10);t._iRecordsDisplay=parseInt(a,10);for(var s=G(t,e),l=0,u=s.length;u>l;l++)x(t,s[l]);t.aiDisplay=t.aiDisplayMaster.slice();t.bAjaxDataGet=!1;F(t);t._bInitComplete||le(t,e);t.bAjaxDataGet=!0;pe(t,!1)}function G(e,n){var r=t.isPlainObject(e.ajax)&&e.ajax.dataSrc!==o?e.ajax.dataSrc:e.sAjaxDataProp;return"data"===r?n.aaData||n[r]:""!==r?M(r)(n):n}function $(e){var n=e.oClasses,r=e.sTableId,o=e.oLanguage,a=e.oPreviousSearch,s=e.aanFeatures,l='<input type="search" class="'+n.sFilterInput+'"/>',u=o.sSearch;u=u.match(/_INPUT_/)?u.replace("_INPUT_",l):u+l;var c=t("<div/>",{id:s.f?null:r+"_filter","class":n.sFilter}).append(t("<label/>").append(u)),f=function(){var t=(s.f,this.value?this.value:"");if(t!=a.sSearch){Y(e,{sSearch:t,bRegex:a.bRegex,bSmart:a.bSmart,bCaseInsensitive:a.bCaseInsensitive});e._iDisplayStart=0;F(e)}},h=t("input",c).val(a.sSearch).attr("placeholder",o.sSearchPlaceholder).bind("keyup.DT search.DT input.DT paste.DT cut.DT","ssp"===Be(e)?be(f,400):f).bind("keypress.DT",function(t){return 13==t.keyCode?!1:void 0}).attr("aria-controls",r);t(e.nTable).on("search.dt.DT",function(t,n){if(e===n)try{h[0]!==i.activeElement&&h.val(a.sSearch)}catch(r){}});return c[0]}function Y(t,e,n){var r=t.oPreviousSearch,i=t.aoPreSearchCols,a=function(t){r.sSearch=t.sSearch;r.bRegex=t.bRegex;r.bSmart=t.bSmart;r.bCaseInsensitive=t.bCaseInsensitive},s=function(t){return t.bEscapeRegex!==o?!t.bEscapeRegex:t.bRegex};y(t);if("ssp"!=Be(t)){Z(t,e.sSearch,n,s(e),e.bSmart,e.bCaseInsensitive);a(e);for(var l=0;l<i.length;l++)K(t,i[l].sSearch,l,s(i[l]),i[l].bSmart,i[l].bCaseInsensitive);J(t)}else a(e);t.bFiltered=!0;ze(t,null,"search",[t])}function J(t){for(var e,n,r=$e.ext.search,i=t.aiDisplay,o=0,a=r.length;a>o;o++){for(var s=[],l=0,u=i.length;u>l;l++){n=i[l];e=t.aoData[n];r[o](t,e._aFilterData,n,e._aData,l)&&s.push(n)}i.length=0;i.push.apply(i,s)}}function K(t,e,n,r,i,o){if(""!==e)for(var a,s=t.aiDisplay,l=Q(e,r,i,o),u=s.length-1;u>=0;u--){a=t.aoData[s[u]]._aFilterData[n];l.test(a)||s.splice(u,1)}}function Z(t,e,n,r,i,o){var a,s,l,u=Q(e,r,i,o),c=t.oPreviousSearch.sSearch,f=t.aiDisplayMaster;0!==$e.ext.search.length&&(n=!0);s=ee(t);if(e.length<=0)t.aiDisplay=f.slice();else{(s||n||c.length>e.length||0!==e.indexOf(c)||t.bSorted)&&(t.aiDisplay=f.slice());a=t.aiDisplay;for(l=a.length-1;l>=0;l--)u.test(t.aoData[a[l]]._sFilterRow)||a.splice(l,1)}}function Q(e,n,r,i){e=n?e:te(e);if(r){var o=t.map(e.match(/"[^"]+"|[^ ]+/g)||"",function(t){return'"'===t.charAt(0)?t.match(/^"(.*)"$/)[1]:t});e="^(?=.*?"+o.join(")(?=.*?")+").*$"}return new RegExp(e,i?"i":"")}function te(t){return t.replace(on,"\\$1")}function ee(t){var e,n,r,i,o,a,s,l,u=t.aoColumns,c=$e.ext.type.search,f=!1;for(n=0,i=t.aoData.length;i>n;n++){l=t.aoData[n];if(!l._aFilterData){a=[];for(r=0,o=u.length;o>r;r++){e=u[r];if(e.bSearchable){s=T(t,n,r,"filter");c[e.sType]&&(s=c[e.sType](s));null===s&&(s="");"string"!=typeof s&&s.toString&&(s=s.toString())}else s="";if(s.indexOf&&-1!==s.indexOf("&")){wn.innerHTML=s;s=Sn?wn.textContent:wn.innerText}s.replace&&(s=s.replace(/[\r\n]/g,""));a.push(s)}l._aFilterData=a;l._sFilterRow=a.join(" ");f=!0}}return f}function ne(t){return{search:t.sSearch,smart:t.bSmart,regex:t.bRegex,caseInsensitive:t.bCaseInsensitive}}function re(t){return{sSearch:t.search,bSmart:t.smart,bRegex:t.regex,bCaseInsensitive:t.caseInsensitive}}function ie(e){var n=e.sTableId,r=e.aanFeatures.i,i=t("<div/>",{"class":e.oClasses.sInfo,id:r?null:n+"_info"});if(!r){e.aoDrawCallback.push({fn:oe,sName:"information"});i.attr("role","status").attr("aria-live","polite");t(e.nTable).attr("aria-describedby",n+"_info")}return i[0]}function oe(e){var n=e.aanFeatures.i;if(0!==n.length){var r=e.oLanguage,i=e._iDisplayStart+1,o=e.fnDisplayEnd(),a=e.fnRecordsTotal(),s=e.fnRecordsDisplay(),l=s?r.sInfo:r.sInfoEmpty;s!==a&&(l+=" "+r.sInfoFiltered);l+=r.sInfoPostFix;l=ae(e,l);var u=r.fnInfoCallback;null!==u&&(l=u.call(e.oInstance,e,i,o,a,s,l));t(n).html(l)}}function ae(t,e){var n=t.fnFormatNumber,r=t._iDisplayStart+1,i=t._iDisplayLength,o=t.fnRecordsDisplay(),a=-1===i;return e.replace(/_START_/g,n.call(t,r)).replace(/_END_/g,n.call(t,t.fnDisplayEnd())).replace(/_MAX_/g,n.call(t,t.fnRecordsTotal())).replace(/_TOTAL_/g,n.call(t,o)).replace(/_PAGE_/g,n.call(t,a?1:Math.ceil(r/i))).replace(/_PAGES_/g,n.call(t,a?1:Math.ceil(o/i)))}function se(t){var e,n,r,i=t.iInitDisplayStart,o=t.aoColumns,a=t.oFeatures;if(t.bInitialised){W(t);H(t);O(t,t.aoHeader);O(t,t.aoFooter);pe(t,!0);a.bAutoWidth&&ye(t);for(e=0,n=o.length;n>e;e++){r=o[e];r.sWidth&&(r.nTh.style.width=Te(r.sWidth))}R(t);var s=Be(t);if("ssp"!=s)if("ajax"==s)U(t,[],function(n){var r=G(t,n);for(e=0;e<r.length;e++)x(t,r[e]);t.iInitDisplayStart=i;R(t);pe(t,!1);le(t,n)},t);else{pe(t,!1);le(t)}}else setTimeout(function(){se(t)},200)}function le(t,e){t._bInitComplete=!0;e&&d(t);ze(t,"aoInitComplete","init",[t,e])}function ue(t,e){var n=parseInt(e,10);t._iDisplayLength=n;qe(t);ze(t,null,"length",[t,n])}function ce(e){for(var n=e.oClasses,r=e.sTableId,i=e.aLengthMenu,o=t.isArray(i[0]),a=o?i[0]:i,s=o?i[1]:i,l=t("<select/>",{name:r+"_length","aria-controls":r,"class":n.sLengthSelect}),u=0,c=a.length;c>u;u++)l[0][u]=new Option(s[u],a[u]);var f=t("<div><label/></div>").addClass(n.sLength);e.aanFeatures.l||(f[0].id=r+"_length");f.children().append(e.oLanguage.sLengthMenu.replace("_MENU_",l[0].outerHTML));t("select",f).val(e._iDisplayLength).bind("change.DT",function(){ue(e,t(this).val());F(e)});t(e.nTable).bind("length.dt.DT",function(n,r,i){e===r&&t("select",f).val(i)});return f[0]}function fe(e){var n=e.sPaginationType,r=$e.ext.pager[n],i="function"==typeof r,o=function(t){F(t)},a=t("<div/>").addClass(e.oClasses.sPaging+n)[0],s=e.aanFeatures;i||r.fnInit(e,a,o);if(!s.p){a.id=e.sTableId+"_paginate";e.aoDrawCallback.push({fn:function(t){if(i){var e,n,a=t._iDisplayStart,l=t._iDisplayLength,u=t.fnRecordsDisplay(),c=-1===l,f=c?0:Math.ceil(a/l),h=c?1:Math.ceil(u/l),d=r(f,h);for(e=0,n=s.p.length;n>e;e++)Ue(t,"pageButton")(t,s.p[e],e,d,f,h)}else r.fnUpdate(t,o)},sName:"pagination"})}return a}function he(t,e,n){var r=t._iDisplayStart,i=t._iDisplayLength,o=t.fnRecordsDisplay();if(0===o||-1===i)r=0;else if("number"==typeof e){r=e*i;r>o&&(r=0)}else if("first"==e)r=0;else if("previous"==e){r=i>=0?r-i:0;0>r&&(r=0)}else"next"==e?o>r+i&&(r+=i):"last"==e?r=Math.floor((o-1)/i)*i:He(t,0,"Unknown paging action: "+e,5);var a=t._iDisplayStart!==r;t._iDisplayStart=r;if(a){ze(t,null,"page",[t]);n&&F(t)}return a}function de(e){return t("<div/>",{id:e.aanFeatures.r?null:e.sTableId+"_processing","class":e.oClasses.sProcessing}).html(e.oLanguage.sProcessing).insertBefore(e.nTable)[0]}function pe(e,n){e.oFeatures.bProcessing&&t(e.aanFeatures.r).css("display",n?"block":"none");ze(e,null,"processing",[e,n])}function ge(e){var n=t(e.nTable);n.attr("role","grid");var r=e.oScroll;if(""===r.sX&&""===r.sY)return e.nTable;var i=r.sX,o=r.sY,a=e.oClasses,s=n.children("caption"),l=s.length?s[0]._captionSide:null,u=t(n[0].cloneNode(!1)),c=t(n[0].cloneNode(!1)),f=n.children("tfoot"),h="<div/>",d=function(t){return t?Te(t):null};r.sX&&"100%"===n.attr("width")&&n.removeAttr("width");f.length||(f=null);var p=t(h,{"class":a.sScrollWrapper}).append(t(h,{"class":a.sScrollHead}).css({overflow:"hidden",position:"relative",border:0,width:i?d(i):"100%"}).append(t(h,{"class":a.sScrollHeadInner}).css({"box-sizing":"content-box",width:r.sXInner||"100%"}).append(u.removeAttr("id").css("margin-left",0).append(n.children("thead")))).append("top"===l?s:null)).append(t(h,{"class":a.sScrollBody}).css({overflow:"auto",height:d(o),width:d(i)}).append(n));f&&p.append(t(h,{"class":a.sScrollFoot}).css({overflow:"hidden",border:0,width:i?d(i):"100%"}).append(t(h,{"class":a.sScrollFootInner}).append(c.removeAttr("id").css("margin-left",0).append(n.children("tfoot")))).append("bottom"===l?s:null));var g=p.children(),m=g[0],v=g[1],y=f?g[2]:null;i&&t(v).scroll(function(){var t=this.scrollLeft;m.scrollLeft=t;f&&(y.scrollLeft=t)});e.nScrollHead=m;e.nScrollBody=v;e.nScrollFoot=y;e.aoDrawCallback.push({fn:me,sName:"scrolling"});return p[0]}function me(e){var n,r,i,o,a,s,l,u,c,f=e.oScroll,h=f.sX,d=f.sXInner,g=f.sY,m=f.iBarWidth,v=t(e.nScrollHead),y=v[0].style,b=v.children("div"),x=b[0].style,w=b.children("table"),S=e.nScrollBody,C=t(S),T=S.style,_=t(e.nScrollFoot),k=_.children("div"),M=k.children("table"),D=t(e.nTHead),L=t(e.nTable),A=L[0],N=A.style,E=e.nTFoot?t(e.nTFoot):null,j=e.oBrowser,I=j.bScrollOversize,P=[],H=[],O=[],F=function(t){var e=t.style;e.paddingTop="0";e.paddingBottom="0";e.borderTopWidth="0";e.borderBottomWidth="0";e.height=0};L.children("thead, tfoot").remove();a=D.clone().prependTo(L);n=D.find("tr");i=a.find("tr");a.find("th, td").removeAttr("tabindex");if(E){s=E.clone().prependTo(L);r=E.find("tr");o=s.find("tr")}if(!h){T.width="100%";v[0].style.width="100%"}t.each(q(e,a),function(t,n){l=p(e,t);n.style.width=e.aoColumns[l].sWidth});E&&ve(function(t){t.style.width=""},o);f.bCollapse&&""!==g&&(T.height=C[0].offsetHeight+D[0].offsetHeight+"px");c=L.outerWidth();if(""===h){N.width="100%";I&&(L.find("tbody").height()>S.offsetHeight||"scroll"==C.css("overflow-y"))&&(N.width=Te(L.outerWidth()-m))}else if(""!==d)N.width=Te(d);else if(c==C.width()&&C.height()<L.height()){N.width=Te(c-m);L.outerWidth()>c-m&&(N.width=Te(c))}else N.width=Te(c);c=L.outerWidth();ve(F,i);ve(function(e){O.push(e.innerHTML);P.push(Te(t(e).css("width")))},i);ve(function(t,e){t.style.width=P[e]},n);t(i).height(0);if(E){ve(F,o);ve(function(e){H.push(Te(t(e).css("width")))},o);ve(function(t,e){t.style.width=H[e]},r);t(o).height(0)}ve(function(t,e){t.innerHTML='<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+O[e]+"</div>";t.style.width=P[e]},i);E&&ve(function(t,e){t.innerHTML="";t.style.width=H[e]},o);if(L.outerWidth()<c){u=S.scrollHeight>S.offsetHeight||"scroll"==C.css("overflow-y")?c+m:c;I&&(S.scrollHeight>S.offsetHeight||"scroll"==C.css("overflow-y"))&&(N.width=Te(u-m));(""===h||""!==d)&&He(e,1,"Possible column misalignment",6)}else u="100%";T.width=Te(u);y.width=Te(u);E&&(e.nScrollFoot.style.width=Te(u));g||I&&(T.height=Te(A.offsetHeight+m));if(g&&f.bCollapse){T.height=Te(g);var R=h&&A.offsetWidth>S.offsetWidth?m:0;A.offsetHeight<S.offsetHeight&&(T.height=Te(A.offsetHeight+R))}var W=L.outerWidth();w[0].style.width=Te(W);x.width=Te(W);var z=L.height()>S.clientHeight||"scroll"==C.css("overflow-y"),U="padding"+(j.bScrollbarLeft?"Left":"Right");x[U]=z?m+"px":"0px";if(E){M[0].style.width=Te(W);k[0].style.width=Te(W);k[0].style[U]=z?m+"px":"0px"}C.scroll();!e.bSorted&&!e.bFiltered||e._drawHold||(S.scrollTop=0)}function ve(t,e,n){for(var r,i,o=0,a=0,s=e.length;s>a;){r=e[a].firstChild;i=n?n[a].firstChild:null;for(;r;){if(1===r.nodeType){n?t(r,i,o):t(r,o);o++}r=r.nextSibling;i=n?i.nextSibling:null}a++}}function ye(e){var r,i,o,a,s,l=e.nTable,u=e.aoColumns,c=e.oScroll,f=c.sY,h=c.sX,p=c.sXInner,g=u.length,y=v(e,"bVisible"),b=t("th",e.nTHead),x=l.getAttribute("width"),w=l.parentNode,S=!1;for(r=0;r<y.length;r++){i=u[y[r]];if(null!==i.sWidth){i.sWidth=xe(i.sWidthOrig,w);S=!0}}if(S||h||f||g!=m(e)||g!=b.length){var C=t(l).clone().empty().css("visibility","hidden").removeAttr("id").append(t(e.nTHead).clone(!1)).append(t(e.nTFoot).clone(!1)).append(t("<tbody><tr/></tbody>"));C.find("tfoot th, tfoot td").css("width","");var T=C.find("tbody tr");b=q(e,C.find("thead")[0]);for(r=0;r<y.length;r++){i=u[y[r]];b[r].style.width=null!==i.sWidthOrig&&""!==i.sWidthOrig?Te(i.sWidthOrig):""}if(e.aoData.length)for(r=0;r<y.length;r++){o=y[r];i=u[o];t(Se(e,o)).clone(!1).append(i.sContentPadding).appendTo(T)}C.appendTo(w);if(h&&p)C.width(p);else if(h){C.css("width","auto");C.width()<w.offsetWidth&&C.width(w.offsetWidth)}else f?C.width(w.offsetWidth):x&&C.width(x);we(e,C[0]);if(h){var _=0;for(r=0;r<y.length;r++){i=u[y[r]];s=t(b[r]).outerWidth();_+=null===i.sWidthOrig?s:parseInt(i.sWidth,10)+s-t(b[r]).width()}C.width(Te(_));l.style.width=Te(_)}for(r=0;r<y.length;r++){i=u[y[r]];a=t(b[r]).width();a&&(i.sWidth=Te(a))}l.style.width=Te(C.css("width"));C.remove()}else for(r=0;g>r;r++)u[r].sWidth=Te(b.eq(r).width());x&&(l.style.width=Te(x));if((x||h)&&!e._reszEvt){t(n).bind("resize.DT-"+e.sInstance,be(function(){d(e)}));e._reszEvt=!0}}function be(t,e){var n,r,i=e||200;return function(){var e=this,a=+new Date,s=arguments;if(n&&n+i>a){clearTimeout(r);r=setTimeout(function(){n=o;t.apply(e,s)},i)}else if(n){n=a;t.apply(e,s)}else n=a}}function xe(e,n){if(!e)return 0;var r=t("<div/>").css("width",Te(e)).appendTo(n||i.body),o=r[0].offsetWidth;r.remove();return o}function we(e,n){var r=e.oScroll;if(r.sX||r.sY){var i=r.sX?0:r.iBarWidth;n.style.width=Te(t(n).outerWidth()-i)}}function Se(e,n){var r=Ce(e,n);if(0>r)return null;var i=e.aoData[r];return i.nTr?i.anCells[n]:t("<td/>").html(T(e,r,n,"display"))[0]}function Ce(t,e){for(var n,r=-1,i=-1,o=0,a=t.aoData.length;a>o;o++){n=T(t,o,e,"display")+"";n=n.replace(Cn,"");if(n.length>r){r=n.length;i=o}}return i}function Te(t){return null===t?"0px":"number"==typeof t?0>t?"0px":t+"px":t.match(/\d$/)?t+"px":t}function _e(){if(!$e.__scrollbarWidth){var e=t("<p/>").css({width:"100%",height:200,padding:0})[0],n=t("<div/>").css({position:"absolute",top:0,left:0,width:200,height:150,padding:0,overflow:"hidden",visibility:"hidden"}).append(e).appendTo("body"),r=e.offsetWidth;n.css("overflow","scroll");var i=e.offsetWidth;r===i&&(i=n[0].clientWidth);n.remove();$e.__scrollbarWidth=r-i}return $e.__scrollbarWidth}function ke(e){var n,r,i,o,a,s,l,u=[],c=e.aoColumns,f=e.aaSortingFixed,h=t.isPlainObject(f),d=[],p=function(e){e.length&&!t.isArray(e[0])?d.push(e):d.push.apply(d,e)};t.isArray(f)&&p(f);h&&f.pre&&p(f.pre);p(e.aaSorting);h&&f.post&&p(f.post);for(n=0;n<d.length;n++){l=d[n][0];o=c[l].aDataSort;for(r=0,i=o.length;i>r;r++){a=o[r];s=c[a].sType||"string";u.push({src:l,col:a,dir:d[n][1],index:d[n][2],type:s,formatter:$e.ext.type.order[s+"-pre"]})}}return u}function Me(t){var e,n,r,i,o,a=[],s=$e.ext.type.order,l=t.aoData,u=(t.aoColumns,0),c=t.aiDisplayMaster;y(t);o=ke(t);for(e=0,n=o.length;n>e;e++){i=o[e];i.formatter&&u++;Ee(t,i.col)}if("ssp"!=Be(t)&&0!==o.length){for(e=0,r=c.length;r>e;e++)a[c[e]]=e;c.sort(u===o.length?function(t,e){var n,r,i,s,u,c=o.length,f=l[t]._aSortData,h=l[e]._aSortData;for(i=0;c>i;i++){u=o[i];n=f[u.col];r=h[u.col];s=r>n?-1:n>r?1:0;if(0!==s)return"asc"===u.dir?s:-s}n=a[t];r=a[e];return r>n?-1:n>r?1:0}:function(t,e){var n,r,i,u,c,f,h=o.length,d=l[t]._aSortData,p=l[e]._aSortData;
for(i=0;h>i;i++){c=o[i];n=d[c.col];r=p[c.col];f=s[c.type+"-"+c.dir]||s["string-"+c.dir];u=f(n,r);if(0!==u)return u}n=a[t];r=a[e];return r>n?-1:n>r?1:0})}t.bSorted=!0}function De(t){for(var e,n,r=t.aoColumns,i=ke(t),o=t.oLanguage.oAria,a=0,s=r.length;s>a;a++){var l=r[a],u=l.asSorting,c=l.sTitle.replace(/<.*?>/g,""),f=l.nTh;f.removeAttribute("aria-sort");if(l.bSortable){if(i.length>0&&i[0].col==a){f.setAttribute("aria-sort","asc"==i[0].dir?"ascending":"descending");n=u[i[0].index+1]||u[0]}else n=u[0];e=c+("asc"===n?o.sSortAscending:o.sSortDescending)}else e=c;f.setAttribute("aria-label",e)}}function Le(e,n,r,i){var a,s=e.aoColumns[n],l=e.aaSorting,u=s.asSorting,c=function(e){var n=e._idx;n===o&&(n=t.inArray(e[1],u));return n+1>=u.length?0:n+1};"number"==typeof l[0]&&(l=e.aaSorting=[l]);if(r&&e.oFeatures.bSortMulti){var f=t.inArray(n,dn(l,"0"));if(-1!==f){a=c(l[f]);l[f][1]=u[a];l[f]._idx=a}else{l.push([n,u[0],0]);l[l.length-1]._idx=0}}else if(l.length&&l[0][0]==n){a=c(l[0]);l.length=1;l[0][1]=u[a];l[0]._idx=a}else{l.length=0;l.push([n,u[0]]);l[0]._idx=0}R(e);"function"==typeof i&&i(e)}function Ae(t,e,n,r){var i=t.aoColumns[n];Re(e,{},function(e){if(i.bSortable!==!1)if(t.oFeatures.bProcessing){pe(t,!0);setTimeout(function(){Le(t,n,e.shiftKey,r);"ssp"!==Be(t)&&pe(t,!1)},0)}else Le(t,n,e.shiftKey,r)})}function Ne(e){var n,r,i,o=e.aLastSort,a=e.oClasses.sSortColumn,s=ke(e),l=e.oFeatures;if(l.bSort&&l.bSortClasses){for(n=0,r=o.length;r>n;n++){i=o[n].src;t(dn(e.aoData,"anCells",i)).removeClass(a+(2>n?n+1:3))}for(n=0,r=s.length;r>n;n++){i=s[n].src;t(dn(e.aoData,"anCells",i)).addClass(a+(2>n?n+1:3))}}e.aLastSort=s}function Ee(t,e){var n,r=t.aoColumns[e],i=$e.ext.order[r.sSortDataType];i&&(n=i.call(t.oInstance,t,e,g(t,e)));for(var o,a,s=$e.ext.type.order[r.sType+"-pre"],l=0,u=t.aoData.length;u>l;l++){o=t.aoData[l];o._aSortData||(o._aSortData=[]);if(!o._aSortData[e]||i){a=i?n[l]:T(t,l,e,"sort");o._aSortData[e]=s?s(a):a}}}function je(e){if(e.oFeatures.bStateSave&&!e.bDestroying){var n={time:+new Date,start:e._iDisplayStart,length:e._iDisplayLength,order:t.extend(!0,[],e.aaSorting),search:ne(e.oPreviousSearch),columns:t.map(e.aoColumns,function(t,n){return{visible:t.bVisible,search:ne(e.aoPreSearchCols[n])}})};ze(e,"aoStateSaveParams","stateSaveParams",[e,n]);e.oSavedState=n;e.fnStateSaveCallback.call(e.oInstance,e,n)}}function Ie(e){var n,r,i=e.aoColumns;if(e.oFeatures.bStateSave){var o=e.fnStateLoadCallback.call(e.oInstance,e);if(o&&o.time){var a=ze(e,"aoStateLoadParams","stateLoadParams",[e,o]);if(-1===t.inArray(!1,a)){var s=e.iStateDuration;if(!(s>0&&o.time<+new Date-1e3*s)&&i.length===o.columns.length){e.oLoadedState=t.extend(!0,{},o);e._iDisplayStart=o.start;e.iInitDisplayStart=o.start;e._iDisplayLength=o.length;e.aaSorting=[];t.each(o.order,function(t,n){e.aaSorting.push(n[0]>=i.length?[0,n[1]]:n)});t.extend(e.oPreviousSearch,re(o.search));for(n=0,r=o.columns.length;r>n;n++){var l=o.columns[n];i[n].bVisible=l.visible;t.extend(e.aoPreSearchCols[n],re(l.search))}ze(e,"aoStateLoaded","stateLoaded",[e,o])}}}}}function Pe(e){var n=$e.settings,r=t.inArray(e,dn(n,"nTable"));return-1!==r?n[r]:null}function He(t,e,r,i){r="DataTables warning: "+(null!==t?"table id="+t.sTableId+" - ":"")+r;i&&(r+=". For more information about this error, please see http://datatables.net/tn/"+i);if(e)n.console&&console.log&&console.log(r);else{var o=$e.ext,a=o.sErrMode||o.errMode;if("alert"!=a)throw new Error(r);alert(r)}}function Oe(e,n,r,i){if(t.isArray(r))t.each(r,function(r,i){t.isArray(i)?Oe(e,n,i[0],i[1]):Oe(e,n,i)});else{i===o&&(i=r);n[r]!==o&&(e[i]=n[r])}}function Fe(e,n,r){var i;for(var o in n)if(n.hasOwnProperty(o)){i=n[o];if(t.isPlainObject(i)){t.isPlainObject(e[o])||(e[o]={});t.extend(!0,e[o],i)}else e[o]=r&&"data"!==o&&"aaData"!==o&&t.isArray(i)?i.slice():i}return e}function Re(e,n,r){t(e).bind("click.DT",n,function(t){e.blur();r(t)}).bind("keypress.DT",n,function(t){if(13===t.which){t.preventDefault();r(t)}}).bind("selectstart.DT",function(){return!1})}function We(t,e,n,r){n&&t[e].push({fn:n,sName:r})}function ze(e,n,r,i){var o=[];n&&(o=t.map(e[n].slice().reverse(),function(t){return t.fn.apply(e.oInstance,i)}));null!==r&&t(e.nTable).trigger(r+".dt",i);return o}function qe(t){var e=t._iDisplayStart,n=t.fnDisplayEnd(),r=t._iDisplayLength;n===t.fnRecordsDisplay()&&(e=n-r);(-1===r||0>e)&&(e=0);t._iDisplayStart=e}function Ue(e,n){var r=e.renderer,i=$e.ext.renderer[n];return t.isPlainObject(r)&&r[n]?i[r[n]]||i._:"string"==typeof r?i[r]||i._:i._}function Be(t){return t.oFeatures.bServerSide?"ssp":t.ajax||t.sAjaxSource?"ajax":"dom"}function Ve(t,e){var n=[],r=Vn.numbers_length,i=Math.floor(r/2);if(r>=e)n=gn(0,e);else if(i>=t){n=gn(0,r-2);n.push("ellipsis");n.push(e-1)}else if(t>=e-1-i){n=gn(e-(r-2),e);n.splice(0,0,"ellipsis");n.splice(0,0,0)}else{n=gn(t-1,t+2);n.push("ellipsis");n.push(e-1);n.splice(0,0,"ellipsis");n.splice(0,0,0)}n.DT_el="span";return n}function Xe(e){t.each({num:function(t){return Xn(t,e)},"num-fmt":function(t){return Xn(t,e,an)},"html-num":function(t){return Xn(t,e,en)},"html-num-fmt":function(t){return Xn(t,e,en,an)}},function(t,n){Ye.type.order[t+e+"-pre"]=n})}function Ge(t){return function(){var e=[Pe(this[$e.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments));return $e.ext.internal[t].apply(this,e)}}var $e,Ye,Je,Ke,Ze,Qe={},tn=/[\r\n]/g,en=/<.*?>/g,nn=/^[\w\+\-]/,rn=/[\w\+\-]$/,on=new RegExp("(\\"+["/",".","*","+","?","|","(",")","[","]","{","}","\\","$","^","-"].join("|\\")+")","g"),an=/[',$£€¥%\u2009\u202F]/g,sn=function(t){return t&&t!==!0&&"-"!==t?!1:!0},ln=function(t){var e=parseInt(t,10);return!isNaN(e)&&isFinite(t)?e:null},un=function(t,e){Qe[e]||(Qe[e]=new RegExp(te(e),"g"));return"string"==typeof t?t.replace(/\./g,"").replace(Qe[e],"."):t},cn=function(t,e,n){var r="string"==typeof t;e&&r&&(t=un(t,e));n&&r&&(t=t.replace(an,""));return sn(t)||!isNaN(parseFloat(t))&&isFinite(t)},fn=function(t){return sn(t)||"string"==typeof t},hn=function(t,e,n){if(sn(t))return!0;var r=fn(t);return r&&cn(mn(t),e,n)?!0:null},dn=function(t,e,n){var r=[],i=0,a=t.length;if(n!==o)for(;a>i;i++)t[i]&&t[i][e]&&r.push(t[i][e][n]);else for(;a>i;i++)t[i]&&r.push(t[i][e]);return r},pn=function(t,e,n,r){var i=[],a=0,s=e.length;if(r!==o)for(;s>a;a++)i.push(t[e[a]][n][r]);else for(;s>a;a++)i.push(t[e[a]][n]);return i},gn=function(t,e){var n,r=[];if(e===o){e=0;n=t}else{n=e;e=t}for(var i=e;n>i;i++)r.push(i);return r},mn=function(t){return t.replace(en,"")},vn=function(t){var e,n,r,i=[],o=t.length,a=0;t:for(n=0;o>n;n++){e=t[n];for(r=0;a>r;r++)if(i[r]===e)continue t;i.push(e);a++}return i},yn=function(t,e,n){t[e]!==o&&(t[n]=t[e])},bn=/\[.*?\]$/,xn=/\(\)$/,wn=t("<div>")[0],Sn=wn.textContent!==o,Cn=/<.*?>/g;$e=function(e){this.$=function(t,e){return this.api(!0).$(t,e)};this._=function(t,e){return this.api(!0).rows(t,e).data()};this.api=function(t){return new Je(t?Pe(this[Ye.iApiIndex]):this)};this.fnAddData=function(e,n){var r=this.api(!0),i=t.isArray(e)&&(t.isArray(e[0])||t.isPlainObject(e[0]))?r.rows.add(e):r.row.add(e);(n===o||n)&&r.draw();return i.flatten().toArray()};this.fnAdjustColumnSizing=function(t){var e=this.api(!0).columns.adjust(),n=e.settings()[0],r=n.oScroll;t===o||t?e.draw(!1):(""!==r.sX||""!==r.sY)&&me(n)};this.fnClearTable=function(t){var e=this.api(!0).clear();(t===o||t)&&e.draw()};this.fnClose=function(t){this.api(!0).row(t).child.hide()};this.fnDeleteRow=function(t,e,n){var r=this.api(!0),i=r.rows(t),a=i.settings()[0],s=a.aoData[i[0][0]];i.remove();e&&e.call(this,a,s);(n===o||n)&&r.draw();return s};this.fnDestroy=function(t){this.api(!0).destroy(t)};this.fnDraw=function(t){this.api(!0).draw(!t)};this.fnFilter=function(t,e,n,r,i,a){var s=this.api(!0);null===e||e===o?s.search(t,n,r,a):s.column(e).search(t,n,r,a);s.draw()};this.fnGetData=function(t,e){var n=this.api(!0);if(t!==o){var r=t.nodeName?t.nodeName.toLowerCase():"";return e!==o||"td"==r||"th"==r?n.cell(t,e).data():n.row(t).data()||null}return n.data().toArray()};this.fnGetNodes=function(t){var e=this.api(!0);return t!==o?e.row(t).node():e.rows().nodes().flatten().toArray()};this.fnGetPosition=function(t){var e=this.api(!0),n=t.nodeName.toUpperCase();if("TR"==n)return e.row(t).index();if("TD"==n||"TH"==n){var r=e.cell(t).index();return[r.row,r.columnVisible,r.column]}return null};this.fnIsOpen=function(t){return this.api(!0).row(t).child.isShown()};this.fnOpen=function(t,e,n){return this.api(!0).row(t).child(e,n).show().child()[0]};this.fnPageChange=function(t,e){var n=this.api(!0).page(t);(e===o||e)&&n.draw(!1)};this.fnSetColumnVis=function(t,e,n){var r=this.api(!0).column(t).visible(e);(n===o||n)&&r.columns.adjust().draw()};this.fnSettings=function(){return Pe(this[Ye.iApiIndex])};this.fnSort=function(t){this.api(!0).order(t).draw()};this.fnSortListener=function(t,e,n){this.api(!0).order.listener(t,e,n)};this.fnUpdate=function(t,e,n,r,i){var a=this.api(!0);n===o||null===n?a.row(e).data(t):a.cell(e,n).data(t);(i===o||i)&&a.columns.adjust();(r===o||r)&&a.draw();return 0};this.fnVersionCheck=Ye.fnVersionCheck;var n=this,i=e===o,c=this.length;i&&(e={});this.oApi=this.internal=Ye.internal;for(var d in $e.ext.internal)d&&(this[d]=Ge(d));this.each(function(){var d,p={},g=c>1?Fe(p,e,!0):e,m=0,v=this.getAttribute("id"),y=!1,S=$e.defaults;if("table"==this.nodeName.toLowerCase()){s(S);l(S.column);r(S,S,!0);r(S.column,S.column,!0);r(S,g);var C=$e.settings;for(m=0,d=C.length;d>m;m++){if(C[m].nTable==this){var T=g.bRetrieve!==o?g.bRetrieve:S.bRetrieve,_=g.bDestroy!==o?g.bDestroy:S.bDestroy;if(i||T)return C[m].oInstance;if(_){C[m].oInstance.fnDestroy();break}He(C[m],0,"Cannot reinitialise DataTable",3);return}if(C[m].sTableId==this.id){C.splice(m,1);break}}if(null===v||""===v){v="DataTables_Table_"+$e.ext._unique++;this.id=v}var k=t.extend(!0,{},$e.models.oSettings,{nTable:this,oApi:n.internal,oInit:g,sDestroyWidth:t(this)[0].style.width,sInstance:v,sTableId:v});C.push(k);k.oInstance=1===n.length?n:t(this).dataTable();s(g);g.oLanguage&&a(g.oLanguage);g.aLengthMenu&&!g.iDisplayLength&&(g.iDisplayLength=t.isArray(g.aLengthMenu[0])?g.aLengthMenu[0][0]:g.aLengthMenu[0]);g=Fe(t.extend(!0,{},S),g);Oe(k.oFeatures,g,["bPaginate","bLengthChange","bFilter","bSort","bSortMulti","bInfo","bProcessing","bAutoWidth","bSortClasses","bServerSide","bDeferRender"]);Oe(k,g,["asStripeClasses","ajax","fnServerData","fnFormatNumber","sServerMethod","aaSorting","aaSortingFixed","aLengthMenu","sPaginationType","sAjaxSource","sAjaxDataProp","iStateDuration","sDom","bSortCellsTop","iTabIndex","fnStateLoadCallback","fnStateSaveCallback","renderer",["iCookieDuration","iStateDuration"],["oSearch","oPreviousSearch"],["aoSearchCols","aoPreSearchCols"],["iDisplayLength","_iDisplayLength"],["bJQueryUI","bJUI"]]);Oe(k.oScroll,g,[["sScrollX","sX"],["sScrollXInner","sXInner"],["sScrollY","sY"],["bScrollCollapse","bCollapse"]]);Oe(k.oLanguage,g,"fnInfoCallback");We(k,"aoDrawCallback",g.fnDrawCallback,"user");We(k,"aoServerParams",g.fnServerParams,"user");We(k,"aoStateSaveParams",g.fnStateSaveParams,"user");We(k,"aoStateLoadParams",g.fnStateLoadParams,"user");We(k,"aoStateLoaded",g.fnStateLoaded,"user");We(k,"aoRowCallback",g.fnRowCallback,"user");We(k,"aoRowCreatedCallback",g.fnCreatedRow,"user");We(k,"aoHeaderCallback",g.fnHeaderCallback,"user");We(k,"aoFooterCallback",g.fnFooterCallback,"user");We(k,"aoInitComplete",g.fnInitComplete,"user");We(k,"aoPreDrawCallback",g.fnPreDrawCallback,"user");var M=k.oClasses;if(g.bJQueryUI){t.extend(M,$e.ext.oJUIClasses,g.oClasses);g.sDom===S.sDom&&"lfrtip"===S.sDom&&(k.sDom='<"H"lfr>t<"F"ip>');k.renderer?t.isPlainObject(k.renderer)&&!k.renderer.header&&(k.renderer.header="jqueryui"):k.renderer="jqueryui"}else t.extend(M,$e.ext.classes,g.oClasses);t(this).addClass(M.sTable);(""!==k.oScroll.sX||""!==k.oScroll.sY)&&(k.oScroll.iBarWidth=_e());k.oScroll.sX===!0&&(k.oScroll.sX="100%");if(k.iInitDisplayStart===o){k.iInitDisplayStart=g.iDisplayStart;k._iDisplayStart=g.iDisplayStart}if(null!==g.iDeferLoading){k.bDeferLoading=!0;var D=t.isArray(g.iDeferLoading);k._iRecordsDisplay=D?g.iDeferLoading[0]:g.iDeferLoading;k._iRecordsTotal=D?g.iDeferLoading[1]:g.iDeferLoading}if(""!==g.oLanguage.sUrl){k.oLanguage.sUrl=g.oLanguage.sUrl;t.getJSON(k.oLanguage.sUrl,null,function(e){a(e);r(S.oLanguage,e);t.extend(!0,k.oLanguage,g.oLanguage,e);se(k)});y=!0}else t.extend(!0,k.oLanguage,g.oLanguage);null===g.asStripeClasses&&(k.asStripeClasses=[M.sStripeOdd,M.sStripeEven]);var L=k.asStripeClasses,A=t("tbody tr:eq(0)",this);if(-1!==t.inArray(!0,t.map(L,function(t){return A.hasClass(t)}))){t("tbody tr",this).removeClass(L.join(" "));k.asDestroyStripes=L.slice()}var N,E=[],I=this.getElementsByTagName("thead");if(0!==I.length){z(k.aoHeader,I[0]);E=q(k)}if(null===g.aoColumns){N=[];for(m=0,d=E.length;d>m;m++)N.push(null)}else N=g.aoColumns;for(m=0,d=N.length;d>m;m++)f(k,E?E[m]:null);b(k,g.aoColumnDefs,N,function(t,e){h(k,t,e)});if(A.length){var P=function(t,e){return t.getAttribute("data-"+e)?e:null};t.each(j(k,A[0]).cells,function(t,e){var n=k.aoColumns[t];if(n.mData===t){var r=P(e,"sort")||P(e,"order"),i=P(e,"filter")||P(e,"search");if(null!==r||null!==i){n.mData={_:t+".display",sort:null!==r?t+".@data-"+r:o,type:null!==r?t+".@data-"+r:o,filter:null!==i?t+".@data-"+i:o};h(k,t)}}})}var H=k.oFeatures;if(g.bStateSave){H.bStateSave=!0;Ie(k,g);We(k,"aoDrawCallback",je,"state_save")}if(g.aaSorting===o){var O=k.aaSorting;for(m=0,d=O.length;d>m;m++)O[m][1]=k.aoColumns[m].asSorting[0]}Ne(k);H.bSort&&We(k,"aoDrawCallback",function(){if(k.bSorted){var e=ke(k),n={};t.each(e,function(t,e){n[e.src]=e.dir});ze(k,null,"order",[k,e,n]);De(k)}});We(k,"aoDrawCallback",function(){(k.bSorted||"ssp"===Be(k)||H.bDeferRender)&&Ne(k)},"sc");u(k);var F=t(this).children("caption").each(function(){this._captionSide=t(this).css("caption-side")}),R=t(this).children("thead");0===R.length&&(R=t("<thead/>").appendTo(this));k.nTHead=R[0];var W=t(this).children("tbody");0===W.length&&(W=t("<tbody/>").appendTo(this));k.nTBody=W[0];var U=t(this).children("tfoot");0===U.length&&F.length>0&&(""!==k.oScroll.sX||""!==k.oScroll.sY)&&(U=t("<tfoot/>").appendTo(this));if(0===U.length||0===U.children().length)t(this).addClass(M.sNoFooter);else if(U.length>0){k.nTFoot=U[0];z(k.aoFooter,k.nTFoot)}if(g.aaData)for(m=0;m<g.aaData.length;m++)x(k,g.aaData[m]);else(k.bDeferLoading||"dom"==Be(k))&&w(k,t(k.nTBody).children("tr"));k.aiDisplay=k.aiDisplayMaster.slice();k.bInitialised=!0;y===!1&&se(k)}else He(null,0,"Non-table node initialisation ("+this.nodeName+")",2)});n=null;return this};var Tn=[],_n=Array.prototype,kn=function(e){var n,r,i=$e.settings,o=t.map(i,function(t){return t.nTable});if(!e)return[];if(e.nTable&&e.oApi)return[e];if(e.nodeName&&"table"===e.nodeName.toLowerCase()){n=t.inArray(e,o);return-1!==n?[i[n]]:null}if(e&&"function"==typeof e.settings)return e.settings().toArray();"string"==typeof e?r=t(e):e instanceof t&&(r=e);return r?r.map(function(){n=t.inArray(this,o);return-1!==n?i[n]:null}).toArray():void 0};Je=function(e,n){if(!this instanceof Je)throw"DT API must be constructed as a new object";var r=[],i=function(t){var e=kn(t);e&&r.push.apply(r,e)};if(t.isArray(e))for(var o=0,a=e.length;a>o;o++)i(e[o]);else i(e);this.context=vn(r);n&&this.push.apply(this,n.toArray?n.toArray():n);this.selector={rows:null,cols:null,opts:null};Je.extend(this,this,Tn)};$e.Api=Je;Je.prototype={concat:_n.concat,context:[],each:function(t){for(var e=0,n=this.length;n>e;e++)t.call(this,this[e],e,this);return this},eq:function(t){var e=this.context;return e.length>t?new Je(e[t],this[t]):null},filter:function(t){var e=[];if(_n.filter)e=_n.filter.call(this,t,this);else for(var n=0,r=this.length;r>n;n++)t.call(this,this[n],n,this)&&e.push(this[n]);return new Je(this.context,e)},flatten:function(){var t=[];return new Je(this.context,t.concat.apply(t,this.toArray()))},join:_n.join,indexOf:_n.indexOf||function(t,e){for(var n=e||0,r=this.length;r>n;n++)if(this[n]===t)return n;return-1},iterator:function(t,e,n){var r,i,a,s,l,u,c,f,h=[],d=this.context,p=this.selector;if("string"==typeof t){n=e;e=t;t=!1}for(i=0,a=d.length;a>i;i++)if("table"===e){r=n(d[i],i);r!==o&&h.push(r)}else if("columns"===e||"rows"===e){r=n(d[i],this[i],i);r!==o&&h.push(r)}else if("column"===e||"column-rows"===e||"row"===e||"cell"===e){c=this[i];"column-rows"===e&&(u=En(d[i],p.opts));for(s=0,l=c.length;l>s;s++){f=c[s];r="cell"===e?n(d[i],f.row,f.column,i,s):n(d[i],f,i,s,u);r!==o&&h.push(r)}}if(h.length){var g=new Je(d,t?h.concat.apply([],h):h),m=g.selector;m.rows=p.rows;m.cols=p.cols;m.opts=p.opts;return g}return this},lastIndexOf:_n.lastIndexOf||function(){return this.indexOf.apply(this.toArray.reverse(),arguments)},length:0,map:function(t){var e=[];if(_n.map)e=_n.map.call(this,t,this);else for(var n=0,r=this.length;r>n;n++)e.push(t.call(this,this[n],n));return new Je(this.context,e)},pluck:function(t){return this.map(function(e){return e[t]})},pop:_n.pop,push:_n.push,reduce:_n.reduce||function(t,e){return c(this,t,e,0,this.length,1)},reduceRight:_n.reduceRight||function(t,e){return c(this,t,e,this.length-1,-1,-1)},reverse:_n.reverse,selector:null,shift:_n.shift,sort:_n.sort,splice:_n.splice,toArray:function(){return _n.slice.call(this)},to$:function(){return t(this)},toJQuery:function(){return t(this)},unique:function(){return new Je(this.context,vn(this))},unshift:_n.unshift};Je.extend=function(e,n,r){if(n&&(n instanceof Je||n.__dt_wrapper)){var i,o,a,s=function(t,e,n){return function(){var r=e.apply(t,arguments);Je.extend(r,r,n.methodExt);return r}};for(i=0,o=r.length;o>i;i++){a=r[i];n[a.name]="function"==typeof a.val?s(e,a.val,a):t.isPlainObject(a.val)?{}:a.val;n[a.name].__dt_wrapper=!0;Je.extend(e,n[a.name],a.propExt)}}};Je.register=Ke=function(e,n){if(t.isArray(e))for(var r=0,i=e.length;i>r;r++)Je.register(e[r],n);else{var o,a,s,l,u=e.split("."),c=Tn,f=function(t,e){for(var n=0,r=t.length;r>n;n++)if(t[n].name===e)return t[n];return null};for(o=0,a=u.length;a>o;o++){l=-1!==u[o].indexOf("()");s=l?u[o].replace("()",""):u[o];var h=f(c,s);if(!h){h={name:s,val:{},methodExt:[],propExt:[]};c.push(h)}o===a-1?h.val=n:c=l?h.methodExt:h.propExt}}};Je.registerPlural=Ze=function(e,n,r){Je.register(e,r);Je.register(n,function(){var e=r.apply(this,arguments);return e===this?this:e instanceof Je?e.length?t.isArray(e[0])?new Je(e.context,e[0]):e[0]:o:e})};var Mn=function(e,n){if("number"==typeof e)return[n[e]];var r=t.map(n,function(t){return t.nTable});return t(r).filter(e).map(function(){var e=t.inArray(this,r);return n[e]}).toArray()};Ke("tables()",function(t){return t?new Je(Mn(t,this.context)):this});Ke("table()",function(t){var e=this.tables(t),n=e.context;return n.length?new Je(n[0]):e});Ze("tables().nodes()","table().node()",function(){return this.iterator("table",function(t){return t.nTable})});Ze("tables().body()","table().body()",function(){return this.iterator("table",function(t){return t.nTBody})});Ze("tables().header()","table().header()",function(){return this.iterator("table",function(t){return t.nTHead})});Ze("tables().footer()","table().footer()",function(){return this.iterator("table",function(t){return t.nTFoot})});Ze("tables().containers()","table().container()",function(){return this.iterator("table",function(t){return t.nTableWrapper})});Ke("draw()",function(t){return this.iterator("table",function(e){R(e,t===!1)})});Ke("page()",function(t){return t===o?this.page.info().page:this.iterator("table",function(e){he(e,t)})});Ke("page.info()",function(){if(0===this.context.length)return o;var t=this.context[0],e=t._iDisplayStart,n=t._iDisplayLength,r=t.fnRecordsDisplay(),i=-1===n;return{page:i?0:Math.floor(e/n),pages:i?1:Math.ceil(r/n),start:e,end:t.fnDisplayEnd(),length:n,recordsTotal:t.fnRecordsTotal(),recordsDisplay:r}});Ke("page.len()",function(t){return t===o?0!==this.context.length?this.context[0]._iDisplayLength:o:this.iterator("table",function(e){ue(e,t)})});var Dn=function(t,e,n){if("ssp"==Be(t))R(t,e);else{pe(t,!0);U(t,[],function(n){A(t);for(var r=G(t,n),i=0,o=r.length;o>i;i++)x(t,r[i]);R(t,e);pe(t,!1)})}if(n){var r=new Je(t);r.one("draw",function(){n(r.ajax.json())})}};Ke("ajax.json()",function(){var t=this.context;return t.length>0?t[0].json:void 0});Ke("ajax.params()",function(){var t=this.context;return t.length>0?t[0].oAjaxData:void 0});Ke("ajax.reload()",function(t,e){return this.iterator("table",function(n){Dn(n,e===!1,t)})});Ke("ajax.url()",function(e){var n=this.context;if(e===o){if(0===n.length)return o;n=n[0];return n.ajax?t.isPlainObject(n.ajax)?n.ajax.url:n.ajax:n.sAjaxSource}return this.iterator("table",function(n){t.isPlainObject(n.ajax)?n.ajax.url=e:n.ajax=e})});Ke("ajax.url().load()",function(t,e){return this.iterator("table",function(n){Dn(n,e===!1,t)})});var Ln=function(e,n){var r,i,a,s,l,u,c=[];e&&"string"!=typeof e&&e.length!==o||(e=[e]);for(a=0,s=e.length;s>a;a++){i=e[a]&&e[a].split?e[a].split(","):[e[a]];for(l=0,u=i.length;u>l;l++){r=n("string"==typeof i[l]?t.trim(i[l]):i[l]);r&&r.length&&c.push.apply(c,r)}}return c},An=function(t){t||(t={});t.filter&&!t.search&&(t.search=t.filter);return{search:t.search||"none",order:t.order||"current",page:t.page||"all"}},Nn=function(t){for(var e=0,n=t.length;n>e;e++)if(t[e].length>0){t[0]=t[e];t.length=1;t.context=[t.context[e]];return t}t.length=0;return t},En=function(e,n){var r,i,o,a=[],s=e.aiDisplay,l=e.aiDisplayMaster,u=n.search,c=n.order,f=n.page;if("ssp"==Be(e))return"removed"===u?[]:gn(0,l.length);if("current"==f)for(r=e._iDisplayStart,i=e.fnDisplayEnd();i>r;r++)a.push(s[r]);else if("current"==c||"applied"==c)a="none"==u?l.slice():"applied"==u?s.slice():t.map(l,function(e){return-1===t.inArray(e,s)?e:null});else if("index"==c||"original"==c)for(r=0,i=e.aoData.length;i>r;r++)if("none"==u)a.push(r);else{o=t.inArray(r,s);(-1===o&&"removed"==u||o>=0&&"applied"==u)&&a.push(r)}return a},jn=function(e,n,r){return Ln(n,function(n){var i=ln(n);if(null!==i&&!r)return[i];var o=En(e,r);if(null!==i&&-1!==t.inArray(i,o))return[i];if(!n)return o;for(var a=[],s=0,l=o.length;l>s;s++)a.push(e.aoData[o[s]].nTr);return n.nodeName&&-1!==t.inArray(n,a)?[n._DT_RowIndex]:t(a).filter(n).map(function(){return this._DT_RowIndex}).toArray()})};Ke("rows()",function(e,n){if(e===o)e="";else if(t.isPlainObject(e)){n=e;e=""}n=An(n);var r=this.iterator("table",function(t){return jn(t,e,n)});r.selector.rows=e;r.selector.opts=n;return r});Ke("rows().nodes()",function(){return this.iterator("row",function(t,e){return t.aoData[e].nTr||o})});Ke("rows().data()",function(){return this.iterator(!0,"rows",function(t,e){return pn(t.aoData,e,"_aData")})});Ze("rows().cache()","row().cache()",function(t){return this.iterator("row",function(e,n){var r=e.aoData[n];return"search"===t?r._aFilterData:r._aSortData})});Ze("rows().invalidate()","row().invalidate()",function(t){return this.iterator("row",function(e,n){E(e,n,t)})});Ze("rows().indexes()","row().index()",function(){return this.iterator("row",function(t,e){return e})});Ze("rows().remove()","row().remove()",function(){var e=this;return this.iterator("row",function(n,r,i){var o=n.aoData;o.splice(r,1);for(var a=0,s=o.length;s>a;a++)null!==o[a].nTr&&(o[a].nTr._DT_RowIndex=a);t.inArray(r,n.aiDisplay);N(n.aiDisplayMaster,r);N(n.aiDisplay,r);N(e[i],r,!1);qe(n)})});Ke("rows.add()",function(t){var e=this.iterator("table",function(e){var n,r,i,o=[];for(r=0,i=t.length;i>r;r++){n=t[r];o.push(n.nodeName&&"TR"===n.nodeName.toUpperCase()?w(e,n)[0]:x(e,n))}return o}),n=this.rows(-1);n.pop();n.push.apply(n,e.toArray());return n});Ke("row()",function(t,e){return Nn(this.rows(t,e))});Ke("row().data()",function(t){var e=this.context;if(t===o)return e.length&&this.length?e[0].aoData[this[0]]._aData:o;e[0].aoData[this[0]]._aData=t;E(e[0],this[0],"data");return this});Ke("row().node()",function(){var t=this.context;return t.length&&this.length?t[0].aoData[this[0]].nTr||null:null});Ke("row.add()",function(e){e instanceof t&&e.length&&(e=e[0]);var n=this.iterator("table",function(t){return e.nodeName&&"TR"===e.nodeName.toUpperCase()?w(t,e)[0]:x(t,e)});return this.row(n[0])});var In=function(e,n,r,i){var o=[],a=function(n,r){if(n.nodeName&&"tr"===n.nodeName.toLowerCase())o.push(n);else{var i=t("<tr><td/></tr>").addClass(r);t("td",i).addClass(r).html(n)[0].colSpan=m(e);o.push(i[0])}};if(t.isArray(r)||r instanceof t)for(var s=0,l=r.length;l>s;s++)a(r[s],i);else a(r,i);n._details&&n._details.remove();n._details=t(o);n._detailsShow&&n._details.insertAfter(n.nTr)},Pn=function(t){var e=t.context;if(e.length&&t.length){var n=e[0].aoData[t[0]];if(n._details){n._details.remove();n._detailsShow=o;n._details=o}}},Hn=function(t,e){var n=t.context;if(n.length&&t.length){var r=n[0].aoData[t[0]];if(r._details){r._detailsShow=e;e?r._details.insertAfter(r.nTr):r._details.detach();On(n[0])}}},On=function(t){var e=new Je(t),n=".dt.DT_details",r="draw"+n,i="column-visibility"+n,o="destroy"+n,a=t.aoData;e.off(r+" "+i+" "+o);if(dn(a,"_details").length>0){e.on(r,function(n,r){t===r&&e.rows({page:"current"}).eq(0).each(function(t){var e=a[t];e._detailsShow&&e._details.insertAfter(e.nTr)})});e.on(i,function(e,n){if(t===n)for(var r,i=m(n),o=0,s=a.length;s>o;o++){r=a[o];r._details&&r._details.children("td[colspan]").attr("colspan",i)}});e.on(o,function(e,n){if(t===n)for(var r=0,i=a.length;i>r;r++)a[r]._details&&Pn(a[r])})}},Fn="",Rn=Fn+"row().child",Wn=Rn+"()";Ke(Wn,function(t,e){var n=this.context;if(t===o)return n.length&&this.length?n[0].aoData[this[0]]._details:o;t===!0?this.child.show():t===!1?Pn(this):n.length&&this.length&&In(n[0],n[0].aoData[this[0]],t,e);return this});Ke([Rn+".show()",Wn+".show()"],function(){Hn(this,!0);return this});Ke([Rn+".hide()",Wn+".hide()"],function(){Hn(this,!1);return this});Ke([Rn+".remove()",Wn+".remove()"],function(){Pn(this);return this});Ke(Rn+".isShown()",function(){var t=this.context;return t.length&&this.length?t[0].aoData[this[0]]._detailsShow||!1:!1});var zn=/^(.+):(name|visIdx|visible)$/,qn=function(e,n){var r=e.aoColumns,i=dn(r,"sName"),o=dn(r,"nTh");return Ln(n,function(n){var a=ln(n);if(""===n)return gn(r.length);if(null!==a)return[a>=0?a:r.length+a];var s="string"==typeof n?n.match(zn):"";if(!s)return t(o).filter(n).map(function(){return t.inArray(this,o)}).toArray();switch(s[2]){case"visIdx":case"visible":var l=parseInt(s[1],10);if(0>l){var u=t.map(r,function(t,e){return t.bVisible?e:null});return[u[u.length+l]]}return[p(e,l)];case"name":return t.map(i,function(t,e){return t===s[1]?e:null})}})},Un=function(e,n,r,i){var a,s,l,u,c=e.aoColumns,f=c[n],h=e.aoData;if(r===o)return f.bVisible;if(f.bVisible!==r){if(r){var p=t.inArray(!0,dn(c,"bVisible"),n+1);for(s=0,l=h.length;l>s;s++){u=h[s].nTr;a=h[s].anCells;u&&u.insertBefore(a[n],a[p]||null)}}else t(dn(e.aoData,"anCells",n)).detach();f.bVisible=r;O(e,e.aoHeader);O(e,e.aoFooter);if(i===o||i){d(e);(e.oScroll.sX||e.oScroll.sY)&&me(e)}ze(e,null,"column-visibility",[e,n,r]);je(e)}};Ke("columns()",function(e,n){if(e===o)e="";else if(t.isPlainObject(e)){n=e;e=""}n=An(n);var r=this.iterator("table",function(t){return qn(t,e,n)});r.selector.cols=e;r.selector.opts=n;return r});Ze("columns().header()","column().header()",function(){return this.iterator("column",function(t,e){return t.aoColumns[e].nTh})});Ze("columns().footer()","column().footer()",function(){return this.iterator("column",function(t,e){return t.aoColumns[e].nTf})});Ze("columns().data()","column().data()",function(){return this.iterator("column-rows",function(t,e,n,r,i){for(var o=[],a=0,s=i.length;s>a;a++)o.push(T(t,i[a],e,""));return o})});Ze("columns().cache()","column().cache()",function(t){return this.iterator("column-rows",function(e,n,r,i,o){return pn(e.aoData,o,"search"===t?"_aFilterData":"_aSortData",n)})});Ze("columns().nodes()","column().nodes()",function(){return this.iterator("column-rows",function(t,e,n,r,i){return pn(t.aoData,i,"anCells",e)})});Ze("columns().visible()","column().visible()",function(t,e){return this.iterator("column",function(n,r){return t===o?n.aoColumns[r].bVisible:Un(n,r,t,e)})});Ze("columns().indexes()","column().index()",function(t){return this.iterator("column",function(e,n){return"visible"===t?g(e,n):n})});Ke("columns.adjust()",function(){return this.iterator("table",function(t){d(t)})});Ke("column.index()",function(t,e){if(0!==this.context.length){var n=this.context[0];if("fromVisible"===t||"toData"===t)return p(n,e);if("fromData"===t||"toVisible"===t)return g(n,e)}});Ke("column()",function(t,e){return Nn(this.columns(t,e))});var Bn=function(e,n,r){var i,a,s,l,u,c=e.aoData,f=En(e,r),h=pn(c,f,"anCells"),d=t([].concat.apply([],h)),p=e.aoColumns.length;return Ln(n,function(e){if(null===e||e===o){a=[];for(s=0,l=f.length;l>s;s++){i=f[s];for(u=0;p>u;u++)a.push({row:i,column:u})}return a}return t.isPlainObject(e)?[e]:d.filter(e).map(function(e,n){i=n.parentNode._DT_RowIndex;return{row:i,column:t.inArray(n,c[i].anCells)}}).toArray()})};Ke("cells()",function(e,n,r){if(t.isPlainObject(e))if(typeof e.row!==o){r=n;n=null}else{r=e;e=null}if(t.isPlainObject(n)){r=n;n=null}if(null===n||n===o)return this.iterator("table",function(t){return Bn(t,e,An(r))});var i,a,s,l,u,c=this.columns(n,r),f=this.rows(e,r),h=this.iterator("table",function(t,e){i=[];for(a=0,s=f[e].length;s>a;a++)for(l=0,u=c[e].length;u>l;l++)i.push({row:f[e][a],column:c[e][l]});return i});t.extend(h.selector,{cols:n,rows:e,opts:r});return h});Ze("cells().nodes()","cell().node()",function(){return this.iterator("cell",function(t,e,n){return t.aoData[e].anCells[n]})});Ke("cells().data()",function(){return this.iterator("cell",function(t,e,n){return T(t,e,n)})});Ze("cells().cache()","cell().cache()",function(t){t="search"===t?"_aFilterData":"_aSortData";return this.iterator("cell",function(e,n,r){return e.aoData[n][t][r]})});Ze("cells().indexes()","cell().index()",function(){return this.iterator("cell",function(t,e,n){return{row:e,column:n,columnVisible:g(t,n)}})});Ke(["cells().invalidate()","cell().invalidate()"],function(t){var e=this.selector;this.rows(e.rows,e.opts).invalidate(t);return this});Ke("cell()",function(t,e,n){return Nn(this.cells(t,e,n))});Ke("cell().data()",function(t){var e=this.context,n=this[0];if(t===o)return e.length&&n.length?T(e[0],n[0].row,n[0].column):o;_(e[0],n[0].row,n[0].column,t);E(e[0],n[0].row,"data",n[0].column);return this});Ke("order()",function(e,n){var r=this.context;if(e===o)return 0!==r.length?r[0].aaSorting:o;"number"==typeof e?e=[[e,n]]:t.isArray(e[0])||(e=Array.prototype.slice.call(arguments));return this.iterator("table",function(t){t.aaSorting=e.slice()})});Ke("order.listener()",function(t,e,n){return this.iterator("table",function(r){Ae(r,t,e,n)})});Ke(["columns().order()","column().order()"],function(e){var n=this;return this.iterator("table",function(r,i){var o=[];t.each(n[i],function(t,n){o.push([n,e])});r.aaSorting=o})});Ke("search()",function(e,n,r,i){var a=this.context;return e===o?0!==a.length?a[0].oPreviousSearch.sSearch:o:this.iterator("table",function(o){o.oFeatures.bFilter&&Y(o,t.extend({},o.oPreviousSearch,{sSearch:e+"",bRegex:null===n?!1:n,bSmart:null===r?!0:r,bCaseInsensitive:null===i?!0:i}),1)})});Ze("columns().search()","column().search()",function(e,n,r,i){return this.iterator("column",function(a,s){var l=a.aoPreSearchCols;if(e===o)return l[s].sSearch;if(a.oFeatures.bFilter){t.extend(l[s],{sSearch:e+"",bRegex:null===n?!1:n,bSmart:null===r?!0:r,bCaseInsensitive:null===i?!0:i});Y(a,a.oPreviousSearch,1)}})});Ke("state()",function(){return this.context.length?this.context[0].oSavedState:null});Ke("state.clear()",function(){return this.iterator("table",function(t){t.fnStateSaveCallback.call(t.oInstance,t,{})})});Ke("state.loaded()",function(){return this.context.length?this.context[0].oLoadedState:null});Ke("state.save()",function(){return this.iterator("table",function(t){je(t)})});$e.versionCheck=$e.fnVersionCheck=function(t){for(var e,n,r=$e.version.split("."),i=t.split("."),o=0,a=i.length;a>o;o++){e=parseInt(r[o],10)||0;n=parseInt(i[o],10)||0;if(e!==n)return e>n}return!0};$e.isDataTable=$e.fnIsDataTable=function(e){var n=t(e).get(0),r=!1;
t.each($e.settings,function(t,e){(e.nTable===n||e.nScrollHead===n||e.nScrollFoot===n)&&(r=!0)});return r};$e.tables=$e.fnTables=function(e){return jQuery.map($e.settings,function(n){return!e||e&&t(n.nTable).is(":visible")?n.nTable:void 0})};$e.camelToHungarian=r;Ke("$()",function(e,n){var r=this.rows(n).nodes(),i=t(r);return t([].concat(i.filter(e).toArray(),i.find(e).toArray()))});t.each(["on","one","off"],function(e,n){Ke(n+"()",function(){var e=Array.prototype.slice.call(arguments);e[0].match(/\.dt\b/)||(e[0]+=".dt");var r=t(this.tables().nodes());r[n].apply(r,e);return this})});Ke("clear()",function(){return this.iterator("table",function(t){A(t)})});Ke("settings()",function(){return new Je(this.context,this.context)});Ke("data()",function(){return this.iterator("table",function(t){return dn(t.aoData,"_aData")}).flatten()});Ke("destroy()",function(e){e=e||!1;return this.iterator("table",function(r){var i,o=r.nTableWrapper.parentNode,a=r.oClasses,s=r.nTable,l=r.nTBody,u=r.nTHead,c=r.nTFoot,f=t(s),h=t(l),d=t(r.nTableWrapper),p=t.map(r.aoData,function(t){return t.nTr});r.bDestroying=!0;ze(r,"aoDestroyCallback","destroy",[r]);e||new Je(r).columns().visible(!0);d.unbind(".DT").find(":not(tbody *)").unbind(".DT");t(n).unbind(".DT-"+r.sInstance);if(s!=u.parentNode){f.children("thead").detach();f.append(u)}if(c&&s!=c.parentNode){f.children("tfoot").detach();f.append(c)}f.detach();d.detach();r.aaSorting=[];r.aaSortingFixed=[];Ne(r);t(p).removeClass(r.asStripeClasses.join(" "));t("th, td",u).removeClass(a.sSortable+" "+a.sSortableAsc+" "+a.sSortableDesc+" "+a.sSortableNone);if(r.bJUI){t("th span."+a.sSortIcon+", td span."+a.sSortIcon,u).detach();t("th, td",u).each(function(){var e=t("div."+a.sSortJUIWrapper,this);t(this).append(e.contents());e.detach()})}!e&&o&&o.insertBefore(s,r.nTableReinsertBefore);h.children().detach();h.append(p);f.css("width",r.sDestroyWidth).removeClass(a.sTable);i=r.asDestroyStripes.length;i&&h.children().each(function(e){t(this).addClass(r.asDestroyStripes[e%i])});var g=t.inArray(r,$e.settings);-1!==g&&$e.settings.splice(g,1)})});$e.version="1.10.2";$e.settings=[];$e.models={};$e.models.oSearch={bCaseInsensitive:!0,sSearch:"",bRegex:!1,bSmart:!0};$e.models.oRow={nTr:null,anCells:null,_aData:[],_aSortData:null,_aFilterData:null,_sFilterRow:null,_sRowStripe:"",src:null};$e.models.oColumn={idx:null,aDataSort:null,asSorting:null,bSearchable:null,bSortable:null,bVisible:null,_sManualType:null,_bAttrSrc:!1,fnCreatedCell:null,fnGetData:null,fnSetData:null,mData:null,mRender:null,nTh:null,nTf:null,sClass:null,sContentPadding:null,sDefaultContent:null,sName:null,sSortDataType:"std",sSortingClass:null,sSortingClassJUI:null,sTitle:null,sType:null,sWidth:null,sWidthOrig:null};$e.defaults={aaData:null,aaSorting:[[0,"asc"]],aaSortingFixed:[],ajax:null,aLengthMenu:[10,25,50,100],aoColumns:null,aoColumnDefs:null,aoSearchCols:[],asStripeClasses:null,bAutoWidth:!0,bDeferRender:!1,bDestroy:!1,bFilter:!0,bInfo:!0,bJQueryUI:!1,bLengthChange:!0,bPaginate:!0,bProcessing:!1,bRetrieve:!1,bScrollCollapse:!1,bServerSide:!1,bSort:!0,bSortMulti:!0,bSortCellsTop:!1,bSortClasses:!0,bStateSave:!1,fnCreatedRow:null,fnDrawCallback:null,fnFooterCallback:null,fnFormatNumber:function(t){return t.toString().replace(/\B(?=(\d{3})+(?!\d))/g,this.oLanguage.sThousands)},fnHeaderCallback:null,fnInfoCallback:null,fnInitComplete:null,fnPreDrawCallback:null,fnRowCallback:null,fnServerData:null,fnServerParams:null,fnStateLoadCallback:function(t){try{return JSON.parse((-1===t.iStateDuration?sessionStorage:localStorage).getItem("DataTables_"+t.sInstance+"_"+location.pathname))}catch(e){}},fnStateLoadParams:null,fnStateLoaded:null,fnStateSaveCallback:function(t,e){try{(-1===t.iStateDuration?sessionStorage:localStorage).setItem("DataTables_"+t.sInstance+"_"+location.pathname,JSON.stringify(e))}catch(n){}},fnStateSaveParams:null,iStateDuration:7200,iDeferLoading:null,iDisplayLength:10,iDisplayStart:0,iTabIndex:0,oClasses:{},oLanguage:{oAria:{sSortAscending:": activate to sort column ascending",sSortDescending:": activate to sort column descending"},oPaginate:{sFirst:"First",sLast:"Last",sNext:"Next",sPrevious:"Previous"},sEmptyTable:"No data available in table",sInfo:"Showing _START_ to _END_ of _TOTAL_ entries",sInfoEmpty:"Showing 0 to 0 of 0 entries",sInfoFiltered:"(filtered from _MAX_ total entries)",sInfoPostFix:"",sDecimal:"",sThousands:",",sLengthMenu:"Show _MENU_ entries",sLoadingRecords:"Loading...",sProcessing:"Processing...",sSearch:"Search:",sSearchPlaceholder:"",sUrl:"",sZeroRecords:"No matching records found"},oSearch:t.extend({},$e.models.oSearch),sAjaxDataProp:"data",sAjaxSource:null,sDom:"lfrtip",sPaginationType:"simple_numbers",sScrollX:"",sScrollXInner:"",sScrollY:"",sServerMethod:"GET",renderer:null};e($e.defaults);$e.defaults.column={aDataSort:null,iDataSort:-1,asSorting:["asc","desc"],bSearchable:!0,bSortable:!0,bVisible:!0,fnCreatedCell:null,mData:null,mRender:null,sCellType:"td",sClass:"",sContentPadding:"",sDefaultContent:null,sName:"",sSortDataType:"std",sTitle:null,sType:null,sWidth:null};e($e.defaults.column);$e.models.oSettings={oFeatures:{bAutoWidth:null,bDeferRender:null,bFilter:null,bInfo:null,bLengthChange:null,bPaginate:null,bProcessing:null,bServerSide:null,bSort:null,bSortMulti:null,bSortClasses:null,bStateSave:null},oScroll:{bCollapse:null,iBarWidth:0,sX:null,sXInner:null,sY:null},oLanguage:{fnInfoCallback:null},oBrowser:{bScrollOversize:!1,bScrollbarLeft:!1},ajax:null,aanFeatures:[],aoData:[],aiDisplay:[],aiDisplayMaster:[],aoColumns:[],aoHeader:[],aoFooter:[],oPreviousSearch:{},aoPreSearchCols:[],aaSorting:null,aaSortingFixed:[],asStripeClasses:null,asDestroyStripes:[],sDestroyWidth:0,aoRowCallback:[],aoHeaderCallback:[],aoFooterCallback:[],aoDrawCallback:[],aoRowCreatedCallback:[],aoPreDrawCallback:[],aoInitComplete:[],aoStateSaveParams:[],aoStateLoadParams:[],aoStateLoaded:[],sTableId:"",nTable:null,nTHead:null,nTFoot:null,nTBody:null,nTableWrapper:null,bDeferLoading:!1,bInitialised:!1,aoOpenRows:[],sDom:null,sPaginationType:"two_button",iStateDuration:0,aoStateSave:[],aoStateLoad:[],oSavedState:null,oLoadedState:null,sAjaxSource:null,sAjaxDataProp:null,bAjaxDataGet:!0,jqXHR:null,json:o,oAjaxData:o,fnServerData:null,aoServerParams:[],sServerMethod:null,fnFormatNumber:null,aLengthMenu:null,iDraw:0,bDrawing:!1,iDrawError:-1,_iDisplayLength:10,_iDisplayStart:0,_iRecordsTotal:0,_iRecordsDisplay:0,bJUI:null,oClasses:{},bFiltered:!1,bSorted:!1,bSortCellsTop:null,oInit:null,aoDestroyCallback:[],fnRecordsTotal:function(){return"ssp"==Be(this)?1*this._iRecordsTotal:this.aiDisplayMaster.length},fnRecordsDisplay:function(){return"ssp"==Be(this)?1*this._iRecordsDisplay:this.aiDisplay.length},fnDisplayEnd:function(){var t=this._iDisplayLength,e=this._iDisplayStart,n=e+t,r=this.aiDisplay.length,i=this.oFeatures,o=i.bPaginate;return i.bServerSide?o===!1||-1===t?e+r:Math.min(e+t,this._iRecordsDisplay):!o||n>r||-1===t?r:n},oInstance:null,sInstance:null,iTabIndex:0,nScrollHead:null,nScrollFoot:null,aLastSort:[],oPlugins:{}};$e.ext=Ye={classes:{},errMode:"alert",feature:[],search:[],internal:{},legacy:{ajax:null},pager:{},renderer:{pageButton:{},header:{}},order:{},type:{detect:[],search:{},order:{}},_unique:0,fnVersionCheck:$e.fnVersionCheck,iApiIndex:0,oJUIClasses:{},sVersion:$e.version};t.extend(Ye,{afnFiltering:Ye.search,aTypes:Ye.type.detect,ofnSearch:Ye.type.search,oSort:Ye.type.order,afnSortData:Ye.order,aoFeatures:Ye.feature,oApi:Ye.internal,oStdClasses:Ye.classes,oPagination:Ye.pager});t.extend($e.ext.classes,{sTable:"dataTable",sNoFooter:"no-footer",sPageButton:"paginate_button",sPageButtonActive:"current",sPageButtonDisabled:"disabled",sStripeOdd:"odd",sStripeEven:"even",sRowEmpty:"dataTables_empty",sWrapper:"dataTables_wrapper",sFilter:"dataTables_filter",sInfo:"dataTables_info",sPaging:"dataTables_paginate paging_",sLength:"dataTables_length",sProcessing:"dataTables_processing",sSortAsc:"sorting_asc",sSortDesc:"sorting_desc",sSortable:"sorting",sSortableAsc:"sorting_asc_disabled",sSortableDesc:"sorting_desc_disabled",sSortableNone:"sorting_disabled",sSortColumn:"sorting_",sFilterInput:"",sLengthSelect:"",sScrollWrapper:"dataTables_scroll",sScrollHead:"dataTables_scrollHead",sScrollHeadInner:"dataTables_scrollHeadInner",sScrollBody:"dataTables_scrollBody",sScrollFoot:"dataTables_scrollFoot",sScrollFootInner:"dataTables_scrollFootInner",sHeaderTH:"",sFooterTH:"",sSortJUIAsc:"",sSortJUIDesc:"",sSortJUI:"",sSortJUIAscAllowed:"",sSortJUIDescAllowed:"",sSortJUIWrapper:"",sSortIcon:"",sJUIHeader:"",sJUIFooter:""});(function(){var e="";e="";var n=e+"ui-state-default",r=e+"css_right ui-icon ui-icon-",i=e+"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix";t.extend($e.ext.oJUIClasses,$e.ext.classes,{sPageButton:"fg-button ui-button "+n,sPageButtonActive:"ui-state-disabled",sPageButtonDisabled:"ui-state-disabled",sPaging:"dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi ui-buttonset-multi paging_",sSortAsc:n+" sorting_asc",sSortDesc:n+" sorting_desc",sSortable:n+" sorting",sSortableAsc:n+" sorting_asc_disabled",sSortableDesc:n+" sorting_desc_disabled",sSortableNone:n+" sorting_disabled",sSortJUIAsc:r+"triangle-1-n",sSortJUIDesc:r+"triangle-1-s",sSortJUI:r+"carat-2-n-s",sSortJUIAscAllowed:r+"carat-1-n",sSortJUIDescAllowed:r+"carat-1-s",sSortJUIWrapper:"DataTables_sort_wrapper",sSortIcon:"DataTables_sort_icon",sScrollHead:"dataTables_scrollHead "+n,sScrollFoot:"dataTables_scrollFoot "+n,sHeaderTH:n,sFooterTH:n,sJUIHeader:i+" ui-corner-tl ui-corner-tr",sJUIFooter:i+" ui-corner-bl ui-corner-br"})})();var Vn=$e.ext.pager;t.extend(Vn,{simple:function(){return["previous","next"]},full:function(){return["first","previous","next","last"]},simple_numbers:function(t,e){return["previous",Ve(t,e),"next"]},full_numbers:function(t,e){return["first","previous",Ve(t,e),"next","last"]},_numbers:Ve,numbers_length:7});t.extend(!0,$e.ext.renderer,{pageButton:{_:function(e,n,r,o,a,s){var l,u,c=e.oClasses,f=e.oLanguage.oPaginate,h=0,d=function(n,i){var o,p,g,m,v=function(t){he(e,t.data.action,!0)};for(o=0,p=i.length;p>o;o++){m=i[o];if(t.isArray(m)){var y=t("<"+(m.DT_el||"div")+"/>").appendTo(n);d(y,m)}else{l="";u="";switch(m){case"ellipsis":n.append("<span>…</span>");break;case"first":l=f.sFirst;u=m+(a>0?"":" "+c.sPageButtonDisabled);break;case"previous":l=f.sPrevious;u=m+(a>0?"":" "+c.sPageButtonDisabled);break;case"next":l=f.sNext;u=m+(s-1>a?"":" "+c.sPageButtonDisabled);break;case"last":l=f.sLast;u=m+(s-1>a?"":" "+c.sPageButtonDisabled);break;default:l=m+1;u=a===m?c.sPageButtonActive:""}if(l){g=t("<a>",{"class":c.sPageButton+" "+u,"aria-controls":e.sTableId,"data-dt-idx":h,tabindex:e.iTabIndex,id:0===r&&"string"==typeof m?e.sTableId+"_"+m:null}).html(l).appendTo(n);Re(g,{action:m},v);h++}}}};try{var p=t(i.activeElement).data("dt-idx");d(t(n).empty(),o);null!==p&&t(n).find("[data-dt-idx="+p+"]").focus()}catch(g){}}}});var Xn=function(t,e,n,r){if(!t||"-"===t)return-1/0;e&&(t=un(t,e));if(t.replace){n&&(t=t.replace(n,""));r&&(t=t.replace(r,""))}return 1*t};t.extend(Ye.type.order,{"date-pre":function(t){return Date.parse(t)||0},"html-pre":function(t){return sn(t)?"":t.replace?t.replace(/<.*?>/g,"").toLowerCase():t+""},"string-pre":function(t){return sn(t)?"":"string"==typeof t?t.toLowerCase():t.toString?t.toString():""},"string-asc":function(t,e){return e>t?-1:t>e?1:0},"string-desc":function(t,e){return e>t?1:t>e?-1:0}});Xe("");t.extend($e.ext.type.detect,[function(t,e){var n=e.oLanguage.sDecimal;return cn(t,n)?"num"+n:null},function(t){if(t&&(!nn.test(t)||!rn.test(t)))return null;var e=Date.parse(t);return null!==e&&!isNaN(e)||sn(t)?"date":null},function(t,e){var n=e.oLanguage.sDecimal;return cn(t,n,!0)?"num-fmt"+n:null},function(t,e){var n=e.oLanguage.sDecimal;return hn(t,n)?"html-num"+n:null},function(t,e){var n=e.oLanguage.sDecimal;return hn(t,n,!0)?"html-num-fmt"+n:null},function(t){return sn(t)||"string"==typeof t&&-1!==t.indexOf("<")?"html":null}]);t.extend($e.ext.type.search,{html:function(t){return sn(t)?t:"string"==typeof t?t.replace(tn," ").replace(en,""):""},string:function(t){return sn(t)?t:"string"==typeof t?t.replace(tn," "):t}});t.extend(!0,$e.ext.renderer,{header:{_:function(e,n,r,i){t(e.nTable).on("order.dt.DT",function(t,o,a,s){if(e===o){var l=r.idx;n.removeClass(r.sSortingClass+" "+i.sSortAsc+" "+i.sSortDesc).addClass("asc"==s[l]?i.sSortAsc:"desc"==s[l]?i.sSortDesc:r.sSortingClass)}})},jqueryui:function(e,n,r,i){var o=r.idx;t("<div/>").addClass(i.sSortJUIWrapper).append(n.contents()).append(t("<span/>").addClass(i.sSortIcon+" "+r.sSortingClassJUI)).appendTo(n);t(e.nTable).on("order.dt.DT",function(t,a,s,l){if(e===a){n.removeClass(i.sSortAsc+" "+i.sSortDesc).addClass("asc"==l[o]?i.sSortAsc:"desc"==l[o]?i.sSortDesc:r.sSortingClass);n.find("span."+i.sSortIcon).removeClass(i.sSortJUIAsc+" "+i.sSortJUIDesc+" "+i.sSortJUI+" "+i.sSortJUIAscAllowed+" "+i.sSortJUIDescAllowed).addClass("asc"==l[o]?i.sSortJUIAsc:"desc"==l[o]?i.sSortJUIDesc:r.sSortingClassJUI)}})}}});$e.render={number:function(t,e,n,r){return{display:function(i){var o=0>i?"-":"";i=Math.abs(parseFloat(i));var a=parseInt(i,10),s=n?e+(i-a).toFixed(n).substring(2):"";return o+(r||"")+a.toString().replace(/\B(?=(\d{3})+(?!\d))/g,t)+s}}}};t.extend($e.ext.internal,{_fnExternApiFunc:Ge,_fnBuildAjax:U,_fnAjaxUpdate:B,_fnAjaxParameters:V,_fnAjaxUpdateDraw:X,_fnAjaxDataSrc:G,_fnAddColumn:f,_fnColumnOptions:h,_fnAdjustColumnSizing:d,_fnVisibleToColumnIndex:p,_fnColumnIndexToVisible:g,_fnVisbleColumns:m,_fnGetColumns:v,_fnColumnTypes:y,_fnApplyColumnDefs:b,_fnHungarianMap:e,_fnCamelToHungarian:r,_fnLanguageCompat:a,_fnBrowserDetect:u,_fnAddData:x,_fnAddTr:w,_fnNodeToDataIndex:S,_fnNodeToColumnIndex:C,_fnGetCellData:T,_fnSetCellData:_,_fnSplitObjNotation:k,_fnGetObjectDataFn:M,_fnSetObjectDataFn:D,_fnGetDataMaster:L,_fnClearTable:A,_fnDeleteIndex:N,_fnInvalidateRow:E,_fnGetRowElements:j,_fnCreateTr:I,_fnBuildHead:H,_fnDrawHead:O,_fnDraw:F,_fnReDraw:R,_fnAddOptionsHtml:W,_fnDetectHeader:z,_fnGetUniqueThs:q,_fnFeatureHtmlFilter:$,_fnFilterComplete:Y,_fnFilterCustom:J,_fnFilterColumn:K,_fnFilter:Z,_fnFilterCreateSearch:Q,_fnEscapeRegex:te,_fnFilterData:ee,_fnFeatureHtmlInfo:ie,_fnUpdateInfo:oe,_fnInfoMacros:ae,_fnInitialise:se,_fnInitComplete:le,_fnLengthChange:ue,_fnFeatureHtmlLength:ce,_fnFeatureHtmlPaginate:fe,_fnPageChange:he,_fnFeatureHtmlProcessing:de,_fnProcessingDisplay:pe,_fnFeatureHtmlTable:ge,_fnScrollDraw:me,_fnApplyToChildren:ve,_fnCalculateColumnWidths:ye,_fnThrottle:be,_fnConvertToWidth:xe,_fnScrollingWidthAdjust:we,_fnGetWidestNode:Se,_fnGetMaxLenString:Ce,_fnStringToCss:Te,_fnScrollBarWidth:_e,_fnSortFlatten:ke,_fnSort:Me,_fnSortAria:De,_fnSortListener:Le,_fnSortAttachListener:Ae,_fnSortingClasses:Ne,_fnSortData:Ee,_fnSaveState:je,_fnLoadState:Ie,_fnSettingsFromNode:Pe,_fnLog:He,_fnMap:Oe,_fnBindAction:Re,_fnCallbackReg:We,_fnCallbackFire:ze,_fnLengthOverflow:qe,_fnRenderer:Ue,_fnDataSource:Be,_fnRowAttributes:P,_fnCalculateEnd:function(){}});t.fn.dataTable=$e;t.fn.dataTableSettings=$e.settings;t.fn.dataTableExt=$e.ext;t.fn.DataTable=function(e){return t(this).dataTable(e).api()};t.each($e,function(e,n){t.fn.DataTable[e]=n});return t.fn.dataTable})})(window,document)},{jquery:17}],3:[function(){RegExp.escape=function(t){return t.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")};(function(t){"use strict";t.csv={defaults:{separator:",",delimiter:'"',headers:!0},hooks:{castToScalar:function(t){var e=/\./;if(isNaN(t))return t;if(e.test(t))return parseFloat(t);var n=parseInt(t);return isNaN(n)?null:n}},parsers:{parse:function(t,e){function n(){l=0;u="";if(e.start&&e.state.rowNum<e.start){s=[];e.state.rowNum++;e.state.colNum=1}else{if(void 0===e.onParseEntry)a.push(s);else{var t=e.onParseEntry(s,e.state);t!==!1&&a.push(t)}s=[];e.end&&e.state.rowNum>=e.end&&(c=!0);e.state.rowNum++;e.state.colNum=1}}function r(){if(void 0===e.onParseValue)s.push(u);else{var t=e.onParseValue(u,e.state);t!==!1&&s.push(t)}u="";l=0;e.state.colNum++}var i=e.separator,o=e.delimiter;e.state.rowNum||(e.state.rowNum=1);e.state.colNum||(e.state.colNum=1);var a=[],s=[],l=0,u="",c=!1,f=RegExp.escape(i),h=RegExp.escape(o),d=/(D|S|\n|\r|[^DS\r\n]+)/,p=d.source;p=p.replace(/S/g,f);p=p.replace(/D/g,h);d=RegExp(p,"gm");t.replace(d,function(t){if(!c)switch(l){case 0:if(t===i){u+="";r();break}if(t===o){l=1;break}if("\n"===t){r();n();break}if(/^\r$/.test(t))break;u+=t;l=3;break;case 1:if(t===o){l=2;break}u+=t;l=1;break;case 2:if(t===o){u+=t;l=1;break}if(t===i){r();break}if("\n"===t){r();n();break}if(/^\r$/.test(t))break;throw new Error("CSVDataError: Illegal State [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]");case 3:if(t===i){r();break}if("\n"===t){r();n();break}if(/^\r$/.test(t))break;if(t===o)throw new Error("CSVDataError: Illegal Quote [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]")}});if(0!==s.length){r();n()}return a},splitLines:function(t,e){function n(){a=0;if(e.start&&e.state.rowNum<e.start){s="";e.state.rowNum++}else{if(void 0===e.onParseEntry)o.push(s);else{var t=e.onParseEntry(s,e.state);t!==!1&&o.push(t)}s="";e.end&&e.state.rowNum>=e.end&&(l=!0);e.state.rowNum++}}var r=e.separator,i=e.delimiter;e.state.rowNum||(e.state.rowNum=1);var o=[],a=0,s="",l=!1,u=RegExp.escape(r),c=RegExp.escape(i),f=/(D|S|\n|\r|[^DS\r\n]+)/,h=f.source;h=h.replace(/S/g,u);h=h.replace(/D/g,c);f=RegExp(h,"gm");t.replace(f,function(t){if(!l)switch(a){case 0:if(t===r){s+=t;a=0;break}if(t===i){s+=t;a=1;break}if("\n"===t){n();break}if(/^\r$/.test(t))break;s+=t;a=3;break;case 1:if(t===i){s+=t;a=2;break}s+=t;a=1;break;case 2:var o=s.substr(s.length-1);if(t===i&&o===i){s+=t;a=1;break}if(t===r){s+=t;a=0;break}if("\n"===t){n();break}if("\r"===t)break;throw new Error("CSVDataError: Illegal state [Row:"+e.state.rowNum+"]");case 3:if(t===r){s+=t;a=0;break}if("\n"===t){n();break}if("\r"===t)break;if(t===i)throw new Error("CSVDataError: Illegal quote [Row:"+e.state.rowNum+"]");throw new Error("CSVDataError: Illegal state [Row:"+e.state.rowNum+"]");default:throw new Error("CSVDataError: Unknown state [Row:"+e.state.rowNum+"]")}});""!==s&&n();return o},parseEntry:function(t,e){function n(){if(void 0===e.onParseValue)o.push(s);else{var t=e.onParseValue(s,e.state);t!==!1&&o.push(t)}s="";a=0;e.state.colNum++}var r=e.separator,i=e.delimiter;e.state.rowNum||(e.state.rowNum=1);e.state.colNum||(e.state.colNum=1);var o=[],a=0,s="";if(!e.match){var l=RegExp.escape(r),u=RegExp.escape(i),c=/(D|S|\n|\r|[^DS\r\n]+)/,f=c.source;f=f.replace(/S/g,l);f=f.replace(/D/g,u);e.match=RegExp(f,"gm")}t.replace(e.match,function(t){switch(a){case 0:if(t===r){s+="";n();break}if(t===i){a=1;break}if("\n"===t||"\r"===t)break;s+=t;a=3;break;case 1:if(t===i){a=2;break}s+=t;a=1;break;case 2:if(t===i){s+=t;a=1;break}if(t===r){n();break}if("\n"===t||"\r"===t)break;throw new Error("CSVDataError: Illegal State [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]");case 3:if(t===r){n();break}if("\n"===t||"\r"===t)break;if(t===i)throw new Error("CSVDataError: Illegal Quote [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+e.state.rowNum+"][Col:"+e.state.colNum+"]")}});n();return o}},toArray:function(e,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1;i.separator="separator"in n?n.separator:t.csv.defaults.separator;i.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;var o=void 0!==n.state?n.state:{},n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,state:o},a=t.csv.parsers.parseEntry(e,n);if(!i.callback)return a;i.callback("",a);return void 0},toArrays:function(e,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1;i.separator="separator"in n?n.separator:t.csv.defaults.separator;i.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;var o=[],n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,start:n.start,end:n.end,state:{rowNum:1,colNum:1}};o=t.csv.parsers.parse(e,n);if(!i.callback)return o;i.callback("",o);return void 0},toObjects:function(e,n,r){var n=void 0!==n?n:{},i={};i.callback=void 0!==r&&"function"==typeof r?r:!1;i.separator="separator"in n?n.separator:t.csv.defaults.separator;i.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;i.headers="headers"in n?n.headers:t.csv.defaults.headers;n.start="start"in n?n.start:1;i.headers&&n.start++;n.end&&i.headers&&n.end++;var o=[],a=[],n={delimiter:i.delimiter,separator:i.separator,onParseEntry:n.onParseEntry,onParseValue:n.onParseValue,start:n.start,end:n.end,state:{rowNum:1,colNum:1},match:!1},s={delimiter:i.delimiter,separator:i.separator,start:1,end:1,state:{rowNum:1,colNum:1}},l=t.csv.parsers.splitLines(e,s),u=t.csv.toArray(l[0],n),o=t.csv.parsers.splitLines(e,n);n.state.colNum=1;n.state.rowNum=u?2:1;for(var c=0,f=o.length;f>c;c++){var h=t.csv.toArray(o[c],n),d={};for(var p in u)d[u[p]]=h[p];a.push(d);n.state.rowNum++}if(!i.callback)return a;i.callback("",a);return void 0},fromArrays:function(e,n,r){var n=void 0!==n?n:{},o={};o.callback=void 0!==r&&"function"==typeof r?r:!1;o.separator="separator"in n?n.separator:t.csv.defaults.separator;o.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;o.escaper="escaper"in n?n.escaper:t.csv.defaults.escaper;o.experimental="experimental"in n?n.experimental:!1;if(!o.experimental)throw new Error("not implemented");var a=[];for(i in e)a.push(e[i]);if(!o.callback)return a;o.callback("",a);return void 0},fromObjects2CSV:function(e,n,r){var n=void 0!==n?n:{},o={};o.callback=void 0!==r&&"function"==typeof r?r:!1;o.separator="separator"in n?n.separator:t.csv.defaults.separator;o.delimiter="delimiter"in n?n.delimiter:t.csv.defaults.delimiter;o.experimental="experimental"in n?n.experimental:!1;if(!o.experimental)throw new Error("not implemented");var a=[];for(i in e)a.push(arrays[i]);if(!o.callback)return a;o.callback("",a);return void 0}};t.csvEntry2Array=t.csv.toArray;t.csv2Array=t.csv.toArrays;t.csv2Dictionary=t.csv.toObjects})(jQuery)},{}],4:[function(e,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(e("../../lib/codemirror")):"function"==typeof t&&t.amd?t(["../../lib/codemirror"],i):i(CodeMirror)})(function(t){function e(t,e,r,i){var o=t.getLineHandle(e.line),l=e.ch-1,u=l>=0&&s[o.text.charAt(l)]||s[o.text.charAt(++l)];if(!u)return null;var c=">"==u.charAt(1)?1:-1;if(r&&c>0!=(l==e.ch))return null;var f=t.getTokenTypeAt(a(e.line,l+1)),h=n(t,a(e.line,l+(c>0?1:0)),c,f||null,i);return null==h?null:{from:a(e.line,l),to:h&&h.pos,match:h&&h.ch==u.charAt(0),forward:c>0}}function n(t,e,n,r,i){for(var o=i&&i.maxScanLineLength||1e4,l=i&&i.maxScanLines||1e3,u=[],c=i&&i.bracketRegex?i.bracketRegex:/[(){}[\]]/,f=n>0?Math.min(e.line+l,t.lastLine()+1):Math.max(t.firstLine()-1,e.line-l),h=e.line;h!=f;h+=n){var d=t.getLine(h);if(d){var p=n>0?0:d.length-1,g=n>0?d.length:-1;if(!(d.length>o)){h==e.line&&(p=e.ch-(0>n?1:0));for(;p!=g;p+=n){var m=d.charAt(p);if(c.test(m)&&(void 0===r||t.getTokenTypeAt(a(h,p+1))==r)){var v=s[m];if(">"==v.charAt(1)==n>0)u.push(m);else{if(!u.length)return{pos:a(h,p),ch:m};u.pop()}}}}}}return h-n==(n>0?t.lastLine():t.firstLine())?!1:null}function r(t,n,r){for(var i=t.state.matchBrackets.maxHighlightLineLength||1e3,s=[],l=t.listSelections(),u=0;u<l.length;u++){var c=l[u].empty()&&e(t,l[u].head,!1,r);if(c&&t.getLine(c.from.line).length<=i){var f=c.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";s.push(t.markText(c.from,a(c.from.line,c.from.ch+1),{className:f}));c.to&&t.getLine(c.to.line).length<=i&&s.push(t.markText(c.to,a(c.to.line,c.to.ch+1),{className:f}))}}if(s.length){o&&t.state.focused&&t.display.input.focus();var h=function(){t.operation(function(){for(var t=0;t<s.length;t++)s[t].clear()})};if(!n)return h;setTimeout(h,800)}}function i(t){t.operation(function(){if(l){l();l=null}l=r(t,!1,t.state.matchBrackets)})}var o=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),a=t.Pos,s={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},l=null;t.defineOption("matchBrackets",!1,function(e,n,r){r&&r!=t.Init&&e.off("cursorActivity",i);if(n){e.state.matchBrackets="object"==typeof n?n:{};e.on("cursorActivity",i)}});t.defineExtension("matchBrackets",function(){r(this,!0)});t.defineExtension("findMatchingBracket",function(t,n,r){return e(this,t,n,r)});t.defineExtension("scanForBracket",function(t,e,r,i){return n(this,t,e,r,i)})})},{"../../lib/codemirror":9}],5:[function(e,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(e("../../lib/codemirror")):"function"==typeof t&&t.amd?t(["../../lib/codemirror"],i):i(CodeMirror)})(function(t){"use strict";t.registerHelper("fold","brace",function(e,n){function r(r){for(var i=n.ch,l=0;;){var u=0>=i?-1:s.lastIndexOf(r,i-1);if(-1!=u){if(1==l&&u<n.ch)break;o=e.getTokenTypeAt(t.Pos(a,u+1));if(!/^(comment|string)/.test(o))return u+1;i=u-1}else{if(1==l)break;l=1;i=s.length}}}var i,o,a=n.line,s=e.getLine(a),l="{",u="}",i=r("{");if(null==i){l="[",u="]";i=r("[")}if(null!=i){var c,f,h=1,d=e.lastLine();t:for(var p=a;d>=p;++p)for(var g=e.getLine(p),m=p==a?i:0;;){var v=g.indexOf(l,m),y=g.indexOf(u,m);0>v&&(v=g.length);0>y&&(y=g.length);m=Math.min(v,y);if(m==g.length)break;if(e.getTokenTypeAt(t.Pos(p,m+1))==o)if(m==v)++h;else if(!--h){c=p;f=m;break t}++m}if(null!=c&&(a!=c||f!=i))return{from:t.Pos(a,i),to:t.Pos(c,f)}}});t.registerHelper("fold","import",function(e,n){function r(n){if(n<e.firstLine()||n>e.lastLine())return null;var r=e.getTokenAt(t.Pos(n,1));/\S/.test(r.string)||(r=e.getTokenAt(t.Pos(n,r.end+1)));if("keyword"!=r.type||"import"!=r.string)return null;for(var i=n,o=Math.min(e.lastLine(),n+10);o>=i;++i){var a=e.getLine(i),s=a.indexOf(";");if(-1!=s)return{startCh:r.end,end:t.Pos(i,s)}}}var i,n=n.line,o=r(n);if(!o||r(n-1)||(i=r(n-2))&&i.end.line==n-1)return null;for(var a=o.end;;){var s=r(a.line+1);if(null==s)break;a=s.end}return{from:e.clipPos(t.Pos(n,o.startCh+1)),to:a}});t.registerHelper("fold","include",function(e,n){function r(n){if(n<e.firstLine()||n>e.lastLine())return null;var r=e.getTokenAt(t.Pos(n,1));/\S/.test(r.string)||(r=e.getTokenAt(t.Pos(n,r.end+1)));return"meta"==r.type&&"#include"==r.string.slice(0,8)?r.start+8:void 0}var n=n.line,i=r(n);if(null==i||null!=r(n-1))return null;for(var o=n;;){var a=r(o+1);if(null==a)break;++o}return{from:t.Pos(n,i+1),to:e.clipPos(t.Pos(o))}})})},{"../../lib/codemirror":9}],6:[function(e,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(e("../../lib/codemirror")):"function"==typeof t&&t.amd?t(["../../lib/codemirror"],i):i(CodeMirror)})(function(t){"use strict";function e(e,i,o,a){function s(t){var n=l(e,i);if(!n||n.to.line-n.from.line<u)return null;for(var r=e.findMarksAt(n.from),o=0;o<r.length;++o)if(r[o].__isFold&&"fold"!==a){if(!t)return null;n.cleared=!0;r[o].clear()}return n}if(o&&o.call){var l=o;o=null}else var l=r(e,o,"rangeFinder");"number"==typeof i&&(i=t.Pos(i,0));var u=r(e,o,"minFoldSize"),c=s(!0);if(r(e,o,"scanUp"))for(;!c&&i.line>e.firstLine();){i=t.Pos(i.line-1,0);c=s(!1)}if(c&&!c.cleared&&"unfold"!==a){var f=n(e,o);t.on(f,"mousedown",function(e){h.clear();t.e_preventDefault(e)});var h=e.markText(c.from,c.to,{replacedWith:f,clearOnEnter:!0,__isFold:!0});h.on("clear",function(n,r){t.signal(e,"unfold",e,n,r)});t.signal(e,"fold",e,c.from,c.to)}}function n(t,e){var n=r(t,e,"widget");if("string"==typeof n){var i=document.createTextNode(n);n=document.createElement("span");n.appendChild(i);n.className="CodeMirror-foldmarker"}return n}function r(t,e,n){if(e&&void 0!==e[n])return e[n];var r=t.options.foldOptions;return r&&void 0!==r[n]?r[n]:i[n]}t.newFoldFunction=function(t,n){return function(r,i){e(r,i,{rangeFinder:t,widget:n})}};t.defineExtension("foldCode",function(t,n,r){e(this,t,n,r)});t.defineExtension("isFolded",function(t){for(var e=this.findMarksAt(t),n=0;n<e.length;++n)if(e[n].__isFold)return!0});t.commands.toggleFold=function(t){t.foldCode(t.getCursor())};t.commands.fold=function(t){t.foldCode(t.getCursor(),null,"fold")};t.commands.unfold=function(t){t.foldCode(t.getCursor(),null,"unfold")};t.commands.foldAll=function(e){e.operation(function(){for(var n=e.firstLine(),r=e.lastLine();r>=n;n++)e.foldCode(t.Pos(n,0),null,"fold")})};t.commands.unfoldAll=function(e){e.operation(function(){for(var n=e.firstLine(),r=e.lastLine();r>=n;n++)e.foldCode(t.Pos(n,0),null,"unfold")})};t.registerHelper("fold","combine",function(){var t=Array.prototype.slice.call(arguments,0);return function(e,n){for(var r=0;r<t.length;++r){var i=t[r](e,n);if(i)return i}}});t.registerHelper("fold","auto",function(t,e){for(var n=t.getHelpers(e,"fold"),r=0;r<n.length;r++){var i=n[r](t,e);if(i)return i}});var i={rangeFinder:t.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1};t.defineOption("foldOptions",null)})},{"../../lib/codemirror":9}],7:[function(e,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(e("../../lib/codemirror"),e("./foldcode")):"function"==typeof t&&t.amd?t(["../../lib/codemirror","./foldcode"],i):i(CodeMirror)})(function(t){"use strict";function e(t){this.options=t;this.from=this.to=0}function n(t){t===!0&&(t={});null==t.gutter&&(t.gutter="CodeMirror-foldgutter");null==t.indicatorOpen&&(t.indicatorOpen="CodeMirror-foldgutter-open");null==t.indicatorFolded&&(t.indicatorFolded="CodeMirror-foldgutter-folded");return t}function r(t,e){for(var n=t.findMarksAt(f(e)),r=0;r<n.length;++r)if(n[r].__isFold&&n[r].find().from.line==e)return!0}function i(t){if("string"==typeof t){var e=document.createElement("div");e.className=t+" CodeMirror-guttermarker-subtle";return e}return t.cloneNode(!0)}function o(e,n,o){var a=e.state.foldGutter.options,s=n;e.eachLine(n,o,function(n){var o=null;if(r(e,s))o=i(a.indicatorFolded);else{var l=f(s,0),u=a.rangeFinder||t.fold.auto,c=u&&u(e,l);c&&c.from.line+1<c.to.line&&(o=i(a.indicatorOpen))}e.setGutterMarker(n,a.gutter,o);++s})}function a(t){var e=t.getViewport(),n=t.state.foldGutter;if(n){t.operation(function(){o(t,e.from,e.to)});n.from=e.from;n.to=e.to}}function s(t,e,n){var r=t.state.foldGutter.options;n==r.gutter&&t.foldCode(f(e,0),r.rangeFinder)}function l(t){var e=t.state.foldGutter,n=t.state.foldGutter.options;e.from=e.to=0;clearTimeout(e.changeUpdate);e.changeUpdate=setTimeout(function(){a(t)},n.foldOnChangeTimeSpan||600)}function u(t){var e=t.state.foldGutter,n=t.state.foldGutter.options;clearTimeout(e.changeUpdate);e.changeUpdate=setTimeout(function(){var n=t.getViewport();e.from==e.to||n.from-e.to>20||e.from-n.to>20?a(t):t.operation(function(){if(n.from<e.from){o(t,n.from,e.from);e.from=n.from}if(n.to>e.to){o(t,e.to,n.to);e.to=n.to}})},n.updateViewportTimeSpan||400)}function c(t,e){var n=t.state.foldGutter,r=e.line;r>=n.from&&r<n.to&&o(t,r,r+1)}t.defineOption("foldGutter",!1,function(r,i,o){if(o&&o!=t.Init){r.clearGutter(r.state.foldGutter.options.gutter);r.state.foldGutter=null;r.off("gutterClick",s);r.off("change",l);r.off("viewportChange",u);r.off("fold",c);r.off("unfold",c);r.off("swapDoc",a)}if(i){r.state.foldGutter=new e(n(i));a(r);r.on("gutterClick",s);r.on("change",l);r.on("viewportChange",u);r.on("fold",c);r.on("unfold",c);r.on("swapDoc",a)}});var f=t.Pos})},{"../../lib/codemirror":9,"./foldcode":6}],8:[function(e,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(e("../../lib/codemirror")):"function"==typeof t&&t.amd?t(["../../lib/codemirror"],i):i(CodeMirror)})(function(t){"use strict";function e(t,e){return t.line-e.line||t.ch-e.ch}function n(t,e,n,r){this.line=e;this.ch=n;this.cm=t;this.text=t.getLine(e);this.min=r?r.from:t.firstLine();this.max=r?r.to-1:t.lastLine()}function r(t,e){var n=t.cm.getTokenTypeAt(h(t.line,e));return n&&/\btag\b/.test(n)}function i(t){if(!(t.line>=t.max)){t.ch=0;
t.text=t.cm.getLine(++t.line);return!0}}function o(t){if(!(t.line<=t.min)){t.text=t.cm.getLine(--t.line);t.ch=t.text.length;return!0}}function a(t){for(;;){var e=t.text.indexOf(">",t.ch);if(-1==e){if(i(t))continue;return}if(r(t,e+1)){var n=t.text.lastIndexOf("/",e),o=n>-1&&!/\S/.test(t.text.slice(n+1,e));t.ch=e+1;return o?"selfClose":"regular"}t.ch=e+1}}function s(t){for(;;){var e=t.ch?t.text.lastIndexOf("<",t.ch-1):-1;if(-1==e){if(o(t))continue;return}if(r(t,e+1)){g.lastIndex=e;t.ch=e;var n=g.exec(t.text);if(n&&n.index==e)return n}else t.ch=e}}function l(t){for(;;){g.lastIndex=t.ch;var e=g.exec(t.text);if(!e){if(i(t))continue;return}if(r(t,e.index+1)){t.ch=e.index+e[0].length;return e}t.ch=e.index+1}}function u(t){for(;;){var e=t.ch?t.text.lastIndexOf(">",t.ch-1):-1;if(-1==e){if(o(t))continue;return}if(r(t,e+1)){var n=t.text.lastIndexOf("/",e),i=n>-1&&!/\S/.test(t.text.slice(n+1,e));t.ch=e+1;return i?"selfClose":"regular"}t.ch=e}}function c(t,e){for(var n=[];;){var r,i=l(t),o=t.line,s=t.ch-(i?i[0].length:0);if(!i||!(r=a(t)))return;if("selfClose"!=r)if(i[1]){for(var u=n.length-1;u>=0;--u)if(n[u]==i[2]){n.length=u;break}if(0>u&&(!e||e==i[2]))return{tag:i[2],from:h(o,s),to:h(t.line,t.ch)}}else n.push(i[2])}}function f(t,e){for(var n=[];;){var r=u(t);if(!r)return;if("selfClose"!=r){var i=t.line,o=t.ch,a=s(t);if(!a)return;if(a[1])n.push(a[2]);else{for(var l=n.length-1;l>=0;--l)if(n[l]==a[2]){n.length=l;break}if(0>l&&(!e||e==a[2]))return{tag:a[2],from:h(t.line,t.ch),to:h(i,o)}}}else s(t)}}var h=t.Pos,d="A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",p=d+"-:.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",g=new RegExp("<(/?)(["+d+"]["+p+"]*)","g");t.registerHelper("fold","xml",function(t,e){for(var r=new n(t,e.line,0);;){var i,o=l(r);if(!o||r.line!=e.line||!(i=a(r)))return;if(!o[1]&&"selfClose"!=i){var e=h(r.line,r.ch),s=c(r,o[2]);return s&&{from:e,to:s.from}}}});t.findMatchingTag=function(t,r,i){var o=new n(t,r.line,r.ch,i);if(-1!=o.text.indexOf(">")||-1!=o.text.indexOf("<")){var l=a(o),u=l&&h(o.line,o.ch),d=l&&s(o);if(l&&d&&!(e(o,r)>0)){var p={from:h(o.line,o.ch),to:u,tag:d[2]};if("selfClose"==l)return{open:p,close:null,at:"open"};if(d[1])return{open:f(o,d[2]),close:p,at:"close"};o=new n(t,u.line,u.ch,i);return{open:p,close:c(o,d[2]),at:"open"}}}};t.findEnclosingTag=function(t,e,r){for(var i=new n(t,e.line,e.ch,r);;){var o=f(i);if(!o)break;var a=new n(t,e.line,e.ch,r),s=c(a,o.tag);if(s)return{open:o,close:s}}};t.scanForClosingTag=function(t,e,r,i){var o=new n(t,e.line,e.ch,i?{from:0,to:i}:null);return c(o,r)}})},{"../../lib/codemirror":9}],9:[function(e,n,r){(function(e){if("object"==typeof r&&"object"==typeof n)n.exports=e();else{if("function"==typeof t&&t.amd)return t([],e);this.CodeMirror=e()}})(function(){"use strict";function t(n,r){if(!(this instanceof t))return new t(n,r);this.options=r=r?yo(r):{};yo(ja,r,!1);d(r);var i=r.value;"string"==typeof i&&(i=new rs(i,r.mode));this.doc=i;var o=this.display=new e(n,i);o.wrapper.CodeMirror=this;u(this);s(this);r.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");r.autofocus&&!ca&&_n(this);this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,draggingText:!1,highlight:new co,keySeq:null};Qo&&11>ta&&setTimeout(bo(Tn,this,!0),20);Dn(this);No();Ze(this);this.curOp.forceUpdate=!0;Ni(this,i);r.autofocus&&!ca||Mo()==o.input?setTimeout(bo(Zn,this),20):Qn(this);for(var a in Ia)Ia.hasOwnProperty(a)&&Ia[a](this,r[a],Pa);b(this);for(var l=0;l<Ra.length;++l)Ra[l](this);tn(this)}function e(t,e){var n=this,r=n.input=Co("textarea",null,null,"position: absolute; padding: 0; width: 1px; height: 1em; outline: none");ea?r.style.width="1000px":r.setAttribute("wrap","off");ua&&(r.style.border="1px solid black");r.setAttribute("autocorrect","off");r.setAttribute("autocapitalize","off");r.setAttribute("spellcheck","false");n.inputDiv=Co("div",[r],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");n.scrollbarH=Co("div",[Co("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");n.scrollbarV=Co("div",[Co("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar");n.scrollbarFiller=Co("div",null,"CodeMirror-scrollbar-filler");n.gutterFiller=Co("div",null,"CodeMirror-gutter-filler");n.lineDiv=Co("div",null,"CodeMirror-code");n.selectionDiv=Co("div",null,null,"position: relative; z-index: 1");n.cursorDiv=Co("div",null,"CodeMirror-cursors");n.measure=Co("div",null,"CodeMirror-measure");n.lineMeasure=Co("div",null,"CodeMirror-measure");n.lineSpace=Co("div",[n.measure,n.lineMeasure,n.selectionDiv,n.cursorDiv,n.lineDiv],null,"position: relative; outline: none");n.mover=Co("div",[Co("div",[n.lineSpace],"CodeMirror-lines")],null,"position: relative");n.sizer=Co("div",[n.mover],"CodeMirror-sizer");n.heightForcer=Co("div",null,null,"position: absolute; height: "+ds+"px; width: 1px;");n.gutters=Co("div",null,"CodeMirror-gutters");n.lineGutter=null;n.scroller=Co("div",[n.sizer,n.heightForcer,n.gutters],"CodeMirror-scroll");n.scroller.setAttribute("tabIndex","-1");n.wrapper=Co("div",[n.inputDiv,n.scrollbarH,n.scrollbarV,n.scrollbarFiller,n.gutterFiller,n.scroller],"CodeMirror");if(Qo&&8>ta){n.gutters.style.zIndex=-1;n.scroller.style.paddingRight=0}ua&&(r.style.width="0px");ea||(n.scroller.draggable=!0);if(aa){n.inputDiv.style.height="1px";n.inputDiv.style.position="absolute"}Qo&&8>ta&&(n.scrollbarH.style.minHeight=n.scrollbarV.style.minWidth="18px");t&&(t.appendChild?t.appendChild(n.wrapper):t(n.wrapper));n.viewFrom=n.viewTo=e.first;n.view=[];n.externalMeasured=null;n.viewOffset=0;n.lastWrapHeight=n.lastWrapWidth=0;n.updateLineNumbers=null;n.lineNumWidth=n.lineNumInnerWidth=n.lineNumChars=null;n.prevInput="";n.alignWidgets=!1;n.pollingFast=!1;n.poll=new co;n.cachedCharWidth=n.cachedTextHeight=n.cachedPaddingH=null;n.inaccurateSelection=!1;n.maxLine=null;n.maxLineLength=0;n.maxLineChanged=!1;n.wheelDX=n.wheelDY=n.wheelStartX=n.wheelStartY=null;n.shift=!1;n.selForContextMenu=null}function n(e){e.doc.mode=t.getMode(e.options,e.doc.modeOption);r(e)}function r(t){t.doc.iter(function(t){t.stateAfter&&(t.stateAfter=null);t.styles&&(t.styles=null)});t.doc.frontier=t.doc.first;we(t,100);t.state.modeGen++;t.curOp&&pn(t)}function i(t){if(t.options.lineWrapping){Ls(t.display.wrapper,"CodeMirror-wrap");t.display.sizer.style.minWidth=""}else{Ds(t.display.wrapper,"CodeMirror-wrap");h(t)}a(t);pn(t);Re(t);setTimeout(function(){m(t)},100)}function o(t){var e=Je(t.display),n=t.options.lineWrapping,r=n&&Math.max(5,t.display.scroller.clientWidth/Ke(t.display)-3);return function(i){if(ri(t.doc,i))return 0;var o=0;if(i.widgets)for(var a=0;a<i.widgets.length;a++)i.widgets[a].height&&(o+=i.widgets[a].height);return n?o+(Math.ceil(i.text.length/r)||1)*e:o+e}}function a(t){var e=t.doc,n=o(t);e.iter(function(t){var e=n(t);e!=t.height&&Pi(t,e)})}function s(t){t.display.wrapper.className=t.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+t.options.theme.replace(/(^|\s)\s*/g," cm-s-");Re(t)}function l(t){u(t);pn(t);setTimeout(function(){y(t)},20)}function u(t){var e=t.display.gutters,n=t.options.gutters;To(e);for(var r=0;r<n.length;++r){var i=n[r],o=e.appendChild(Co("div",null,"CodeMirror-gutter "+i));if("CodeMirror-linenumbers"==i){t.display.lineGutter=o;o.style.width=(t.display.lineNumWidth||1)+"px"}}e.style.display=r?"":"none";c(t)}function c(t){var e=t.display.gutters.offsetWidth;t.display.sizer.style.marginLeft=e+"px";t.display.scrollbarH.style.left=t.options.fixedGutter?e+"px":0}function f(t){if(0==t.height)return 0;for(var e,n=t.text.length,r=t;e=Jr(r);){var i=e.find(0,!0);r=i.from.line;n+=i.from.ch-i.to.ch}r=t;for(;e=Kr(r);){var i=e.find(0,!0);n-=r.text.length-i.from.ch;r=i.to.line;n+=r.text.length-i.to.ch}return n}function h(t){var e=t.display,n=t.doc;e.maxLine=Ei(n,n.first);e.maxLineLength=f(e.maxLine);e.maxLineChanged=!0;n.iter(function(t){var n=f(t);if(n>e.maxLineLength){e.maxLineLength=n;e.maxLine=t}})}function d(t){var e=go(t.gutters,"CodeMirror-linenumbers");if(-1==e&&t.lineNumbers)t.gutters=t.gutters.concat(["CodeMirror-linenumbers"]);else if(e>-1&&!t.lineNumbers){t.gutters=t.gutters.slice(0);t.gutters.splice(e,1)}}function p(t){return t.display.scroller.clientHeight-t.display.wrapper.clientHeight<ds-3}function g(t){var e=t.display.scroller;return{clientHeight:e.clientHeight,barHeight:t.display.scrollbarV.clientHeight,scrollWidth:e.scrollWidth,clientWidth:e.clientWidth,hScrollbarTakesSpace:p(t),barWidth:t.display.scrollbarH.clientWidth,docHeight:Math.round(t.doc.height+ke(t.display))}}function m(t,e){e||(e=g(t));var n=t.display,r=jo(n.measure),i=e.docHeight+ds,o=e.scrollWidth>e.clientWidth;o&&e.scrollWidth<=e.clientWidth+1&&r>0&&!e.hScrollbarTakesSpace&&(o=!1);var a=i>e.clientHeight;if(a){n.scrollbarV.style.display="block";n.scrollbarV.style.bottom=o?r+"px":"0";n.scrollbarV.firstChild.style.height=Math.max(0,i-e.clientHeight+(e.barHeight||n.scrollbarV.clientHeight))+"px"}else{n.scrollbarV.style.display="";n.scrollbarV.firstChild.style.height="0"}if(o){n.scrollbarH.style.display="block";n.scrollbarH.style.right=a?r+"px":"0";n.scrollbarH.firstChild.style.width=e.scrollWidth-e.clientWidth+(e.barWidth||n.scrollbarH.clientWidth)+"px"}else{n.scrollbarH.style.display="";n.scrollbarH.firstChild.style.width="0"}if(o&&a){n.scrollbarFiller.style.display="block";n.scrollbarFiller.style.height=n.scrollbarFiller.style.width=r+"px"}else n.scrollbarFiller.style.display="";if(o&&t.options.coverGutterNextToScrollbar&&t.options.fixedGutter){n.gutterFiller.style.display="block";n.gutterFiller.style.height=r+"px";n.gutterFiller.style.width=n.gutters.offsetWidth+"px"}else n.gutterFiller.style.display="";if(!t.state.checkedOverlayScrollbar&&e.clientHeight>0){if(0===r){var s=fa&&!sa?"12px":"18px";n.scrollbarV.style.minWidth=n.scrollbarH.style.minHeight=s;var l=function(e){no(e)!=n.scrollbarV&&no(e)!=n.scrollbarH&&un(t,En)(e)};us(n.scrollbarV,"mousedown",l);us(n.scrollbarH,"mousedown",l)}t.state.checkedOverlayScrollbar=!0}}function v(t,e,n){var r=n&&null!=n.top?Math.max(0,n.top):t.scroller.scrollTop;r=Math.floor(r-_e(t));var i=n&&null!=n.bottom?n.bottom:r+t.wrapper.clientHeight,o=Oi(e,r),a=Oi(e,i);if(n&&n.ensure){var s=n.ensure.from.line,l=n.ensure.to.line;if(o>s)return{from:s,to:Oi(e,Fi(Ei(e,s))+t.wrapper.clientHeight)};if(Math.min(l,e.lastLine())>=a)return{from:Oi(e,Fi(Ei(e,l))-t.wrapper.clientHeight),to:l}}return{from:o,to:Math.max(a,o+1)}}function y(t){var e=t.display,n=e.view;if(e.alignWidgets||e.gutters.firstChild&&t.options.fixedGutter){for(var r=w(e)-e.scroller.scrollLeft+t.doc.scrollLeft,i=e.gutters.offsetWidth,o=r+"px",a=0;a<n.length;a++)if(!n[a].hidden){t.options.fixedGutter&&n[a].gutter&&(n[a].gutter.style.left=o);var s=n[a].alignable;if(s)for(var l=0;l<s.length;l++)s[l].style.left=o}t.options.fixedGutter&&(e.gutters.style.left=r+i+"px")}}function b(t){if(!t.options.lineNumbers)return!1;var e=t.doc,n=x(t.options,e.first+e.size-1),r=t.display;if(n.length!=r.lineNumChars){var i=r.measure.appendChild(Co("div",[Co("div",n)],"CodeMirror-linenumber CodeMirror-gutter-elt")),o=i.firstChild.offsetWidth,a=i.offsetWidth-o;r.lineGutter.style.width="";r.lineNumInnerWidth=Math.max(o,r.lineGutter.offsetWidth-a);r.lineNumWidth=r.lineNumInnerWidth+a;r.lineNumChars=r.lineNumInnerWidth?n.length:-1;r.lineGutter.style.width=r.lineNumWidth+"px";c(t);return!0}return!1}function x(t,e){return String(t.lineNumberFormatter(e+t.firstLineNumber))}function w(t){return t.scroller.getBoundingClientRect().left-t.sizer.getBoundingClientRect().left}function S(t,e,n){var r=t.display;this.viewport=e;this.visible=v(r,t.doc,e);this.editorIsHidden=!r.wrapper.offsetWidth;this.wrapperHeight=r.wrapper.clientHeight;this.wrapperWidth=r.wrapper.clientWidth;this.oldViewFrom=r.viewFrom;this.oldViewTo=r.viewTo;this.oldScrollerWidth=r.scroller.clientWidth;this.force=n;this.dims=A(t)}function C(t,e){var n=t.display,r=t.doc;if(e.editorIsHidden){mn(t);return!1}if(!e.force&&e.visible.from>=n.viewFrom&&e.visible.to<=n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo)&&0==xn(t))return!1;if(b(t)){mn(t);e.dims=A(t)}var i=r.first+r.size,o=Math.max(e.visible.from-t.options.viewportMargin,r.first),a=Math.min(i,e.visible.to+t.options.viewportMargin);n.viewFrom<o&&o-n.viewFrom<20&&(o=Math.max(r.first,n.viewFrom));n.viewTo>a&&n.viewTo-a<20&&(a=Math.min(i,n.viewTo));if(va){o=ei(t.doc,o);a=ni(t.doc,a)}var s=o!=n.viewFrom||a!=n.viewTo||n.lastWrapHeight!=e.wrapperHeight||n.lastWrapWidth!=e.wrapperWidth;bn(t,o,a);n.viewOffset=Fi(Ei(t.doc,n.viewFrom));t.display.mover.style.top=n.viewOffset+"px";var l=xn(t);if(!s&&0==l&&!e.force&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo))return!1;var u=Mo();l>4&&(n.lineDiv.style.display="none");N(t,n.updateLineNumbers,e.dims);l>4&&(n.lineDiv.style.display="");u&&Mo()!=u&&u.offsetHeight&&u.focus();To(n.cursorDiv);To(n.selectionDiv);if(s){n.lastWrapHeight=e.wrapperHeight;n.lastWrapWidth=e.wrapperWidth;we(t,400)}n.updateLineNumbers=null;return!0}function T(t,e){for(var n=e.force,r=e.viewport,i=!0;;i=!1){if(i&&t.options.lineWrapping&&e.oldScrollerWidth!=t.display.scroller.clientWidth)n=!0;else{n=!1;r&&null!=r.top&&(r={top:Math.min(t.doc.height+ke(t.display)-ds-t.display.scroller.clientHeight,r.top)});e.visible=v(t.display,t.doc,r);if(e.visible.from>=t.display.viewFrom&&e.visible.to<=t.display.viewTo)break}if(!C(t,e))break;D(t);var o=g(t);ve(t);k(t,o);m(t,o)}io(t,"update",t);(t.display.viewFrom!=e.oldViewFrom||t.display.viewTo!=e.oldViewTo)&&io(t,"viewportChange",t,t.display.viewFrom,t.display.viewTo)}function _(t,e){var n=new S(t,e);if(C(t,n)){D(t);T(t,n);var r=g(t);ve(t);k(t,r);m(t,r)}}function k(t,e){t.display.sizer.style.minHeight=t.display.heightForcer.style.top=e.docHeight+"px";t.display.gutters.style.height=Math.max(e.docHeight,e.clientHeight-ds)+"px"}function M(t,e){if(t.display.sizer.offsetWidth+t.display.gutters.offsetWidth<t.display.scroller.clientWidth-1){t.display.sizer.style.minHeight=t.display.heightForcer.style.top="0px";t.display.gutters.style.height=e.docHeight+"px"}}function D(t){for(var e=t.display,n=e.lineDiv.offsetTop,r=0;r<e.view.length;r++){var i,o=e.view[r];if(!o.hidden){if(Qo&&8>ta){var a=o.node.offsetTop+o.node.offsetHeight;i=a-n;n=a}else{var s=o.node.getBoundingClientRect();i=s.bottom-s.top}var l=o.line.height-i;2>i&&(i=Je(e));if(l>.001||-.001>l){Pi(o.line,i);L(o.line);if(o.rest)for(var u=0;u<o.rest.length;u++)L(o.rest[u])}}}}function L(t){if(t.widgets)for(var e=0;e<t.widgets.length;++e)t.widgets[e].height=t.widgets[e].node.offsetHeight}function A(t){for(var e=t.display,n={},r={},i=e.gutters.clientLeft,o=e.gutters.firstChild,a=0;o;o=o.nextSibling,++a){n[t.options.gutters[a]]=o.offsetLeft+o.clientLeft+i;r[t.options.gutters[a]]=o.clientWidth}return{fixedPos:w(e),gutterTotalWidth:e.gutters.offsetWidth,gutterLeft:n,gutterWidth:r,wrapperWidth:e.wrapper.clientWidth}}function N(t,e,n){function r(e){var n=e.nextSibling;ea&&fa&&t.display.currentWheelTarget==e?e.style.display="none":e.parentNode.removeChild(e);return n}for(var i=t.display,o=t.options.lineNumbers,a=i.lineDiv,s=a.firstChild,l=i.view,u=i.viewFrom,c=0;c<l.length;c++){var f=l[c];if(f.hidden);else if(f.node){for(;s!=f.node;)s=r(s);var h=o&&null!=e&&u>=e&&f.lineNumber;if(f.changes){go(f.changes,"gutter")>-1&&(h=!1);E(t,f,u,n)}if(h){To(f.lineNumber);f.lineNumber.appendChild(document.createTextNode(x(t.options,u)))}s=f.node.nextSibling}else{var d=W(t,f,u,n);a.insertBefore(d,s)}u+=f.size}for(;s;)s=r(s)}function E(t,e,n,r){for(var i=0;i<e.changes.length;i++){var o=e.changes[i];"text"==o?H(t,e):"gutter"==o?F(t,e,n,r):"class"==o?O(e):"widget"==o&&R(e,r)}e.changes=null}function j(t){if(t.node==t.text){t.node=Co("div",null,null,"position: relative");t.text.parentNode&&t.text.parentNode.replaceChild(t.node,t.text);t.node.appendChild(t.text);Qo&&8>ta&&(t.node.style.zIndex=2)}return t.node}function I(t){var e=t.bgClass?t.bgClass+" "+(t.line.bgClass||""):t.line.bgClass;e&&(e+=" CodeMirror-linebackground");if(t.background)if(e)t.background.className=e;else{t.background.parentNode.removeChild(t.background);t.background=null}else if(e){var n=j(t);t.background=n.insertBefore(Co("div",null,e),n.firstChild)}}function P(t,e){var n=t.display.externalMeasured;if(n&&n.line==e.line){t.display.externalMeasured=null;e.measure=n.measure;return n.built}return bi(t,e)}function H(t,e){var n=e.text.className,r=P(t,e);e.text==e.node&&(e.node=r.pre);e.text.parentNode.replaceChild(r.pre,e.text);e.text=r.pre;if(r.bgClass!=e.bgClass||r.textClass!=e.textClass){e.bgClass=r.bgClass;e.textClass=r.textClass;O(e)}else n&&(e.text.className=n)}function O(t){I(t);t.line.wrapClass?j(t).className=t.line.wrapClass:t.node!=t.text&&(t.node.className="");var e=t.textClass?t.textClass+" "+(t.line.textClass||""):t.line.textClass;t.text.className=e||""}function F(t,e,n,r){if(e.gutter){e.node.removeChild(e.gutter);e.gutter=null}var i=e.line.gutterMarkers;if(t.options.lineNumbers||i){var o=j(e),a=e.gutter=o.insertBefore(Co("div",null,"CodeMirror-gutter-wrapper","left: "+(t.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px; width: "+r.gutterTotalWidth+"px"),e.text);e.line.gutterClass&&(a.className+=" "+e.line.gutterClass);!t.options.lineNumbers||i&&i["CodeMirror-linenumbers"]||(e.lineNumber=a.appendChild(Co("div",x(t.options,n),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+r.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+t.display.lineNumInnerWidth+"px")));if(i)for(var s=0;s<t.options.gutters.length;++s){var l=t.options.gutters[s],u=i.hasOwnProperty(l)&&i[l];u&&a.appendChild(Co("div",[u],"CodeMirror-gutter-elt","left: "+r.gutterLeft[l]+"px; width: "+r.gutterWidth[l]+"px"))}}}function R(t,e){t.alignable&&(t.alignable=null);for(var n,r=t.node.firstChild;r;r=n){var n=r.nextSibling;"CodeMirror-linewidget"==r.className&&t.node.removeChild(r)}z(t,e)}function W(t,e,n,r){var i=P(t,e);e.text=e.node=i.pre;i.bgClass&&(e.bgClass=i.bgClass);i.textClass&&(e.textClass=i.textClass);O(e);F(t,e,n,r);z(e,r);return e.node}function z(t,e){q(t.line,t,e,!0);if(t.rest)for(var n=0;n<t.rest.length;n++)q(t.rest[n],t,e,!1)}function q(t,e,n,r){if(t.widgets)for(var i=j(e),o=0,a=t.widgets;o<a.length;++o){var s=a[o],l=Co("div",[s.node],"CodeMirror-linewidget");s.handleMouseEvents||(l.ignoreEvents=!0);U(s,l,e,n);r&&s.above?i.insertBefore(l,e.gutter||e.text):i.appendChild(l);io(s,"redraw")}}function U(t,e,n,r){if(t.noHScroll){(n.alignable||(n.alignable=[])).push(e);var i=r.wrapperWidth;e.style.left=r.fixedPos+"px";if(!t.coverGutter){i-=r.gutterTotalWidth;e.style.paddingLeft=r.gutterTotalWidth+"px"}e.style.width=i+"px"}if(t.coverGutter){e.style.zIndex=5;e.style.position="relative";t.noHScroll||(e.style.marginLeft=-r.gutterTotalWidth+"px")}}function B(t){return ya(t.line,t.ch)}function V(t,e){return ba(t,e)<0?e:t}function X(t,e){return ba(t,e)<0?t:e}function G(t,e){this.ranges=t;this.primIndex=e}function $(t,e){this.anchor=t;this.head=e}function Y(t,e){var n=t[e];t.sort(function(t,e){return ba(t.from(),e.from())});e=go(t,n);for(var r=1;r<t.length;r++){var i=t[r],o=t[r-1];if(ba(o.to(),i.from())>=0){var a=X(o.from(),i.from()),s=V(o.to(),i.to()),l=o.empty()?i.from()==i.head:o.from()==o.head;e>=r&&--e;t.splice(--r,2,new $(l?s:a,l?a:s))}}return new G(t,e)}function J(t,e){return new G([new $(t,e||t)],0)}function K(t,e){return Math.max(t.first,Math.min(e,t.first+t.size-1))}function Z(t,e){if(e.line<t.first)return ya(t.first,0);var n=t.first+t.size-1;return e.line>n?ya(n,Ei(t,n).text.length):Q(e,Ei(t,e.line).text.length)}function Q(t,e){var n=t.ch;return null==n||n>e?ya(t.line,e):0>n?ya(t.line,0):t}function te(t,e){return e>=t.first&&e<t.first+t.size}function ee(t,e){for(var n=[],r=0;r<e.length;r++)n[r]=Z(t,e[r]);return n}function ne(t,e,n,r){if(t.cm&&t.cm.display.shift||t.extend){var i=e.anchor;if(r){var o=ba(n,i)<0;if(o!=ba(r,i)<0){i=n;n=r}else o!=ba(n,r)<0&&(n=r)}return new $(i,n)}return new $(r||n,n)}function re(t,e,n,r){ue(t,new G([ne(t,t.sel.primary(),e,n)],0),r)}function ie(t,e,n){for(var r=[],i=0;i<t.sel.ranges.length;i++)r[i]=ne(t,t.sel.ranges[i],e[i],null);var o=Y(r,t.sel.primIndex);ue(t,o,n)}function oe(t,e,n,r){var i=t.sel.ranges.slice(0);i[e]=n;ue(t,Y(i,t.sel.primIndex),r)}function ae(t,e,n,r){ue(t,J(e,n),r)}function se(t,e){var n={ranges:e.ranges,update:function(e){this.ranges=[];for(var n=0;n<e.length;n++)this.ranges[n]=new $(Z(t,e[n].anchor),Z(t,e[n].head))}};fs(t,"beforeSelectionChange",t,n);t.cm&&fs(t.cm,"beforeSelectionChange",t.cm,n);return n.ranges!=e.ranges?Y(n.ranges,n.ranges.length-1):e}function le(t,e,n){var r=t.history.done,i=po(r);if(i&&i.ranges){r[r.length-1]=e;ce(t,e,n)}else ue(t,e,n)}function ue(t,e,n){ce(t,e,n);Xi(t,t.sel,t.cm?t.cm.curOp.id:0/0,n)}function ce(t,e,n){(lo(t,"beforeSelectionChange")||t.cm&&lo(t.cm,"beforeSelectionChange"))&&(e=se(t,e));var r=n&&n.bias||(ba(e.primary().head,t.sel.primary().head)<0?-1:1);fe(t,de(t,e,r,!0));n&&n.scroll===!1||!t.cm||br(t.cm)}function fe(t,e){if(!e.equals(t.sel)){t.sel=e;if(t.cm){t.cm.curOp.updateInput=t.cm.curOp.selectionChanged=!0;so(t.cm)}io(t,"cursorActivity",t)}}function he(t){fe(t,de(t,t.sel,null,!1),gs)}function de(t,e,n,r){for(var i,o=0;o<e.ranges.length;o++){var a=e.ranges[o],s=pe(t,a.anchor,n,r),l=pe(t,a.head,n,r);if(i||s!=a.anchor||l!=a.head){i||(i=e.ranges.slice(0,o));i[o]=new $(s,l)}}return i?Y(i,e.primIndex):e}function pe(t,e,n,r){var i=!1,o=e,a=n||1;t.cantEdit=!1;t:for(;;){var s=Ei(t,o.line);if(s.markedSpans)for(var l=0;l<s.markedSpans.length;++l){var u=s.markedSpans[l],c=u.marker;if((null==u.from||(c.inclusiveLeft?u.from<=o.ch:u.from<o.ch))&&(null==u.to||(c.inclusiveRight?u.to>=o.ch:u.to>o.ch))){if(r){fs(c,"beforeCursorEnter");if(c.explicitlyCleared){if(s.markedSpans){--l;continue}break}}if(!c.atomic)continue;var f=c.find(0>a?-1:1);if(0==ba(f,o)){f.ch+=a;f.ch<0?f=f.line>t.first?Z(t,ya(f.line-1)):null:f.ch>s.text.length&&(f=f.line<t.first+t.size-1?ya(f.line+1,0):null);if(!f){if(i){if(!r)return pe(t,e,n,!0);t.cantEdit=!0;return ya(t.first,0)}i=!0;f=e;a=-a}}o=f;continue t}}return o}}function ge(t){for(var e=t.display,n=t.doc,r={},i=r.cursors=document.createDocumentFragment(),o=r.selection=document.createDocumentFragment(),a=0;a<n.sel.ranges.length;a++){var s=n.sel.ranges[a],l=s.empty();(l||t.options.showCursorWhenSelecting)&&ye(t,s,i);l||be(t,s,o)}if(t.options.moveInputWithCursor){var u=Ve(t,n.sel.primary().head,"div"),c=e.wrapper.getBoundingClientRect(),f=e.lineDiv.getBoundingClientRect();r.teTop=Math.max(0,Math.min(e.wrapper.clientHeight-10,u.top+f.top-c.top));r.teLeft=Math.max(0,Math.min(e.wrapper.clientWidth-10,u.left+f.left-c.left))}return r}function me(t,e){_o(t.display.cursorDiv,e.cursors);_o(t.display.selectionDiv,e.selection);if(null!=e.teTop){t.display.inputDiv.style.top=e.teTop+"px";t.display.inputDiv.style.left=e.teLeft+"px"}}function ve(t){me(t,ge(t))}function ye(t,e,n){var r=Ve(t,e.head,"div",null,null,!t.options.singleCursorHeightPerLine),i=n.appendChild(Co("div"," ","CodeMirror-cursor"));i.style.left=r.left+"px";i.style.top=r.top+"px";i.style.height=Math.max(0,r.bottom-r.top)*t.options.cursorHeight+"px";if(r.other){var o=n.appendChild(Co("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));o.style.display="";o.style.left=r.other.left+"px";o.style.top=r.other.top+"px";o.style.height=.85*(r.other.bottom-r.other.top)+"px"}}function be(t,e,n){function r(t,e,n,r){0>e&&(e=0);e=Math.round(e);r=Math.round(r);s.appendChild(Co("div",null,"CodeMirror-selected","position: absolute; left: "+t+"px; top: "+e+"px; width: "+(null==n?c-t:n)+"px; height: "+(r-e)+"px"))}function i(e,n,i){function o(n,r){return Be(t,ya(e,n),"div",f,r)}var s,l,f=Ei(a,e),h=f.text.length;Oo(Ri(f),n||0,null==i?h:i,function(t,e,a){var f,d,p,g=o(t,"left");if(t==e){f=g;d=p=g.left}else{f=o(e-1,"right");if("rtl"==a){var m=g;g=f;f=m}d=g.left;p=f.right}null==n&&0==t&&(d=u);if(f.top-g.top>3){r(d,g.top,null,g.bottom);d=u;g.bottom<f.top&&r(d,g.bottom,null,f.top)}null==i&&e==h&&(p=c);(!s||g.top<s.top||g.top==s.top&&g.left<s.left)&&(s=g);(!l||f.bottom>l.bottom||f.bottom==l.bottom&&f.right>l.right)&&(l=f);u+1>d&&(d=u);r(d,f.top,p-d,f.bottom)});return{start:s,end:l}}var o=t.display,a=t.doc,s=document.createDocumentFragment(),l=Me(t.display),u=l.left,c=o.lineSpace.offsetWidth-l.right,f=e.from(),h=e.to();if(f.line==h.line)i(f.line,f.ch,h.ch);else{var d=Ei(a,f.line),p=Ei(a,h.line),g=Qr(d)==Qr(p),m=i(f.line,f.ch,g?d.text.length+1:null).end,v=i(h.line,g?0:null,h.ch).start;if(g)if(m.top<v.top-2){r(m.right,m.top,null,m.bottom);r(u,v.top,v.left,v.bottom)}else r(m.right,m.top,v.left-m.right,m.bottom);m.bottom<v.top&&r(u,m.bottom,null,v.top)}n.appendChild(s)}function xe(t){if(t.state.focused){var e=t.display;clearInterval(e.blinker);var n=!0;e.cursorDiv.style.visibility="";t.options.cursorBlinkRate>0?e.blinker=setInterval(function(){e.cursorDiv.style.visibility=(n=!n)?"":"hidden"},t.options.cursorBlinkRate):t.options.cursorBlinkRate<0&&(e.cursorDiv.style.visibility="hidden")}}function we(t,e){t.doc.mode.startState&&t.doc.frontier<t.display.viewTo&&t.state.highlight.set(e,bo(Se,t))}function Se(t){var e=t.doc;e.frontier<e.first&&(e.frontier=e.first);if(!(e.frontier>=t.display.viewTo)){var n=+new Date+t.options.workTime,r=za(e.mode,Te(t,e.frontier)),i=[];e.iter(e.frontier,Math.min(e.first+e.size,t.display.viewTo+500),function(o){if(e.frontier>=t.display.viewFrom){var a=o.styles,s=gi(t,o,r,!0);o.styles=s.styles;var l=o.styleClasses,u=s.classes;u?o.styleClasses=u:l&&(o.styleClasses=null);for(var c=!a||a.length!=o.styles.length||l!=u&&(!l||!u||l.bgClass!=u.bgClass||l.textClass!=u.textClass),f=0;!c&&f<a.length;++f)c=a[f]!=o.styles[f];c&&i.push(e.frontier);o.stateAfter=za(e.mode,r)}else{vi(t,o.text,r);o.stateAfter=e.frontier%5==0?za(e.mode,r):null}++e.frontier;if(+new Date>n){we(t,t.options.workDelay);return!0}});i.length&&ln(t,function(){for(var e=0;e<i.length;e++)gn(t,i[e],"text")})}}function Ce(t,e,n){for(var r,i,o=t.doc,a=n?-1:e-(t.doc.mode.innerMode?1e3:100),s=e;s>a;--s){if(s<=o.first)return o.first;var l=Ei(o,s-1);if(l.stateAfter&&(!n||s<=o.frontier))return s;var u=ys(l.text,null,t.options.tabSize);if(null==i||r>u){i=s-1;r=u}}return i}function Te(t,e,n){var r=t.doc,i=t.display;if(!r.mode.startState)return!0;var o=Ce(t,e,n),a=o>r.first&&Ei(r,o-1).stateAfter;a=a?za(r.mode,a):qa(r.mode);r.iter(o,e,function(n){vi(t,n.text,a);var s=o==e-1||o%5==0||o>=i.viewFrom&&o<i.viewTo;n.stateAfter=s?za(r.mode,a):null;++o});n&&(r.frontier=o);return a}function _e(t){return t.lineSpace.offsetTop}function ke(t){return t.mover.offsetHeight-t.lineSpace.offsetHeight}function Me(t){if(t.cachedPaddingH)return t.cachedPaddingH;var e=_o(t.measure,Co("pre","x")),n=window.getComputedStyle?window.getComputedStyle(e):e.currentStyle,r={left:parseInt(n.paddingLeft),right:parseInt(n.paddingRight)};isNaN(r.left)||isNaN(r.right)||(t.cachedPaddingH=r);return r}function De(t,e,n){var r=t.options.lineWrapping,i=r&&t.display.scroller.clientWidth;if(!e.measure.heights||r&&e.measure.width!=i){var o=e.measure.heights=[];if(r){e.measure.width=i;for(var a=e.text.firstChild.getClientRects(),s=0;s<a.length-1;s++){var l=a[s],u=a[s+1];Math.abs(l.bottom-u.bottom)>2&&o.push((l.bottom+u.top)/2-n.top)}}o.push(n.bottom-n.top)}}function Le(t,e,n){if(t.line==e)return{map:t.measure.map,cache:t.measure.cache};for(var r=0;r<t.rest.length;r++)if(t.rest[r]==e)return{map:t.measure.maps[r],cache:t.measure.caches[r]};for(var r=0;r<t.rest.length;r++)if(Hi(t.rest[r])>n)return{map:t.measure.maps[r],cache:t.measure.caches[r],before:!0}}function Ae(t,e){e=Qr(e);var n=Hi(e),r=t.display.externalMeasured=new hn(t.doc,e,n);r.lineN=n;var i=r.built=bi(t,r);r.text=i.pre;_o(t.display.lineMeasure,i.pre);return r}function Ne(t,e,n,r){return Ie(t,je(t,e),n,r)}function Ee(t,e){if(e>=t.display.viewFrom&&e<t.display.viewTo)return t.display.view[vn(t,e)];var n=t.display.externalMeasured;return n&&e>=n.lineN&&e<n.lineN+n.size?n:void 0}function je(t,e){var n=Hi(e),r=Ee(t,n);r&&!r.text?r=null:r&&r.changes&&E(t,r,n,A(t));r||(r=Ae(t,e));var i=Le(r,e,n);return{line:e,view:r,rect:null,map:i.map,cache:i.cache,before:i.before,hasHeights:!1}}function Ie(t,e,n,r,i){e.before&&(n=-1);var o,a=n+(r||"");if(e.cache.hasOwnProperty(a))o=e.cache[a];else{e.rect||(e.rect=e.view.text.getBoundingClientRect());if(!e.hasHeights){De(t,e.view,e.rect);e.hasHeights=!0}o=Pe(t,e,n,r);o.bogus||(e.cache[a]=o)}return{left:o.left,right:o.right,top:i?o.rtop:o.top,bottom:i?o.rbottom:o.bottom}}function Pe(t,e,n,r){for(var i,o,a,s,l=e.map,u=0;u<l.length;u+=3){var c=l[u],f=l[u+1];if(c>n){o=0;a=1;s="left"}else if(f>n){o=n-c;a=o+1}else if(u==l.length-3||n==f&&l[u+3]>n){a=f-c;o=a-1;n>=f&&(s="right")}if(null!=o){i=l[u+2];c==f&&r==(i.insertLeft?"left":"right")&&(s=r);if("left"==r&&0==o)for(;u&&l[u-2]==l[u-3]&&l[u-1].insertLeft;){i=l[(u-=3)+2];s="left"}if("right"==r&&o==f-c)for(;u<l.length-3&&l[u+3]==l[u+4]&&!l[u+5].insertLeft;){i=l[(u+=3)+2];s="right"}break}}var h;if(3==i.nodeType){for(var u=0;4>u;u++){for(;o&&So(e.line.text.charAt(c+o));)--o;for(;f>c+a&&So(e.line.text.charAt(c+a));)++a;if(Qo&&9>ta&&0==o&&a==f-c)h=i.parentNode.getBoundingClientRect();else if(Qo&&t.options.lineWrapping){var d=ws(i,o,a).getClientRects();h=d.length?d["right"==r?d.length-1:0]:Ca}else h=ws(i,o,a).getBoundingClientRect()||Ca;if(h.left||h.right||0==o)break;a=o;o-=1;s="right"}Qo&&11>ta&&(h=He(t.display.measure,h))}else{o>0&&(s=r="right");var d;h=t.options.lineWrapping&&(d=i.getClientRects()).length>1?d["right"==r?d.length-1:0]:i.getBoundingClientRect()}if(Qo&&9>ta&&!o&&(!h||!h.left&&!h.right)){var p=i.parentNode.getClientRects()[0];h=p?{left:p.left,right:p.left+Ke(t.display),top:p.top,bottom:p.bottom}:Ca}for(var g=h.top-e.rect.top,m=h.bottom-e.rect.top,v=(g+m)/2,y=e.view.measure.heights,u=0;u<y.length-1&&!(v<y[u]);u++);var b=u?y[u-1]:0,x=y[u],w={left:("right"==s?h.right:h.left)-e.rect.left,right:("left"==s?h.left:h.right)-e.rect.left,top:b,bottom:x};h.left||h.right||(w.bogus=!0);if(!t.options.singleCursorHeightPerLine){w.rtop=g;w.rbottom=m}return w}function He(t,e){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!Ho(t))return e;var n=screen.logicalXDPI/screen.deviceXDPI,r=screen.logicalYDPI/screen.deviceYDPI;return{left:e.left*n,right:e.right*n,top:e.top*r,bottom:e.bottom*r}}function Oe(t){if(t.measure){t.measure.cache={};t.measure.heights=null;if(t.rest)for(var e=0;e<t.rest.length;e++)t.measure.caches[e]={}}}function Fe(t){t.display.externalMeasure=null;To(t.display.lineMeasure);for(var e=0;e<t.display.view.length;e++)Oe(t.display.view[e])}function Re(t){Fe(t);t.display.cachedCharWidth=t.display.cachedTextHeight=t.display.cachedPaddingH=null;t.options.lineWrapping||(t.display.maxLineChanged=!0);t.display.lineNumChars=null}function We(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function ze(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function qe(t,e,n,r){if(e.widgets)for(var i=0;i<e.widgets.length;++i)if(e.widgets[i].above){var o=ai(e.widgets[i]);n.top+=o;n.bottom+=o}if("line"==r)return n;r||(r="local");var a=Fi(e);"local"==r?a+=_e(t.display):a-=t.display.viewOffset;if("page"==r||"window"==r){var s=t.display.lineSpace.getBoundingClientRect();a+=s.top+("window"==r?0:ze());var l=s.left+("window"==r?0:We());n.left+=l;n.right+=l}n.top+=a;n.bottom+=a;return n}function Ue(t,e,n){if("div"==n)return e;var r=e.left,i=e.top;if("page"==n){r-=We();i-=ze()}else if("local"==n||!n){var o=t.display.sizer.getBoundingClientRect();r+=o.left;i+=o.top}var a=t.display.lineSpace.getBoundingClientRect();return{left:r-a.left,top:i-a.top}}function Be(t,e,n,r,i){r||(r=Ei(t.doc,e.line));return qe(t,r,Ne(t,r,e.ch,i),n)}function Ve(t,e,n,r,i,o){function a(e,a){var s=Ie(t,i,e,a?"right":"left",o);a?s.left=s.right:s.right=s.left;return qe(t,r,s,n)}function s(t,e){var n=l[e],r=n.level%2;if(t==Fo(n)&&e&&n.level<l[e-1].level){n=l[--e];t=Ro(n)-(n.level%2?0:1);r=!0}else if(t==Ro(n)&&e<l.length-1&&n.level<l[e+1].level){n=l[++e];
t=Fo(n)-n.level%2;r=!1}return r&&t==n.to&&t>n.from?a(t-1):a(t,r)}r=r||Ei(t.doc,e.line);i||(i=je(t,r));var l=Ri(r),u=e.ch;if(!l)return a(u);var c=Xo(l,u),f=s(u,c);null!=Os&&(f.other=s(u,Os));return f}function Xe(t,e){var n=0,e=Z(t.doc,e);t.options.lineWrapping||(n=Ke(t.display)*e.ch);var r=Ei(t.doc,e.line),i=Fi(r)+_e(t.display);return{left:n,right:n,top:i,bottom:i+r.height}}function Ge(t,e,n,r){var i=ya(t,e);i.xRel=r;n&&(i.outside=!0);return i}function $e(t,e,n){var r=t.doc;n+=t.display.viewOffset;if(0>n)return Ge(r.first,0,!0,-1);var i=Oi(r,n),o=r.first+r.size-1;if(i>o)return Ge(r.first+r.size-1,Ei(r,o).text.length,!0,1);0>e&&(e=0);for(var a=Ei(r,i);;){var s=Ye(t,a,i,e,n),l=Kr(a),u=l&&l.find(0,!0);if(!l||!(s.ch>u.from.ch||s.ch==u.from.ch&&s.xRel>0))return s;i=Hi(a=u.to.line)}}function Ye(t,e,n,r,i){function o(r){var i=Ve(t,ya(n,r),"line",e,u);s=!0;if(a>i.bottom)return i.left-l;if(a<i.top)return i.left+l;s=!1;return i.left}var a=i-Fi(e),s=!1,l=2*t.display.wrapper.clientWidth,u=je(t,e),c=Ri(e),f=e.text.length,h=Wo(e),d=zo(e),p=o(h),g=s,m=o(d),v=s;if(r>m)return Ge(n,d,v,1);for(;;){if(c?d==h||d==$o(e,h,1):1>=d-h){for(var y=p>r||m-r>=r-p?h:d,b=r-(y==h?p:m);So(e.text.charAt(y));)++y;var x=Ge(n,y,y==h?g:v,-1>b?-1:b>1?1:0);return x}var w=Math.ceil(f/2),S=h+w;if(c){S=h;for(var C=0;w>C;++C)S=$o(e,S,1)}var T=o(S);if(T>r){d=S;m=T;(v=s)&&(m+=1e3);f=w}else{h=S;p=T;g=s;f-=w}}}function Je(t){if(null!=t.cachedTextHeight)return t.cachedTextHeight;if(null==xa){xa=Co("pre");for(var e=0;49>e;++e){xa.appendChild(document.createTextNode("x"));xa.appendChild(Co("br"))}xa.appendChild(document.createTextNode("x"))}_o(t.measure,xa);var n=xa.offsetHeight/50;n>3&&(t.cachedTextHeight=n);To(t.measure);return n||1}function Ke(t){if(null!=t.cachedCharWidth)return t.cachedCharWidth;var e=Co("span","xxxxxxxxxx"),n=Co("pre",[e]);_o(t.measure,n);var r=e.getBoundingClientRect(),i=(r.right-r.left)/10;i>2&&(t.cachedCharWidth=i);return i||10}function Ze(t){t.curOp={cm:t,viewChanged:!1,startHeight:t.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,id:++_a};Ta?Ta.ops.push(t.curOp):t.curOp.ownsGroup=Ta={ops:[t.curOp],delayedCallbacks:[]}}function Qe(t){var e=t.delayedCallbacks,n=0;do{for(;n<e.length;n++)e[n]();for(var r=0;r<t.ops.length;r++){var i=t.ops[r];if(i.cursorActivityHandlers)for(;i.cursorActivityCalled<i.cursorActivityHandlers.length;)i.cursorActivityHandlers[i.cursorActivityCalled++](i.cm)}}while(n<e.length)}function tn(t){var e=t.curOp,n=e.ownsGroup;if(n)try{Qe(n)}finally{Ta=null;for(var r=0;r<n.ops.length;r++)n.ops[r].cm.curOp=null;en(n)}}function en(t){for(var e=t.ops,n=0;n<e.length;n++)nn(e[n]);for(var n=0;n<e.length;n++)rn(e[n]);for(var n=0;n<e.length;n++)on(e[n]);for(var n=0;n<e.length;n++)an(e[n]);for(var n=0;n<e.length;n++)sn(e[n])}function nn(t){var e=t.cm,n=e.display;t.updateMaxLine&&h(e);t.mustUpdate=t.viewChanged||t.forceUpdate||null!=t.scrollTop||t.scrollToPos&&(t.scrollToPos.from.line<n.viewFrom||t.scrollToPos.to.line>=n.viewTo)||n.maxLineChanged&&e.options.lineWrapping;t.update=t.mustUpdate&&new S(e,t.mustUpdate&&{top:t.scrollTop,ensure:t.scrollToPos},t.forceUpdate)}function rn(t){t.updatedDisplay=t.mustUpdate&&C(t.cm,t.update)}function on(t){var e=t.cm,n=e.display;t.updatedDisplay&&D(e);t.barMeasure=g(e);if(n.maxLineChanged&&!e.options.lineWrapping){t.adjustWidthTo=Ne(e,n.maxLine,n.maxLine.text.length).left+3;t.maxScrollLeft=Math.max(0,n.sizer.offsetLeft+t.adjustWidthTo+ds-n.scroller.clientWidth)}(t.updatedDisplay||t.selectionChanged)&&(t.newSelectionNodes=ge(e))}function an(t){var e=t.cm;if(null!=t.adjustWidthTo){e.display.sizer.style.minWidth=t.adjustWidthTo+"px";t.maxScrollLeft<e.doc.scrollLeft&&zn(e,Math.min(e.display.scroller.scrollLeft,t.maxScrollLeft),!0);e.display.maxLineChanged=!1}t.newSelectionNodes&&me(e,t.newSelectionNodes);t.updatedDisplay&&k(e,t.barMeasure);(t.updatedDisplay||t.startHeight!=e.doc.height)&&m(e,t.barMeasure);t.selectionChanged&&xe(e);e.state.focused&&t.updateInput&&Tn(e,t.typing)}function sn(t){var e=t.cm,n=e.display,r=e.doc;null!=t.adjustWidthTo&&Math.abs(t.barMeasure.scrollWidth-e.display.scroller.scrollWidth)>1&&m(e);t.updatedDisplay&&T(e,t.update);null==n.wheelStartX||null==t.scrollTop&&null==t.scrollLeft&&!t.scrollToPos||(n.wheelStartX=n.wheelStartY=null);if(null!=t.scrollTop&&(n.scroller.scrollTop!=t.scrollTop||t.forceScroll)){var i=Math.max(0,Math.min(n.scroller.scrollHeight-n.scroller.clientHeight,t.scrollTop));n.scroller.scrollTop=n.scrollbarV.scrollTop=r.scrollTop=i}if(null!=t.scrollLeft&&(n.scroller.scrollLeft!=t.scrollLeft||t.forceScroll)){var o=Math.max(0,Math.min(n.scroller.scrollWidth-n.scroller.clientWidth,t.scrollLeft));n.scroller.scrollLeft=n.scrollbarH.scrollLeft=r.scrollLeft=o;y(e)}if(t.scrollToPos){var a=gr(e,Z(r,t.scrollToPos.from),Z(r,t.scrollToPos.to),t.scrollToPos.margin);t.scrollToPos.isCursor&&e.state.focused&&pr(e,a)}var s=t.maybeHiddenMarkers,l=t.maybeUnhiddenMarkers;if(s)for(var u=0;u<s.length;++u)s[u].lines.length||fs(s[u],"hide");if(l)for(var u=0;u<l.length;++u)l[u].lines.length&&fs(l[u],"unhide");n.wrapper.offsetHeight&&(r.scrollTop=e.display.scroller.scrollTop);if(t.updatedDisplay&&ea){e.options.lineWrapping&&M(e,t.barMeasure);t.barMeasure.scrollWidth>t.barMeasure.clientWidth&&t.barMeasure.scrollWidth<t.barMeasure.clientWidth+1&&!p(e)&&m(e)}t.changeObjs&&fs(e,"changes",e,t.changeObjs)}function ln(t,e){if(t.curOp)return e();Ze(t);try{return e()}finally{tn(t)}}function un(t,e){return function(){if(t.curOp)return e.apply(t,arguments);Ze(t);try{return e.apply(t,arguments)}finally{tn(t)}}}function cn(t){return function(){if(this.curOp)return t.apply(this,arguments);Ze(this);try{return t.apply(this,arguments)}finally{tn(this)}}}function fn(t){return function(){var e=this.cm;if(!e||e.curOp)return t.apply(this,arguments);Ze(e);try{return t.apply(this,arguments)}finally{tn(e)}}}function hn(t,e,n){this.line=e;this.rest=ti(e);this.size=this.rest?Hi(po(this.rest))-n+1:1;this.node=this.text=null;this.hidden=ri(t,e)}function dn(t,e,n){for(var r,i=[],o=e;n>o;o=r){var a=new hn(t.doc,Ei(t.doc,o),o);r=o+a.size;i.push(a)}return i}function pn(t,e,n,r){null==e&&(e=t.doc.first);null==n&&(n=t.doc.first+t.doc.size);r||(r=0);var i=t.display;r&&n<i.viewTo&&(null==i.updateLineNumbers||i.updateLineNumbers>e)&&(i.updateLineNumbers=e);t.curOp.viewChanged=!0;if(e>=i.viewTo)va&&ei(t.doc,e)<i.viewTo&&mn(t);else if(n<=i.viewFrom)if(va&&ni(t.doc,n+r)>i.viewFrom)mn(t);else{i.viewFrom+=r;i.viewTo+=r}else if(e<=i.viewFrom&&n>=i.viewTo)mn(t);else if(e<=i.viewFrom){var o=yn(t,n,n+r,1);if(o){i.view=i.view.slice(o.index);i.viewFrom=o.lineN;i.viewTo+=r}else mn(t)}else if(n>=i.viewTo){var o=yn(t,e,e,-1);if(o){i.view=i.view.slice(0,o.index);i.viewTo=o.lineN}else mn(t)}else{var a=yn(t,e,e,-1),s=yn(t,n,n+r,1);if(a&&s){i.view=i.view.slice(0,a.index).concat(dn(t,a.lineN,s.lineN)).concat(i.view.slice(s.index));i.viewTo+=r}else mn(t)}var l=i.externalMeasured;l&&(n<l.lineN?l.lineN+=r:e<l.lineN+l.size&&(i.externalMeasured=null))}function gn(t,e,n){t.curOp.viewChanged=!0;var r=t.display,i=t.display.externalMeasured;i&&e>=i.lineN&&e<i.lineN+i.size&&(r.externalMeasured=null);if(!(e<r.viewFrom||e>=r.viewTo)){var o=r.view[vn(t,e)];if(null!=o.node){var a=o.changes||(o.changes=[]);-1==go(a,n)&&a.push(n)}}}function mn(t){t.display.viewFrom=t.display.viewTo=t.doc.first;t.display.view=[];t.display.viewOffset=0}function vn(t,e){if(e>=t.display.viewTo)return null;e-=t.display.viewFrom;if(0>e)return null;for(var n=t.display.view,r=0;r<n.length;r++){e-=n[r].size;if(0>e)return r}}function yn(t,e,n,r){var i,o=vn(t,e),a=t.display.view;if(!va||n==t.doc.first+t.doc.size)return{index:o,lineN:n};for(var s=0,l=t.display.viewFrom;o>s;s++)l+=a[s].size;if(l!=e){if(r>0){if(o==a.length-1)return null;i=l+a[o].size-e;o++}else i=l-e;e+=i;n+=i}for(;ei(t.doc,n)!=n;){if(o==(0>r?0:a.length-1))return null;n+=r*a[o-(0>r?1:0)].size;o+=r}return{index:o,lineN:n}}function bn(t,e,n){var r=t.display,i=r.view;if(0==i.length||e>=r.viewTo||n<=r.viewFrom){r.view=dn(t,e,n);r.viewFrom=e}else{r.viewFrom>e?r.view=dn(t,e,r.viewFrom).concat(r.view):r.viewFrom<e&&(r.view=r.view.slice(vn(t,e)));r.viewFrom=e;r.viewTo<n?r.view=r.view.concat(dn(t,r.viewTo,n)):r.viewTo>n&&(r.view=r.view.slice(0,vn(t,n)))}r.viewTo=n}function xn(t){for(var e=t.display.view,n=0,r=0;r<e.length;r++){var i=e[r];i.hidden||i.node&&!i.changes||++n}return n}function wn(t){t.display.pollingFast||t.display.poll.set(t.options.pollInterval,function(){Cn(t);t.state.focused&&wn(t)})}function Sn(t){function e(){var r=Cn(t);if(r||n){t.display.pollingFast=!1;wn(t)}else{n=!0;t.display.poll.set(60,e)}}var n=!1;t.display.pollingFast=!0;t.display.poll.set(20,e)}function Cn(t){var e=t.display.input,n=t.display.prevInput,r=t.doc;if(!t.state.focused||js(e)&&!n||Mn(t)||t.options.disableInput||t.state.keySeq)return!1;if(t.state.pasteIncoming&&t.state.fakedLastChar){e.value=e.value.substring(0,e.value.length-1);t.state.fakedLastChar=!1}var i=e.value;if(i==n&&!t.somethingSelected())return!1;if(Qo&&ta>=9&&t.display.inputHasSelection===i||fa&&/[\uf700-\uf7ff]/.test(i)){Tn(t);return!1}var o=!t.curOp;o&&Ze(t);t.display.shift=!1;8203!=i.charCodeAt(0)||r.sel!=t.display.selForContextMenu||n||(n="");for(var a=0,s=Math.min(n.length,i.length);s>a&&n.charCodeAt(a)==i.charCodeAt(a);)++a;var l=i.slice(a),u=Es(l),c=null;t.state.pasteIncoming&&r.sel.ranges.length>1&&(ka&&ka.join("\n")==l?c=r.sel.ranges.length%ka.length==0&&mo(ka,Es):u.length==r.sel.ranges.length&&(c=mo(u,function(t){return[t]})));for(var f=r.sel.ranges.length-1;f>=0;f--){var h=r.sel.ranges[f],d=h.from(),p=h.to();a<n.length?d=ya(d.line,d.ch-(n.length-a)):t.state.overwrite&&h.empty()&&!t.state.pasteIncoming&&(p=ya(p.line,Math.min(Ei(r,p.line).text.length,p.ch+po(u).length)));var g=t.curOp.updateInput,m={from:d,to:p,text:c?c[f%c.length]:u,origin:t.state.pasteIncoming?"paste":t.state.cutIncoming?"cut":"+input"};sr(t.doc,m);io(t,"inputRead",t,m);if(l&&!t.state.pasteIncoming&&t.options.electricChars&&t.options.smartIndent&&h.head.ch<100&&(!f||r.sel.ranges[f-1].head.line!=h.head.line)){var v=t.getModeAt(h.head),y=Ea(m);if(v.electricChars){for(var b=0;b<v.electricChars.length;b++)if(l.indexOf(v.electricChars.charAt(b))>-1){wr(t,y.line,"smart");break}}else v.electricInput&&v.electricInput.test(Ei(r,y.line).text.slice(0,y.ch))&&wr(t,y.line,"smart")}}br(t);t.curOp.updateInput=g;t.curOp.typing=!0;i.length>1e3||i.indexOf("\n")>-1?e.value=t.display.prevInput="":t.display.prevInput=i;o&&tn(t);t.state.pasteIncoming=t.state.cutIncoming=!1;return!0}function Tn(t,e){var n,r,i=t.doc;if(t.somethingSelected()){t.display.prevInput="";var o=i.sel.primary();n=Is&&(o.to().line-o.from().line>100||(r=t.getSelection()).length>1e3);var a=n?"-":r||t.getSelection();t.display.input.value=a;t.state.focused&&xs(t.display.input);Qo&&ta>=9&&(t.display.inputHasSelection=a)}else if(!e){t.display.prevInput=t.display.input.value="";Qo&&ta>=9&&(t.display.inputHasSelection=null)}t.display.inaccurateSelection=n}function _n(t){"nocursor"==t.options.readOnly||ca&&Mo()==t.display.input||t.display.input.focus()}function kn(t){if(!t.state.focused){_n(t);Zn(t)}}function Mn(t){return t.options.readOnly||t.doc.cantEdit}function Dn(t){function e(){t.state.focused&&setTimeout(bo(_n,t),0)}function n(e){ao(t,e)||ls(e)}function r(e){if(t.somethingSelected()){ka=t.getSelections();if(i.inaccurateSelection){i.prevInput="";i.inaccurateSelection=!1;i.input.value=ka.join("\n");xs(i.input)}}else{for(var n=[],r=[],o=0;o<t.doc.sel.ranges.length;o++){var a=t.doc.sel.ranges[o].head.line,s={anchor:ya(a,0),head:ya(a+1,0)};r.push(s);n.push(t.getRange(s.anchor,s.head))}if("cut"==e.type)t.setSelections(r,null,gs);else{i.prevInput="";i.input.value=n.join("\n");xs(i.input)}ka=n}"cut"==e.type&&(t.state.cutIncoming=!0)}var i=t.display;us(i.scroller,"mousedown",un(t,En));Qo&&11>ta?us(i.scroller,"dblclick",un(t,function(e){if(!ao(t,e)){var n=Nn(t,e);if(n&&!On(t,e)&&!An(t.display,e)){as(e);var r=t.findWordAt(n);re(t.doc,r.anchor,r.head)}}})):us(i.scroller,"dblclick",function(e){ao(t,e)||as(e)});us(i.lineSpace,"selectstart",function(t){An(i,t)||as(t)});ga||us(i.scroller,"contextmenu",function(e){tr(t,e)});us(i.scroller,"scroll",function(){if(i.scroller.clientHeight){Wn(t,i.scroller.scrollTop);zn(t,i.scroller.scrollLeft,!0);fs(t,"scroll",t)}});us(i.scrollbarV,"scroll",function(){i.scroller.clientHeight&&Wn(t,i.scrollbarV.scrollTop)});us(i.scrollbarH,"scroll",function(){i.scroller.clientHeight&&zn(t,i.scrollbarH.scrollLeft)});us(i.scroller,"mousewheel",function(e){qn(t,e)});us(i.scroller,"DOMMouseScroll",function(e){qn(t,e)});us(i.scrollbarH,"mousedown",e);us(i.scrollbarV,"mousedown",e);us(i.wrapper,"scroll",function(){i.wrapper.scrollTop=i.wrapper.scrollLeft=0});us(i.input,"keyup",function(e){Jn.call(t,e)});us(i.input,"input",function(){Qo&&ta>=9&&t.display.inputHasSelection&&(t.display.inputHasSelection=null);Sn(t)});us(i.input,"keydown",un(t,$n));us(i.input,"keypress",un(t,Kn));us(i.input,"focus",bo(Zn,t));us(i.input,"blur",bo(Qn,t));if(t.options.dragDrop){us(i.scroller,"dragstart",function(e){Rn(t,e)});us(i.scroller,"dragenter",n);us(i.scroller,"dragover",n);us(i.scroller,"drop",un(t,Fn))}us(i.scroller,"paste",function(e){if(!An(i,e)){t.state.pasteIncoming=!0;_n(t);Sn(t)}});us(i.input,"paste",function(){if(ea&&!t.state.fakedLastChar&&!(new Date-t.state.lastMiddleDown<200)){var e=i.input.selectionStart,n=i.input.selectionEnd;i.input.value+="$";i.input.selectionEnd=n;i.input.selectionStart=e;t.state.fakedLastChar=!0}t.state.pasteIncoming=!0;Sn(t)});us(i.input,"cut",r);us(i.input,"copy",r);aa&&us(i.sizer,"mouseup",function(){Mo()==i.input&&i.input.blur();_n(t)})}function Ln(t){var e=t.display;if(e.lastWrapHeight!=e.wrapper.clientHeight||e.lastWrapWidth!=e.wrapper.clientWidth){e.cachedCharWidth=e.cachedTextHeight=e.cachedPaddingH=null;t.setSize()}}function An(t,e){for(var n=no(e);n!=t.wrapper;n=n.parentNode)if(!n||n.ignoreEvents||n.parentNode==t.sizer&&n!=t.mover)return!0}function Nn(t,e,n,r){var i=t.display;if(!n){var o=no(e);if(o==i.scrollbarH||o==i.scrollbarV||o==i.scrollbarFiller||o==i.gutterFiller)return null}var a,s,l=i.lineSpace.getBoundingClientRect();try{a=e.clientX-l.left;s=e.clientY-l.top}catch(e){return null}var u,c=$e(t,a,s);if(r&&1==c.xRel&&(u=Ei(t.doc,c.line).text).length==c.ch){var f=ys(u,u.length,t.options.tabSize)-u.length;c=ya(c.line,Math.max(0,Math.round((a-Me(t.display).left)/Ke(t.display))-f))}return c}function En(t){if(!ao(this,t)){var e=this,n=e.display;n.shift=t.shiftKey;if(An(n,t)){if(!ea){n.scroller.draggable=!1;setTimeout(function(){n.scroller.draggable=!0},100)}}else if(!On(e,t)){var r=Nn(e,t);window.focus();switch(ro(t)){case 1:r?jn(e,t,r):no(t)==n.scroller&&as(t);break;case 2:ea&&(e.state.lastMiddleDown=+new Date);r&&re(e.doc,r);setTimeout(bo(_n,e),20);as(t);break;case 3:ga&&tr(e,t)}}}}function jn(t,e,n){setTimeout(bo(kn,t),0);var r,i=+new Date;if(Sa&&Sa.time>i-400&&0==ba(Sa.pos,n))r="triple";else if(wa&&wa.time>i-400&&0==ba(wa.pos,n)){r="double";Sa={time:i,pos:n}}else{r="single";wa={time:i,pos:n}}var o=t.doc.sel,a=fa?e.metaKey:e.ctrlKey;t.options.dragDrop&&Ns&&!Mn(t)&&"single"==r&&o.contains(n)>-1&&o.somethingSelected()?In(t,e,n,a):Pn(t,e,n,r,a)}function In(t,e,n,r){var i=t.display,o=un(t,function(a){ea&&(i.scroller.draggable=!1);t.state.draggingText=!1;cs(document,"mouseup",o);cs(i.scroller,"drop",o);if(Math.abs(e.clientX-a.clientX)+Math.abs(e.clientY-a.clientY)<10){as(a);r||re(t.doc,n);_n(t);Qo&&9==ta&&setTimeout(function(){document.body.focus();_n(t)},20)}});ea&&(i.scroller.draggable=!0);t.state.draggingText=o;i.scroller.dragDrop&&i.scroller.dragDrop();us(document,"mouseup",o);us(i.scroller,"drop",o)}function Pn(t,e,n,r,i){function o(e){if(0!=ba(g,e)){g=e;if("rect"==r){for(var i=[],o=t.options.tabSize,a=ys(Ei(u,n.line).text,n.ch,o),s=ys(Ei(u,e.line).text,e.ch,o),l=Math.min(a,s),d=Math.max(a,s),p=Math.min(n.line,e.line),m=Math.min(t.lastLine(),Math.max(n.line,e.line));m>=p;p++){var v=Ei(u,p).text,y=fo(v,l,o);l==d?i.push(new $(ya(p,y),ya(p,y))):v.length>y&&i.push(new $(ya(p,y),ya(p,fo(v,d,o))))}i.length||i.push(new $(n,n));ue(u,Y(h.ranges.slice(0,f).concat(i),f),{origin:"*mouse",scroll:!1});t.scrollIntoView(e)}else{var b=c,x=b.anchor,w=e;if("single"!=r){if("double"==r)var S=t.findWordAt(e);else var S=new $(ya(e.line,0),Z(u,ya(e.line+1,0)));if(ba(S.anchor,x)>0){w=S.head;x=X(b.from(),S.anchor)}else{w=S.anchor;x=V(b.to(),S.head)}}var i=h.ranges.slice(0);i[f]=new $(Z(u,x),w);ue(u,Y(i,f),ms)}}}function a(e){var n=++y,i=Nn(t,e,!0,"rect"==r);if(i)if(0!=ba(i,g)){kn(t);o(i);var s=v(l,u);(i.line>=s.to||i.line<s.from)&&setTimeout(un(t,function(){y==n&&a(e)}),150)}else{var c=e.clientY<m.top?-20:e.clientY>m.bottom?20:0;c&&setTimeout(un(t,function(){if(y==n){l.scroller.scrollTop+=c;a(e)}}),50)}}function s(e){y=1/0;as(e);_n(t);cs(document,"mousemove",b);cs(document,"mouseup",x);u.history.lastSelOrigin=null}var l=t.display,u=t.doc;as(e);var c,f,h=u.sel;if(i&&!e.shiftKey){f=u.sel.contains(n);c=f>-1?u.sel.ranges[f]:new $(n,n)}else c=u.sel.primary();if(e.altKey){r="rect";i||(c=new $(n,n));n=Nn(t,e,!0,!0);f=-1}else if("double"==r){var d=t.findWordAt(n);c=t.display.shift||u.extend?ne(u,c,d.anchor,d.head):d}else if("triple"==r){var p=new $(ya(n.line,0),Z(u,ya(n.line+1,0)));c=t.display.shift||u.extend?ne(u,c,p.anchor,p.head):p}else c=ne(u,c,n);if(i)if(f>-1)oe(u,f,c,ms);else{f=u.sel.ranges.length;ue(u,Y(u.sel.ranges.concat([c]),f),{scroll:!1,origin:"*mouse"})}else{f=0;ue(u,new G([c],0),ms);h=u.sel}var g=n,m=l.wrapper.getBoundingClientRect(),y=0,b=un(t,function(t){ro(t)?a(t):s(t)}),x=un(t,s);us(document,"mousemove",b);us(document,"mouseup",x)}function Hn(t,e,n,r,i){try{var o=e.clientX,a=e.clientY}catch(e){return!1}if(o>=Math.floor(t.display.gutters.getBoundingClientRect().right))return!1;r&&as(e);var s=t.display,l=s.lineDiv.getBoundingClientRect();if(a>l.bottom||!lo(t,n))return eo(e);a-=l.top-s.viewOffset;for(var u=0;u<t.options.gutters.length;++u){var c=s.gutters.childNodes[u];if(c&&c.getBoundingClientRect().right>=o){var f=Oi(t.doc,a),h=t.options.gutters[u];i(t,n,t,f,h,e);return eo(e)}}}function On(t,e){return Hn(t,e,"gutterClick",!0,io)}function Fn(t){var e=this;if(!ao(e,t)&&!An(e.display,t)){as(t);Qo&&(Ma=+new Date);var n=Nn(e,t,!0),r=t.dataTransfer.files;if(n&&!Mn(e))if(r&&r.length&&window.FileReader&&window.File)for(var i=r.length,o=Array(i),a=0,s=function(t,r){var s=new FileReader;s.onload=un(e,function(){o[r]=s.result;if(++a==i){n=Z(e.doc,n);var t={from:n,to:n,text:Es(o.join("\n")),origin:"paste"};sr(e.doc,t);le(e.doc,J(n,Ea(t)))}});s.readAsText(t)},l=0;i>l;++l)s(r[l],l);else{if(e.state.draggingText&&e.doc.sel.contains(n)>-1){e.state.draggingText(t);setTimeout(bo(_n,e),20);return}try{var o=t.dataTransfer.getData("Text");if(o){if(e.state.draggingText&&!(fa?t.metaKey:t.ctrlKey))var u=e.listSelections();ce(e.doc,J(n,n));if(u)for(var l=0;l<u.length;++l)dr(e.doc,"",u[l].anchor,u[l].head,"drag");e.replaceSelection(o,"around","paste");_n(e)}}catch(t){}}}}function Rn(t,e){if(Qo&&(!t.state.draggingText||+new Date-Ma<100))ls(e);else if(!ao(t,e)&&!An(t.display,e)){e.dataTransfer.setData("Text",t.getSelection());if(e.dataTransfer.setDragImage&&!oa){var n=Co("img",null,null,"position: fixed; left: 0; top: 0;");n.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";if(ia){n.width=n.height=1;t.display.wrapper.appendChild(n);n._top=n.offsetTop}e.dataTransfer.setDragImage(n,0,0);ia&&n.parentNode.removeChild(n)}}}function Wn(t,e){if(!(Math.abs(t.doc.scrollTop-e)<2)){t.doc.scrollTop=e;Jo||_(t,{top:e});t.display.scroller.scrollTop!=e&&(t.display.scroller.scrollTop=e);t.display.scrollbarV.scrollTop!=e&&(t.display.scrollbarV.scrollTop=e);Jo&&_(t);we(t,100)}}function zn(t,e,n){if(!(n?e==t.doc.scrollLeft:Math.abs(t.doc.scrollLeft-e)<2)){e=Math.min(e,t.display.scroller.scrollWidth-t.display.scroller.clientWidth);t.doc.scrollLeft=e;y(t);t.display.scroller.scrollLeft!=e&&(t.display.scroller.scrollLeft=e);t.display.scrollbarH.scrollLeft!=e&&(t.display.scrollbarH.scrollLeft=e)}}function qn(t,e){var n=e.wheelDeltaX,r=e.wheelDeltaY;null==n&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(n=e.detail);null==r&&e.detail&&e.axis==e.VERTICAL_AXIS?r=e.detail:null==r&&(r=e.wheelDelta);var i=t.display,o=i.scroller;if(n&&o.scrollWidth>o.clientWidth||r&&o.scrollHeight>o.clientHeight){if(r&&fa&&ea)t:for(var a=e.target,s=i.view;a!=o;a=a.parentNode)for(var l=0;l<s.length;l++)if(s[l].node==a){t.display.currentWheelTarget=a;break t}if(!n||Jo||ia||null==La){if(r&&null!=La){var u=r*La,c=t.doc.scrollTop,f=c+i.wrapper.clientHeight;0>u?c=Math.max(0,c+u-50):f=Math.min(t.doc.height,f+u+50);_(t,{top:c,bottom:f})}if(20>Da)if(null==i.wheelStartX){i.wheelStartX=o.scrollLeft;i.wheelStartY=o.scrollTop;i.wheelDX=n;i.wheelDY=r;setTimeout(function(){if(null!=i.wheelStartX){var t=o.scrollLeft-i.wheelStartX,e=o.scrollTop-i.wheelStartY,n=e&&i.wheelDY&&e/i.wheelDY||t&&i.wheelDX&&t/i.wheelDX;i.wheelStartX=i.wheelStartY=null;if(n){La=(La*Da+n)/(Da+1);++Da}}},200)}else{i.wheelDX+=n;i.wheelDY+=r}}else{r&&Wn(t,Math.max(0,Math.min(o.scrollTop+r*La,o.scrollHeight-o.clientHeight)));zn(t,Math.max(0,Math.min(o.scrollLeft+n*La,o.scrollWidth-o.clientWidth)));as(e);i.wheelStartX=null}}}function Un(t,e,n){if("string"==typeof e){e=Ua[e];if(!e)return!1}t.display.pollingFast&&Cn(t)&&(t.display.pollingFast=!1);var r=t.display.shift,i=!1;try{Mn(t)&&(t.state.suppressEdits=!0);n&&(t.display.shift=!1);i=e(t)!=ps}finally{t.display.shift=r;t.state.suppressEdits=!1}return i}function Bn(t,e,n){for(var r=0;r<t.state.keyMaps.length;r++){var i=Va(e,t.state.keyMaps[r],n);if(i)return i}return t.options.extraKeys&&Va(e,t.options.extraKeys,n)||Va(e,t.options.keyMap,n)}function Vn(t,e,n,r){var i=t.state.keySeq;if(i){if(Xa(e))return"handled";Aa.set(50,function(){if(t.state.keySeq==i){t.state.keySeq=null;Tn(t)}});e=i+" "+e}var o=Bn(t,e,r);"multi"==o&&(t.state.keySeq=e);"handled"==o&&io(t,"keyHandled",t,e,n);if("handled"==o||"multi"==o){as(n);xe(t)}if(i&&!o&&/\'$/.test(e)){as(n);return!0}return!!o}function Xn(t,e){var n=Ga(e,!0);return n?e.shiftKey&&!t.state.keySeq?Vn(t,"Shift-"+n,e,function(e){return Un(t,e,!0)})||Vn(t,n,e,function(e){return("string"==typeof e?/^go[A-Z]/.test(e):e.motion)?Un(t,e):void 0}):Vn(t,n,e,function(e){return Un(t,e)}):!1}function Gn(t,e,n){return Vn(t,"'"+n+"'",e,function(e){return Un(t,e,!0)})}function $n(t){var e=this;kn(e);if(!ao(e,t)){Qo&&11>ta&&27==t.keyCode&&(t.returnValue=!1);var n=t.keyCode;e.display.shift=16==n||t.shiftKey;var r=Xn(e,t);if(ia){Na=r?n:null;!r&&88==n&&!Is&&(fa?t.metaKey:t.ctrlKey)&&e.replaceSelection("",null,"cut")}18!=n||/\bCodeMirror-crosshair\b/.test(e.display.lineDiv.className)||Yn(e)}}function Yn(t){function e(t){if(18==t.keyCode||!t.altKey){Ds(n,"CodeMirror-crosshair");cs(document,"keyup",e);cs(document,"mouseover",e)}}var n=t.display.lineDiv;Ls(n,"CodeMirror-crosshair");us(document,"keyup",e);us(document,"mouseover",e)}function Jn(t){16==t.keyCode&&(this.doc.sel.shift=!1);ao(this,t)}function Kn(t){var e=this;if(!(ao(e,t)||t.ctrlKey&&!t.altKey||fa&&t.metaKey)){var n=t.keyCode,r=t.charCode;if(ia&&n==Na){Na=null;as(t)}else if(!(ia&&(!t.which||t.which<10)||aa)||!Xn(e,t)){var i=String.fromCharCode(null==r?n:r);if(!Gn(e,t,i)){Qo&&ta>=9&&(e.display.inputHasSelection=null);Sn(e)}}}}function Zn(t){if("nocursor"!=t.options.readOnly){if(!t.state.focused){fs(t,"focus",t);t.state.focused=!0;Ls(t.display.wrapper,"CodeMirror-focused");if(!t.curOp&&t.display.selForContextMenu!=t.doc.sel){Tn(t);ea&&setTimeout(bo(Tn,t,!0),0)}}wn(t);xe(t)}}function Qn(t){if(t.state.focused){fs(t,"blur",t);t.state.focused=!1;Ds(t.display.wrapper,"CodeMirror-focused")}clearInterval(t.display.blinker);setTimeout(function(){t.state.focused||(t.display.shift=!1)},150)}function tr(t,e){function n(){if(null!=i.input.selectionStart){var e=t.somethingSelected(),n=i.input.value=""+(e?i.input.value:"");i.prevInput=e?"":"";i.input.selectionStart=1;i.input.selectionEnd=n.length;i.selForContextMenu=t.doc.sel}}function r(){i.inputDiv.style.position="relative";i.input.style.cssText=l;Qo&&9>ta&&(i.scrollbarV.scrollTop=i.scroller.scrollTop=a);wn(t);if(null!=i.input.selectionStart){(!Qo||Qo&&9>ta)&&n();var e=0,r=function(){i.selForContextMenu==t.doc.sel&&0==i.input.selectionStart?un(t,Ua.selectAll)(t):e++<10?i.detectingSelectAll=setTimeout(r,500):Tn(t)};i.detectingSelectAll=setTimeout(r,200)}}if(!ao(t,e,"contextmenu")){var i=t.display;if(!An(i,e)&&!er(t,e)){var o=Nn(t,e),a=i.scroller.scrollTop;if(o&&!ia){var s=t.options.resetSelectionOnContextMenu;s&&-1==t.doc.sel.contains(o)&&un(t,ue)(t.doc,J(o),gs);var l=i.input.style.cssText;i.inputDiv.style.position="absolute";i.input.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(e.clientY-5)+"px; left: "+(e.clientX-5)+"px; z-index: 1000; background: "+(Qo?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";if(ea)var u=window.scrollY;_n(t);ea&&window.scrollTo(null,u);Tn(t);t.somethingSelected()||(i.input.value=i.prevInput=" ");i.selForContextMenu=t.doc.sel;clearTimeout(i.detectingSelectAll);Qo&&ta>=9&&n();if(ga){ls(e);var c=function(){cs(window,"mouseup",c);setTimeout(r,20)};us(window,"mouseup",c)}else setTimeout(r,50)}}}}function er(t,e){return lo(t,"gutterContextMenu")?Hn(t,e,"gutterContextMenu",!1,fs):!1}function nr(t,e){if(ba(t,e.from)<0)return t;if(ba(t,e.to)<=0)return Ea(e);var n=t.line+e.text.length-(e.to.line-e.from.line)-1,r=t.ch;t.line==e.to.line&&(r+=Ea(e).ch-e.to.ch);return ya(n,r)}function rr(t,e){for(var n=[],r=0;r<t.sel.ranges.length;r++){var i=t.sel.ranges[r];n.push(new $(nr(i.anchor,e),nr(i.head,e)))}return Y(n,t.sel.primIndex)}function ir(t,e,n){return t.line==e.line?ya(n.line,t.ch-e.ch+n.ch):ya(n.line+(t.line-e.line),t.ch)}function or(t,e,n){for(var r=[],i=ya(t.first,0),o=i,a=0;a<e.length;a++){var s=e[a],l=ir(s.from,i,o),u=ir(Ea(s),i,o);i=s.to;o=u;if("around"==n){var c=t.sel.ranges[a],f=ba(c.head,c.anchor)<0;r[a]=new $(f?u:l,f?l:u)}else r[a]=new $(l,l)}return new G(r,t.sel.primIndex)}function ar(t,e,n){var r={canceled:!1,from:e.from,to:e.to,text:e.text,origin:e.origin,cancel:function(){this.canceled=!0}};n&&(r.update=function(e,n,r,i){e&&(this.from=Z(t,e));n&&(this.to=Z(t,n));r&&(this.text=r);void 0!==i&&(this.origin=i)});fs(t,"beforeChange",t,r);t.cm&&fs(t.cm,"beforeChange",t.cm,r);return r.canceled?null:{from:r.from,to:r.to,text:r.text,origin:r.origin}}function sr(t,e,n){if(t.cm){if(!t.cm.curOp)return un(t.cm,sr)(t,e,n);if(t.cm.state.suppressEdits)return}if(lo(t,"beforeChange")||t.cm&&lo(t.cm,"beforeChange")){e=ar(t,e,!0);if(!e)return}var r=ma&&!n&&Ur(t,e.from,e.to);if(r)for(var i=r.length-1;i>=0;--i)lr(t,{from:r[i].from,to:r[i].to,text:i?[""]:e.text});else lr(t,e)}function lr(t,e){if(1!=e.text.length||""!=e.text[0]||0!=ba(e.from,e.to)){var n=rr(t,e);Bi(t,e,n,t.cm?t.cm.curOp.id:0/0);fr(t,e,n,Wr(t,e));var r=[];Ai(t,function(t,n){if(!n&&-1==go(r,t.history)){to(t.history,e);r.push(t.history)}fr(t,e,null,Wr(t,e))})}}function ur(t,e,n){if(!t.cm||!t.cm.state.suppressEdits){for(var r,i=t.history,o=t.sel,a="undo"==e?i.done:i.undone,s="undo"==e?i.undone:i.done,l=0;l<a.length;l++){r=a[l];if(n?r.ranges&&!r.equals(t.sel):!r.ranges)break}if(l!=a.length){i.lastOrigin=i.lastSelOrigin=null;for(;;){r=a.pop();if(!r.ranges)break;Gi(r,s);if(n&&!r.equals(t.sel)){ue(t,r,{clearRedo:!1});return}o=r}var u=[];Gi(o,s);s.push({changes:u,generation:i.generation});i.generation=r.generation||++i.maxGeneration;for(var c=lo(t,"beforeChange")||t.cm&&lo(t.cm,"beforeChange"),l=r.changes.length-1;l>=0;--l){var f=r.changes[l];f.origin=e;if(c&&!ar(t,f,!1)){a.length=0;return}u.push(zi(t,f));var h=l?rr(t,f):po(a);fr(t,f,h,qr(t,f));!l&&t.cm&&t.cm.scrollIntoView({from:f.from,to:Ea(f)});var d=[];Ai(t,function(t,e){if(!e&&-1==go(d,t.history)){to(t.history,f);d.push(t.history)}fr(t,f,null,qr(t,f))})}}}}function cr(t,e){if(0!=e){t.first+=e;t.sel=new G(mo(t.sel.ranges,function(t){return new $(ya(t.anchor.line+e,t.anchor.ch),ya(t.head.line+e,t.head.ch))}),t.sel.primIndex);if(t.cm){pn(t.cm,t.first,t.first-e,e);for(var n=t.cm.display,r=n.viewFrom;r<n.viewTo;r++)gn(t.cm,r,"gutter")}}}function fr(t,e,n,r){if(t.cm&&!t.cm.curOp)return un(t.cm,fr)(t,e,n,r);if(e.to.line<t.first)cr(t,e.text.length-1-(e.to.line-e.from.line));else if(!(e.from.line>t.lastLine())){if(e.from.line<t.first){var i=e.text.length-1-(t.first-e.from.line);cr(t,i);e={from:ya(t.first,0),to:ya(e.to.line+i,e.to.ch),text:[po(e.text)],origin:e.origin}}var o=t.lastLine();e.to.line>o&&(e={from:e.from,to:ya(o,Ei(t,o).text.length),text:[e.text[0]],origin:e.origin});e.removed=ji(t,e.from,e.to);n||(n=rr(t,e));t.cm?hr(t.cm,e,r):Mi(t,e,r);ce(t,n,gs)}}function hr(t,e,n){var r=t.doc,i=t.display,a=e.from,s=e.to,l=!1,u=a.line;if(!t.options.lineWrapping){u=Hi(Qr(Ei(r,a.line)));r.iter(u,s.line+1,function(t){if(t==i.maxLine){l=!0;return!0}})}r.sel.contains(e.from,e.to)>-1&&so(t);Mi(r,e,n,o(t));if(!t.options.lineWrapping){r.iter(u,a.line+e.text.length,function(t){var e=f(t);if(e>i.maxLineLength){i.maxLine=t;i.maxLineLength=e;i.maxLineChanged=!0;l=!1}});l&&(t.curOp.updateMaxLine=!0)}r.frontier=Math.min(r.frontier,a.line);we(t,400);var c=e.text.length-(s.line-a.line)-1;a.line!=s.line||1!=e.text.length||ki(t.doc,e)?pn(t,a.line,s.line+1,c):gn(t,a.line,"text");var h=lo(t,"changes"),d=lo(t,"change");if(d||h){var p={from:a,to:s,text:e.text,removed:e.removed,origin:e.origin};d&&io(t,"change",t,p);h&&(t.curOp.changeObjs||(t.curOp.changeObjs=[])).push(p)}t.display.selForContextMenu=null}function dr(t,e,n,r,i){r||(r=n);if(ba(r,n)<0){var o=r;r=n;n=o}"string"==typeof e&&(e=Es(e));sr(t,{from:n,to:r,text:e,origin:i})}function pr(t,e){if(!ao(t,"scrollCursorIntoView")){var n=t.display,r=n.sizer.getBoundingClientRect(),i=null;e.top+r.top<0?i=!0:e.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(i=!1);if(null!=i&&!la){var o=Co("div","",null,"position: absolute; top: "+(e.top-n.viewOffset-_e(t.display))+"px; height: "+(e.bottom-e.top+ds)+"px; left: "+e.left+"px; width: 2px;");t.display.lineSpace.appendChild(o);o.scrollIntoView(i);t.display.lineSpace.removeChild(o)}}}function gr(t,e,n,r){null==r&&(r=0);for(var i=0;5>i;i++){var o=!1,a=Ve(t,e),s=n&&n!=e?Ve(t,n):a,l=vr(t,Math.min(a.left,s.left),Math.min(a.top,s.top)-r,Math.max(a.left,s.left),Math.max(a.bottom,s.bottom)+r),u=t.doc.scrollTop,c=t.doc.scrollLeft;if(null!=l.scrollTop){Wn(t,l.scrollTop);Math.abs(t.doc.scrollTop-u)>1&&(o=!0)}if(null!=l.scrollLeft){zn(t,l.scrollLeft);Math.abs(t.doc.scrollLeft-c)>1&&(o=!0)}if(!o)return a}}function mr(t,e,n,r,i){var o=vr(t,e,n,r,i);null!=o.scrollTop&&Wn(t,o.scrollTop);null!=o.scrollLeft&&zn(t,o.scrollLeft)}function vr(t,e,n,r,i){var o=t.display,a=Je(t.display);0>n&&(n=0);var s=t.curOp&&null!=t.curOp.scrollTop?t.curOp.scrollTop:o.scroller.scrollTop,l=o.scroller.clientHeight-ds,u={};i-n>l&&(i=n+l);var c=t.doc.height+ke(o),f=a>n,h=i>c-a;if(s>n)u.scrollTop=f?0:n;else if(i>s+l){var d=Math.min(n,(h?c:i)-l);d!=s&&(u.scrollTop=d)}var p=t.curOp&&null!=t.curOp.scrollLeft?t.curOp.scrollLeft:o.scroller.scrollLeft,g=o.scroller.clientWidth-ds-o.gutters.offsetWidth,m=r-e>g;m&&(r=e+g);10>e?u.scrollLeft=0:p>e?u.scrollLeft=Math.max(0,e-(m?0:10)):r>g+p-3&&(u.scrollLeft=r+(m?0:10)-g);return u}function yr(t,e,n){(null!=e||null!=n)&&xr(t);null!=e&&(t.curOp.scrollLeft=(null==t.curOp.scrollLeft?t.doc.scrollLeft:t.curOp.scrollLeft)+e);null!=n&&(t.curOp.scrollTop=(null==t.curOp.scrollTop?t.doc.scrollTop:t.curOp.scrollTop)+n)}function br(t){xr(t);var e=t.getCursor(),n=e,r=e;if(!t.options.lineWrapping){n=e.ch?ya(e.line,e.ch-1):e;r=ya(e.line,e.ch+1)}t.curOp.scrollToPos={from:n,to:r,margin:t.options.cursorScrollMargin,isCursor:!0}}function xr(t){var e=t.curOp.scrollToPos;if(e){t.curOp.scrollToPos=null;var n=Xe(t,e.from),r=Xe(t,e.to),i=vr(t,Math.min(n.left,r.left),Math.min(n.top,r.top)-e.margin,Math.max(n.right,r.right),Math.max(n.bottom,r.bottom)+e.margin);t.scrollTo(i.scrollLeft,i.scrollTop)}}function wr(t,e,n,r){var i,o=t.doc;
null==n&&(n="add");"smart"==n&&(o.mode.indent?i=Te(t,e):n="prev");var a=t.options.tabSize,s=Ei(o,e),l=ys(s.text,null,a);s.stateAfter&&(s.stateAfter=null);var u,c=s.text.match(/^\s*/)[0];if(r||/\S/.test(s.text)){if("smart"==n){u=o.mode.indent(i,s.text.slice(c.length),s.text);if(u==ps||u>150){if(!r)return;n="prev"}}}else{u=0;n="not"}"prev"==n?u=e>o.first?ys(Ei(o,e-1).text,null,a):0:"add"==n?u=l+t.options.indentUnit:"subtract"==n?u=l-t.options.indentUnit:"number"==typeof n&&(u=l+n);u=Math.max(0,u);var f="",h=0;if(t.options.indentWithTabs)for(var d=Math.floor(u/a);d;--d){h+=a;f+=" "}u>h&&(f+=ho(u-h));if(f!=c)dr(o,f,ya(e,0),ya(e,c.length),"+input");else for(var d=0;d<o.sel.ranges.length;d++){var p=o.sel.ranges[d];if(p.head.line==e&&p.head.ch<c.length){var h=ya(e,c.length);oe(o,d,new $(h,h));break}}s.stateAfter=null}function Sr(t,e,n,r){var i=e,o=e;"number"==typeof e?o=Ei(t,K(t,e)):i=Hi(e);if(null==i)return null;r(o,i)&&t.cm&&gn(t.cm,i,n);return o}function Cr(t,e){for(var n=t.doc.sel.ranges,r=[],i=0;i<n.length;i++){for(var o=e(n[i]);r.length&&ba(o.from,po(r).to)<=0;){var a=r.pop();if(ba(a.from,o.from)<0){o.from=a.from;break}}r.push(o)}ln(t,function(){for(var e=r.length-1;e>=0;e--)dr(t.doc,"",r[e].from,r[e].to,"+delete");br(t)})}function Tr(t,e,n,r,i){function o(){var e=s+n;if(e<t.first||e>=t.first+t.size)return f=!1;s=e;return c=Ei(t,e)}function a(t){var e=(i?$o:Yo)(c,l,n,!0);if(null==e){if(t||!o())return f=!1;l=i?(0>n?zo:Wo)(c):0>n?c.text.length:0}else l=e;return!0}var s=e.line,l=e.ch,u=n,c=Ei(t,s),f=!0;if("char"==r)a();else if("column"==r)a(!0);else if("word"==r||"group"==r)for(var h=null,d="group"==r,p=t.cm&&t.cm.getHelper(e,"wordChars"),g=!0;!(0>n)||a(!g);g=!1){var m=c.text.charAt(l)||"\n",v=xo(m,p)?"w":d&&"\n"==m?"n":!d||/\s/.test(m)?null:"p";!d||g||v||(v="s");if(h&&h!=v){if(0>n){n=1;a()}break}v&&(h=v);if(n>0&&!a(!g))break}var y=pe(t,ya(s,l),u,!0);f||(y.hitSide=!0);return y}function _r(t,e,n,r){var i,o=t.doc,a=e.left;if("page"==r){var s=Math.min(t.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);i=e.top+n*(s-(0>n?1.5:.5)*Je(t.display))}else"line"==r&&(i=n>0?e.bottom+3:e.top-3);for(;;){var l=$e(t,a,i);if(!l.outside)break;if(0>n?0>=i:i>=o.height){l.hitSide=!0;break}i+=5*n}return l}function kr(e,n,r,i){t.defaults[e]=n;r&&(Ia[e]=i?function(t,e,n){n!=Pa&&r(t,e,n)}:r)}function Mr(t){for(var e,n,r,i,o=t.split(/-(?!$)/),t=o[o.length-1],a=0;a<o.length-1;a++){var s=o[a];if(/^(cmd|meta|m)$/i.test(s))i=!0;else if(/^a(lt)?$/i.test(s))e=!0;else if(/^(c|ctrl|control)$/i.test(s))n=!0;else{if(!/^s(hift)$/i.test(s))throw new Error("Unrecognized modifier name: "+s);r=!0}}e&&(t="Alt-"+t);n&&(t="Ctrl-"+t);i&&(t="Cmd-"+t);r&&(t="Shift-"+t);return t}function Dr(t){return"string"==typeof t?Ba[t]:t}function Lr(t,e,n,r,i){if(r&&r.shared)return Ar(t,e,n,r,i);if(t.cm&&!t.cm.curOp)return un(t.cm,Lr)(t,e,n,r,i);var o=new Ya(t,i),a=ba(e,n);r&&yo(r,o,!1);if(a>0||0==a&&o.clearWhenEmpty!==!1)return o;if(o.replacedWith){o.collapsed=!0;o.widgetNode=Co("span",[o.replacedWith],"CodeMirror-widget");r.handleMouseEvents||(o.widgetNode.ignoreEvents=!0);r.insertLeft&&(o.widgetNode.insertLeft=!0)}if(o.collapsed){if(Zr(t,e.line,e,n,o)||e.line!=n.line&&Zr(t,n.line,e,n,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");va=!0}o.addToHistory&&Bi(t,{from:e,to:n,origin:"markText"},t.sel,0/0);var s,l=e.line,u=t.cm;t.iter(l,n.line+1,function(t){u&&o.collapsed&&!u.options.lineWrapping&&Qr(t)==u.display.maxLine&&(s=!0);o.collapsed&&l!=e.line&&Pi(t,0);Or(t,new Ir(o,l==e.line?e.ch:null,l==n.line?n.ch:null));++l});o.collapsed&&t.iter(e.line,n.line+1,function(e){ri(t,e)&&Pi(e,0)});o.clearOnEnter&&us(o,"beforeCursorEnter",function(){o.clear()});if(o.readOnly){ma=!0;(t.history.done.length||t.history.undone.length)&&t.clearHistory()}if(o.collapsed){o.id=++Ja;o.atomic=!0}if(u){s&&(u.curOp.updateMaxLine=!0);if(o.collapsed)pn(u,e.line,n.line+1);else if(o.className||o.title||o.startStyle||o.endStyle)for(var c=e.line;c<=n.line;c++)gn(u,c,"text");o.atomic&&he(u.doc);io(u,"markerAdded",u,o)}return o}function Ar(t,e,n,r,i){r=yo(r);r.shared=!1;var o=[Lr(t,e,n,r,i)],a=o[0],s=r.widgetNode;Ai(t,function(t){s&&(r.widgetNode=s.cloneNode(!0));o.push(Lr(t,Z(t,e),Z(t,n),r,i));for(var l=0;l<t.linked.length;++l)if(t.linked[l].isParent)return;a=po(o)});return new Ka(o,a)}function Nr(t){return t.findMarks(ya(t.first,0),t.clipPos(ya(t.lastLine())),function(t){return t.parent})}function Er(t,e){for(var n=0;n<e.length;n++){var r=e[n],i=r.find(),o=t.clipPos(i.from),a=t.clipPos(i.to);if(ba(o,a)){var s=Lr(t,o,a,r.primary,r.primary.type);r.markers.push(s);s.parent=r}}}function jr(t){for(var e=0;e<t.length;e++){var n=t[e],r=[n.primary.doc];Ai(n.primary.doc,function(t){r.push(t)});for(var i=0;i<n.markers.length;i++){var o=n.markers[i];if(-1==go(r,o.doc)){o.parent=null;n.markers.splice(i--,1)}}}}function Ir(t,e,n){this.marker=t;this.from=e;this.to=n}function Pr(t,e){if(t)for(var n=0;n<t.length;++n){var r=t[n];if(r.marker==e)return r}}function Hr(t,e){for(var n,r=0;r<t.length;++r)t[r]!=e&&(n||(n=[])).push(t[r]);return n}function Or(t,e){t.markedSpans=t.markedSpans?t.markedSpans.concat([e]):[e];e.marker.attachLine(t)}function Fr(t,e,n){if(t)for(var r,i=0;i<t.length;++i){var o=t[i],a=o.marker,s=null==o.from||(a.inclusiveLeft?o.from<=e:o.from<e);if(s||o.from==e&&"bookmark"==a.type&&(!n||!o.marker.insertLeft)){var l=null==o.to||(a.inclusiveRight?o.to>=e:o.to>e);(r||(r=[])).push(new Ir(a,o.from,l?null:o.to))}}return r}function Rr(t,e,n){if(t)for(var r,i=0;i<t.length;++i){var o=t[i],a=o.marker,s=null==o.to||(a.inclusiveRight?o.to>=e:o.to>e);if(s||o.from==e&&"bookmark"==a.type&&(!n||o.marker.insertLeft)){var l=null==o.from||(a.inclusiveLeft?o.from<=e:o.from<e);(r||(r=[])).push(new Ir(a,l?null:o.from-e,null==o.to?null:o.to-e))}}return r}function Wr(t,e){var n=te(t,e.from.line)&&Ei(t,e.from.line).markedSpans,r=te(t,e.to.line)&&Ei(t,e.to.line).markedSpans;if(!n&&!r)return null;var i=e.from.ch,o=e.to.ch,a=0==ba(e.from,e.to),s=Fr(n,i,a),l=Rr(r,o,a),u=1==e.text.length,c=po(e.text).length+(u?i:0);if(s)for(var f=0;f<s.length;++f){var h=s[f];if(null==h.to){var d=Pr(l,h.marker);d?u&&(h.to=null==d.to?null:d.to+c):h.to=i}}if(l)for(var f=0;f<l.length;++f){var h=l[f];null!=h.to&&(h.to+=c);if(null==h.from){var d=Pr(s,h.marker);if(!d){h.from=c;u&&(s||(s=[])).push(h)}}else{h.from+=c;u&&(s||(s=[])).push(h)}}s&&(s=zr(s));l&&l!=s&&(l=zr(l));var p=[s];if(!u){var g,m=e.text.length-2;if(m>0&&s)for(var f=0;f<s.length;++f)null==s[f].to&&(g||(g=[])).push(new Ir(s[f].marker,null,null));for(var f=0;m>f;++f)p.push(g);p.push(l)}return p}function zr(t){for(var e=0;e<t.length;++e){var n=t[e];null!=n.from&&n.from==n.to&&n.marker.clearWhenEmpty!==!1&&t.splice(e--,1)}return t.length?t:null}function qr(t,e){var n=Ji(t,e),r=Wr(t,e);if(!n)return r;if(!r)return n;for(var i=0;i<n.length;++i){var o=n[i],a=r[i];if(o&&a)t:for(var s=0;s<a.length;++s){for(var l=a[s],u=0;u<o.length;++u)if(o[u].marker==l.marker)continue t;o.push(l)}else a&&(n[i]=a)}return n}function Ur(t,e,n){var r=null;t.iter(e.line,n.line+1,function(t){if(t.markedSpans)for(var e=0;e<t.markedSpans.length;++e){var n=t.markedSpans[e].marker;!n.readOnly||r&&-1!=go(r,n)||(r||(r=[])).push(n)}});if(!r)return null;for(var i=[{from:e,to:n}],o=0;o<r.length;++o)for(var a=r[o],s=a.find(0),l=0;l<i.length;++l){var u=i[l];if(!(ba(u.to,s.from)<0||ba(u.from,s.to)>0)){var c=[l,1],f=ba(u.from,s.from),h=ba(u.to,s.to);(0>f||!a.inclusiveLeft&&!f)&&c.push({from:u.from,to:s.from});(h>0||!a.inclusiveRight&&!h)&&c.push({from:s.to,to:u.to});i.splice.apply(i,c);l+=c.length-1}}return i}function Br(t){var e=t.markedSpans;if(e){for(var n=0;n<e.length;++n)e[n].marker.detachLine(t);t.markedSpans=null}}function Vr(t,e){if(e){for(var n=0;n<e.length;++n)e[n].marker.attachLine(t);t.markedSpans=e}}function Xr(t){return t.inclusiveLeft?-1:0}function Gr(t){return t.inclusiveRight?1:0}function $r(t,e){var n=t.lines.length-e.lines.length;if(0!=n)return n;var r=t.find(),i=e.find(),o=ba(r.from,i.from)||Xr(t)-Xr(e);if(o)return-o;var a=ba(r.to,i.to)||Gr(t)-Gr(e);return a?a:e.id-t.id}function Yr(t,e){var n,r=va&&t.markedSpans;if(r)for(var i,o=0;o<r.length;++o){i=r[o];i.marker.collapsed&&null==(e?i.from:i.to)&&(!n||$r(n,i.marker)<0)&&(n=i.marker)}return n}function Jr(t){return Yr(t,!0)}function Kr(t){return Yr(t,!1)}function Zr(t,e,n,r,i){var o=Ei(t,e),a=va&&o.markedSpans;if(a)for(var s=0;s<a.length;++s){var l=a[s];if(l.marker.collapsed){var u=l.marker.find(0),c=ba(u.from,n)||Xr(l.marker)-Xr(i),f=ba(u.to,r)||Gr(l.marker)-Gr(i);if(!(c>=0&&0>=f||0>=c&&f>=0)&&(0>=c&&(ba(u.to,n)>0||l.marker.inclusiveRight&&i.inclusiveLeft)||c>=0&&(ba(u.from,r)<0||l.marker.inclusiveLeft&&i.inclusiveRight)))return!0}}}function Qr(t){for(var e;e=Jr(t);)t=e.find(-1,!0).line;return t}function ti(t){for(var e,n;e=Kr(t);){t=e.find(1,!0).line;(n||(n=[])).push(t)}return n}function ei(t,e){var n=Ei(t,e),r=Qr(n);return n==r?e:Hi(r)}function ni(t,e){if(e>t.lastLine())return e;var n,r=Ei(t,e);if(!ri(t,r))return e;for(;n=Kr(r);)r=n.find(1,!0).line;return Hi(r)+1}function ri(t,e){var n=va&&e.markedSpans;if(n)for(var r,i=0;i<n.length;++i){r=n[i];if(r.marker.collapsed){if(null==r.from)return!0;if(!r.marker.widgetNode&&0==r.from&&r.marker.inclusiveLeft&&ii(t,e,r))return!0}}}function ii(t,e,n){if(null==n.to){var r=n.marker.find(1,!0);return ii(t,r.line,Pr(r.line.markedSpans,n.marker))}if(n.marker.inclusiveRight&&n.to==e.text.length)return!0;for(var i,o=0;o<e.markedSpans.length;++o){i=e.markedSpans[o];if(i.marker.collapsed&&!i.marker.widgetNode&&i.from==n.to&&(null==i.to||i.to!=n.from)&&(i.marker.inclusiveLeft||n.marker.inclusiveRight)&&ii(t,e,i))return!0}}function oi(t,e,n){Fi(e)<(t.curOp&&t.curOp.scrollTop||t.doc.scrollTop)&&yr(t,null,n)}function ai(t){if(null!=t.height)return t.height;if(!ko(document.body,t.node)){var e="position: relative;";t.coverGutter&&(e+="margin-left: -"+t.cm.getGutterElement().offsetWidth+"px;");_o(t.cm.display.measure,Co("div",[t.node],null,e))}return t.height=t.node.offsetHeight}function si(t,e,n,r){var i=new Za(t,n,r);i.noHScroll&&(t.display.alignWidgets=!0);Sr(t.doc,e,"widget",function(e){var n=e.widgets||(e.widgets=[]);null==i.insertAt?n.push(i):n.splice(Math.min(n.length-1,Math.max(0,i.insertAt)),0,i);i.line=e;if(!ri(t.doc,e)){var r=Fi(e)<t.doc.scrollTop;Pi(e,e.height+ai(i));r&&yr(t,null,i.height);t.curOp.forceUpdate=!0}return!0});return i}function li(t,e,n,r){t.text=e;t.stateAfter&&(t.stateAfter=null);t.styles&&(t.styles=null);null!=t.order&&(t.order=null);Br(t);Vr(t,n);var i=r?r(t):1;i!=t.height&&Pi(t,i)}function ui(t){t.parent=null;Br(t)}function ci(t,e){if(t)for(;;){var n=t.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!n)break;t=t.slice(0,n.index)+t.slice(n.index+n[0].length);var r=n[1]?"bgClass":"textClass";null==e[r]?e[r]=n[2]:new RegExp("(?:^|s)"+n[2]+"(?:$|s)").test(e[r])||(e[r]+=" "+n[2])}return t}function fi(e,n){if(e.blankLine)return e.blankLine(n);if(e.innerMode){var r=t.innerMode(e,n);return r.mode.blankLine?r.mode.blankLine(r.state):void 0}}function hi(e,n,r,i){for(var o=0;10>o;o++){i&&(i[0]=t.innerMode(e,r).mode);var a=e.token(n,r);if(n.pos>n.start)return a}throw new Error("Mode "+e.name+" failed to advance stream.")}function di(t,e,n,r){function i(t){return{start:f.start,end:f.pos,string:f.current(),type:o||null,state:t?za(a.mode,c):c}}var o,a=t.doc,s=a.mode;e=Z(a,e);var l,u=Ei(a,e.line),c=Te(t,e.line,n),f=new $a(u.text,t.options.tabSize);r&&(l=[]);for(;(r||f.pos<e.ch)&&!f.eol();){f.start=f.pos;o=hi(s,f,c);r&&l.push(i(!0))}return r?l:i()}function pi(t,e,n,r,i,o,a){var s=n.flattenSpans;null==s&&(s=t.options.flattenSpans);var l,u=0,c=null,f=new $a(e,t.options.tabSize),h=t.options.addModeClass&&[null];""==e&&ci(fi(n,r),o);for(;!f.eol();){if(f.pos>t.options.maxHighlightLength){s=!1;a&&vi(t,e,r,f.pos);f.pos=e.length;l=null}else l=ci(hi(n,f,r,h),o);if(h){var d=h[0].name;d&&(l="m-"+(l?d+" "+l:d))}if(!s||c!=l){u<f.start&&i(f.start,c);u=f.start;c=l}f.start=f.pos}for(;u<f.pos;){var p=Math.min(f.pos,u+5e4);i(p,c);u=p}}function gi(t,e,n,r){var i=[t.state.modeGen],o={};pi(t,e.text,t.doc.mode,n,function(t,e){i.push(t,e)},o,r);for(var a=0;a<t.state.overlays.length;++a){var s=t.state.overlays[a],l=1,u=0;pi(t,e.text,s.mode,!0,function(t,e){for(var n=l;t>u;){var r=i[l];r>t&&i.splice(l,1,t,i[l+1],r);l+=2;u=Math.min(t,r)}if(e)if(s.opaque){i.splice(n,l-n,t,"cm-overlay "+e);l=n+2}else for(;l>n;n+=2){var o=i[n+1];i[n+1]=(o?o+" ":"")+"cm-overlay "+e}},o)}return{styles:i,classes:o.bgClass||o.textClass?o:null}}function mi(t,e,n){if(!e.styles||e.styles[0]!=t.state.modeGen){var r=gi(t,e,e.stateAfter=Te(t,Hi(e)));e.styles=r.styles;r.classes?e.styleClasses=r.classes:e.styleClasses&&(e.styleClasses=null);n===t.doc.frontier&&t.doc.frontier++}return e.styles}function vi(t,e,n,r){var i=t.doc.mode,o=new $a(e,t.options.tabSize);o.start=o.pos=r||0;""==e&&fi(i,n);for(;!o.eol()&&o.pos<=t.options.maxHighlightLength;){hi(i,o,n);o.start=o.pos}}function yi(t,e){if(!t||/^\s*$/.test(t))return null;var n=e.addModeClass?es:ts;return n[t]||(n[t]=t.replace(/\S+/g,"cm-$&"))}function bi(t,e){var n=Co("span",null,null,ea?"padding-right: .1px":null),r={pre:Co("pre",[n]),content:n,col:0,pos:0,cm:t};e.measure={};for(var i=0;i<=(e.rest?e.rest.length:0);i++){var o,a=i?e.rest[i-1]:e.line;r.pos=0;r.addToken=wi;(Qo||ea)&&t.getOption("lineWrapping")&&(r.addToken=Si(r.addToken));Po(t.display.measure)&&(o=Ri(a))&&(r.addToken=Ci(r.addToken,o));r.map=[];var s=e!=t.display.externalMeasured&&Hi(a);_i(a,r,mi(t,a,s));if(a.styleClasses){a.styleClasses.bgClass&&(r.bgClass=Lo(a.styleClasses.bgClass,r.bgClass||""));a.styleClasses.textClass&&(r.textClass=Lo(a.styleClasses.textClass,r.textClass||""))}0==r.map.length&&r.map.push(0,0,r.content.appendChild(Io(t.display.measure)));if(0==i){e.measure.map=r.map;e.measure.cache={}}else{(e.measure.maps||(e.measure.maps=[])).push(r.map);(e.measure.caches||(e.measure.caches=[])).push({})}}ea&&/\bcm-tab\b/.test(r.content.lastChild.className)&&(r.content.className="cm-tab-wrap-hack");fs(t,"renderLine",t,e.line,r.pre);r.pre.className&&(r.textClass=Lo(r.pre.className,r.textClass||""));return r}function xi(t){var e=Co("span","•","cm-invalidchar");e.title="\\u"+t.charCodeAt(0).toString(16);return e}function wi(t,e,n,r,i,o){if(e){var a=t.cm.options.specialChars,s=!1;if(a.test(e))for(var l=document.createDocumentFragment(),u=0;;){a.lastIndex=u;var c=a.exec(e),f=c?c.index-u:e.length-u;if(f){var h=document.createTextNode(e.slice(u,u+f));l.appendChild(Qo&&9>ta?Co("span",[h]):h);t.map.push(t.pos,t.pos+f,h);t.col+=f;t.pos+=f}if(!c)break;u+=f+1;if(" "==c[0]){var d=t.cm.options.tabSize,p=d-t.col%d,h=l.appendChild(Co("span",ho(p),"cm-tab"));t.col+=p}else{var h=t.cm.options.specialCharPlaceholder(c[0]);l.appendChild(Qo&&9>ta?Co("span",[h]):h);t.col+=1}t.map.push(t.pos,t.pos+1,h);t.pos++}else{t.col+=e.length;var l=document.createTextNode(e);t.map.push(t.pos,t.pos+e.length,l);Qo&&9>ta&&(s=!0);t.pos+=e.length}if(n||r||i||s){var g=n||"";r&&(g+=r);i&&(g+=i);var m=Co("span",[l],g);o&&(m.title=o);return t.content.appendChild(m)}t.content.appendChild(l)}}function Si(t){function e(t){for(var e=" ",n=0;n<t.length-2;++n)e+=n%2?" ":" ";e+=" ";return e}return function(n,r,i,o,a,s){t(n,r.replace(/ {3,}/g,e),i,o,a,s)}}function Ci(t,e){return function(n,r,i,o,a,s){i=i?i+" cm-force-border":"cm-force-border";for(var l=n.pos,u=l+r.length;;){for(var c=0;c<e.length;c++){var f=e[c];if(f.to>l&&f.from<=l)break}if(f.to>=u)return t(n,r,i,o,a,s);t(n,r.slice(0,f.to-l),i,o,null,s);o=null;r=r.slice(f.to-l);l=f.to}}}function Ti(t,e,n,r){var i=!r&&n.widgetNode;if(i){t.map.push(t.pos,t.pos+e,i);t.content.appendChild(i)}t.pos+=e}function _i(t,e,n){var r=t.markedSpans,i=t.text,o=0;if(r)for(var a,s,l,u,c,f,h=i.length,d=0,p=1,g="",m=0;;){if(m==d){s=l=u=c="";f=null;m=1/0;for(var v=[],y=0;y<r.length;++y){var b=r[y],x=b.marker;if(b.from<=d&&(null==b.to||b.to>d)){if(null!=b.to&&m>b.to){m=b.to;l=""}x.className&&(s+=" "+x.className);x.startStyle&&b.from==d&&(u+=" "+x.startStyle);x.endStyle&&b.to==m&&(l+=" "+x.endStyle);x.title&&!c&&(c=x.title);x.collapsed&&(!f||$r(f.marker,x)<0)&&(f=b)}else b.from>d&&m>b.from&&(m=b.from);"bookmark"==x.type&&b.from==d&&x.widgetNode&&v.push(x)}if(f&&(f.from||0)==d){Ti(e,(null==f.to?h+1:f.to)-d,f.marker,null==f.from);if(null==f.to)return}if(!f&&v.length)for(var y=0;y<v.length;++y)Ti(e,0,v[y])}if(d>=h)break;for(var w=Math.min(h,m);;){if(g){var S=d+g.length;if(!f){var C=S>w?g.slice(0,w-d):g;e.addToken(e,C,a?a+s:s,u,d+C.length==m?l:"",c)}if(S>=w){g=g.slice(w-d);d=w;break}d=S;u=""}g=i.slice(o,o=n[p++]);a=yi(n[p++],e.cm.options)}}else for(var p=1;p<n.length;p+=2)e.addToken(e,i.slice(o,o=n[p]),yi(n[p+1],e.cm.options))}function ki(t,e){return 0==e.from.ch&&0==e.to.ch&&""==po(e.text)&&(!t.cm||t.cm.options.wholeLineUpdateBefore)}function Mi(t,e,n,r){function i(t){return n?n[t]:null}function o(t,n,i){li(t,n,i,r);io(t,"change",t,e)}var a=e.from,s=e.to,l=e.text,u=Ei(t,a.line),c=Ei(t,s.line),f=po(l),h=i(l.length-1),d=s.line-a.line;if(ki(t,e)){for(var p=0,g=[];p<l.length-1;++p)g.push(new Qa(l[p],i(p),r));o(c,c.text,h);d&&t.remove(a.line,d);g.length&&t.insert(a.line,g)}else if(u==c)if(1==l.length)o(u,u.text.slice(0,a.ch)+f+u.text.slice(s.ch),h);else{for(var g=[],p=1;p<l.length-1;++p)g.push(new Qa(l[p],i(p),r));g.push(new Qa(f+u.text.slice(s.ch),h,r));o(u,u.text.slice(0,a.ch)+l[0],i(0));t.insert(a.line+1,g)}else if(1==l.length){o(u,u.text.slice(0,a.ch)+l[0]+c.text.slice(s.ch),i(0));t.remove(a.line+1,d)}else{o(u,u.text.slice(0,a.ch)+l[0],i(0));o(c,f+c.text.slice(s.ch),h);for(var p=1,g=[];p<l.length-1;++p)g.push(new Qa(l[p],i(p),r));d>1&&t.remove(a.line+1,d-1);t.insert(a.line+1,g)}io(t,"change",t,e)}function Di(t){this.lines=t;this.parent=null;for(var e=0,n=0;e<t.length;++e){t[e].parent=this;n+=t[e].height}this.height=n}function Li(t){this.children=t;for(var e=0,n=0,r=0;r<t.length;++r){var i=t[r];e+=i.chunkSize();n+=i.height;i.parent=this}this.size=e;this.height=n;this.parent=null}function Ai(t,e,n){function r(t,i,o){if(t.linked)for(var a=0;a<t.linked.length;++a){var s=t.linked[a];if(s.doc!=i){var l=o&&s.sharedHist;if(!n||l){e(s.doc,l);r(s.doc,t,l)}}}}r(t,null,!0)}function Ni(t,e){if(e.cm)throw new Error("This document is already in use.");t.doc=e;e.cm=t;a(t);n(t);t.options.lineWrapping||h(t);t.options.mode=e.modeOption;pn(t)}function Ei(t,e){e-=t.first;if(0>e||e>=t.size)throw new Error("There is no line "+(e+t.first)+" in the document.");for(var n=t;!n.lines;)for(var r=0;;++r){var i=n.children[r],o=i.chunkSize();if(o>e){n=i;break}e-=o}return n.lines[e]}function ji(t,e,n){var r=[],i=e.line;t.iter(e.line,n.line+1,function(t){var o=t.text;i==n.line&&(o=o.slice(0,n.ch));i==e.line&&(o=o.slice(e.ch));r.push(o);++i});return r}function Ii(t,e,n){var r=[];t.iter(e,n,function(t){r.push(t.text)});return r}function Pi(t,e){var n=e-t.height;if(n)for(var r=t;r;r=r.parent)r.height+=n}function Hi(t){if(null==t.parent)return null;for(var e=t.parent,n=go(e.lines,t),r=e.parent;r;e=r,r=r.parent)for(var i=0;r.children[i]!=e;++i)n+=r.children[i].chunkSize();return n+e.first}function Oi(t,e){var n=t.first;t:do{for(var r=0;r<t.children.length;++r){var i=t.children[r],o=i.height;if(o>e){t=i;continue t}e-=o;n+=i.chunkSize()}return n}while(!t.lines);for(var r=0;r<t.lines.length;++r){var a=t.lines[r],s=a.height;if(s>e)break;e-=s}return n+r}function Fi(t){t=Qr(t);for(var e=0,n=t.parent,r=0;r<n.lines.length;++r){var i=n.lines[r];if(i==t)break;e+=i.height}for(var o=n.parent;o;n=o,o=n.parent)for(var r=0;r<o.children.length;++r){var a=o.children[r];if(a==n)break;e+=a.height}return e}function Ri(t){var e=t.order;null==e&&(e=t.order=Fs(t.text));return e}function Wi(t){this.done=[];this.undone=[];this.undoDepth=1/0;this.lastModTime=this.lastSelTime=0;this.lastOp=this.lastSelOp=null;this.lastOrigin=this.lastSelOrigin=null;this.generation=this.maxGeneration=t||1}function zi(t,e){var n={from:B(e.from),to:Ea(e),text:ji(t,e.from,e.to)};$i(t,n,e.from.line,e.to.line+1);Ai(t,function(t){$i(t,n,e.from.line,e.to.line+1)},!0);return n}function qi(t){for(;t.length;){var e=po(t);if(!e.ranges)break;t.pop()}}function Ui(t,e){if(e){qi(t.done);return po(t.done)}if(t.done.length&&!po(t.done).ranges)return po(t.done);if(t.done.length>1&&!t.done[t.done.length-2].ranges){t.done.pop();return po(t.done)}}function Bi(t,e,n,r){var i=t.history;i.undone.length=0;var o,a=+new Date;if((i.lastOp==r||i.lastOrigin==e.origin&&e.origin&&("+"==e.origin.charAt(0)&&t.cm&&i.lastModTime>a-t.cm.options.historyEventDelay||"*"==e.origin.charAt(0)))&&(o=Ui(i,i.lastOp==r))){var s=po(o.changes);0==ba(e.from,e.to)&&0==ba(e.from,s.to)?s.to=Ea(e):o.changes.push(zi(t,e))}else{var l=po(i.done);l&&l.ranges||Gi(t.sel,i.done);o={changes:[zi(t,e)],generation:i.generation};i.done.push(o);for(;i.done.length>i.undoDepth;){i.done.shift();i.done[0].ranges||i.done.shift()}}i.done.push(n);i.generation=++i.maxGeneration;i.lastModTime=i.lastSelTime=a;i.lastOp=i.lastSelOp=r;i.lastOrigin=i.lastSelOrigin=e.origin;s||fs(t,"historyAdded")}function Vi(t,e,n,r){var i=e.charAt(0);return"*"==i||"+"==i&&n.ranges.length==r.ranges.length&&n.somethingSelected()==r.somethingSelected()&&new Date-t.history.lastSelTime<=(t.cm?t.cm.options.historyEventDelay:500)}function Xi(t,e,n,r){var i=t.history,o=r&&r.origin;n==i.lastSelOp||o&&i.lastSelOrigin==o&&(i.lastModTime==i.lastSelTime&&i.lastOrigin==o||Vi(t,o,po(i.done),e))?i.done[i.done.length-1]=e:Gi(e,i.done);i.lastSelTime=+new Date;i.lastSelOrigin=o;i.lastSelOp=n;r&&r.clearRedo!==!1&&qi(i.undone)}function Gi(t,e){var n=po(e);n&&n.ranges&&n.equals(t)||e.push(t)}function $i(t,e,n,r){var i=e["spans_"+t.id],o=0;t.iter(Math.max(t.first,n),Math.min(t.first+t.size,r),function(n){n.markedSpans&&((i||(i=e["spans_"+t.id]={}))[o]=n.markedSpans);++o})}function Yi(t){if(!t)return null;for(var e,n=0;n<t.length;++n)t[n].marker.explicitlyCleared?e||(e=t.slice(0,n)):e&&e.push(t[n]);return e?e.length?e:null:t}function Ji(t,e){var n=e["spans_"+t.id];if(!n)return null;for(var r=0,i=[];r<e.text.length;++r)i.push(Yi(n[r]));return i}function Ki(t,e,n){for(var r=0,i=[];r<t.length;++r){var o=t[r];if(o.ranges)i.push(n?G.prototype.deepCopy.call(o):o);else{var a=o.changes,s=[];i.push({changes:s});for(var l=0;l<a.length;++l){var u,c=a[l];s.push({from:c.from,to:c.to,text:c.text});if(e)for(var f in c)if((u=f.match(/^spans_(\d+)$/))&&go(e,Number(u[1]))>-1){po(s)[f]=c[f];delete c[f]}}}}return i}function Zi(t,e,n,r){if(n<t.line)t.line+=r;else if(e<t.line){t.line=e;t.ch=0}}function Qi(t,e,n,r){for(var i=0;i<t.length;++i){var o=t[i],a=!0;if(o.ranges){if(!o.copied){o=t[i]=o.deepCopy();o.copied=!0}for(var s=0;s<o.ranges.length;s++){Zi(o.ranges[s].anchor,e,n,r);Zi(o.ranges[s].head,e,n,r)}}else{for(var s=0;s<o.changes.length;++s){var l=o.changes[s];if(n<l.from.line){l.from=ya(l.from.line+r,l.from.ch);l.to=ya(l.to.line+r,l.to.ch)}else if(e<=l.to.line){a=!1;break}}if(!a){t.splice(0,i+1);i=0}}}}function to(t,e){var n=e.from.line,r=e.to.line,i=e.text.length-(r-n)-1;Qi(t.done,n,r,i);Qi(t.undone,n,r,i)}function eo(t){return null!=t.defaultPrevented?t.defaultPrevented:0==t.returnValue}function no(t){return t.target||t.srcElement}function ro(t){var e=t.which;null==e&&(1&t.button?e=1:2&t.button?e=3:4&t.button&&(e=2));fa&&t.ctrlKey&&1==e&&(e=3);return e}function io(t,e){function n(t){return function(){t.apply(null,o)}}var r=t._handlers&&t._handlers[e];if(r){var i,o=Array.prototype.slice.call(arguments,2);if(Ta)i=Ta.delayedCallbacks;else if(hs)i=hs;else{i=hs=[];setTimeout(oo,0)}for(var a=0;a<r.length;++a)i.push(n(r[a]))}}function oo(){var t=hs;hs=null;for(var e=0;e<t.length;++e)t[e]()}function ao(t,e,n){"string"==typeof e&&(e={type:e,preventDefault:function(){this.defaultPrevented=!0}});fs(t,n||e.type,t,e);return eo(e)||e.codemirrorIgnore}function so(t){var e=t._handlers&&t._handlers.cursorActivity;if(e)for(var n=t.curOp.cursorActivityHandlers||(t.curOp.cursorActivityHandlers=[]),r=0;r<e.length;++r)-1==go(n,e[r])&&n.push(e[r])}function lo(t,e){var n=t._handlers&&t._handlers[e];return n&&n.length>0}function uo(t){t.prototype.on=function(t,e){us(this,t,e)};t.prototype.off=function(t,e){cs(this,t,e)}}function co(){this.id=null}function fo(t,e,n){for(var r=0,i=0;;){var o=t.indexOf(" ",r);-1==o&&(o=t.length);var a=o-r;if(o==t.length||i+a>=e)return r+Math.min(a,e-i);i+=o-r;i+=n-i%n;r=o+1;if(i>=e)return r}}function ho(t){for(;bs.length<=t;)bs.push(po(bs)+" ");return bs[t]}function po(t){return t[t.length-1]}function go(t,e){for(var n=0;n<t.length;++n)if(t[n]==e)return n;return-1}function mo(t,e){for(var n=[],r=0;r<t.length;r++)n[r]=e(t[r],r);return n}function vo(t,e){var n;if(Object.create)n=Object.create(t);else{var r=function(){};r.prototype=t;n=new r}e&&yo(e,n);return n}function yo(t,e,n){e||(e={});for(var r in t)!t.hasOwnProperty(r)||n===!1&&e.hasOwnProperty(r)||(e[r]=t[r]);return e}function bo(t){var e=Array.prototype.slice.call(arguments,1);return function(){return t.apply(null,e)}}function xo(t,e){return e?e.source.indexOf("\\w")>-1&&Cs(t)?!0:e.test(t):Cs(t)}function wo(t){for(var e in t)if(t.hasOwnProperty(e)&&t[e])return!1;return!0}function So(t){return t.charCodeAt(0)>=768&&Ts.test(t)}function Co(t,e,n,r){var i=document.createElement(t);n&&(i.className=n);r&&(i.style.cssText=r);if("string"==typeof e)i.appendChild(document.createTextNode(e));else if(e)for(var o=0;o<e.length;++o)i.appendChild(e[o]);return i}function To(t){for(var e=t.childNodes.length;e>0;--e)t.removeChild(t.firstChild);return t}function _o(t,e){return To(t).appendChild(e)}function ko(t,e){if(t.contains)return t.contains(e);for(;e=e.parentNode;)if(e==t)return!0}function Mo(){return document.activeElement}function Do(t){return new RegExp("(^|\\s)"+t+"(?:$|\\s)\\s*")}function Lo(t,e){for(var n=t.split(" "),r=0;r<n.length;r++)n[r]&&!Do(n[r]).test(e)&&(e+=" "+n[r]);return e}function Ao(t){if(document.body.getElementsByClassName)for(var e=document.body.getElementsByClassName("CodeMirror"),n=0;n<e.length;n++){var r=e[n].CodeMirror;r&&t(r)}}function No(){if(!As){Eo();As=!0}}function Eo(){var t;us(window,"resize",function(){null==t&&(t=setTimeout(function(){t=null;_s=null;Ao(Ln)},100))});us(window,"blur",function(){Ao(Qn)})}function jo(t){if(null!=_s)return _s;var e=Co("div",null,null,"width: 50px; height: 50px; overflow-x: scroll");_o(t,e);e.offsetWidth&&(_s=e.offsetHeight-e.clientHeight);return _s||0}function Io(t){if(null==ks){var e=Co("span","");_o(t,Co("span",[e,document.createTextNode("x")]));0!=t.firstChild.offsetHeight&&(ks=e.offsetWidth<=1&&e.offsetHeight>2&&!(Qo&&8>ta))}return ks?Co("span",""):Co("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")}function Po(t){if(null!=Ms)return Ms;var e=_o(t,document.createTextNode("AخA")),n=ws(e,0,1).getBoundingClientRect();if(!n||n.left==n.right)return!1;var r=ws(e,1,2).getBoundingClientRect();return Ms=r.right-n.right<3}function Ho(t){if(null!=Ps)return Ps;var e=_o(t,Co("span","x")),n=e.getBoundingClientRect(),r=ws(e,0,1).getBoundingClientRect();return Ps=Math.abs(n.left-r.left)>1}function Oo(t,e,n,r){if(!t)return r(e,n,"ltr");for(var i=!1,o=0;o<t.length;++o){var a=t[o];if(a.from<n&&a.to>e||e==n&&a.to==e){r(Math.max(a.from,e),Math.min(a.to,n),1==a.level?"rtl":"ltr");i=!0}}i||r(e,n,"ltr")}function Fo(t){return t.level%2?t.to:t.from}function Ro(t){return t.level%2?t.from:t.to}function Wo(t){var e=Ri(t);return e?Fo(e[0]):0}function zo(t){var e=Ri(t);return e?Ro(po(e)):t.text.length}function qo(t,e){var n=Ei(t.doc,e),r=Qr(n);r!=n&&(e=Hi(r));var i=Ri(r),o=i?i[0].level%2?zo(r):Wo(r):0;return ya(e,o)}function Uo(t,e){for(var n,r=Ei(t.doc,e);n=Kr(r);){r=n.find(1,!0).line;e=null}var i=Ri(r),o=i?i[0].level%2?Wo(r):zo(r):r.text.length;return ya(null==e?Hi(r):e,o)}function Bo(t,e){var n=qo(t,e.line),r=Ei(t.doc,n.line),i=Ri(r);if(!i||0==i[0].level){var o=Math.max(0,r.text.search(/\S/)),a=e.line==n.line&&e.ch<=o&&e.ch;return ya(n.line,a?0:o)}return n}function Vo(t,e,n){var r=t[0].level;return e==r?!0:n==r?!1:n>e}function Xo(t,e){Os=null;for(var n,r=0;r<t.length;++r){var i=t[r];if(i.from<e&&i.to>e)return r;if(i.from==e||i.to==e){if(null!=n){if(Vo(t,i.level,t[n].level)){i.from!=i.to&&(Os=n);return r}i.from!=i.to&&(Os=r);return n}n=r}}return n}function Go(t,e,n,r){if(!r)return e+n;do e+=n;while(e>0&&So(t.text.charAt(e)));return e}function $o(t,e,n,r){var i=Ri(t);if(!i)return Yo(t,e,n,r);for(var o=Xo(i,e),a=i[o],s=Go(t,e,a.level%2?-n:n,r);;){if(s>a.from&&s<a.to)return s;if(s==a.from||s==a.to){if(Xo(i,s)==o)return s;a=i[o+=n];return n>0==a.level%2?a.to:a.from}a=i[o+=n];if(!a)return null;s=n>0==a.level%2?Go(t,a.to,-1,r):Go(t,a.from,1,r)}}function Yo(t,e,n,r){var i=e+n;if(r)for(;i>0&&So(t.text.charAt(i));)i+=n;return 0>i||i>t.text.length?null:i}var Jo=/gecko\/\d/i.test(navigator.userAgent),Ko=/MSIE \d/.test(navigator.userAgent),Zo=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),Qo=Ko||Zo,ta=Qo&&(Ko?document.documentMode||6:Zo[1]),ea=/WebKit\//.test(navigator.userAgent),na=ea&&/Qt\/\d+\.\d+/.test(navigator.userAgent),ra=/Chrome\//.test(navigator.userAgent),ia=/Opera\//.test(navigator.userAgent),oa=/Apple Computer/.test(navigator.vendor),aa=/KHTML\//.test(navigator.userAgent),sa=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),la=/PhantomJS/.test(navigator.userAgent),ua=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),ca=ua||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),fa=ua||/Mac/.test(navigator.platform),ha=/win/i.test(navigator.platform),da=ia&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);da&&(da=Number(da[1]));if(da&&da>=15){ia=!1;ea=!0}var pa=fa&&(na||ia&&(null==da||12.11>da)),ga=Jo||Qo&&ta>=9,ma=!1,va=!1,ya=t.Pos=function(t,e){if(!(this instanceof ya))return new ya(t,e);this.line=t;this.ch=e},ba=t.cmpPos=function(t,e){return t.line-e.line||t.ch-e.ch};G.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(t){if(t==this)return!0;if(t.primIndex!=this.primIndex||t.ranges.length!=this.ranges.length)return!1;for(var e=0;e<this.ranges.length;e++){var n=this.ranges[e],r=t.ranges[e];if(0!=ba(n.anchor,r.anchor)||0!=ba(n.head,r.head))return!1}return!0},deepCopy:function(){for(var t=[],e=0;e<this.ranges.length;e++)t[e]=new $(B(this.ranges[e].anchor),B(this.ranges[e].head));return new G(t,this.primIndex)},somethingSelected:function(){for(var t=0;t<this.ranges.length;t++)if(!this.ranges[t].empty())return!0;return!1},contains:function(t,e){e||(e=t);for(var n=0;n<this.ranges.length;n++){var r=this.ranges[n];if(ba(e,r.from())>=0&&ba(t,r.to())<=0)return n}return-1}};$.prototype={from:function(){return X(this.anchor,this.head)},to:function(){return V(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var xa,wa,Sa,Ca={left:0,right:0,top:0,bottom:0},Ta=null,_a=0,ka=null,Ma=0,Da=0,La=null;Qo?La=-.53:Jo?La=15:ra?La=-.7:oa&&(La=-1/3);var Aa=new co,Na=null,Ea=t.changeEnd=function(t){return t.text?ya(t.from.line+t.text.length-1,po(t.text).length+(1==t.text.length?t.from.ch:0)):t.to};t.prototype={constructor:t,focus:function(){window.focus();_n(this);Sn(this)},setOption:function(t,e){var n=this.options,r=n[t];if(n[t]!=e||"mode"==t){n[t]=e;Ia.hasOwnProperty(t)&&un(this,Ia[t])(this,e,r)}},getOption:function(t){return this.options[t]},getDoc:function(){return this.doc},addKeyMap:function(t,e){this.state.keyMaps[e?"push":"unshift"](Dr(t))},removeKeyMap:function(t){for(var e=this.state.keyMaps,n=0;n<e.length;++n)if(e[n]==t||e[n].name==t){e.splice(n,1);return!0}},addOverlay:cn(function(e,n){var r=e.token?e:t.getMode(this.options,e);if(r.startState)throw new Error("Overlays may not be stateful.");this.state.overlays.push({mode:r,modeSpec:e,opaque:n&&n.opaque});this.state.modeGen++;pn(this)}),removeOverlay:cn(function(t){for(var e=this.state.overlays,n=0;n<e.length;++n){var r=e[n].modeSpec;if(r==t||"string"==typeof t&&r.name==t){e.splice(n,1);this.state.modeGen++;pn(this);return}}}),indentLine:cn(function(t,e,n){"string"!=typeof e&&"number"!=typeof e&&(e=null==e?this.options.smartIndent?"smart":"prev":e?"add":"subtract");te(this.doc,t)&&wr(this,t,e,n)
}),indentSelection:cn(function(t){for(var e=this.doc.sel.ranges,n=-1,r=0;r<e.length;r++){var i=e[r];if(i.empty()){if(i.head.line>n){wr(this,i.head.line,t,!0);n=i.head.line;r==this.doc.sel.primIndex&&br(this)}}else{var o=i.from(),a=i.to(),s=Math.max(n,o.line);n=Math.min(this.lastLine(),a.line-(a.ch?0:1))+1;for(var l=s;n>l;++l)wr(this,l,t);var u=this.doc.sel.ranges;0==o.ch&&e.length==u.length&&u[r].from().ch>0&&oe(this.doc,r,new $(o,u[r].to()),gs)}}}),getTokenAt:function(t,e){return di(this,t,e)},getLineTokens:function(t,e){return di(this,ya(t),e,!0)},getTokenTypeAt:function(t){t=Z(this.doc,t);var e,n=mi(this,Ei(this.doc,t.line)),r=0,i=(n.length-1)/2,o=t.ch;if(0==o)e=n[2];else for(;;){var a=r+i>>1;if((a?n[2*a-1]:0)>=o)i=a;else{if(!(n[2*a+1]<o)){e=n[2*a+2];break}r=a+1}}var s=e?e.indexOf("cm-overlay "):-1;return 0>s?e:0==s?null:e.slice(0,s-1)},getModeAt:function(e){var n=this.doc.mode;return n.innerMode?t.innerMode(n,this.getTokenAt(e).state).mode:n},getHelper:function(t,e){return this.getHelpers(t,e)[0]},getHelpers:function(t,e){var n=[];if(!Wa.hasOwnProperty(e))return Wa;var r=Wa[e],i=this.getModeAt(t);if("string"==typeof i[e])r[i[e]]&&n.push(r[i[e]]);else if(i[e])for(var o=0;o<i[e].length;o++){var a=r[i[e][o]];a&&n.push(a)}else i.helperType&&r[i.helperType]?n.push(r[i.helperType]):r[i.name]&&n.push(r[i.name]);for(var o=0;o<r._global.length;o++){var s=r._global[o];s.pred(i,this)&&-1==go(n,s.val)&&n.push(s.val)}return n},getStateAfter:function(t,e){var n=this.doc;t=K(n,null==t?n.first+n.size-1:t);return Te(this,t+1,e)},cursorCoords:function(t,e){var n,r=this.doc.sel.primary();n=null==t?r.head:"object"==typeof t?Z(this.doc,t):t?r.from():r.to();return Ve(this,n,e||"page")},charCoords:function(t,e){return Be(this,Z(this.doc,t),e||"page")},coordsChar:function(t,e){t=Ue(this,t,e||"page");return $e(this,t.left,t.top)},lineAtHeight:function(t,e){t=Ue(this,{top:t,left:0},e||"page").top;return Oi(this.doc,t+this.display.viewOffset)},heightAtLine:function(t,e){var n=!1,r=this.doc.first+this.doc.size-1;if(t<this.doc.first)t=this.doc.first;else if(t>r){t=r;n=!0}var i=Ei(this.doc,t);return qe(this,i,{top:0,left:0},e||"page").top+(n?this.doc.height-Fi(i):0)},defaultTextHeight:function(){return Je(this.display)},defaultCharWidth:function(){return Ke(this.display)},setGutterMarker:cn(function(t,e,n){return Sr(this.doc,t,"gutter",function(t){var r=t.gutterMarkers||(t.gutterMarkers={});r[e]=n;!n&&wo(r)&&(t.gutterMarkers=null);return!0})}),clearGutter:cn(function(t){var e=this,n=e.doc,r=n.first;n.iter(function(n){if(n.gutterMarkers&&n.gutterMarkers[t]){n.gutterMarkers[t]=null;gn(e,r,"gutter");wo(n.gutterMarkers)&&(n.gutterMarkers=null)}++r})}),addLineWidget:cn(function(t,e,n){return si(this,t,e,n)}),removeLineWidget:function(t){t.clear()},lineInfo:function(t){if("number"==typeof t){if(!te(this.doc,t))return null;var e=t;t=Ei(this.doc,t);if(!t)return null}else{var e=Hi(t);if(null==e)return null}return{line:e,handle:t,text:t.text,gutterMarkers:t.gutterMarkers,textClass:t.textClass,bgClass:t.bgClass,wrapClass:t.wrapClass,widgets:t.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(t,e,n,r,i){var o=this.display;t=Ve(this,Z(this.doc,t));var a=t.bottom,s=t.left;e.style.position="absolute";o.sizer.appendChild(e);if("over"==r)a=t.top;else if("above"==r||"near"==r){var l=Math.max(o.wrapper.clientHeight,this.doc.height),u=Math.max(o.sizer.clientWidth,o.lineSpace.clientWidth);("above"==r||t.bottom+e.offsetHeight>l)&&t.top>e.offsetHeight?a=t.top-e.offsetHeight:t.bottom+e.offsetHeight<=l&&(a=t.bottom);s+e.offsetWidth>u&&(s=u-e.offsetWidth)}e.style.top=a+"px";e.style.left=e.style.right="";if("right"==i){s=o.sizer.clientWidth-e.offsetWidth;e.style.right="0px"}else{"left"==i?s=0:"middle"==i&&(s=(o.sizer.clientWidth-e.offsetWidth)/2);e.style.left=s+"px"}n&&mr(this,s,a,s+e.offsetWidth,a+e.offsetHeight)},triggerOnKeyDown:cn($n),triggerOnKeyPress:cn(Kn),triggerOnKeyUp:Jn,execCommand:function(t){return Ua.hasOwnProperty(t)?Ua[t](this):void 0},findPosH:function(t,e,n,r){var i=1;if(0>e){i=-1;e=-e}for(var o=0,a=Z(this.doc,t);e>o;++o){a=Tr(this.doc,a,i,n,r);if(a.hitSide)break}return a},moveH:cn(function(t,e){var n=this;n.extendSelectionsBy(function(r){return n.display.shift||n.doc.extend||r.empty()?Tr(n.doc,r.head,t,e,n.options.rtlMoveVisually):0>t?r.from():r.to()},vs)}),deleteH:cn(function(t,e){var n=this.doc.sel,r=this.doc;n.somethingSelected()?r.replaceSelection("",null,"+delete"):Cr(this,function(n){var i=Tr(r,n.head,t,e,!1);return 0>t?{from:i,to:n.head}:{from:n.head,to:i}})}),findPosV:function(t,e,n,r){var i=1,o=r;if(0>e){i=-1;e=-e}for(var a=0,s=Z(this.doc,t);e>a;++a){var l=Ve(this,s,"div");null==o?o=l.left:l.left=o;s=_r(this,l,i,n);if(s.hitSide)break}return s},moveV:cn(function(t,e){var n=this,r=this.doc,i=[],o=!n.display.shift&&!r.extend&&r.sel.somethingSelected();r.extendSelectionsBy(function(a){if(o)return 0>t?a.from():a.to();var s=Ve(n,a.head,"div");null!=a.goalColumn&&(s.left=a.goalColumn);i.push(s.left);var l=_r(n,s,t,e);"page"==e&&a==r.sel.primary()&&yr(n,null,Be(n,l,"div").top-s.top);return l},vs);if(i.length)for(var a=0;a<r.sel.ranges.length;a++)r.sel.ranges[a].goalColumn=i[a]}),findWordAt:function(t){var e=this.doc,n=Ei(e,t.line).text,r=t.ch,i=t.ch;if(n){var o=this.getHelper(t,"wordChars");(t.xRel<0||i==n.length)&&r?--r:++i;for(var a=n.charAt(r),s=xo(a,o)?function(t){return xo(t,o)}:/\s/.test(a)?function(t){return/\s/.test(t)}:function(t){return!/\s/.test(t)&&!xo(t)};r>0&&s(n.charAt(r-1));)--r;for(;i<n.length&&s(n.charAt(i));)++i}return new $(ya(t.line,r),ya(t.line,i))},toggleOverwrite:function(t){if(null==t||t!=this.state.overwrite){(this.state.overwrite=!this.state.overwrite)?Ls(this.display.cursorDiv,"CodeMirror-overwrite"):Ds(this.display.cursorDiv,"CodeMirror-overwrite");fs(this,"overwriteToggle",this,this.state.overwrite)}},hasFocus:function(){return Mo()==this.display.input},scrollTo:cn(function(t,e){(null!=t||null!=e)&&xr(this);null!=t&&(this.curOp.scrollLeft=t);null!=e&&(this.curOp.scrollTop=e)}),getScrollInfo:function(){var t=this.display.scroller,e=ds;return{left:t.scrollLeft,top:t.scrollTop,height:t.scrollHeight-e,width:t.scrollWidth-e,clientHeight:t.clientHeight-e,clientWidth:t.clientWidth-e}},scrollIntoView:cn(function(t,e){if(null==t){t={from:this.doc.sel.primary().head,to:null};null==e&&(e=this.options.cursorScrollMargin)}else"number"==typeof t?t={from:ya(t,0),to:null}:null==t.from&&(t={from:t,to:null});t.to||(t.to=t.from);t.margin=e||0;if(null!=t.from.line){xr(this);this.curOp.scrollToPos=t}else{var n=vr(this,Math.min(t.from.left,t.to.left),Math.min(t.from.top,t.to.top)-t.margin,Math.max(t.from.right,t.to.right),Math.max(t.from.bottom,t.to.bottom)+t.margin);this.scrollTo(n.scrollLeft,n.scrollTop)}}),setSize:cn(function(t,e){function n(t){return"number"==typeof t||/^\d+$/.test(String(t))?t+"px":t}var r=this;null!=t&&(r.display.wrapper.style.width=n(t));null!=e&&(r.display.wrapper.style.height=n(e));r.options.lineWrapping&&Fe(this);var i=r.display.viewFrom;r.doc.iter(i,r.display.viewTo,function(t){if(t.widgets)for(var e=0;e<t.widgets.length;e++)if(t.widgets[e].noHScroll){gn(r,i,"widget");break}++i});r.curOp.forceUpdate=!0;fs(r,"refresh",this)}),operation:function(t){return ln(this,t)},refresh:cn(function(){var t=this.display.cachedTextHeight;pn(this);this.curOp.forceUpdate=!0;Re(this);this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop);c(this);(null==t||Math.abs(t-Je(this.display))>.5)&&a(this);fs(this,"refresh",this)}),swapDoc:cn(function(t){var e=this.doc;e.cm=null;Ni(this,t);Re(this);Tn(this);this.scrollTo(t.scrollLeft,t.scrollTop);this.curOp.forceScroll=!0;io(this,"swapDoc",this,e);return e}),getInputField:function(){return this.display.input},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}};uo(t);var ja=t.defaults={},Ia=t.optionHandlers={},Pa=t.Init={toString:function(){return"CodeMirror.Init"}};kr("value","",function(t,e){t.setValue(e)},!0);kr("mode",null,function(t,e){t.doc.modeOption=e;n(t)},!0);kr("indentUnit",2,n,!0);kr("indentWithTabs",!1);kr("smartIndent",!0);kr("tabSize",4,function(t){r(t);Re(t);pn(t)},!0);kr("specialChars",/[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,function(t,e){t.options.specialChars=new RegExp(e.source+(e.test(" ")?"":"| "),"g");t.refresh()},!0);kr("specialCharPlaceholder",xi,function(t){t.refresh()},!0);kr("electricChars",!0);kr("rtlMoveVisually",!ha);kr("wholeLineUpdateBefore",!0);kr("theme","default",function(t){s(t);l(t)},!0);kr("keyMap","default",function(e,n,r){var i=Dr(n),o=r!=t.Init&&Dr(r);o&&o.detach&&o.detach(e,i);i.attach&&i.attach(e,o||null)});kr("extraKeys",null);kr("lineWrapping",!1,i,!0);kr("gutters",[],function(t){d(t.options);l(t)},!0);kr("fixedGutter",!0,function(t,e){t.display.gutters.style.left=e?w(t.display)+"px":"0";t.refresh()},!0);kr("coverGutterNextToScrollbar",!1,m,!0);kr("lineNumbers",!1,function(t){d(t.options);l(t)},!0);kr("firstLineNumber",1,l,!0);kr("lineNumberFormatter",function(t){return t},l,!0);kr("showCursorWhenSelecting",!1,ve,!0);kr("resetSelectionOnContextMenu",!0);kr("readOnly",!1,function(t,e){if("nocursor"==e){Qn(t);t.display.input.blur();t.display.disabled=!0}else{t.display.disabled=!1;e||Tn(t)}});kr("disableInput",!1,function(t,e){e||Tn(t)},!0);kr("dragDrop",!0);kr("cursorBlinkRate",530);kr("cursorScrollMargin",0);kr("cursorHeight",1,ve,!0);kr("singleCursorHeightPerLine",!0,ve,!0);kr("workTime",100);kr("workDelay",100);kr("flattenSpans",!0,r,!0);kr("addModeClass",!1,r,!0);kr("pollInterval",100);kr("undoDepth",200,function(t,e){t.doc.history.undoDepth=e});kr("historyEventDelay",1250);kr("viewportMargin",10,function(t){t.refresh()},!0);kr("maxHighlightLength",1e4,r,!0);kr("moveInputWithCursor",!0,function(t,e){e||(t.display.inputDiv.style.top=t.display.inputDiv.style.left=0)});kr("tabindex",null,function(t,e){t.display.input.tabIndex=e||""});kr("autofocus",null);var Ha=t.modes={},Oa=t.mimeModes={};t.defineMode=function(e,n){t.defaults.mode||"null"==e||(t.defaults.mode=e);arguments.length>2&&(n.dependencies=Array.prototype.slice.call(arguments,2));Ha[e]=n};t.defineMIME=function(t,e){Oa[t]=e};t.resolveMode=function(e){if("string"==typeof e&&Oa.hasOwnProperty(e))e=Oa[e];else if(e&&"string"==typeof e.name&&Oa.hasOwnProperty(e.name)){var n=Oa[e.name];"string"==typeof n&&(n={name:n});e=vo(n,e);e.name=n.name}else if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+xml$/.test(e))return t.resolveMode("application/xml");return"string"==typeof e?{name:e}:e||{name:"null"}};t.getMode=function(e,n){var n=t.resolveMode(n),r=Ha[n.name];if(!r)return t.getMode(e,"text/plain");var i=r(e,n);if(Fa.hasOwnProperty(n.name)){var o=Fa[n.name];for(var a in o)if(o.hasOwnProperty(a)){i.hasOwnProperty(a)&&(i["_"+a]=i[a]);i[a]=o[a]}}i.name=n.name;n.helperType&&(i.helperType=n.helperType);if(n.modeProps)for(var a in n.modeProps)i[a]=n.modeProps[a];return i};t.defineMode("null",function(){return{token:function(t){t.skipToEnd()}}});t.defineMIME("text/plain","null");var Fa=t.modeExtensions={};t.extendMode=function(t,e){var n=Fa.hasOwnProperty(t)?Fa[t]:Fa[t]={};yo(e,n)};t.defineExtension=function(e,n){t.prototype[e]=n};t.defineDocExtension=function(t,e){rs.prototype[t]=e};t.defineOption=kr;var Ra=[];t.defineInitHook=function(t){Ra.push(t)};var Wa=t.helpers={};t.registerHelper=function(e,n,r){Wa.hasOwnProperty(e)||(Wa[e]=t[e]={_global:[]});Wa[e][n]=r};t.registerGlobalHelper=function(e,n,r,i){t.registerHelper(e,n,i);Wa[e]._global.push({pred:r,val:i})};var za=t.copyState=function(t,e){if(e===!0)return e;if(t.copyState)return t.copyState(e);var n={};for(var r in e){var i=e[r];i instanceof Array&&(i=i.concat([]));n[r]=i}return n},qa=t.startState=function(t,e,n){return t.startState?t.startState(e,n):!0};t.innerMode=function(t,e){for(;t.innerMode;){var n=t.innerMode(e);if(!n||n.mode==t)break;e=n.state;t=n.mode}return n||{mode:t,state:e}};var Ua=t.commands={selectAll:function(t){t.setSelection(ya(t.firstLine(),0),ya(t.lastLine()),gs)},singleSelection:function(t){t.setSelection(t.getCursor("anchor"),t.getCursor("head"),gs)},killLine:function(t){Cr(t,function(e){if(e.empty()){var n=Ei(t.doc,e.head.line).text.length;return e.head.ch==n&&e.head.line<t.lastLine()?{from:e.head,to:ya(e.head.line+1,0)}:{from:e.head,to:ya(e.head.line,n)}}return{from:e.from(),to:e.to()}})},deleteLine:function(t){Cr(t,function(e){return{from:ya(e.from().line,0),to:Z(t.doc,ya(e.to().line+1,0))}})},delLineLeft:function(t){Cr(t,function(t){return{from:ya(t.from().line,0),to:t.from()}})},delWrappedLineLeft:function(t){Cr(t,function(e){var n=t.charCoords(e.head,"div").top+5,r=t.coordsChar({left:0,top:n},"div");return{from:r,to:e.from()}})},delWrappedLineRight:function(t){Cr(t,function(e){var n=t.charCoords(e.head,"div").top+5,r=t.coordsChar({left:t.display.lineDiv.offsetWidth+100,top:n},"div");return{from:e.from(),to:r}})},undo:function(t){t.undo()},redo:function(t){t.redo()},undoSelection:function(t){t.undoSelection()},redoSelection:function(t){t.redoSelection()},goDocStart:function(t){t.extendSelection(ya(t.firstLine(),0))},goDocEnd:function(t){t.extendSelection(ya(t.lastLine()))},goLineStart:function(t){t.extendSelectionsBy(function(e){return qo(t,e.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(t){t.extendSelectionsBy(function(e){return Bo(t,e.head)},{origin:"+move",bias:1})},goLineEnd:function(t){t.extendSelectionsBy(function(e){return Uo(t,e.head.line)},{origin:"+move",bias:-1})},goLineRight:function(t){t.extendSelectionsBy(function(e){var n=t.charCoords(e.head,"div").top+5;return t.coordsChar({left:t.display.lineDiv.offsetWidth+100,top:n},"div")},vs)},goLineLeft:function(t){t.extendSelectionsBy(function(e){var n=t.charCoords(e.head,"div").top+5;return t.coordsChar({left:0,top:n},"div")},vs)},goLineLeftSmart:function(t){t.extendSelectionsBy(function(e){var n=t.charCoords(e.head,"div").top+5,r=t.coordsChar({left:0,top:n},"div");return r.ch<t.getLine(r.line).search(/\S/)?Bo(t,e.head):r},vs)},goLineUp:function(t){t.moveV(-1,"line")},goLineDown:function(t){t.moveV(1,"line")},goPageUp:function(t){t.moveV(-1,"page")},goPageDown:function(t){t.moveV(1,"page")},goCharLeft:function(t){t.moveH(-1,"char")},goCharRight:function(t){t.moveH(1,"char")},goColumnLeft:function(t){t.moveH(-1,"column")},goColumnRight:function(t){t.moveH(1,"column")},goWordLeft:function(t){t.moveH(-1,"word")},goGroupRight:function(t){t.moveH(1,"group")},goGroupLeft:function(t){t.moveH(-1,"group")},goWordRight:function(t){t.moveH(1,"word")},delCharBefore:function(t){t.deleteH(-1,"char")},delCharAfter:function(t){t.deleteH(1,"char")},delWordBefore:function(t){t.deleteH(-1,"word")},delWordAfter:function(t){t.deleteH(1,"word")},delGroupBefore:function(t){t.deleteH(-1,"group")},delGroupAfter:function(t){t.deleteH(1,"group")},indentAuto:function(t){t.indentSelection("smart")},indentMore:function(t){t.indentSelection("add")},indentLess:function(t){t.indentSelection("subtract")},insertTab:function(t){t.replaceSelection(" ")},insertSoftTab:function(t){for(var e=[],n=t.listSelections(),r=t.options.tabSize,i=0;i<n.length;i++){var o=n[i].from(),a=ys(t.getLine(o.line),o.ch,r);e.push(new Array(r-a%r+1).join(" "))}t.replaceSelections(e)},defaultTab:function(t){t.somethingSelected()?t.indentSelection("add"):t.execCommand("insertTab")},transposeChars:function(t){ln(t,function(){for(var e=t.listSelections(),n=[],r=0;r<e.length;r++){var i=e[r].head,o=Ei(t.doc,i.line).text;if(o){i.ch==o.length&&(i=new ya(i.line,i.ch-1));if(i.ch>0){i=new ya(i.line,i.ch+1);t.replaceRange(o.charAt(i.ch-1)+o.charAt(i.ch-2),ya(i.line,i.ch-2),i,"+transpose")}else if(i.line>t.doc.first){var a=Ei(t.doc,i.line-1).text;a&&t.replaceRange(o.charAt(0)+"\n"+a.charAt(a.length-1),ya(i.line-1,a.length-1),ya(i.line,1),"+transpose")}}n.push(new $(i,i))}t.setSelections(n)})},newlineAndIndent:function(t){ln(t,function(){for(var e=t.listSelections().length,n=0;e>n;n++){var r=t.listSelections()[n];t.replaceRange("\n",r.anchor,r.head,"+input");t.indentLine(r.from().line+1,null,!0);br(t)}})},toggleOverwrite:function(t){t.toggleOverwrite()}},Ba=t.keyMap={};Ba.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"};Ba.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"};Ba.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars"};Ba.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]};Ba["default"]=fa?Ba.macDefault:Ba.pcDefault;t.normalizeKeyMap=function(t){var e={};for(var n in t)if(t.hasOwnProperty(n)){var r=t[n];if(/^(name|fallthrough|(de|at)tach)$/.test(n))continue;if("..."==r){delete t[n];continue}for(var i=mo(n.split(" "),Mr),o=0;o<i.length;o++){var a,s;if(o==i.length-1){s=n;a=r}else{s=i.slice(0,o+1).join(" ");a="..."}var l=e[s];if(l){if(l!=a)throw new Error("Inconsistent bindings for "+s)}else e[s]=a}delete t[n]}for(var u in e)t[u]=e[u];return t};var Va=t.lookupKey=function(t,e,n){e=Dr(e);var r=e.call?e.call(t):e[t];if(r===!1)return"nothing";if("..."===r)return"multi";if(null!=r&&n(r))return"handled";if(e.fallthrough){if("[object Array]"!=Object.prototype.toString.call(e.fallthrough))return Va(t,e.fallthrough,n);for(var i=0;i<e.fallthrough.length;i++){var o=Va(t,e.fallthrough[i],n);if(o)return o}}},Xa=t.isModifierKey=function(t){var e="string"==typeof t?t:Hs[t.keyCode];return"Ctrl"==e||"Alt"==e||"Shift"==e||"Mod"==e},Ga=t.keyName=function(t,e){if(ia&&34==t.keyCode&&t["char"])return!1;var n=Hs[t.keyCode],r=n;if(null==r||t.altGraphKey)return!1;t.altKey&&"Alt"!=n&&(r="Alt-"+r);(pa?t.metaKey:t.ctrlKey)&&"Ctrl"!=n&&(r="Ctrl-"+r);(pa?t.ctrlKey:t.metaKey)&&"Cmd"!=n&&(r="Cmd-"+r);!e&&t.shiftKey&&"Shift"!=n&&(r="Shift-"+r);return r};t.fromTextArea=function(e,n){function r(){e.value=u.getValue()}n||(n={});n.value=e.value;!n.tabindex&&e.tabindex&&(n.tabindex=e.tabindex);!n.placeholder&&e.placeholder&&(n.placeholder=e.placeholder);if(null==n.autofocus){var i=Mo();n.autofocus=i==e||null!=e.getAttribute("autofocus")&&i==document.body}if(e.form){us(e.form,"submit",r);if(!n.leaveSubmitMethodAlone){var o=e.form,a=o.submit;try{var s=o.submit=function(){r();o.submit=a;o.submit();o.submit=s}}catch(l){}}}e.style.display="none";var u=t(function(t){e.parentNode.insertBefore(t,e.nextSibling)},n);u.save=r;u.getTextArea=function(){return e};u.toTextArea=function(){u.toTextArea=isNaN;r();e.parentNode.removeChild(u.getWrapperElement());e.style.display="";if(e.form){cs(e.form,"submit",r);"function"==typeof e.form.submit&&(e.form.submit=a)}};return u};var $a=t.StringStream=function(t,e){this.pos=this.start=0;this.string=t;this.tabSize=e||8;this.lastColumnPos=this.lastColumnValue=0;this.lineStart=0};$a.prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.pos<this.string.length?this.string.charAt(this.pos++):void 0},eat:function(t){var e=this.string.charAt(this.pos);if("string"==typeof t)var n=e==t;else var n=e&&(t.test?t.test(e):t(e));if(n){++this.pos;return e}},eatWhile:function(t){for(var e=this.pos;this.eat(t););return this.pos>e},eatSpace:function(){for(var t=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>t},skipToEnd:function(){this.pos=this.string.length},skipTo:function(t){var e=this.string.indexOf(t,this.pos);if(e>-1){this.pos=e;return!0}},backUp:function(t){this.pos-=t},column:function(){if(this.lastColumnPos<this.start){this.lastColumnValue=ys(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue);this.lastColumnPos=this.start}return this.lastColumnValue-(this.lineStart?ys(this.string,this.lineStart,this.tabSize):0)},indentation:function(){return ys(this.string,null,this.tabSize)-(this.lineStart?ys(this.string,this.lineStart,this.tabSize):0)},match:function(t,e,n){if("string"!=typeof t){var r=this.string.slice(this.pos).match(t);if(r&&r.index>0)return null;r&&e!==!1&&(this.pos+=r[0].length);return r}var i=function(t){return n?t.toLowerCase():t},o=this.string.substr(this.pos,t.length);if(i(o)==i(t)){e!==!1&&(this.pos+=t.length);return!0}},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(t,e){this.lineStart+=t;try{return e()}finally{this.lineStart-=t}}};var Ya=t.TextMarker=function(t,e){this.lines=[];this.type=e;this.doc=t};uo(Ya);Ya.prototype.clear=function(){if(!this.explicitlyCleared){var t=this.doc.cm,e=t&&!t.curOp;e&&Ze(t);if(lo(this,"clear")){var n=this.find();n&&io(this,"clear",n.from,n.to)}for(var r=null,i=null,o=0;o<this.lines.length;++o){var a=this.lines[o],s=Pr(a.markedSpans,this);if(t&&!this.collapsed)gn(t,Hi(a),"text");else if(t){null!=s.to&&(i=Hi(a));null!=s.from&&(r=Hi(a))}a.markedSpans=Hr(a.markedSpans,s);null==s.from&&this.collapsed&&!ri(this.doc,a)&&t&&Pi(a,Je(t.display))}if(t&&this.collapsed&&!t.options.lineWrapping)for(var o=0;o<this.lines.length;++o){var l=Qr(this.lines[o]),u=f(l);if(u>t.display.maxLineLength){t.display.maxLine=l;t.display.maxLineLength=u;t.display.maxLineChanged=!0}}null!=r&&t&&this.collapsed&&pn(t,r,i+1);this.lines.length=0;this.explicitlyCleared=!0;if(this.atomic&&this.doc.cantEdit){this.doc.cantEdit=!1;t&&he(t.doc)}t&&io(t,"markerCleared",t,this);e&&tn(t);this.parent&&this.parent.clear()}};Ya.prototype.find=function(t,e){null==t&&"bookmark"==this.type&&(t=1);for(var n,r,i=0;i<this.lines.length;++i){var o=this.lines[i],a=Pr(o.markedSpans,this);if(null!=a.from){n=ya(e?o:Hi(o),a.from);if(-1==t)return n}if(null!=a.to){r=ya(e?o:Hi(o),a.to);if(1==t)return r}}return n&&{from:n,to:r}};Ya.prototype.changed=function(){var t=this.find(-1,!0),e=this,n=this.doc.cm;t&&n&&ln(n,function(){var r=t.line,i=Hi(t.line),o=Ee(n,i);if(o){Oe(o);n.curOp.selectionChanged=n.curOp.forceUpdate=!0}n.curOp.updateMaxLine=!0;if(!ri(e.doc,r)&&null!=e.height){var a=e.height;e.height=null;var s=ai(e)-a;s&&Pi(r,r.height+s)}})};Ya.prototype.attachLine=function(t){if(!this.lines.length&&this.doc.cm){var e=this.doc.cm.curOp;e.maybeHiddenMarkers&&-1!=go(e.maybeHiddenMarkers,this)||(e.maybeUnhiddenMarkers||(e.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(t)};Ya.prototype.detachLine=function(t){this.lines.splice(go(this.lines,t),1);if(!this.lines.length&&this.doc.cm){var e=this.doc.cm.curOp;(e.maybeHiddenMarkers||(e.maybeHiddenMarkers=[])).push(this)}};var Ja=0,Ka=t.SharedTextMarker=function(t,e){this.markers=t;this.primary=e;for(var n=0;n<t.length;++n)t[n].parent=this};uo(Ka);Ka.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var t=0;t<this.markers.length;++t)this.markers[t].clear();io(this,"clear")}};Ka.prototype.find=function(t,e){return this.primary.find(t,e)};var Za=t.LineWidget=function(t,e,n){if(n)for(var r in n)n.hasOwnProperty(r)&&(this[r]=n[r]);this.cm=t;this.node=e};uo(Za);Za.prototype.clear=function(){var t=this.cm,e=this.line.widgets,n=this.line,r=Hi(n);if(null!=r&&e){for(var i=0;i<e.length;++i)e[i]==this&&e.splice(i--,1);e.length||(n.widgets=null);var o=ai(this);ln(t,function(){oi(t,n,-o);gn(t,r,"widget");Pi(n,Math.max(0,n.height-o))})}};Za.prototype.changed=function(){var t=this.height,e=this.cm,n=this.line;this.height=null;var r=ai(this)-t;r&&ln(e,function(){e.curOp.forceUpdate=!0;oi(e,n,r);Pi(n,n.height+r)})};var Qa=t.Line=function(t,e,n){this.text=t;Vr(this,e);this.height=n?n(this):1};uo(Qa);Qa.prototype.lineNo=function(){return Hi(this)};var ts={},es={};Di.prototype={chunkSize:function(){return this.lines.length},removeInner:function(t,e){for(var n=t,r=t+e;r>n;++n){var i=this.lines[n];this.height-=i.height;ui(i);io(i,"delete")}this.lines.splice(t,e)},collapse:function(t){t.push.apply(t,this.lines)},insertInner:function(t,e,n){this.height+=n;this.lines=this.lines.slice(0,t).concat(e).concat(this.lines.slice(t));for(var r=0;r<e.length;++r)e[r].parent=this},iterN:function(t,e,n){for(var r=t+e;r>t;++t)if(n(this.lines[t]))return!0}};Li.prototype={chunkSize:function(){return this.size},removeInner:function(t,e){this.size-=e;for(var n=0;n<this.children.length;++n){var r=this.children[n],i=r.chunkSize();if(i>t){var o=Math.min(e,i-t),a=r.height;r.removeInner(t,o);this.height-=a-r.height;if(i==o){this.children.splice(n--,1);r.parent=null}if(0==(e-=o))break;t=0}else t-=i}if(this.size-e<25&&(this.children.length>1||!(this.children[0]instanceof Di))){var s=[];this.collapse(s);this.children=[new Di(s)];this.children[0].parent=this}},collapse:function(t){for(var e=0;e<this.children.length;++e)this.children[e].collapse(t)},insertInner:function(t,e,n){this.size+=e.length;this.height+=n;for(var r=0;r<this.children.length;++r){var i=this.children[r],o=i.chunkSize();if(o>=t){i.insertInner(t,e,n);if(i.lines&&i.lines.length>50){for(;i.lines.length>50;){var a=i.lines.splice(i.lines.length-25,25),s=new Di(a);i.height-=s.height;this.children.splice(r+1,0,s);s.parent=this}this.maybeSpill()}break}t-=o}},maybeSpill:function(){if(!(this.children.length<=10)){var t=this;do{var e=t.children.splice(t.children.length-5,5),n=new Li(e);if(t.parent){t.size-=n.size;t.height-=n.height;var r=go(t.parent.children,t);t.parent.children.splice(r+1,0,n)}else{var i=new Li(t.children);i.parent=t;t.children=[i,n];t=i}n.parent=t.parent}while(t.children.length>10);t.parent.maybeSpill()}},iterN:function(t,e,n){for(var r=0;r<this.children.length;++r){var i=this.children[r],o=i.chunkSize();if(o>t){var a=Math.min(e,o-t);if(i.iterN(t,a,n))return!0;if(0==(e-=a))break;t=0}else t-=o}}};var ns=0,rs=t.Doc=function(t,e,n){if(!(this instanceof rs))return new rs(t,e,n);null==n&&(n=0);Li.call(this,[new Di([new Qa("",null)])]);this.first=n;this.scrollTop=this.scrollLeft=0;this.cantEdit=!1;this.cleanGeneration=1;this.frontier=n;var r=ya(n,0);this.sel=J(r);this.history=new Wi(null);this.id=++ns;this.modeOption=e;"string"==typeof t&&(t=Es(t));Mi(this,{from:r,to:r,text:t});ue(this,J(r),gs)};rs.prototype=vo(Li.prototype,{constructor:rs,iter:function(t,e,n){n?this.iterN(t-this.first,e-t,n):this.iterN(this.first,this.first+this.size,t)},insert:function(t,e){for(var n=0,r=0;r<e.length;++r)n+=e[r].height;this.insertInner(t-this.first,e,n)},remove:function(t,e){this.removeInner(t-this.first,e)},getValue:function(t){var e=Ii(this,this.first,this.first+this.size);return t===!1?e:e.join(t||"\n")},setValue:fn(function(t){var e=ya(this.first,0),n=this.first+this.size-1;sr(this,{from:e,to:ya(n,Ei(this,n).text.length),text:Es(t),origin:"setValue"},!0);ue(this,J(e))}),replaceRange:function(t,e,n,r){e=Z(this,e);n=n?Z(this,n):e;dr(this,t,e,n,r)},getRange:function(t,e,n){var r=ji(this,Z(this,t),Z(this,e));return n===!1?r:r.join(n||"\n")},getLine:function(t){var e=this.getLineHandle(t);return e&&e.text},getLineHandle:function(t){return te(this,t)?Ei(this,t):void 0},getLineNumber:function(t){return Hi(t)},getLineHandleVisualStart:function(t){"number"==typeof t&&(t=Ei(this,t));return Qr(t)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(t){return Z(this,t)},getCursor:function(t){var e,n=this.sel.primary();e=null==t||"head"==t?n.head:"anchor"==t?n.anchor:"end"==t||"to"==t||t===!1?n.to():n.from();return e},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:fn(function(t,e,n){ae(this,Z(this,"number"==typeof t?ya(t,e||0):t),null,n)}),setSelection:fn(function(t,e,n){ae(this,Z(this,t),Z(this,e||t),n)}),extendSelection:fn(function(t,e,n){re(this,Z(this,t),e&&Z(this,e),n)}),extendSelections:fn(function(t,e){ie(this,ee(this,t,e))}),extendSelectionsBy:fn(function(t,e){ie(this,mo(this.sel.ranges,t),e)}),setSelections:fn(function(t,e,n){if(t.length){for(var r=0,i=[];r<t.length;r++)i[r]=new $(Z(this,t[r].anchor),Z(this,t[r].head));null==e&&(e=Math.min(t.length-1,this.sel.primIndex));ue(this,Y(i,e),n)}}),addSelection:fn(function(t,e,n){var r=this.sel.ranges.slice(0);r.push(new $(Z(this,t),Z(this,e||t)));ue(this,Y(r,r.length-1),n)}),getSelection:function(t){for(var e,n=this.sel.ranges,r=0;r<n.length;r++){var i=ji(this,n[r].from(),n[r].to());e=e?e.concat(i):i}return t===!1?e:e.join(t||"\n")},getSelections:function(t){for(var e=[],n=this.sel.ranges,r=0;r<n.length;r++){var i=ji(this,n[r].from(),n[r].to());t!==!1&&(i=i.join(t||"\n"));e[r]=i}return e},replaceSelection:function(t,e,n){for(var r=[],i=0;i<this.sel.ranges.length;i++)r[i]=t;this.replaceSelections(r,e,n||"+input")},replaceSelections:fn(function(t,e,n){for(var r=[],i=this.sel,o=0;o<i.ranges.length;o++){var a=i.ranges[o];r[o]={from:a.from(),to:a.to(),text:Es(t[o]),origin:n}}for(var s=e&&"end"!=e&&or(this,r,e),o=r.length-1;o>=0;o--)sr(this,r[o]);s?le(this,s):this.cm&&br(this.cm)}),undo:fn(function(){ur(this,"undo")}),redo:fn(function(){ur(this,"redo")}),undoSelection:fn(function(){ur(this,"undo",!0)}),redoSelection:fn(function(){ur(this,"redo",!0)}),setExtending:function(t){this.extend=t},getExtending:function(){return this.extend},historySize:function(){for(var t=this.history,e=0,n=0,r=0;r<t.done.length;r++)t.done[r].ranges||++e;for(var r=0;r<t.undone.length;r++)t.undone[r].ranges||++n;return{undo:e,redo:n}},clearHistory:function(){this.history=new Wi(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(t){t&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null);return this.history.generation},isClean:function(t){return this.history.generation==(t||this.cleanGeneration)},getHistory:function(){return{done:Ki(this.history.done),undone:Ki(this.history.undone)}},setHistory:function(t){var e=this.history=new Wi(this.history.maxGeneration);e.done=Ki(t.done.slice(0),null,!0);e.undone=Ki(t.undone.slice(0),null,!0)},addLineClass:fn(function(t,e,n){return Sr(this,t,"gutter"==e?"gutter":"class",function(t){var r="text"==e?"textClass":"background"==e?"bgClass":"gutter"==e?"gutterClass":"wrapClass";if(t[r]){if(Do(n).test(t[r]))return!1;t[r]+=" "+n}else t[r]=n;return!0})}),removeLineClass:fn(function(t,e,n){return Sr(this,t,"class",function(t){var r="text"==e?"textClass":"background"==e?"bgClass":"gutter"==e?"gutterClass":"wrapClass",i=t[r];
if(!i)return!1;if(null==n)t[r]=null;else{var o=i.match(Do(n));if(!o)return!1;var a=o.index+o[0].length;t[r]=i.slice(0,o.index)+(o.index&&a!=i.length?" ":"")+i.slice(a)||null}return!0})}),markText:function(t,e,n){return Lr(this,Z(this,t),Z(this,e),n,"range")},setBookmark:function(t,e){var n={replacedWith:e&&(null==e.nodeType?e.widget:e),insertLeft:e&&e.insertLeft,clearWhenEmpty:!1,shared:e&&e.shared};t=Z(this,t);return Lr(this,t,t,n,"bookmark")},findMarksAt:function(t){t=Z(this,t);var e=[],n=Ei(this,t.line).markedSpans;if(n)for(var r=0;r<n.length;++r){var i=n[r];(null==i.from||i.from<=t.ch)&&(null==i.to||i.to>=t.ch)&&e.push(i.marker.parent||i.marker)}return e},findMarks:function(t,e,n){t=Z(this,t);e=Z(this,e);var r=[],i=t.line;this.iter(t.line,e.line+1,function(o){var a=o.markedSpans;if(a)for(var s=0;s<a.length;s++){var l=a[s];i==t.line&&t.ch>l.to||null==l.from&&i!=t.line||i==e.line&&l.from>e.ch||n&&!n(l.marker)||r.push(l.marker.parent||l.marker)}++i});return r},getAllMarks:function(){var t=[];this.iter(function(e){var n=e.markedSpans;if(n)for(var r=0;r<n.length;++r)null!=n[r].from&&t.push(n[r].marker)});return t},posFromIndex:function(t){var e,n=this.first;this.iter(function(r){var i=r.text.length+1;if(i>t){e=t;return!0}t-=i;++n});return Z(this,ya(n,e))},indexFromPos:function(t){t=Z(this,t);var e=t.ch;if(t.line<this.first||t.ch<0)return 0;this.iter(this.first,t.line,function(t){e+=t.text.length+1});return e},copy:function(t){var e=new rs(Ii(this,this.first,this.first+this.size),this.modeOption,this.first);e.scrollTop=this.scrollTop;e.scrollLeft=this.scrollLeft;e.sel=this.sel;e.extend=!1;if(t){e.history.undoDepth=this.history.undoDepth;e.setHistory(this.getHistory())}return e},linkedDoc:function(t){t||(t={});var e=this.first,n=this.first+this.size;null!=t.from&&t.from>e&&(e=t.from);null!=t.to&&t.to<n&&(n=t.to);var r=new rs(Ii(this,e,n),t.mode||this.modeOption,e);t.sharedHist&&(r.history=this.history);(this.linked||(this.linked=[])).push({doc:r,sharedHist:t.sharedHist});r.linked=[{doc:this,isParent:!0,sharedHist:t.sharedHist}];Er(r,Nr(this));return r},unlinkDoc:function(e){e instanceof t&&(e=e.doc);if(this.linked)for(var n=0;n<this.linked.length;++n){var r=this.linked[n];if(r.doc==e){this.linked.splice(n,1);e.unlinkDoc(this);jr(Nr(this));break}}if(e.history==this.history){var i=[e.id];Ai(e,function(t){i.push(t.id)},!0);e.history=new Wi(null);e.history.done=Ki(this.history.done,i);e.history.undone=Ki(this.history.undone,i)}},iterLinkedDocs:function(t){Ai(this,t)},getMode:function(){return this.mode},getEditor:function(){return this.cm}});rs.prototype.eachLine=rs.prototype.iter;var is="iter insert remove copy getEditor".split(" ");for(var os in rs.prototype)rs.prototype.hasOwnProperty(os)&&go(is,os)<0&&(t.prototype[os]=function(t){return function(){return t.apply(this.doc,arguments)}}(rs.prototype[os]));uo(rs);var as=t.e_preventDefault=function(t){t.preventDefault?t.preventDefault():t.returnValue=!1},ss=t.e_stopPropagation=function(t){t.stopPropagation?t.stopPropagation():t.cancelBubble=!0},ls=t.e_stop=function(t){as(t);ss(t)},us=t.on=function(t,e,n){if(t.addEventListener)t.addEventListener(e,n,!1);else if(t.attachEvent)t.attachEvent("on"+e,n);else{var r=t._handlers||(t._handlers={}),i=r[e]||(r[e]=[]);i.push(n)}},cs=t.off=function(t,e,n){if(t.removeEventListener)t.removeEventListener(e,n,!1);else if(t.detachEvent)t.detachEvent("on"+e,n);else{var r=t._handlers&&t._handlers[e];if(!r)return;for(var i=0;i<r.length;++i)if(r[i]==n){r.splice(i,1);break}}},fs=t.signal=function(t,e){var n=t._handlers&&t._handlers[e];if(n)for(var r=Array.prototype.slice.call(arguments,2),i=0;i<n.length;++i)n[i].apply(null,r)},hs=null,ds=30,ps=t.Pass={toString:function(){return"CodeMirror.Pass"}},gs={scroll:!1},ms={origin:"*mouse"},vs={origin:"+move"};co.prototype.set=function(t,e){clearTimeout(this.id);this.id=setTimeout(e,t)};var ys=t.countColumn=function(t,e,n,r,i){if(null==e){e=t.search(/[^\s\u00a0]/);-1==e&&(e=t.length)}for(var o=r||0,a=i||0;;){var s=t.indexOf(" ",o);if(0>s||s>=e)return a+(e-o);a+=s-o;a+=n-a%n;o=s+1}},bs=[""],xs=function(t){t.select()};ua?xs=function(t){t.selectionStart=0;t.selectionEnd=t.value.length}:Qo&&(xs=function(t){try{t.select()}catch(e){}});[].indexOf&&(go=function(t,e){return t.indexOf(e)});[].map&&(mo=function(t,e){return t.map(e)});var ws,Ss=/[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Cs=t.isWordChar=function(t){return/\w/.test(t)||t>""&&(t.toUpperCase()!=t.toLowerCase()||Ss.test(t))},Ts=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;ws=document.createRange?function(t,e,n){var r=document.createRange();r.setEnd(t,n);r.setStart(t,e);return r}:function(t,e,n){var r=document.body.createTextRange();try{r.moveToElementText(t.parentNode)}catch(i){return r}r.collapse(!0);r.moveEnd("character",n);r.moveStart("character",e);return r};Qo&&11>ta&&(Mo=function(){try{return document.activeElement}catch(t){return document.body}});var _s,ks,Ms,Ds=t.rmClass=function(t,e){var n=t.className,r=Do(e).exec(n);if(r){var i=n.slice(r.index+r[0].length);t.className=n.slice(0,r.index)+(i?r[1]+i:"")}},Ls=t.addClass=function(t,e){var n=t.className;Do(e).test(n)||(t.className+=(n?" ":"")+e)},As=!1,Ns=function(){if(Qo&&9>ta)return!1;var t=Co("div");return"draggable"in t||"dragDrop"in t}(),Es=t.splitLines=3!="\n\nb".split(/\n/).length?function(t){for(var e=0,n=[],r=t.length;r>=e;){var i=t.indexOf("\n",e);-1==i&&(i=t.length);var o=t.slice(e,"\r"==t.charAt(i-1)?i-1:i),a=o.indexOf("\r");if(-1!=a){n.push(o.slice(0,a));e+=a+1}else{n.push(o);e=i+1}}return n}:function(t){return t.split(/\r\n?|\n/)},js=window.getSelection?function(t){try{return t.selectionStart!=t.selectionEnd}catch(e){return!1}}:function(t){try{var e=t.ownerDocument.selection.createRange()}catch(n){}return e&&e.parentElement()==t?0!=e.compareEndPoints("StartToEnd",e):!1},Is=function(){var t=Co("div");if("oncopy"in t)return!0;t.setAttribute("oncopy","return;");return"function"==typeof t.oncopy}(),Ps=null,Hs={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",107:"=",109:"-",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};t.keyNames=Hs;(function(){for(var t=0;10>t;t++)Hs[t+48]=Hs[t+96]=String(t);for(var t=65;90>=t;t++)Hs[t]=String.fromCharCode(t);for(var t=1;12>=t;t++)Hs[t+111]=Hs[t+63235]="F"+t})();var Os,Fs=function(){function t(t){return 247>=t?n.charAt(t):t>=1424&&1524>=t?"R":t>=1536&&1773>=t?r.charAt(t-1536):t>=1774&&2220>=t?"r":t>=8192&&8203>=t?"w":8204==t?"b":"L"}function e(t,e,n){this.level=t;this.from=e;this.to=n}var n="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",r="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",i=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,o=/[stwN]/,a=/[LRr]/,s=/[Lb1n]/,l=/[1n]/,u="L";return function(n){if(!i.test(n))return!1;for(var r,c=n.length,f=[],h=0;c>h;++h)f.push(r=t(n.charCodeAt(h)));for(var h=0,d=u;c>h;++h){var r=f[h];"m"==r?f[h]=d:d=r}for(var h=0,p=u;c>h;++h){var r=f[h];if("1"==r&&"r"==p)f[h]="n";else if(a.test(r)){p=r;"r"==r&&(f[h]="R")}}for(var h=1,d=f[0];c-1>h;++h){var r=f[h];"+"==r&&"1"==d&&"1"==f[h+1]?f[h]="1":","!=r||d!=f[h+1]||"1"!=d&&"n"!=d||(f[h]=d);d=r}for(var h=0;c>h;++h){var r=f[h];if(","==r)f[h]="N";else if("%"==r){for(var g=h+1;c>g&&"%"==f[g];++g);for(var m=h&&"!"==f[h-1]||c>g&&"1"==f[g]?"1":"N",v=h;g>v;++v)f[v]=m;h=g-1}}for(var h=0,p=u;c>h;++h){var r=f[h];"L"==p&&"1"==r?f[h]="L":a.test(r)&&(p=r)}for(var h=0;c>h;++h)if(o.test(f[h])){for(var g=h+1;c>g&&o.test(f[g]);++g);for(var y="L"==(h?f[h-1]:u),b="L"==(c>g?f[g]:u),m=y||b?"L":"R",v=h;g>v;++v)f[v]=m;h=g-1}for(var x,w=[],h=0;c>h;)if(s.test(f[h])){var S=h;for(++h;c>h&&s.test(f[h]);++h);w.push(new e(0,S,h))}else{var C=h,T=w.length;for(++h;c>h&&"L"!=f[h];++h);for(var v=C;h>v;)if(l.test(f[v])){v>C&&w.splice(T,0,new e(1,C,v));var _=v;for(++v;h>v&&l.test(f[v]);++v);w.splice(T,0,new e(2,_,v));C=v}else++v;h>C&&w.splice(T,0,new e(1,C,h))}if(1==w[0].level&&(x=n.match(/^\s+/))){w[0].from=x[0].length;w.unshift(new e(0,0,x[0].length))}if(1==po(w).level&&(x=n.match(/\s+$/))){po(w).to-=x[0].length;w.push(new e(0,c-x[0].length,c))}w[0].level!=po(w).level&&w.push(new e(w[0].level,c,c));return w}}();t.version="4.8.0";return t})},{}],10:[function(e,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(e("../../lib/codemirror")):"function"==typeof t&&t.amd?t(["../../lib/codemirror"],i):i(CodeMirror)})(function(t){"use strict";t.defineMode("javascript",function(e,n){function r(t){for(var e,n=!1,r=!1;null!=(e=t.next());){if(!n){if("/"==e&&!r)return;"["==e?r=!0:r&&"]"==e&&(r=!1)}n=!n&&"\\"==e}}function i(t,e,n){pe=t;ge=n;return e}function o(t,e){var n=t.next();if('"'==n||"'"==n){e.tokenize=a(n);return e.tokenize(t,e)}if("."==n&&t.match(/^\d+(?:[eE][+\-]?\d+)?/))return i("number","number");if("."==n&&t.match(".."))return i("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(n))return i(n);if("="==n&&t.eat(">"))return i("=>","operator");if("0"==n&&t.eat(/x/i)){t.eatWhile(/[\da-f]/i);return i("number","number")}if(/\d/.test(n)){t.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);return i("number","number")}if("/"==n){if(t.eat("*")){e.tokenize=s;return s(t,e)}if(t.eat("/")){t.skipToEnd();return i("comment","comment")}if("operator"==e.lastType||"keyword c"==e.lastType||"sof"==e.lastType||/^[\[{}\(,;:]$/.test(e.lastType)){r(t);t.eatWhile(/[gimy]/);return i("regexp","string-2")}t.eatWhile(Ce);return i("operator","operator",t.current())}if("`"==n){e.tokenize=l;return l(t,e)}if("#"==n){t.skipToEnd();return i("error","error")}if(Ce.test(n)){t.eatWhile(Ce);return i("operator","operator",t.current())}if(we.test(n)){t.eatWhile(we);var o=t.current(),u=Se.propertyIsEnumerable(o)&&Se[o];return u&&"."!=e.lastType?i(u.type,u.style,o):i("variable","variable",o)}}function a(t){return function(e,n){var r,a=!1;if(ye&&"@"==e.peek()&&e.match(Te)){n.tokenize=o;return i("jsonld-keyword","meta")}for(;null!=(r=e.next())&&(r!=t||a);)a=!a&&"\\"==r;a||(n.tokenize=o);return i("string","string")}}function s(t,e){for(var n,r=!1;n=t.next();){if("/"==n&&r){e.tokenize=o;break}r="*"==n}return i("comment","comment")}function l(t,e){for(var n,r=!1;null!=(n=t.next());){if(!r&&("`"==n||"$"==n&&t.eat("{"))){e.tokenize=o;break}r=!r&&"\\"==n}return i("quasi","string-2",t.current())}function u(t,e){e.fatArrowAt&&(e.fatArrowAt=null);var n=t.string.indexOf("=>",t.start);if(!(0>n)){for(var r=0,i=!1,o=n-1;o>=0;--o){var a=t.string.charAt(o),s=_e.indexOf(a);if(s>=0&&3>s){if(!r){++o;break}if(0==--r)break}else if(s>=3&&6>s)++r;else if(we.test(a))i=!0;else if(i&&!r){++o;break}}i&&!r&&(e.fatArrowAt=o)}}function c(t,e,n,r,i,o){this.indented=t;this.column=e;this.type=n;this.prev=i;this.info=o;null!=r&&(this.align=r)}function f(t,e){for(var n=t.localVars;n;n=n.next)if(n.name==e)return!0;for(var r=t.context;r;r=r.prev)for(var n=r.vars;n;n=n.next)if(n.name==e)return!0}function h(t,e,n,r,i){var o=t.cc;Me.state=t;Me.stream=i;Me.marked=null,Me.cc=o;Me.style=e;t.lexical.hasOwnProperty("align")||(t.lexical.align=!0);for(;;){var a=o.length?o.pop():be?S:w;if(a(n,r)){for(;o.length&&o[o.length-1].lex;)o.pop()();return Me.marked?Me.marked:"variable"==n&&f(t,r)?"variable-2":e}}}function d(){for(var t=arguments.length-1;t>=0;t--)Me.cc.push(arguments[t])}function p(){d.apply(null,arguments);return!0}function g(t){function e(e){for(var n=e;n;n=n.next)if(n.name==t)return!0;return!1}var r=Me.state;if(r.context){Me.marked="def";if(e(r.localVars))return;r.localVars={name:t,next:r.localVars}}else{if(e(r.globalVars))return;n.globalVars&&(r.globalVars={name:t,next:r.globalVars})}}function m(){Me.state.context={prev:Me.state.context,vars:Me.state.localVars};Me.state.localVars=De}function v(){Me.state.localVars=Me.state.context.vars;Me.state.context=Me.state.context.prev}function y(t,e){var n=function(){var n=Me.state,r=n.indented;if("stat"==n.lexical.type)r=n.lexical.indented;else for(var i=n.lexical;i&&")"==i.type&&i.align;i=i.prev)r=i.indented;n.lexical=new c(r,Me.stream.column(),t,null,n.lexical,e)};n.lex=!0;return n}function b(){var t=Me.state;if(t.lexical.prev){")"==t.lexical.type&&(t.indented=t.lexical.indented);t.lexical=t.lexical.prev}}function x(t){function e(n){return n==t?p():";"==t?d():p(e)}return e}function w(t,e){if("var"==t)return p(y("vardef",e.length),U,x(";"),b);if("keyword a"==t)return p(y("form"),S,w,b);if("keyword b"==t)return p(y("form"),w,b);if("{"==t)return p(y("}"),W,b);if(";"==t)return p();if("if"==t){"else"==Me.state.lexical.info&&Me.state.cc[Me.state.cc.length-1]==b&&Me.state.cc.pop()();return p(y("form"),S,w,b,$)}return"function"==t?p(te):"for"==t?p(y("form"),Y,w,b):"variable"==t?p(y("stat"),j):"switch"==t?p(y("form"),S,y("}","switch"),x("{"),W,b,b):"case"==t?p(S,x(":")):"default"==t?p(x(":")):"catch"==t?p(y("form"),m,x("("),ee,x(")"),w,b,v):"module"==t?p(y("form"),m,ae,v,b):"class"==t?p(y("form"),ne,b):"export"==t?p(y("form"),se,b):"import"==t?p(y("form"),le,b):d(y("stat"),S,x(";"),b)}function S(t){return T(t,!1)}function C(t){return T(t,!0)}function T(t,e){if(Me.state.fatArrowAt==Me.stream.start){var n=e?E:N;if("("==t)return p(m,y(")"),F(B,")"),b,x("=>"),n,v);if("variable"==t)return d(m,B,x("=>"),n,v)}var r=e?D:M;return ke.hasOwnProperty(t)?p(r):"function"==t?p(te,r):"keyword c"==t?p(e?k:_):"("==t?p(y(")"),_,de,x(")"),b,r):"operator"==t||"spread"==t?p(e?C:S):"["==t?p(y("]"),fe,b,r):"{"==t?R(P,"}",null,r):"quasi"==t?d(L,r):p()}function _(t){return t.match(/[;\}\)\],]/)?d():d(S)}function k(t){return t.match(/[;\}\)\],]/)?d():d(C)}function M(t,e){return","==t?p(S):D(t,e,!1)}function D(t,e,n){var r=0==n?M:D,i=0==n?S:C;return"=>"==t?p(m,n?E:N,v):"operator"==t?/\+\+|--/.test(e)?p(r):"?"==e?p(S,x(":"),i):p(i):"quasi"==t?d(L,r):";"!=t?"("==t?R(C,")","call",r):"."==t?p(I,r):"["==t?p(y("]"),_,x("]"),b,r):void 0:void 0}function L(t,e){return"quasi"!=t?d():"${"!=e.slice(e.length-2)?p(L):p(S,A)}function A(t){if("}"==t){Me.marked="string-2";Me.state.tokenize=l;return p(L)}}function N(t){u(Me.stream,Me.state);return d("{"==t?w:S)}function E(t){u(Me.stream,Me.state);return d("{"==t?w:C)}function j(t){return":"==t?p(b,w):d(M,x(";"),b)}function I(t){if("variable"==t){Me.marked="property";return p()}}function P(t,e){if("variable"==t||"keyword"==Me.style){Me.marked="property";return p("get"==e||"set"==e?H:O)}if("number"==t||"string"==t){Me.marked=ye?"property":Me.style+" property";return p(O)}return"jsonld-keyword"==t?p(O):"["==t?p(S,x("]"),O):void 0}function H(t){if("variable"!=t)return d(O);Me.marked="property";return p(te)}function O(t){return":"==t?p(C):"("==t?d(te):void 0}function F(t,e){function n(r){if(","==r){var i=Me.state.lexical;"call"==i.info&&(i.pos=(i.pos||0)+1);return p(t,n)}return r==e?p():p(x(e))}return function(r){return r==e?p():d(t,n)}}function R(t,e,n){for(var r=3;r<arguments.length;r++)Me.cc.push(arguments[r]);return p(y(e,n),F(t,e),b)}function W(t){return"}"==t?p():d(w,W)}function z(t){return xe&&":"==t?p(q):void 0}function q(t){if("variable"==t){Me.marked="variable-3";return p()}}function U(){return d(B,z,X,G)}function B(t,e){if("variable"==t){g(e);return p()}return"["==t?R(B,"]"):"{"==t?R(V,"}"):void 0}function V(t,e){if("variable"==t&&!Me.stream.match(/^\s*:/,!1)){g(e);return p(X)}"variable"==t&&(Me.marked="property");return p(x(":"),B,X)}function X(t,e){return"="==e?p(C):void 0}function G(t){return","==t?p(U):void 0}function $(t,e){return"keyword b"==t&&"else"==e?p(y("form","else"),w,b):void 0}function Y(t){return"("==t?p(y(")"),J,x(")"),b):void 0}function J(t){return"var"==t?p(U,x(";"),Z):";"==t?p(Z):"variable"==t?p(K):d(S,x(";"),Z)}function K(t,e){if("in"==e||"of"==e){Me.marked="keyword";return p(S)}return p(M,Z)}function Z(t,e){if(";"==t)return p(Q);if("in"==e||"of"==e){Me.marked="keyword";return p(S)}return d(S,x(";"),Q)}function Q(t){")"!=t&&p(S)}function te(t,e){if("*"==e){Me.marked="keyword";return p(te)}if("variable"==t){g(e);return p(te)}return"("==t?p(m,y(")"),F(ee,")"),b,w,v):void 0}function ee(t){return"spread"==t?p(ee):d(B,z)}function ne(t,e){if("variable"==t){g(e);return p(re)}}function re(t,e){return"extends"==e?p(S,re):"{"==t?p(y("}"),ie,b):void 0}function ie(t,e){if("variable"==t||"keyword"==Me.style){Me.marked="property";return"get"==e||"set"==e?p(oe,te,ie):p(te,ie)}if("*"==e){Me.marked="keyword";return p(ie)}return";"==t?p(ie):"}"==t?p():void 0}function oe(t){if("variable"!=t)return d();Me.marked="property";return p()}function ae(t,e){if("string"==t)return p(w);if("variable"==t){g(e);return p(ce)}}function se(t,e){if("*"==e){Me.marked="keyword";return p(ce,x(";"))}if("default"==e){Me.marked="keyword";return p(S,x(";"))}return d(w)}function le(t){return"string"==t?p():d(ue,ce)}function ue(t,e){if("{"==t)return R(ue,"}");"variable"==t&&g(e);return p()}function ce(t,e){if("from"==e){Me.marked="keyword";return p(S)}}function fe(t){return"]"==t?p():d(C,he)}function he(t){return"for"==t?d(de,x("]")):","==t?p(F(k,"]")):d(F(C,"]"))}function de(t){return"for"==t?p(Y,de):"if"==t?p(S,de):void 0}var pe,ge,me=e.indentUnit,ve=n.statementIndent,ye=n.jsonld,be=n.json||ye,xe=n.typescript,we=n.wordCharacters||/[\w$\xa1-\uffff]/,Se=function(){function t(t){return{type:t,style:"keyword"}}var e=t("keyword a"),n=t("keyword b"),r=t("keyword c"),i=t("operator"),o={type:"atom",style:"atom"},a={"if":t("if"),"while":e,"with":e,"else":n,"do":n,"try":n,"finally":n,"return":r,"break":r,"continue":r,"new":r,"delete":r,"throw":r,"debugger":r,"var":t("var"),"const":t("var"),let:t("var"),"function":t("function"),"catch":t("catch"),"for":t("for"),"switch":t("switch"),"case":t("case"),"default":t("default"),"in":i,"typeof":i,"instanceof":i,"true":o,"false":o,"null":o,undefined:o,NaN:o,Infinity:o,"this":t("this"),module:t("module"),"class":t("class"),"super":t("atom"),"yield":r,"export":t("export"),"import":t("import"),"extends":r};if(xe){var s={type:"variable",style:"variable-3"},l={"interface":t("interface"),"extends":t("extends"),constructor:t("constructor"),"public":t("public"),"private":t("private"),"protected":t("protected"),"static":t("static"),string:s,number:s,bool:s,any:s};for(var u in l)a[u]=l[u]}return a}(),Ce=/[+\-*&%=<>!?|~^]/,Te=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,_e="([{}])",ke={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"jsonld-keyword":!0},Me={state:null,column:null,marked:null,cc:null},De={name:"this",next:{name:"arguments"}};b.lex=!0;return{startState:function(t){var e={tokenize:o,lastType:"sof",cc:[],lexical:new c((t||0)-me,0,"block",!1),localVars:n.localVars,context:n.localVars&&{vars:n.localVars},indented:0};n.globalVars&&"object"==typeof n.globalVars&&(e.globalVars=n.globalVars);return e},token:function(t,e){if(t.sol()){e.lexical.hasOwnProperty("align")||(e.lexical.align=!1);e.indented=t.indentation();u(t,e)}if(e.tokenize!=s&&t.eatSpace())return null;var n=e.tokenize(t,e);if("comment"==pe)return n;e.lastType="operator"!=pe||"++"!=ge&&"--"!=ge?pe:"incdec";return h(e,n,pe,ge,t)},indent:function(e,r){if(e.tokenize==s)return t.Pass;if(e.tokenize!=o)return 0;var i=r&&r.charAt(0),a=e.lexical;if(!/^\s*else\b/.test(r))for(var l=e.cc.length-1;l>=0;--l){var u=e.cc[l];if(u==b)a=a.prev;else if(u!=$)break}"stat"==a.type&&"}"==i&&(a=a.prev);ve&&")"==a.type&&"stat"==a.prev.type&&(a=a.prev);var c=a.type,f=i==c;return"vardef"==c?a.indented+("operator"==e.lastType||","==e.lastType?a.info+1:0):"form"==c&&"{"==i?a.indented:"form"==c?a.indented+me:"stat"==c?a.indented+("operator"==e.lastType||","==e.lastType?ve||me:0):"switch"!=a.info||f||0==n.doubleIndentSwitch?a.align?a.column+(f?0:1):a.indented+(f?0:me):a.indented+(/^(?:case|default)\b/.test(r)?me:2*me)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:be?null:"/*",blockCommentEnd:be?null:"*/",lineComment:be?null:"//",fold:"brace",helperType:be?"json":"javascript",jsonldMode:ye,jsonMode:be}});t.registerHelper("wordChars","javascript",/[\w$]/);t.defineMIME("text/javascript","javascript");t.defineMIME("text/ecmascript","javascript");t.defineMIME("application/javascript","javascript");t.defineMIME("application/x-javascript","javascript");t.defineMIME("application/ecmascript","javascript");t.defineMIME("application/json",{name:"javascript",json:!0});t.defineMIME("application/x-json",{name:"javascript",json:!0});t.defineMIME("application/ld+json",{name:"javascript",jsonld:!0});t.defineMIME("text/typescript",{name:"javascript",typescript:!0});t.defineMIME("application/typescript",{name:"javascript",typescript:!0})})},{"../../lib/codemirror":9}],11:[function(e,n,r){(function(i){"object"==typeof r&&"object"==typeof n?i(e("../../lib/codemirror")):"function"==typeof t&&t.amd?t(["../../lib/codemirror"],i):i(CodeMirror)})(function(t){"use strict";t.defineMode("xml",function(e,n){function r(t,e){function n(n){e.tokenize=n;return n(t,e)}var r=t.next();if("<"==r){if(t.eat("!")){if(t.eat("["))return t.match("CDATA[")?n(a("atom","]]>")):null;if(t.match("--"))return n(a("comment","-->"));if(t.match("DOCTYPE",!0,!0)){t.eatWhile(/[\w\._\-]/);return n(s(1))}return null}if(t.eat("?")){t.eatWhile(/[\w\._\-]/);e.tokenize=a("meta","?>");return"meta"}C=t.eat("/")?"closeTag":"openTag";e.tokenize=i;return"tag bracket"}if("&"==r){var o;o=t.eat("#")?t.eat("x")?t.eatWhile(/[a-fA-F\d]/)&&t.eat(";"):t.eatWhile(/[\d]/)&&t.eat(";"):t.eatWhile(/[\w\.\-:]/)&&t.eat(";");return o?"atom":"error"}t.eatWhile(/[^&<]/);return null}function i(t,e){var n=t.next();if(">"==n||"/"==n&&t.eat(">")){e.tokenize=r;C=">"==n?"endTag":"selfcloseTag";return"tag bracket"}if("="==n){C="equals";return null}if("<"==n){e.tokenize=r;e.state=f;e.tagName=e.tagStart=null;var i=e.tokenize(t,e);return i?i+" tag error":"tag error"}if(/[\'\"]/.test(n)){e.tokenize=o(n);e.stringStartCol=t.column();return e.tokenize(t,e)}t.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);return"word"}function o(t){var e=function(e,n){for(;!e.eol();)if(e.next()==t){n.tokenize=i;break}return"string"};e.isInAttribute=!0;return e}function a(t,e){return function(n,i){for(;!n.eol();){if(n.match(e)){i.tokenize=r;break}n.next()}return t}}function s(t){return function(e,n){for(var i;null!=(i=e.next());){if("<"==i){n.tokenize=s(t+1);return n.tokenize(e,n)}if(">"==i){if(1==t){n.tokenize=r;break}n.tokenize=s(t-1);return n.tokenize(e,n)}}return"meta"}}function l(t,e,n){this.prev=t.context;this.tagName=e;this.indent=t.indented;this.startOfLine=n;(_.doNotIndent.hasOwnProperty(e)||t.context&&t.context.noIndent)&&(this.noIndent=!0)}function u(t){t.context&&(t.context=t.context.prev)}function c(t,e){for(var n;;){if(!t.context)return;n=t.context.tagName;if(!_.contextGrabbers.hasOwnProperty(n)||!_.contextGrabbers[n].hasOwnProperty(e))return;u(t)}}function f(t,e,n){if("openTag"==t){n.tagStart=e.column();return h}return"closeTag"==t?d:f}function h(t,e,n){if("word"==t){n.tagName=e.current();T="tag";return m}T="error";return h}function d(t,e,n){if("word"==t){var r=e.current();n.context&&n.context.tagName!=r&&_.implicitlyClosed.hasOwnProperty(n.context.tagName)&&u(n);if(n.context&&n.context.tagName==r){T="tag";return p}T="tag error";return g}T="error";return g}function p(t,e,n){if("endTag"!=t){T="error";return p}u(n);return f}function g(t,e,n){T="error";return p(t,e,n)}function m(t,e,n){if("word"==t){T="attribute";return v}if("endTag"==t||"selfcloseTag"==t){var r=n.tagName,i=n.tagStart;n.tagName=n.tagStart=null;if("selfcloseTag"==t||_.autoSelfClosers.hasOwnProperty(r))c(n,r);else{c(n,r);n.context=new l(n,r,i==n.indented)}return f}T="error";return m}function v(t,e,n){if("equals"==t)return y;_.allowMissing||(T="error");return m(t,e,n)}function y(t,e,n){if("string"==t)return b;if("word"==t&&_.allowUnquoted){T="string";return m}T="error";return m(t,e,n)}function b(t,e,n){return"string"==t?b:m(t,e,n)}var x=e.indentUnit,w=n.multilineTagIndentFactor||1,S=n.multilineTagIndentPastTag;null==S&&(S=!0);var C,T,_=n.htmlMode?{autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0}:{autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,caseFold:!1},k=n.alignCDATA;return{startState:function(){return{tokenize:r,state:f,indented:0,tagName:null,tagStart:null,context:null}},token:function(t,e){!e.tagName&&t.sol()&&(e.indented=t.indentation());if(t.eatSpace())return null;C=null;var n=e.tokenize(t,e);if((n||C)&&"comment"!=n){T=null;e.state=e.state(C||n,t,e);T&&(n="error"==T?n+" error":T)}return n},indent:function(e,n,o){var a=e.context;if(e.tokenize.isInAttribute)return e.tagStart==e.indented?e.stringStartCol+1:e.indented+x;if(a&&a.noIndent)return t.Pass;if(e.tokenize!=i&&e.tokenize!=r)return o?o.match(/^(\s*)/)[0].length:0;if(e.tagName)return S?e.tagStart+e.tagName.length+2:e.tagStart+x*w;if(k&&/<!\[CDATA\[/.test(n))return 0;var s=n&&/^<(\/)?([\w_:\.-]*)/.exec(n);if(s&&s[1])for(;a;){if(a.tagName==s[2]){a=a.prev;break}if(!_.implicitlyClosed.hasOwnProperty(a.tagName))break;a=a.prev}else if(s)for(;a;){var l=_.contextGrabbers[a.tagName];if(!l||!l.hasOwnProperty(s[2]))break;a=a.prev}for(;a&&!a.startOfLine;)a=a.prev;return a?a.indent+x:0},electricInput:/<\/[\s\w:]+>$/,blockCommentStart:"<!--",blockCommentEnd:"-->",configuration:n.htmlMode?"html":"xml",helperType:n.htmlMode?"html":"xml"}});t.defineMIME("text/xml","xml");t.defineMIME("application/xml","xml");t.mimeModes.hasOwnProperty("text/html")||t.defineMIME("text/html",{name:"xml",htmlMode:!0})})},{"../../lib/codemirror":9}],12:[function(e,n){!function(){function e(t,e){return e>t?-1:t>e?1:t>=e?0:0/0}function r(t){return null===t?0/0:+t}function i(t){return!isNaN(t)}function o(t){return{left:function(e,n,r,i){arguments.length<3&&(r=0);arguments.length<4&&(i=e.length);for(;i>r;){var o=r+i>>>1;t(e[o],n)<0?r=o+1:i=o}return r},right:function(e,n,r,i){arguments.length<3&&(r=0);arguments.length<4&&(i=e.length);for(;i>r;){var o=r+i>>>1;t(e[o],n)>0?i=o:r=o+1}return r}}}function a(t){return t.length}function s(t){for(var e=1;t*e%1;)e*=10;return e}function l(t,e){for(var n in e)Object.defineProperty(t.prototype,n,{value:e[n],enumerable:!1})}function u(){this._=Object.create(null)}function c(t){return(t+="")===hs||t[0]===ds?ds+t:t}function f(t){return(t+="")[0]===ds?t.slice(1):t}function h(t){return c(t)in this._}function d(t){return(t=c(t))in this._&&delete this._[t]}function p(){var t=[];for(var e in this._)t.push(f(e));return t}function g(){var t=0;for(var e in this._)++t;return t}function m(){for(var t in this._)return!1;return!0}function v(){this._=Object.create(null)}function y(t,e,n){return function(){var r=n.apply(e,arguments);return r===e?t:r}}function b(t,e){if(e in t)return e;e=e.charAt(0).toUpperCase()+e.slice(1);for(var n=0,r=ps.length;r>n;++n){var i=ps[n]+e;if(i in t)return i}}function x(){}function w(){}function S(t){function e(){for(var e,r=n,i=-1,o=r.length;++i<o;)(e=r[i].on)&&e.apply(this,arguments);return t}var n=[],r=new u;e.on=function(e,i){var o,a=r.get(e);if(arguments.length<2)return a&&a.on;if(a){a.on=null;n=n.slice(0,o=n.indexOf(a)).concat(n.slice(o+1));r.remove(e)}i&&n.push(r.set(e,{on:i}));return t};return e}function C(){Ka.event.preventDefault()}function T(){for(var t,e=Ka.event;t=e.sourceEvent;)e=t;return e}function _(t){for(var e=new w,n=0,r=arguments.length;++n<r;)e[arguments[n]]=S(e);e.of=function(n,r){return function(i){try{var o=i.sourceEvent=Ka.event;i.target=t;Ka.event=i;e[i.type].apply(n,r)}finally{Ka.event=o}}};return e}function k(t){ms(t,ws);return t}function M(t){return"function"==typeof t?t:function(){return vs(t,this)}}function D(t){return"function"==typeof t?t:function(){return ys(t,this)}}function L(t,e){function n(){this.removeAttribute(t)}function r(){this.removeAttributeNS(t.space,t.local)}function i(){this.setAttribute(t,e)}function o(){this.setAttributeNS(t.space,t.local,e)}function a(){var n=e.apply(this,arguments);null==n?this.removeAttribute(t):this.setAttribute(t,n)}function s(){var n=e.apply(this,arguments);null==n?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,n)}t=Ka.ns.qualify(t);return null==e?t.local?r:n:"function"==typeof e?t.local?s:a:t.local?o:i}function A(t){return t.trim().replace(/\s+/g," ")}function N(t){return new RegExp("(?:^|\\s+)"+Ka.requote(t)+"(?:\\s+|$)","g")}function E(t){return(t+"").trim().split(/^|\s+/)}function j(t,e){function n(){for(var n=-1;++n<i;)t[n](this,e)}function r(){for(var n=-1,r=e.apply(this,arguments);++n<i;)t[n](this,r)}t=E(t).map(I);var i=t.length;return"function"==typeof e?r:n}function I(t){var e=N(t);return function(n,r){if(i=n.classList)return r?i.add(t):i.remove(t);var i=n.getAttribute("class")||"";if(r){e.lastIndex=0;e.test(i)||n.setAttribute("class",A(i+" "+t))}else n.setAttribute("class",A(i.replace(e," ")))}}function P(t,e,n){function r(){this.style.removeProperty(t)
}function i(){this.style.setProperty(t,e,n)}function o(){var r=e.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,n)}return null==e?r:"function"==typeof e?o:i}function H(t,e){function n(){delete this[t]}function r(){this[t]=e}function i(){var n=e.apply(this,arguments);null==n?delete this[t]:this[t]=n}return null==e?n:"function"==typeof e?i:r}function O(t){return"function"==typeof t?t:(t=Ka.ns.qualify(t)).local?function(){return this.ownerDocument.createElementNS(t.space,t.local)}:function(){return this.ownerDocument.createElementNS(this.namespaceURI,t)}}function F(t){return{__data__:t}}function R(t){return function(){return xs(this,t)}}function W(t){arguments.length||(t=e);return function(e,n){return e&&n?t(e.__data__,n.__data__):!e-!n}}function z(t,e){for(var n=0,r=t.length;r>n;n++)for(var i,o=t[n],a=0,s=o.length;s>a;a++)(i=o[a])&&e(i,a,n);return t}function q(t){ms(t,Cs);return t}function U(t){var e,n;return function(r,i,o){var a,s=t[o].update,l=s.length;o!=n&&(n=o,e=0);i>=e&&(e=i+1);for(;!(a=s[e])&&++e<l;);return a}}function B(){var t=this.__transition__;t&&++t.active}function V(t,e,n){function r(){var e=this[a];if(e){this.removeEventListener(t,e,e.$);delete this[a]}}function i(){var i=l(e,Qa(arguments));r.call(this);this.addEventListener(t,this[a]=i,i.$=n);i._=e}function o(){var e,n=new RegExp("^__on([^.]+)"+Ka.requote(t)+"$");for(var r in this)if(e=r.match(n)){var i=this[r];this.removeEventListener(e[1],i,i.$);delete this[r]}}var a="__on"+t,s=t.indexOf("."),l=X;s>0&&(t=t.slice(0,s));var u=_s.get(t);u&&(t=u,l=G);return s?e?i:r:e?x:o}function X(t,e){return function(n){var r=Ka.event;Ka.event=n;e[0]=this.__data__;try{t.apply(this,e)}finally{Ka.event=r}}}function G(t,e){var n=X(t,e);return function(t){var e=this,r=t.relatedTarget;r&&(r===e||8&r.compareDocumentPosition(e))||n.call(e,t)}}function $(){var t=".dragsuppress-"+ ++Ms,e="click"+t,n=Ka.select(ns).on("touchmove"+t,C).on("dragstart"+t,C).on("selectstart"+t,C);if(ks){var r=es.style,i=r[ks];r[ks]="none"}return function(o){function a(){n.on(e,null)}n.on(t,null);ks&&(r[ks]=i);if(o){n.on(e,function(){C();a()},!0);setTimeout(a,0)}}}function Y(t,e){e.changedTouches&&(e=e.changedTouches[0]);var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();if(0>Ds&&(ns.scrollX||ns.scrollY)){n=Ka.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var i=n[0][0].getScreenCTM();Ds=!(i.f||i.e);n.remove()}Ds?(r.x=e.pageX,r.y=e.pageY):(r.x=e.clientX,r.y=e.clientY);r=r.matrixTransform(t.getScreenCTM().inverse());return[r.x,r.y]}var o=t.getBoundingClientRect();return[e.clientX-o.left-t.clientLeft,e.clientY-o.top-t.clientTop]}function J(){return Ka.event.changedTouches[0].identifier}function K(){return Ka.event.target}function Z(){return ns}function Q(t){return t>0?1:0>t?-1:0}function te(t,e,n){return(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0])}function ee(t){return t>1?0:-1>t?Ls:Math.acos(t)}function ne(t){return t>1?Ns:-1>t?-Ns:Math.asin(t)}function re(t){return((t=Math.exp(t))-1/t)/2}function ie(t){return((t=Math.exp(t))+1/t)/2}function oe(t){return((t=Math.exp(2*t))-1)/(t+1)}function ae(t){return(t=Math.sin(t/2))*t}function se(){}function le(t,e,n){return this instanceof le?void(this.h=+t,this.s=+e,this.l=+n):arguments.length<2?t instanceof le?new le(t.h,t.s,t.l):Se(""+t,Ce,le):new le(t,e,n)}function ue(t,e,n){function r(t){t>360?t-=360:0>t&&(t+=360);return 60>t?o+(a-o)*t/60:180>t?a:240>t?o+(a-o)*(240-t)/60:o}function i(t){return Math.round(255*r(t))}var o,a;t=isNaN(t)?0:(t%=360)<0?t+360:t;e=isNaN(e)?0:0>e?0:e>1?1:e;n=0>n?0:n>1?1:n;a=.5>=n?n*(1+e):n+e-n*e;o=2*n-a;return new ye(i(t+120),i(t),i(t-120))}function ce(t,e,n){return this instanceof ce?void(this.h=+t,this.c=+e,this.l=+n):arguments.length<2?t instanceof ce?new ce(t.h,t.c,t.l):t instanceof he?pe(t.l,t.a,t.b):pe((t=Te((t=Ka.rgb(t)).r,t.g,t.b)).l,t.a,t.b):new ce(t,e,n)}function fe(t,e,n){isNaN(t)&&(t=0);isNaN(e)&&(e=0);return new he(n,Math.cos(t*=Is)*e,Math.sin(t)*e)}function he(t,e,n){return this instanceof he?void(this.l=+t,this.a=+e,this.b=+n):arguments.length<2?t instanceof he?new he(t.l,t.a,t.b):t instanceof ce?fe(t.h,t.c,t.l):Te((t=ye(t)).r,t.g,t.b):new he(t,e,n)}function de(t,e,n){var r=(t+16)/116,i=r+e/500,o=r-n/200;i=ge(i)*Vs;r=ge(r)*Xs;o=ge(o)*Gs;return new ye(ve(3.2404542*i-1.5371385*r-.4985314*o),ve(-.969266*i+1.8760108*r+.041556*o),ve(.0556434*i-.2040259*r+1.0572252*o))}function pe(t,e,n){return t>0?new ce(Math.atan2(n,e)*Ps,Math.sqrt(e*e+n*n),t):new ce(0/0,0/0,t)}function ge(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function me(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function ve(t){return Math.round(255*(.00304>=t?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function ye(t,e,n){return this instanceof ye?void(this.r=~~t,this.g=~~e,this.b=~~n):arguments.length<2?t instanceof ye?new ye(t.r,t.g,t.b):Se(""+t,ye,ue):new ye(t,e,n)}function be(t){return new ye(t>>16,t>>8&255,255&t)}function xe(t){return be(t)+""}function we(t){return 16>t?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function Se(t,e,n){var r,i,o,a=0,s=0,l=0;r=/([a-z]+)\((.*)\)/i.exec(t);if(r){i=r[2].split(",");switch(r[1]){case"hsl":return n(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return e(ke(i[0]),ke(i[1]),ke(i[2]))}}if(o=Js.get(t))return e(o.r,o.g,o.b);if(null!=t&&"#"===t.charAt(0)&&!isNaN(o=parseInt(t.slice(1),16)))if(4===t.length){a=(3840&o)>>4;a=a>>4|a;s=240&o;s=s>>4|s;l=15&o;l=l<<4|l}else if(7===t.length){a=(16711680&o)>>16;s=(65280&o)>>8;l=255&o}return e(a,s,l)}function Ce(t,e,n){var r,i,o=Math.min(t/=255,e/=255,n/=255),a=Math.max(t,e,n),s=a-o,l=(a+o)/2;if(s){i=.5>l?s/(a+o):s/(2-a-o);r=t==a?(e-n)/s+(n>e?6:0):e==a?(n-t)/s+2:(t-e)/s+4;r*=60}else{r=0/0;i=l>0&&1>l?0:r}return new le(r,i,l)}function Te(t,e,n){t=_e(t);e=_e(e);n=_e(n);var r=me((.4124564*t+.3575761*e+.1804375*n)/Vs),i=me((.2126729*t+.7151522*e+.072175*n)/Xs),o=me((.0193339*t+.119192*e+.9503041*n)/Gs);return he(116*i-16,500*(r-i),200*(i-o))}function _e(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function ke(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}function Me(t){return"function"==typeof t?t:function(){return t}}function De(t){return t}function Le(t){return function(e,n,r){2===arguments.length&&"function"==typeof n&&(r=n,n=null);return Ae(e,n,t,r)}}function Ae(t,e,n,r){function i(){var t,e=l.status;if(!e&&Ee(l)||e>=200&&300>e||304===e){try{t=n.call(o,l)}catch(r){a.error.call(o,r);return}a.load.call(o,t)}else a.error.call(o,l)}var o={},a=Ka.dispatch("beforesend","progress","load","error"),s={},l=new XMLHttpRequest,u=null;!ns.XDomainRequest||"withCredentials"in l||!/^(http(s)?:)?\/\//.test(t)||(l=new XDomainRequest);"onload"in l?l.onload=l.onerror=i:l.onreadystatechange=function(){l.readyState>3&&i()};l.onprogress=function(t){var e=Ka.event;Ka.event=t;try{a.progress.call(o,l)}finally{Ka.event=e}};o.header=function(t,e){t=(t+"").toLowerCase();if(arguments.length<2)return s[t];null==e?delete s[t]:s[t]=e+"";return o};o.mimeType=function(t){if(!arguments.length)return e;e=null==t?null:t+"";return o};o.responseType=function(t){if(!arguments.length)return u;u=t;return o};o.response=function(t){n=t;return o};["get","post"].forEach(function(t){o[t]=function(){return o.send.apply(o,[t].concat(Qa(arguments)))}});o.send=function(n,r,i){2===arguments.length&&"function"==typeof r&&(i=r,r=null);l.open(n,t,!0);null==e||"accept"in s||(s.accept=e+",*/*");if(l.setRequestHeader)for(var c in s)l.setRequestHeader(c,s[c]);null!=e&&l.overrideMimeType&&l.overrideMimeType(e);null!=u&&(l.responseType=u);null!=i&&o.on("error",i).on("load",function(t){i(null,t)});a.beforesend.call(o,l);l.send(null==r?null:r);return o};o.abort=function(){l.abort();return o};Ka.rebind(o,a,"on");return null==r?o:o.get(Ne(r))}function Ne(t){return 1===t.length?function(e,n){t(null==e?n:null)}:t}function Ee(t){var e=t.responseType;return e&&"text"!==e?t.response:t.responseText}function je(){var t=Ie(),e=Pe()-t;if(e>24){if(isFinite(e)){clearTimeout(tl);tl=setTimeout(je,e)}Qs=0}else{Qs=1;nl(je)}}function Ie(){var t=Date.now();el=Ks;for(;el;){t>=el.t&&(el.f=el.c(t-el.t));el=el.n}return t}function Pe(){for(var t,e=Ks,n=1/0;e;)if(e.f)e=t?t.n=e.n:Ks=e.n;else{e.t<n&&(n=e.t);e=(t=e).n}Zs=t;return n}function He(t,e){return e-(t?Math.ceil(Math.log(t)/Math.LN10):1)}function Oe(t,e){var n=Math.pow(10,3*fs(8-e));return{scale:e>8?function(t){return t/n}:function(t){return t*n},symbol:t}}function Fe(t){var e=t.decimal,n=t.thousands,r=t.grouping,i=t.currency,o=r&&n?function(t,e){for(var i=t.length,o=[],a=0,s=r[0],l=0;i>0&&s>0;){l+s+1>e&&(s=Math.max(1,e-l));o.push(t.substring(i-=s,i+s));if((l+=s+1)>e)break;s=r[a=(a+1)%r.length]}return o.reverse().join(n)}:De;return function(t){var n=il.exec(t),r=n[1]||" ",a=n[2]||">",s=n[3]||"-",l=n[4]||"",u=n[5],c=+n[6],f=n[7],h=n[8],d=n[9],p=1,g="",m="",v=!1,y=!0;h&&(h=+h.substring(1));if(u||"0"===r&&"="===a){u=r="0";a="="}switch(d){case"n":f=!0;d="g";break;case"%":p=100;m="%";d="f";break;case"p":p=100;m="%";d="r";break;case"b":case"o":case"x":case"X":"#"===l&&(g="0"+d.toLowerCase());case"c":y=!1;case"d":v=!0;h=0;break;case"s":p=-1;d="r"}"$"===l&&(g=i[0],m=i[1]);"r"!=d||h||(d="g");null!=h&&("g"==d?h=Math.max(1,Math.min(21,h)):("e"==d||"f"==d)&&(h=Math.max(0,Math.min(20,h))));d=ol.get(d)||Re;var b=u&&f;return function(t){var n=m;if(v&&t%1)return"";var i=0>t||0===t&&0>1/t?(t=-t,"-"):"-"===s?"":s;if(0>p){var l=Ka.formatPrefix(t,h);t=l.scale(t);n=l.symbol+m}else t*=p;t=d(t,h);var x,w,S=t.lastIndexOf(".");if(0>S){var C=y?t.lastIndexOf("e"):-1;0>C?(x=t,w=""):(x=t.substring(0,C),w=t.substring(C))}else{x=t.substring(0,S);w=e+t.substring(S+1)}!u&&f&&(x=o(x,1/0));var T=g.length+x.length+w.length+(b?0:i.length),_=c>T?new Array(T=c-T+1).join(r):"";b&&(x=o(_+x,_.length?c-w.length:1/0));i+=g;t=x+w;return("<"===a?i+t+_:">"===a?_+i+t:"^"===a?_.substring(0,T>>=1)+i+t+_.substring(T):i+(b?t:_+t))+n}}}function Re(t){return t+""}function We(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function ze(t,e,n){function r(e){var n=t(e),r=o(n,1);return r-e>e-n?n:r}function i(n){e(n=t(new sl(n-1)),1);return n}function o(t,n){e(t=new sl(+t),n);return t}function a(t,r,o){var a=i(t),s=[];if(o>1)for(;r>a;){n(a)%o||s.push(new Date(+a));e(a,1)}else for(;r>a;)s.push(new Date(+a)),e(a,1);return s}function s(t,e,n){try{sl=We;var r=new We;r._=t;return a(r,e,n)}finally{sl=Date}}t.floor=t;t.round=r;t.ceil=i;t.offset=o;t.range=a;var l=t.utc=qe(t);l.floor=l;l.round=qe(r);l.ceil=qe(i);l.offset=qe(o);l.range=s;return t}function qe(t){return function(e,n){try{sl=We;var r=new We;r._=e;return t(r,n)._}finally{sl=Date}}}function Ue(t){function e(t){function e(e){for(var n,i,o,a=[],s=-1,l=0;++s<r;)if(37===t.charCodeAt(s)){a.push(t.slice(l,s));null!=(i=ul[n=t.charAt(++s)])&&(n=t.charAt(++s));(o=D[n])&&(n=o(e,null==i?"e"===n?" ":"0":i));a.push(n);l=s+1}a.push(t.slice(l,s));return a.join("")}var r=t.length;e.parse=function(e){var r={y:1900,m:0,d:1,H:0,M:0,S:0,L:0,Z:null},i=n(r,t,e,0);if(i!=e.length)return null;"p"in r&&(r.H=r.H%12+12*r.p);var o=null!=r.Z&&sl!==We,a=new(o?We:sl);if("j"in r)a.setFullYear(r.y,0,r.j);else if("w"in r&&("W"in r||"U"in r)){a.setFullYear(r.y,0,1);a.setFullYear(r.y,0,"W"in r?(r.w+6)%7+7*r.W-(a.getDay()+5)%7:r.w+7*r.U-(a.getDay()+6)%7)}else a.setFullYear(r.y,r.m,r.d);a.setHours(r.H+(r.Z/100|0),r.M+r.Z%100,r.S,r.L);return o?a._:a};e.toString=function(){return t};return e}function n(t,e,n,r){for(var i,o,a,s=0,l=e.length,u=n.length;l>s;){if(r>=u)return-1;i=e.charCodeAt(s++);if(37===i){a=e.charAt(s++);o=L[a in ul?e.charAt(s++):a];if(!o||(r=o(t,n,r))<0)return-1}else if(i!=n.charCodeAt(r++))return-1}return r}function r(t,e,n){S.lastIndex=0;var r=S.exec(e.slice(n));return r?(t.w=C.get(r[0].toLowerCase()),n+r[0].length):-1}function i(t,e,n){x.lastIndex=0;var r=x.exec(e.slice(n));return r?(t.w=w.get(r[0].toLowerCase()),n+r[0].length):-1}function o(t,e,n){k.lastIndex=0;var r=k.exec(e.slice(n));return r?(t.m=M.get(r[0].toLowerCase()),n+r[0].length):-1}function a(t,e,n){T.lastIndex=0;var r=T.exec(e.slice(n));return r?(t.m=_.get(r[0].toLowerCase()),n+r[0].length):-1}function s(t,e,r){return n(t,D.c.toString(),e,r)}function l(t,e,r){return n(t,D.x.toString(),e,r)}function u(t,e,r){return n(t,D.X.toString(),e,r)}function c(t,e,n){var r=b.get(e.slice(n,n+=2).toLowerCase());return null==r?-1:(t.p=r,n)}var f=t.dateTime,h=t.date,d=t.time,p=t.periods,g=t.days,m=t.shortDays,v=t.months,y=t.shortMonths;e.utc=function(t){function n(t){try{sl=We;var e=new sl;e._=t;return r(e)}finally{sl=Date}}var r=e(t);n.parse=function(t){try{sl=We;var e=r.parse(t);return e&&e._}finally{sl=Date}};n.toString=r.toString;return n};e.multi=e.utc.multi=cn;var b=Ka.map(),x=Ve(g),w=Xe(g),S=Ve(m),C=Xe(m),T=Ve(v),_=Xe(v),k=Ve(y),M=Xe(y);p.forEach(function(t,e){b.set(t.toLowerCase(),e)});var D={a:function(t){return m[t.getDay()]},A:function(t){return g[t.getDay()]},b:function(t){return y[t.getMonth()]},B:function(t){return v[t.getMonth()]},c:e(f),d:function(t,e){return Be(t.getDate(),e,2)},e:function(t,e){return Be(t.getDate(),e,2)},H:function(t,e){return Be(t.getHours(),e,2)},I:function(t,e){return Be(t.getHours()%12||12,e,2)},j:function(t,e){return Be(1+al.dayOfYear(t),e,3)},L:function(t,e){return Be(t.getMilliseconds(),e,3)},m:function(t,e){return Be(t.getMonth()+1,e,2)},M:function(t,e){return Be(t.getMinutes(),e,2)},p:function(t){return p[+(t.getHours()>=12)]},S:function(t,e){return Be(t.getSeconds(),e,2)},U:function(t,e){return Be(al.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return Be(al.mondayOfYear(t),e,2)},x:e(h),X:e(d),y:function(t,e){return Be(t.getFullYear()%100,e,2)},Y:function(t,e){return Be(t.getFullYear()%1e4,e,4)},Z:ln,"%":function(){return"%"}},L={a:r,A:i,b:o,B:a,c:s,d:en,e:en,H:rn,I:rn,j:nn,L:sn,m:tn,M:on,p:c,S:an,U:$e,w:Ge,W:Ye,x:l,X:u,y:Ke,Y:Je,Z:Ze,"%":un};return e}function Be(t,e,n){var r=0>t?"-":"",i=(r?-t:t)+"",o=i.length;return r+(n>o?new Array(n-o+1).join(e)+i:i)}function Ve(t){return new RegExp("^(?:"+t.map(Ka.requote).join("|")+")","i")}function Xe(t){for(var e=new u,n=-1,r=t.length;++n<r;)e.set(t[n].toLowerCase(),n);return e}function Ge(t,e,n){cl.lastIndex=0;var r=cl.exec(e.slice(n,n+1));return r?(t.w=+r[0],n+r[0].length):-1}function $e(t,e,n){cl.lastIndex=0;var r=cl.exec(e.slice(n));return r?(t.U=+r[0],n+r[0].length):-1}function Ye(t,e,n){cl.lastIndex=0;var r=cl.exec(e.slice(n));return r?(t.W=+r[0],n+r[0].length):-1}function Je(t,e,n){cl.lastIndex=0;var r=cl.exec(e.slice(n,n+4));return r?(t.y=+r[0],n+r[0].length):-1}function Ke(t,e,n){cl.lastIndex=0;var r=cl.exec(e.slice(n,n+2));return r?(t.y=Qe(+r[0]),n+r[0].length):-1}function Ze(t,e,n){return/^[+-]\d{4}$/.test(e=e.slice(n,n+5))?(t.Z=-e,n+5):-1}function Qe(t){return t+(t>68?1900:2e3)}function tn(t,e,n){cl.lastIndex=0;var r=cl.exec(e.slice(n,n+2));return r?(t.m=r[0]-1,n+r[0].length):-1}function en(t,e,n){cl.lastIndex=0;var r=cl.exec(e.slice(n,n+2));return r?(t.d=+r[0],n+r[0].length):-1}function nn(t,e,n){cl.lastIndex=0;var r=cl.exec(e.slice(n,n+3));return r?(t.j=+r[0],n+r[0].length):-1}function rn(t,e,n){cl.lastIndex=0;var r=cl.exec(e.slice(n,n+2));return r?(t.H=+r[0],n+r[0].length):-1}function on(t,e,n){cl.lastIndex=0;var r=cl.exec(e.slice(n,n+2));return r?(t.M=+r[0],n+r[0].length):-1}function an(t,e,n){cl.lastIndex=0;var r=cl.exec(e.slice(n,n+2));return r?(t.S=+r[0],n+r[0].length):-1}function sn(t,e,n){cl.lastIndex=0;var r=cl.exec(e.slice(n,n+3));return r?(t.L=+r[0],n+r[0].length):-1}function ln(t){var e=t.getTimezoneOffset(),n=e>0?"-":"+",r=fs(e)/60|0,i=fs(e)%60;return n+Be(r,"0",2)+Be(i,"0",2)}function un(t,e,n){fl.lastIndex=0;var r=fl.exec(e.slice(n,n+1));return r?n+r[0].length:-1}function cn(t){for(var e=t.length,n=-1;++n<e;)t[n][0]=this(t[n][0]);return function(e){for(var n=0,r=t[n];!r[1](e);)r=t[++n];return r[0](e)}}function fn(){}function hn(t,e,n){var r=n.s=t+e,i=r-t,o=r-i;n.t=t-o+(e-i)}function dn(t,e){t&&gl.hasOwnProperty(t.type)&&gl[t.type](t,e)}function pn(t,e,n){var r,i=-1,o=t.length-n;e.lineStart();for(;++i<o;)r=t[i],e.point(r[0],r[1],r[2]);e.lineEnd()}function gn(t,e){var n=-1,r=t.length;e.polygonStart();for(;++n<r;)pn(t[n],e,1);e.polygonEnd()}function mn(){function t(t,e){t*=Is;e=e*Is/2+Ls/4;var n=t-r,a=n>=0?1:-1,s=a*n,l=Math.cos(e),u=Math.sin(e),c=o*u,f=i*l+c*Math.cos(s),h=c*a*Math.sin(s);vl.add(Math.atan2(h,f));r=t,i=l,o=u}var e,n,r,i,o;yl.point=function(a,s){yl.point=t;r=(e=a)*Is,i=Math.cos(s=(n=s)*Is/2+Ls/4),o=Math.sin(s)};yl.lineEnd=function(){t(e,n)}}function vn(t){var e=t[0],n=t[1],r=Math.cos(n);return[r*Math.cos(e),r*Math.sin(e),Math.sin(n)]}function yn(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function bn(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function xn(t,e){t[0]+=e[0];t[1]+=e[1];t[2]+=e[2]}function wn(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function Sn(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e;t[1]/=e;t[2]/=e}function Cn(t){return[Math.atan2(t[1],t[0]),ne(t[2])]}function Tn(t,e){return fs(t[0]-e[0])<Es&&fs(t[1]-e[1])<Es}function _n(t,e){t*=Is;var n=Math.cos(e*=Is);kn(n*Math.cos(t),n*Math.sin(t),Math.sin(e))}function kn(t,e,n){++bl;wl+=(t-wl)/bl;Sl+=(e-Sl)/bl;Cl+=(n-Cl)/bl}function Mn(){function t(t,i){t*=Is;var o=Math.cos(i*=Is),a=o*Math.cos(t),s=o*Math.sin(t),l=Math.sin(i),u=Math.atan2(Math.sqrt((u=n*l-r*s)*u+(u=r*a-e*l)*u+(u=e*s-n*a)*u),e*a+n*s+r*l);xl+=u;Tl+=u*(e+(e=a));_l+=u*(n+(n=s));kl+=u*(r+(r=l));kn(e,n,r)}var e,n,r;Al.point=function(i,o){i*=Is;var a=Math.cos(o*=Is);e=a*Math.cos(i);n=a*Math.sin(i);r=Math.sin(o);Al.point=t;kn(e,n,r)}}function Dn(){Al.point=_n}function Ln(){function t(t,e){t*=Is;var n=Math.cos(e*=Is),a=n*Math.cos(t),s=n*Math.sin(t),l=Math.sin(e),u=i*l-o*s,c=o*a-r*l,f=r*s-i*a,h=Math.sqrt(u*u+c*c+f*f),d=r*a+i*s+o*l,p=h&&-ee(d)/h,g=Math.atan2(h,d);Ml+=p*u;Dl+=p*c;Ll+=p*f;xl+=g;Tl+=g*(r+(r=a));_l+=g*(i+(i=s));kl+=g*(o+(o=l));kn(r,i,o)}var e,n,r,i,o;Al.point=function(a,s){e=a,n=s;Al.point=t;a*=Is;var l=Math.cos(s*=Is);r=l*Math.cos(a);i=l*Math.sin(a);o=Math.sin(s);kn(r,i,o)};Al.lineEnd=function(){t(e,n);Al.lineEnd=Dn;Al.point=_n}}function An(){return!0}function Nn(t,e,n,r,i){var o=[],a=[];t.forEach(function(t){if(!((e=t.length-1)<=0)){var e,n=t[0],r=t[e];if(Tn(n,r)){i.lineStart();for(var s=0;e>s;++s)i.point((n=t[s])[0],n[1]);i.lineEnd()}else{var l=new jn(n,t,null,!0),u=new jn(n,null,l,!1);l.o=u;o.push(l);a.push(u);l=new jn(r,t,null,!1);u=new jn(r,null,l,!0);l.o=u;o.push(l);a.push(u)}}});a.sort(e);En(o);En(a);if(o.length){for(var s=0,l=n,u=a.length;u>s;++s)a[s].e=l=!l;for(var c,f,h=o[0];;){for(var d=h,p=!0;d.v;)if((d=d.n)===h)return;c=d.z;i.lineStart();do{d.v=d.o.v=!0;if(d.e){if(p)for(var s=0,u=c.length;u>s;++s)i.point((f=c[s])[0],f[1]);else r(d.x,d.n.x,1,i);d=d.n}else{if(p){c=d.p.z;for(var s=c.length-1;s>=0;--s)i.point((f=c[s])[0],f[1])}else r(d.x,d.p.x,-1,i);d=d.p}d=d.o;c=d.z;p=!p}while(!d.v);i.lineEnd()}}}function En(t){if(e=t.length){for(var e,n,r=0,i=t[0];++r<e;){i.n=n=t[r];n.p=i;i=n}i.n=n=t[0];n.p=i}}function jn(t,e,n,r){this.x=t;this.z=e;this.o=n;this.e=r;this.v=!1;this.n=this.p=null}function In(t,e,n,r){return function(i,o){function a(e,n){var r=i(e,n);t(e=r[0],n=r[1])&&o.point(e,n)}function s(t,e){var n=i(t,e);m.point(n[0],n[1])}function l(){y.point=s;m.lineStart()}function u(){y.point=a;m.lineEnd()}function c(t,e){g.push([t,e]);var n=i(t,e);x.point(n[0],n[1])}function f(){x.lineStart();g=[]}function h(){c(g[0][0],g[0][1]);x.lineEnd();var t,e=x.clean(),n=b.buffer(),r=n.length;g.pop();p.push(g);g=null;if(r)if(1&e){t=n[0];var i,r=t.length-1,a=-1;if(r>0){w||(o.polygonStart(),w=!0);o.lineStart();for(;++a<r;)o.point((i=t[a])[0],i[1]);o.lineEnd()}}else{r>1&&2&e&&n.push(n.pop().concat(n.shift()));d.push(n.filter(Pn))}}var d,p,g,m=e(o),v=i.invert(r[0],r[1]),y={point:a,lineStart:l,lineEnd:u,polygonStart:function(){y.point=c;y.lineStart=f;y.lineEnd=h;d=[];p=[]},polygonEnd:function(){y.point=a;y.lineStart=l;y.lineEnd=u;d=Ka.merge(d);var t=zn(v,p);if(d.length){w||(o.polygonStart(),w=!0);Nn(d,On,t,n,o)}else if(t){w||(o.polygonStart(),w=!0);o.lineStart();n(null,null,1,o);o.lineEnd()}w&&(o.polygonEnd(),w=!1);d=p=null},sphere:function(){o.polygonStart();o.lineStart();n(null,null,1,o);o.lineEnd();o.polygonEnd()}},b=Hn(),x=e(b),w=!1;return y}}function Pn(t){return t.length>1}function Hn(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,n){t.push([e,n])},lineEnd:x,buffer:function(){var n=e;e=[];t=null;return n},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function On(t,e){return((t=t.x)[0]<0?t[1]-Ns-Es:Ns-t[1])-((e=e.x)[0]<0?e[1]-Ns-Es:Ns-e[1])}function Fn(t){var e,n=0/0,r=0/0,i=0/0;return{lineStart:function(){t.lineStart();e=1},point:function(o,a){var s=o>0?Ls:-Ls,l=fs(o-n);if(fs(l-Ls)<Es){t.point(n,r=(r+a)/2>0?Ns:-Ns);t.point(i,r);t.lineEnd();t.lineStart();t.point(s,r);t.point(o,r);e=0}else if(i!==s&&l>=Ls){fs(n-i)<Es&&(n-=i*Es);fs(o-s)<Es&&(o-=s*Es);r=Rn(n,r,o,a);t.point(i,r);t.lineEnd();t.lineStart();t.point(s,r);e=0}t.point(n=o,r=a);i=s},lineEnd:function(){t.lineEnd();n=r=0/0},clean:function(){return 2-e}}}function Rn(t,e,n,r){var i,o,a=Math.sin(t-n);return fs(a)>Es?Math.atan((Math.sin(e)*(o=Math.cos(r))*Math.sin(n)-Math.sin(r)*(i=Math.cos(e))*Math.sin(t))/(i*o*a)):(e+r)/2}function Wn(t,e,n,r){var i;if(null==t){i=n*Ns;r.point(-Ls,i);r.point(0,i);r.point(Ls,i);r.point(Ls,0);r.point(Ls,-i);r.point(0,-i);r.point(-Ls,-i);r.point(-Ls,0);r.point(-Ls,i)}else if(fs(t[0]-e[0])>Es){var o=t[0]<e[0]?Ls:-Ls;i=n*o/2;r.point(-o,i);r.point(0,i);r.point(o,i)}else r.point(e[0],e[1])}function zn(t,e){var n=t[0],r=t[1],i=[Math.sin(n),-Math.cos(n),0],o=0,a=0;vl.reset();for(var s=0,l=e.length;l>s;++s){var u=e[s],c=u.length;if(c)for(var f=u[0],h=f[0],d=f[1]/2+Ls/4,p=Math.sin(d),g=Math.cos(d),m=1;;){m===c&&(m=0);t=u[m];var v=t[0],y=t[1]/2+Ls/4,b=Math.sin(y),x=Math.cos(y),w=v-h,S=w>=0?1:-1,C=S*w,T=C>Ls,_=p*b;vl.add(Math.atan2(_*S*Math.sin(C),g*x+_*Math.cos(C)));o+=T?w+S*As:w;if(T^h>=n^v>=n){var k=bn(vn(f),vn(t));Sn(k);var M=bn(i,k);Sn(M);var D=(T^w>=0?-1:1)*ne(M[2]);(r>D||r===D&&(k[0]||k[1]))&&(a+=T^w>=0?1:-1)}if(!m++)break;h=v,p=b,g=x,f=t}}return(-Es>o||Es>o&&0>vl)^1&a}function qn(t){function e(t,e){return Math.cos(t)*Math.cos(e)>o}function n(t){var n,o,l,u,c;return{lineStart:function(){u=l=!1;c=1},point:function(f,h){var d,p=[f,h],g=e(f,h),m=a?g?0:i(f,h):g?i(f+(0>f?Ls:-Ls),h):0;!n&&(u=l=g)&&t.lineStart();if(g!==l){d=r(n,p);if(Tn(n,d)||Tn(p,d)){p[0]+=Es;p[1]+=Es;g=e(p[0],p[1])}}if(g!==l){c=0;if(g){t.lineStart();d=r(p,n);t.point(d[0],d[1])}else{d=r(n,p);t.point(d[0],d[1]);t.lineEnd()}n=d}else if(s&&n&&a^g){var v;if(!(m&o)&&(v=r(p,n,!0))){c=0;if(a){t.lineStart();t.point(v[0][0],v[0][1]);t.point(v[1][0],v[1][1]);t.lineEnd()}else{t.point(v[1][0],v[1][1]);t.lineEnd();t.lineStart();t.point(v[0][0],v[0][1])}}}!g||n&&Tn(n,p)||t.point(p[0],p[1]);n=p,l=g,o=m},lineEnd:function(){l&&t.lineEnd();n=null},clean:function(){return c|(u&&l)<<1}}}function r(t,e,n){var r=vn(t),i=vn(e),a=[1,0,0],s=bn(r,i),l=yn(s,s),u=s[0],c=l-u*u;if(!c)return!n&&t;var f=o*l/c,h=-o*u/c,d=bn(a,s),p=wn(a,f),g=wn(s,h);xn(p,g);var m=d,v=yn(p,m),y=yn(m,m),b=v*v-y*(yn(p,p)-1);if(!(0>b)){var x=Math.sqrt(b),w=wn(m,(-v-x)/y);xn(w,p);w=Cn(w);if(!n)return w;var S,C=t[0],T=e[0],_=t[1],k=e[1];C>T&&(S=C,C=T,T=S);var M=T-C,D=fs(M-Ls)<Es,L=D||Es>M;!D&&_>k&&(S=_,_=k,k=S);if(L?D?_+k>0^w[1]<(fs(w[0]-C)<Es?_:k):_<=w[1]&&w[1]<=k:M>Ls^(C<=w[0]&&w[0]<=T)){var A=wn(m,(-v+x)/y);xn(A,p);return[w,Cn(A)]}}}function i(e,n){var r=a?t:Ls-t,i=0;-r>e?i|=1:e>r&&(i|=2);-r>n?i|=4:n>r&&(i|=8);return i}var o=Math.cos(t),a=o>0,s=fs(o)>Es,l=mr(t,6*Is);return In(e,n,l,a?[0,-t]:[-Ls,t-Ls])}function Un(t,e,n,r){return function(i){var o,a=i.a,s=i.b,l=a.x,u=a.y,c=s.x,f=s.y,h=0,d=1,p=c-l,g=f-u;o=t-l;if(p||!(o>0)){o/=p;if(0>p){if(h>o)return;d>o&&(d=o)}else if(p>0){if(o>d)return;o>h&&(h=o)}o=n-l;if(p||!(0>o)){o/=p;if(0>p){if(o>d)return;o>h&&(h=o)}else if(p>0){if(h>o)return;d>o&&(d=o)}o=e-u;if(g||!(o>0)){o/=g;if(0>g){if(h>o)return;d>o&&(d=o)}else if(g>0){if(o>d)return;o>h&&(h=o)}o=r-u;if(g||!(0>o)){o/=g;if(0>g){if(o>d)return;o>h&&(h=o)}else if(g>0){if(h>o)return;d>o&&(d=o)}h>0&&(i.a={x:l+h*p,y:u+h*g});1>d&&(i.b={x:l+d*p,y:u+d*g});return i}}}}}}function Bn(t,e,n,r){function i(r,i){return fs(r[0]-t)<Es?i>0?0:3:fs(r[0]-n)<Es?i>0?2:1:fs(r[1]-e)<Es?i>0?1:0:i>0?3:2}function o(t,e){return a(t.x,e.x)}function a(t,e){var n=i(t,1),r=i(e,1);return n!==r?n-r:0===n?e[1]-t[1]:1===n?t[0]-e[0]:2===n?t[1]-e[1]:e[0]-t[0]}return function(s){function l(t){for(var e=0,n=m.length,r=t[1],i=0;n>i;++i)for(var o,a=1,s=m[i],l=s.length,u=s[0];l>a;++a){o=s[a];u[1]<=r?o[1]>r&&te(u,o,t)>0&&++e:o[1]<=r&&te(u,o,t)<0&&--e;u=o}return 0!==e}function u(o,s,l,u){var c=0,f=0;if(null==o||(c=i(o,l))!==(f=i(s,l))||a(o,s)<0^l>0){do u.point(0===c||3===c?t:n,c>1?r:e);while((c=(c+l+4)%4)!==f)}else u.point(s[0],s[1])}function c(i,o){return i>=t&&n>=i&&o>=e&&r>=o}function f(t,e){c(t,e)&&s.point(t,e)}function h(){L.point=p;m&&m.push(v=[]);T=!0;C=!1;w=S=0/0}function d(){if(g){p(y,b);x&&C&&M.rejoin();g.push(M.buffer())}L.point=f;C&&s.lineEnd()}function p(t,e){t=Math.max(-El,Math.min(El,t));e=Math.max(-El,Math.min(El,e));var n=c(t,e);m&&v.push([t,e]);if(T){y=t,b=e,x=n;T=!1;if(n){s.lineStart();s.point(t,e)}}else if(n&&C)s.point(t,e);else{var r={a:{x:w,y:S},b:{x:t,y:e}};if(D(r)){if(!C){s.lineStart();s.point(r.a.x,r.a.y)}s.point(r.b.x,r.b.y);n||s.lineEnd();_=!1}else if(n){s.lineStart();s.point(t,e);_=!1}}w=t,S=e,C=n}var g,m,v,y,b,x,w,S,C,T,_,k=s,M=Hn(),D=Un(t,e,n,r),L={point:f,lineStart:h,lineEnd:d,polygonStart:function(){s=M;g=[];m=[];_=!0},polygonEnd:function(){s=k;g=Ka.merge(g);var e=l([t,r]),n=_&&e,i=g.length;if(n||i){s.polygonStart();if(n){s.lineStart();u(null,null,1,s);s.lineEnd()}i&&Nn(g,o,e,u,s);s.polygonEnd()}g=m=v=null}};return L}}function Vn(t,e){function n(n,r){return n=t(n,r),e(n[0],n[1])}t.invert&&e.invert&&(n.invert=function(n,r){return n=e.invert(n,r),n&&t.invert(n[0],n[1])});return n}function Xn(t){var e=0,n=Ls/3,r=lr(t),i=r(e,n);i.parallels=function(t){return arguments.length?r(e=t[0]*Ls/180,n=t[1]*Ls/180):[e/Ls*180,n/Ls*180]};return i}function Gn(t,e){function n(t,e){var n=Math.sqrt(o-2*i*Math.sin(e))/i;return[n*Math.sin(t*=i),a-n*Math.cos(t)]}var r=Math.sin(t),i=(r+Math.sin(e))/2,o=1+r*(2*i-r),a=Math.sqrt(o)/i;n.invert=function(t,e){var n=a-e;return[Math.atan2(t,n)/i,ne((o-(t*t+n*n)*i*i)/(2*i))]};return n}function $n(){function t(t,e){Il+=i*t-r*e;r=t,i=e}var e,n,r,i;Rl.point=function(o,a){Rl.point=t;e=r=o,n=i=a};Rl.lineEnd=function(){t(e,n)}}function Yn(t,e){Pl>t&&(Pl=t);t>Ol&&(Ol=t);Hl>e&&(Hl=e);e>Fl&&(Fl=e)}function Jn(){function t(t,e){a.push("M",t,",",e,o)}function e(t,e){a.push("M",t,",",e);s.point=n}function n(t,e){a.push("L",t,",",e)}function r(){s.point=t}function i(){a.push("Z")}var o=Kn(4.5),a=[],s={point:t,lineStart:function(){s.point=e},lineEnd:r,polygonStart:function(){s.lineEnd=i},polygonEnd:function(){s.lineEnd=r;s.point=t},pointRadius:function(t){o=Kn(t);return s},result:function(){if(a.length){var t=a.join("");a=[];return t}}};return s}function Kn(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function Zn(t,e){wl+=t;Sl+=e;++Cl}function Qn(){function t(t,r){var i=t-e,o=r-n,a=Math.sqrt(i*i+o*o);Tl+=a*(e+t)/2;_l+=a*(n+r)/2;kl+=a;Zn(e=t,n=r)}var e,n;zl.point=function(r,i){zl.point=t;Zn(e=r,n=i)}}function tr(){zl.point=Zn}function er(){function t(t,e){var n=t-r,o=e-i,a=Math.sqrt(n*n+o*o);Tl+=a*(r+t)/2;_l+=a*(i+e)/2;kl+=a;a=i*t-r*e;Ml+=a*(r+t);Dl+=a*(i+e);Ll+=3*a;Zn(r=t,i=e)}var e,n,r,i;zl.point=function(o,a){zl.point=t;Zn(e=r=o,n=i=a)};zl.lineEnd=function(){t(e,n)}}function nr(t){function e(e,n){t.moveTo(e,n);t.arc(e,n,a,0,As)}function n(e,n){t.moveTo(e,n);s.point=r}function r(e,n){t.lineTo(e,n)}function i(){s.point=e}function o(){t.closePath()}var a=4.5,s={point:e,lineStart:function(){s.point=n},lineEnd:i,polygonStart:function(){s.lineEnd=o},polygonEnd:function(){s.lineEnd=i;s.point=e},pointRadius:function(t){a=t;return s},result:x};return s}function rr(t){function e(t){return(s?r:n)(t)}function n(e){return ar(e,function(n,r){n=t(n,r);e.point(n[0],n[1])})}function r(e){function n(n,r){n=t(n,r);e.point(n[0],n[1])}function r(){b=0/0;T.point=o;e.lineStart()}function o(n,r){var o=vn([n,r]),a=t(n,r);i(b,x,y,w,S,C,b=a[0],x=a[1],y=n,w=o[0],S=o[1],C=o[2],s,e);e.point(b,x)}function a(){T.point=n;e.lineEnd()}function l(){r();T.point=u;T.lineEnd=c}function u(t,e){o(f=t,h=e),d=b,p=x,g=w,m=S,v=C;T.point=o}function c(){i(b,x,y,w,S,C,d,p,f,g,m,v,s,e);T.lineEnd=a;a()}var f,h,d,p,g,m,v,y,b,x,w,S,C,T={point:n,lineStart:r,lineEnd:a,polygonStart:function(){e.polygonStart();T.lineStart=l},polygonEnd:function(){e.polygonEnd();T.lineStart=r}};return T}function i(e,n,r,s,l,u,c,f,h,d,p,g,m,v){var y=c-e,b=f-n,x=y*y+b*b;if(x>4*o&&m--){var w=s+d,S=l+p,C=u+g,T=Math.sqrt(w*w+S*S+C*C),_=Math.asin(C/=T),k=fs(fs(C)-1)<Es||fs(r-h)<Es?(r+h)/2:Math.atan2(S,w),M=t(k,_),D=M[0],L=M[1],A=D-e,N=L-n,E=b*A-y*N;if(E*E/x>o||fs((y*A+b*N)/x-.5)>.3||a>s*d+l*p+u*g){i(e,n,r,s,l,u,D,L,k,w/=T,S/=T,C,m,v);v.point(D,L);i(D,L,k,w,S,C,c,f,h,d,p,g,m,v)}}}var o=.5,a=Math.cos(30*Is),s=16;e.precision=function(t){if(!arguments.length)return Math.sqrt(o);s=(o=t*t)>0&&16;return e};return e}function ir(t){var e=rr(function(e,n){return t([e*Ps,n*Ps])});return function(t){return ur(e(t))}}function or(t){this.stream=t}function ar(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function sr(t){return lr(function(){return t})()}function lr(t){function e(t){t=s(t[0]*Is,t[1]*Is);return[t[0]*h+l,u-t[1]*h]}function n(t){t=s.invert((t[0]-l)/h,(u-t[1])/h);return t&&[t[0]*Ps,t[1]*Ps]}function r(){s=Vn(a=hr(v,y,b),o);var t=o(g,m);l=d-t[0]*h;u=p+t[1]*h;return i()}function i(){c&&(c.valid=!1,c=null);return e}var o,a,s,l,u,c,f=rr(function(t,e){t=o(t,e);return[t[0]*h+l,u-t[1]*h]}),h=150,d=480,p=250,g=0,m=0,v=0,y=0,b=0,x=Nl,w=De,S=null,C=null;e.stream=function(t){c&&(c.valid=!1);c=ur(x(a,f(w(t))));c.valid=!0;return c};e.clipAngle=function(t){if(!arguments.length)return S;x=null==t?(S=t,Nl):qn((S=+t)*Is);return i()};e.clipExtent=function(t){if(!arguments.length)return C;C=t;w=t?Bn(t[0][0],t[0][1],t[1][0],t[1][1]):De;return i()};e.scale=function(t){if(!arguments.length)return h;h=+t;return r()};e.translate=function(t){if(!arguments.length)return[d,p];d=+t[0];p=+t[1];return r()};e.center=function(t){if(!arguments.length)return[g*Ps,m*Ps];g=t[0]%360*Is;m=t[1]%360*Is;return r()};e.rotate=function(t){if(!arguments.length)return[v*Ps,y*Ps,b*Ps];v=t[0]%360*Is;y=t[1]%360*Is;b=t.length>2?t[2]%360*Is:0;return r()};Ka.rebind(e,f,"precision");return function(){o=t.apply(this,arguments);e.invert=o.invert&&n;return r()}}function ur(t){return ar(t,function(e,n){t.point(e*Is,n*Is)})}function cr(t,e){return[t,e]}function fr(t,e){return[t>Ls?t-As:-Ls>t?t+As:t,e]}function hr(t,e,n){return t?e||n?Vn(pr(t),gr(e,n)):pr(t):e||n?gr(e,n):fr}function dr(t){return function(e,n){return e+=t,[e>Ls?e-As:-Ls>e?e+As:e,n]}}function pr(t){var e=dr(t);e.invert=dr(-t);return e}function gr(t,e){function n(t,e){var n=Math.cos(e),s=Math.cos(t)*n,l=Math.sin(t)*n,u=Math.sin(e),c=u*r+s*i;return[Math.atan2(l*o-c*a,s*r-u*i),ne(c*o+l*a)]}var r=Math.cos(t),i=Math.sin(t),o=Math.cos(e),a=Math.sin(e);n.invert=function(t,e){var n=Math.cos(e),s=Math.cos(t)*n,l=Math.sin(t)*n,u=Math.sin(e),c=u*o-l*a;return[Math.atan2(l*o+u*a,s*r+c*i),ne(c*r-s*i)]};return n}function mr(t,e){var n=Math.cos(t),r=Math.sin(t);return function(i,o,a,s){var l=a*e;if(null!=i){i=vr(n,i);o=vr(n,o);(a>0?o>i:i>o)&&(i+=a*As)}else{i=t+a*As;o=t-.5*l}for(var u,c=i;a>0?c>o:o>c;c-=l)s.point((u=Cn([n,-r*Math.cos(c),-r*Math.sin(c)]))[0],u[1])}}function vr(t,e){var n=vn(e);n[0]-=t;Sn(n);var r=ee(-n[1]);return((-n[2]<0?-r:r)+2*Math.PI-Es)%(2*Math.PI)}function yr(t,e,n){var r=Ka.range(t,e-Es,n).concat(e);return function(t){return r.map(function(e){return[t,e]})}}function br(t,e,n){var r=Ka.range(t,e-Es,n).concat(e);
return function(t){return r.map(function(e){return[e,t]})}}function xr(t){return t.source}function wr(t){return t.target}function Sr(t,e,n,r){var i=Math.cos(e),o=Math.sin(e),a=Math.cos(r),s=Math.sin(r),l=i*Math.cos(t),u=i*Math.sin(t),c=a*Math.cos(n),f=a*Math.sin(n),h=2*Math.asin(Math.sqrt(ae(r-e)+i*a*ae(n-t))),d=1/Math.sin(h),p=h?function(t){var e=Math.sin(t*=h)*d,n=Math.sin(h-t)*d,r=n*l+e*c,i=n*u+e*f,a=n*o+e*s;return[Math.atan2(i,r)*Ps,Math.atan2(a,Math.sqrt(r*r+i*i))*Ps]}:function(){return[t*Ps,e*Ps]};p.distance=h;return p}function Cr(){function t(t,i){var o=Math.sin(i*=Is),a=Math.cos(i),s=fs((t*=Is)-e),l=Math.cos(s);ql+=Math.atan2(Math.sqrt((s=a*Math.sin(s))*s+(s=r*o-n*a*l)*s),n*o+r*a*l);e=t,n=o,r=a}var e,n,r;Ul.point=function(i,o){e=i*Is,n=Math.sin(o*=Is),r=Math.cos(o);Ul.point=t};Ul.lineEnd=function(){Ul.point=Ul.lineEnd=x}}function Tr(t,e){function n(e,n){var r=Math.cos(e),i=Math.cos(n),o=t(r*i);return[o*i*Math.sin(e),o*Math.sin(n)]}n.invert=function(t,n){var r=Math.sqrt(t*t+n*n),i=e(r),o=Math.sin(i),a=Math.cos(i);return[Math.atan2(t*o,r*a),Math.asin(r&&n*o/r)]};return n}function _r(t,e){function n(t,e){a>0?-Ns+Es>e&&(e=-Ns+Es):e>Ns-Es&&(e=Ns-Es);var n=a/Math.pow(i(e),o);return[n*Math.sin(o*t),a-n*Math.cos(o*t)]}var r=Math.cos(t),i=function(t){return Math.tan(Ls/4+t/2)},o=t===e?Math.sin(t):Math.log(r/Math.cos(e))/Math.log(i(e)/i(t)),a=r*Math.pow(i(t),o)/o;if(!o)return Mr;n.invert=function(t,e){var n=a-e,r=Q(o)*Math.sqrt(t*t+n*n);return[Math.atan2(t,n)/o,2*Math.atan(Math.pow(a/r,1/o))-Ns]};return n}function kr(t,e){function n(t,e){var n=o-e;return[n*Math.sin(i*t),o-n*Math.cos(i*t)]}var r=Math.cos(t),i=t===e?Math.sin(t):(r-Math.cos(e))/(e-t),o=r/i+t;if(fs(i)<Es)return cr;n.invert=function(t,e){var n=o-e;return[Math.atan2(t,n)/i,o-Q(i)*Math.sqrt(t*t+n*n)]};return n}function Mr(t,e){return[t,Math.log(Math.tan(Ls/4+e/2))]}function Dr(t){var e,n=sr(t),r=n.scale,i=n.translate,o=n.clipExtent;n.scale=function(){var t=r.apply(n,arguments);return t===n?e?n.clipExtent(null):n:t};n.translate=function(){var t=i.apply(n,arguments);return t===n?e?n.clipExtent(null):n:t};n.clipExtent=function(t){var a=o.apply(n,arguments);if(a===n){if(e=null==t){var s=Ls*r(),l=i();o([[l[0]-s,l[1]-s],[l[0]+s,l[1]+s]])}}else e&&(a=null);return a};return n.clipExtent(null)}function Lr(t,e){return[Math.log(Math.tan(Ls/4+e/2)),-t]}function Ar(t){return t[0]}function Nr(t){return t[1]}function Er(t){for(var e=t.length,n=[0,1],r=2,i=2;e>i;i++){for(;r>1&&te(t[n[r-2]],t[n[r-1]],t[i])<=0;)--r;n[r++]=i}return n.slice(0,r)}function jr(t,e){return t[0]-e[0]||t[1]-e[1]}function Ir(t,e,n){return(n[0]-e[0])*(t[1]-e[1])<(n[1]-e[1])*(t[0]-e[0])}function Pr(t,e,n,r){var i=t[0],o=n[0],a=e[0]-i,s=r[0]-o,l=t[1],u=n[1],c=e[1]-l,f=r[1]-u,h=(s*(l-u)-f*(i-o))/(f*a-s*c);return[i+h*a,l+h*c]}function Hr(t){var e=t[0],n=t[t.length-1];return!(e[0]-n[0]||e[1]-n[1])}function Or(){ii(this);this.edge=this.site=this.circle=null}function Fr(t){var e=eu.pop()||new Or;e.site=t;return e}function Rr(t){Yr(t);Zl.remove(t);eu.push(t);ii(t)}function Wr(t){var e=t.circle,n=e.x,r=e.cy,i={x:n,y:r},o=t.P,a=t.N,s=[t];Rr(t);for(var l=o;l.circle&&fs(n-l.circle.x)<Es&&fs(r-l.circle.cy)<Es;){o=l.P;s.unshift(l);Rr(l);l=o}s.unshift(l);Yr(l);for(var u=a;u.circle&&fs(n-u.circle.x)<Es&&fs(r-u.circle.cy)<Es;){a=u.N;s.push(u);Rr(u);u=a}s.push(u);Yr(u);var c,f=s.length;for(c=1;f>c;++c){u=s[c];l=s[c-1];ei(u.edge,l.site,u.site,i)}l=s[0];u=s[f-1];u.edge=Qr(l.site,u.site,null,i);$r(l);$r(u)}function zr(t){for(var e,n,r,i,o=t.x,a=t.y,s=Zl._;s;){r=qr(s,a)-o;if(r>Es)s=s.L;else{i=o-Ur(s,a);if(!(i>Es)){if(r>-Es){e=s.P;n=s}else if(i>-Es){e=s;n=s.N}else e=n=s;break}if(!s.R){e=s;break}s=s.R}}var l=Fr(t);Zl.insert(e,l);if(e||n)if(e!==n)if(n){Yr(e);Yr(n);var u=e.site,c=u.x,f=u.y,h=t.x-c,d=t.y-f,p=n.site,g=p.x-c,m=p.y-f,v=2*(h*m-d*g),y=h*h+d*d,b=g*g+m*m,x={x:(m*y-d*b)/v+c,y:(h*b-g*y)/v+f};ei(n.edge,u,p,x);l.edge=Qr(u,t,null,x);n.edge=Qr(t,p,null,x);$r(e);$r(n)}else l.edge=Qr(e.site,l.site);else{Yr(e);n=Fr(e.site);Zl.insert(l,n);l.edge=n.edge=Qr(e.site,l.site);$r(e);$r(n)}}function qr(t,e){var n=t.site,r=n.x,i=n.y,o=i-e;if(!o)return r;var a=t.P;if(!a)return-1/0;n=a.site;var s=n.x,l=n.y,u=l-e;if(!u)return s;var c=s-r,f=1/o-1/u,h=c/u;return f?(-h+Math.sqrt(h*h-2*f*(c*c/(-2*u)-l+u/2+i-o/2)))/f+r:(r+s)/2}function Ur(t,e){var n=t.N;if(n)return qr(n,e);var r=t.site;return r.y===e?r.x:1/0}function Br(t){this.site=t;this.edges=[]}function Vr(t){for(var e,n,r,i,o,a,s,l,u,c,f=t[0][0],h=t[1][0],d=t[0][1],p=t[1][1],g=Kl,m=g.length;m--;){o=g[m];if(o&&o.prepare()){s=o.edges;l=s.length;a=0;for(;l>a;){c=s[a].end(),r=c.x,i=c.y;u=s[++a%l].start(),e=u.x,n=u.y;if(fs(r-e)>Es||fs(i-n)>Es){s.splice(a,0,new ni(ti(o.site,c,fs(r-f)<Es&&p-i>Es?{x:f,y:fs(e-f)<Es?n:p}:fs(i-p)<Es&&h-r>Es?{x:fs(n-p)<Es?e:h,y:p}:fs(r-h)<Es&&i-d>Es?{x:h,y:fs(e-h)<Es?n:d}:fs(i-d)<Es&&r-f>Es?{x:fs(n-d)<Es?e:f,y:d}:null),o.site,null));++l}}}}}function Xr(t,e){return e.angle-t.angle}function Gr(){ii(this);this.x=this.y=this.arc=this.site=this.cy=null}function $r(t){var e=t.P,n=t.N;if(e&&n){var r=e.site,i=t.site,o=n.site;if(r!==o){var a=i.x,s=i.y,l=r.x-a,u=r.y-s,c=o.x-a,f=o.y-s,h=2*(l*f-u*c);if(!(h>=-js)){var d=l*l+u*u,p=c*c+f*f,g=(f*d-u*p)/h,m=(l*p-c*d)/h,f=m+s,v=nu.pop()||new Gr;v.arc=t;v.site=i;v.x=g+a;v.y=f+Math.sqrt(g*g+m*m);v.cy=f;t.circle=v;for(var y=null,b=tu._;b;)if(v.y<b.y||v.y===b.y&&v.x<=b.x){if(!b.L){y=b.P;break}b=b.L}else{if(!b.R){y=b;break}b=b.R}tu.insert(y,v);y||(Ql=v)}}}}function Yr(t){var e=t.circle;if(e){e.P||(Ql=e.N);tu.remove(e);nu.push(e);ii(e);t.circle=null}}function Jr(t){for(var e,n=Jl,r=Un(t[0][0],t[0][1],t[1][0],t[1][1]),i=n.length;i--;){e=n[i];if(!Kr(e,t)||!r(e)||fs(e.a.x-e.b.x)<Es&&fs(e.a.y-e.b.y)<Es){e.a=e.b=null;n.splice(i,1)}}}function Kr(t,e){var n=t.b;if(n)return!0;var r,i,o=t.a,a=e[0][0],s=e[1][0],l=e[0][1],u=e[1][1],c=t.l,f=t.r,h=c.x,d=c.y,p=f.x,g=f.y,m=(h+p)/2,v=(d+g)/2;if(g===d){if(a>m||m>=s)return;if(h>p){if(o){if(o.y>=u)return}else o={x:m,y:l};n={x:m,y:u}}else{if(o){if(o.y<l)return}else o={x:m,y:u};n={x:m,y:l}}}else{r=(h-p)/(g-d);i=v-r*m;if(-1>r||r>1)if(h>p){if(o){if(o.y>=u)return}else o={x:(l-i)/r,y:l};n={x:(u-i)/r,y:u}}else{if(o){if(o.y<l)return}else o={x:(u-i)/r,y:u};n={x:(l-i)/r,y:l}}else if(g>d){if(o){if(o.x>=s)return}else o={x:a,y:r*a+i};n={x:s,y:r*s+i}}else{if(o){if(o.x<a)return}else o={x:s,y:r*s+i};n={x:a,y:r*a+i}}}t.a=o;t.b=n;return!0}function Zr(t,e){this.l=t;this.r=e;this.a=this.b=null}function Qr(t,e,n,r){var i=new Zr(t,e);Jl.push(i);n&&ei(i,t,e,n);r&&ei(i,e,t,r);Kl[t.i].edges.push(new ni(i,t,e));Kl[e.i].edges.push(new ni(i,e,t));return i}function ti(t,e,n){var r=new Zr(t,null);r.a=e;r.b=n;Jl.push(r);return r}function ei(t,e,n,r){if(t.a||t.b)t.l===n?t.b=r:t.a=r;else{t.a=r;t.l=e;t.r=n}}function ni(t,e,n){var r=t.a,i=t.b;this.edge=t;this.site=e;this.angle=n?Math.atan2(n.y-e.y,n.x-e.x):t.l===e?Math.atan2(i.x-r.x,r.y-i.y):Math.atan2(r.x-i.x,i.y-r.y)}function ri(){this._=null}function ii(t){t.U=t.C=t.L=t.R=t.P=t.N=null}function oi(t,e){var n=e,r=e.R,i=n.U;i?i.L===n?i.L=r:i.R=r:t._=r;r.U=i;n.U=r;n.R=r.L;n.R&&(n.R.U=n);r.L=n}function ai(t,e){var n=e,r=e.L,i=n.U;i?i.L===n?i.L=r:i.R=r:t._=r;r.U=i;n.U=r;n.L=r.R;n.L&&(n.L.U=n);r.R=n}function si(t){for(;t.L;)t=t.L;return t}function li(t,e){var n,r,i,o=t.sort(ui).pop();Jl=[];Kl=new Array(t.length);Zl=new ri;tu=new ri;for(;;){i=Ql;if(o&&(!i||o.y<i.y||o.y===i.y&&o.x<i.x)){if(o.x!==n||o.y!==r){Kl[o.i]=new Br(o);zr(o);n=o.x,r=o.y}o=t.pop()}else{if(!i)break;Wr(i.arc)}}e&&(Jr(e),Vr(e));var a={cells:Kl,edges:Jl};Zl=tu=Jl=Kl=null;return a}function ui(t,e){return e.y-t.y||e.x-t.x}function ci(t,e,n){return(t.x-n.x)*(e.y-t.y)-(t.x-e.x)*(n.y-t.y)}function fi(t){return t.x}function hi(t){return t.y}function di(){return{leaf:!0,nodes:[],point:null,x:null,y:null}}function pi(t,e,n,r,i,o){if(!t(e,n,r,i,o)){var a=.5*(n+i),s=.5*(r+o),l=e.nodes;l[0]&&pi(t,l[0],n,r,a,s);l[1]&&pi(t,l[1],a,r,i,s);l[2]&&pi(t,l[2],n,s,a,o);l[3]&&pi(t,l[3],a,s,i,o)}}function gi(t,e){t=Ka.rgb(t);e=Ka.rgb(e);var n=t.r,r=t.g,i=t.b,o=e.r-n,a=e.g-r,s=e.b-i;return function(t){return"#"+we(Math.round(n+o*t))+we(Math.round(r+a*t))+we(Math.round(i+s*t))}}function mi(t,e){var n,r={},i={};for(n in t)n in e?r[n]=bi(t[n],e[n]):i[n]=t[n];for(n in e)n in t||(i[n]=e[n]);return function(t){for(n in r)i[n]=r[n](t);return i}}function vi(t,e){t=+t,e=+e;return function(n){return t*(1-n)+e*n}}function yi(t,e){var n,r,i,o=iu.lastIndex=ou.lastIndex=0,a=-1,s=[],l=[];t+="",e+="";for(;(n=iu.exec(t))&&(r=ou.exec(e));){if((i=r.index)>o){i=e.slice(o,i);s[a]?s[a]+=i:s[++a]=i}if((n=n[0])===(r=r[0]))s[a]?s[a]+=r:s[++a]=r;else{s[++a]=null;l.push({i:a,x:vi(n,r)})}o=ou.lastIndex}if(o<e.length){i=e.slice(o);s[a]?s[a]+=i:s[++a]=i}return s.length<2?l[0]?(e=l[0].x,function(t){return e(t)+""}):function(){return e}:(e=l.length,function(t){for(var n,r=0;e>r;++r)s[(n=l[r]).i]=n.x(t);return s.join("")})}function bi(t,e){for(var n,r=Ka.interpolators.length;--r>=0&&!(n=Ka.interpolators[r](t,e)););return n}function xi(t,e){var n,r=[],i=[],o=t.length,a=e.length,s=Math.min(t.length,e.length);for(n=0;s>n;++n)r.push(bi(t[n],e[n]));for(;o>n;++n)i[n]=t[n];for(;a>n;++n)i[n]=e[n];return function(t){for(n=0;s>n;++n)i[n]=r[n](t);return i}}function wi(t){return function(e){return 0>=e?0:e>=1?1:t(e)}}function Si(t){return function(e){return 1-t(1-e)}}function Ci(t){return function(e){return.5*(.5>e?t(2*e):2-t(2-2*e))}}function Ti(t){return t*t}function _i(t){return t*t*t}function ki(t){if(0>=t)return 0;if(t>=1)return 1;var e=t*t,n=e*t;return 4*(.5>t?n:3*(t-e)+n-.75)}function Mi(t){return function(e){return Math.pow(e,t)}}function Di(t){return 1-Math.cos(t*Ns)}function Li(t){return Math.pow(2,10*(t-1))}function Ai(t){return 1-Math.sqrt(1-t*t)}function Ni(t,e){var n;arguments.length<2&&(e=.45);arguments.length?n=e/As*Math.asin(1/t):(t=1,n=e/4);return function(r){return 1+t*Math.pow(2,-10*r)*Math.sin((r-n)*As/e)}}function Ei(t){t||(t=1.70158);return function(e){return e*e*((t+1)*e-t)}}function ji(t){return 1/2.75>t?7.5625*t*t:2/2.75>t?7.5625*(t-=1.5/2.75)*t+.75:2.5/2.75>t?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}function Ii(t,e){t=Ka.hcl(t);e=Ka.hcl(e);var n=t.h,r=t.c,i=t.l,o=e.h-n,a=e.c-r,s=e.l-i;isNaN(a)&&(a=0,r=isNaN(r)?e.c:r);isNaN(o)?(o=0,n=isNaN(n)?e.h:n):o>180?o-=360:-180>o&&(o+=360);return function(t){return fe(n+o*t,r+a*t,i+s*t)+""}}function Pi(t,e){t=Ka.hsl(t);e=Ka.hsl(e);var n=t.h,r=t.s,i=t.l,o=e.h-n,a=e.s-r,s=e.l-i;isNaN(a)&&(a=0,r=isNaN(r)?e.s:r);isNaN(o)?(o=0,n=isNaN(n)?e.h:n):o>180?o-=360:-180>o&&(o+=360);return function(t){return ue(n+o*t,r+a*t,i+s*t)+""}}function Hi(t,e){t=Ka.lab(t);e=Ka.lab(e);var n=t.l,r=t.a,i=t.b,o=e.l-n,a=e.a-r,s=e.b-i;return function(t){return de(n+o*t,r+a*t,i+s*t)+""}}function Oi(t,e){e-=t;return function(n){return Math.round(t+e*n)}}function Fi(t){var e=[t.a,t.b],n=[t.c,t.d],r=Wi(e),i=Ri(e,n),o=Wi(zi(n,e,-i))||0;if(e[0]*n[1]<n[0]*e[1]){e[0]*=-1;e[1]*=-1;r*=-1;i*=-1}this.rotate=(r?Math.atan2(e[1],e[0]):Math.atan2(-n[0],n[1]))*Ps;this.translate=[t.e,t.f];this.scale=[r,o];this.skew=o?Math.atan2(i,o)*Ps:0}function Ri(t,e){return t[0]*e[0]+t[1]*e[1]}function Wi(t){var e=Math.sqrt(Ri(t,t));if(e){t[0]/=e;t[1]/=e}return e}function zi(t,e,n){t[0]+=n*e[0];t[1]+=n*e[1];return t}function qi(t,e){var n,r=[],i=[],o=Ka.transform(t),a=Ka.transform(e),s=o.translate,l=a.translate,u=o.rotate,c=a.rotate,f=o.skew,h=a.skew,d=o.scale,p=a.scale;if(s[0]!=l[0]||s[1]!=l[1]){r.push("translate(",null,",",null,")");i.push({i:1,x:vi(s[0],l[0])},{i:3,x:vi(s[1],l[1])})}else r.push(l[0]||l[1]?"translate("+l+")":"");if(u!=c){u-c>180?c+=360:c-u>180&&(u+=360);i.push({i:r.push(r.pop()+"rotate(",null,")")-2,x:vi(u,c)})}else c&&r.push(r.pop()+"rotate("+c+")");f!=h?i.push({i:r.push(r.pop()+"skewX(",null,")")-2,x:vi(f,h)}):h&&r.push(r.pop()+"skewX("+h+")");if(d[0]!=p[0]||d[1]!=p[1]){n=r.push(r.pop()+"scale(",null,",",null,")");i.push({i:n-4,x:vi(d[0],p[0])},{i:n-2,x:vi(d[1],p[1])})}else(1!=p[0]||1!=p[1])&&r.push(r.pop()+"scale("+p+")");n=i.length;return function(t){for(var e,o=-1;++o<n;)r[(e=i[o]).i]=e.x(t);return r.join("")}}function Ui(t,e){e=(e-=t=+t)||1/e;return function(n){return(n-t)/e}}function Bi(t,e){e=(e-=t=+t)||1/e;return function(n){return Math.max(0,Math.min(1,(n-t)/e))}}function Vi(t){for(var e=t.source,n=t.target,r=Gi(e,n),i=[e];e!==r;){e=e.parent;i.push(e)}for(var o=i.length;n!==r;){i.splice(o,0,n);n=n.parent}return i}function Xi(t){for(var e=[],n=t.parent;null!=n;){e.push(t);t=n;n=n.parent}e.push(t);return e}function Gi(t,e){if(t===e)return t;for(var n=Xi(t),r=Xi(e),i=n.pop(),o=r.pop(),a=null;i===o;){a=i;i=n.pop();o=r.pop()}return a}function $i(t){t.fixed|=2}function Yi(t){t.fixed&=-7}function Ji(t){t.fixed|=4;t.px=t.x,t.py=t.y}function Ki(t){t.fixed&=-5}function Zi(t,e,n){var r=0,i=0;t.charge=0;if(!t.leaf)for(var o,a=t.nodes,s=a.length,l=-1;++l<s;){o=a[l];if(null!=o){Zi(o,e,n);t.charge+=o.charge;r+=o.charge*o.cx;i+=o.charge*o.cy}}if(t.point){if(!t.leaf){t.point.x+=Math.random()-.5;t.point.y+=Math.random()-.5}var u=e*n[t.point.index];t.charge+=t.pointCharge=u;r+=u*t.point.x;i+=u*t.point.y}t.cx=r/t.charge;t.cy=i/t.charge}function Qi(t,e){Ka.rebind(t,e,"sort","children","value");t.nodes=t;t.links=oo;return t}function to(t,e){for(var n=[t];null!=(t=n.pop());){e(t);if((i=t.children)&&(r=i.length))for(var r,i;--r>=0;)n.push(i[r])}}function eo(t,e){for(var n=[t],r=[];null!=(t=n.pop());){r.push(t);if((o=t.children)&&(i=o.length))for(var i,o,a=-1;++a<i;)n.push(o[a])}for(;null!=(t=r.pop());)e(t)}function no(t){return t.children}function ro(t){return t.value}function io(t,e){return e.value-t.value}function oo(t){return Ka.merge(t.map(function(t){return(t.children||[]).map(function(e){return{source:t,target:e}})}))}function ao(t){return t.x}function so(t){return t.y}function lo(t,e,n){t.y0=e;t.y=n}function uo(t){return Ka.range(t.length)}function co(t){for(var e=-1,n=t[0].length,r=[];++e<n;)r[e]=0;return r}function fo(t){for(var e,n=1,r=0,i=t[0][1],o=t.length;o>n;++n)if((e=t[n][1])>i){r=n;i=e}return r}function ho(t){return t.reduce(po,0)}function po(t,e){return t+e[1]}function go(t,e){return mo(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function mo(t,e){for(var n=-1,r=+t[0],i=(t[1]-r)/e,o=[];++n<=e;)o[n]=i*n+r;return o}function vo(t){return[Ka.min(t),Ka.max(t)]}function yo(t,e){return t.value-e.value}function bo(t,e){var n=t._pack_next;t._pack_next=e;e._pack_prev=t;e._pack_next=n;n._pack_prev=e}function xo(t,e){t._pack_next=e;e._pack_prev=t}function wo(t,e){var n=e.x-t.x,r=e.y-t.y,i=t.r+e.r;return.999*i*i>n*n+r*r}function So(t){function e(t){c=Math.min(t.x-t.r,c);f=Math.max(t.x+t.r,f);h=Math.min(t.y-t.r,h);d=Math.max(t.y+t.r,d)}if((n=t.children)&&(u=n.length)){var n,r,i,o,a,s,l,u,c=1/0,f=-1/0,h=1/0,d=-1/0;n.forEach(Co);r=n[0];r.x=-r.r;r.y=0;e(r);if(u>1){i=n[1];i.x=i.r;i.y=0;e(i);if(u>2){o=n[2];ko(r,i,o);e(o);bo(r,o);r._pack_prev=o;bo(o,i);i=r._pack_next;for(a=3;u>a;a++){ko(r,i,o=n[a]);var p=0,g=1,m=1;for(s=i._pack_next;s!==i;s=s._pack_next,g++)if(wo(s,o)){p=1;break}if(1==p)for(l=r._pack_prev;l!==s._pack_prev&&!wo(l,o);l=l._pack_prev,m++);if(p){m>g||g==m&&i.r<r.r?xo(r,i=s):xo(r=l,i);a--}else{bo(r,o);i=o;e(o)}}}}var v=(c+f)/2,y=(h+d)/2,b=0;for(a=0;u>a;a++){o=n[a];o.x-=v;o.y-=y;b=Math.max(b,o.r+Math.sqrt(o.x*o.x+o.y*o.y))}t.r=b;n.forEach(To)}}function Co(t){t._pack_next=t._pack_prev=t}function To(t){delete t._pack_next;delete t._pack_prev}function _o(t,e,n,r){var i=t.children;t.x=e+=r*t.x;t.y=n+=r*t.y;t.r*=r;if(i)for(var o=-1,a=i.length;++o<a;)_o(i[o],e,n,r)}function ko(t,e,n){var r=t.r+n.r,i=e.x-t.x,o=e.y-t.y;if(r&&(i||o)){var a=e.r+n.r,s=i*i+o*o;a*=a;r*=r;var l=.5+(r-a)/(2*s),u=Math.sqrt(Math.max(0,2*a*(r+s)-(r-=s)*r-a*a))/(2*s);n.x=t.x+l*i+u*o;n.y=t.y+l*o-u*i}else{n.x=t.x+r;n.y=t.y}}function Mo(t,e){return t.parent==e.parent?1:2}function Do(t){var e=t.children;return e.length?e[0]:t.t}function Lo(t){var e,n=t.children;return(e=n.length)?n[e-1]:t.t}function Ao(t,e,n){var r=n/(e.i-t.i);e.c-=r;e.s+=n;t.c+=r;e.z+=n;e.m+=n}function No(t){for(var e,n=0,r=0,i=t.children,o=i.length;--o>=0;){e=i[o];e.z+=n;e.m+=n;n+=e.s+(r+=e.c)}}function Eo(t,e,n){return t.a.parent===e.parent?t.a:n}function jo(t){return 1+Ka.max(t,function(t){return t.y})}function Io(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}function Po(t){var e=t.children;return e&&e.length?Po(e[0]):t}function Ho(t){var e,n=t.children;return n&&(e=n.length)?Ho(n[e-1]):t}function Oo(t){return{x:t.x,y:t.y,dx:t.dx,dy:t.dy}}function Fo(t,e){var n=t.x+e[3],r=t.y+e[0],i=t.dx-e[1]-e[3],o=t.dy-e[0]-e[2];if(0>i){n+=i/2;i=0}if(0>o){r+=o/2;o=0}return{x:n,y:r,dx:i,dy:o}}function Ro(t){var e=t[0],n=t[t.length-1];return n>e?[e,n]:[n,e]}function Wo(t){return t.rangeExtent?t.rangeExtent():Ro(t.range())}function zo(t,e,n,r){var i=n(t[0],t[1]),o=r(e[0],e[1]);return function(t){return o(i(t))}}function qo(t,e){var n,r=0,i=t.length-1,o=t[r],a=t[i];if(o>a){n=r,r=i,i=n;n=o,o=a,a=n}t[r]=e.floor(o);t[i]=e.ceil(a);return t}function Uo(t){return t?{floor:function(e){return Math.floor(e/t)*t},ceil:function(e){return Math.ceil(e/t)*t}}:mu}function Bo(t,e,n,r){var i=[],o=[],a=0,s=Math.min(t.length,e.length)-1;if(t[s]<t[0]){t=t.slice().reverse();e=e.slice().reverse()}for(;++a<=s;){i.push(n(t[a-1],t[a]));o.push(r(e[a-1],e[a]))}return function(e){var n=Ka.bisect(t,e,1,s)-1;return o[n](i[n](e))}}function Vo(t,e,n,r){function i(){var i=Math.min(t.length,e.length)>2?Bo:zo,l=r?Bi:Ui;a=i(t,e,l,n);s=i(e,t,l,bi);return o}function o(t){return a(t)}var a,s;o.invert=function(t){return s(t)};o.domain=function(e){if(!arguments.length)return t;t=e.map(Number);return i()};o.range=function(t){if(!arguments.length)return e;e=t;return i()};o.rangeRound=function(t){return o.range(t).interpolate(Oi)};o.clamp=function(t){if(!arguments.length)return r;r=t;return i()};o.interpolate=function(t){if(!arguments.length)return n;n=t;return i()};o.ticks=function(e){return Yo(t,e)};o.tickFormat=function(e,n){return Jo(t,e,n)};o.nice=function(e){Go(t,e);return i()};o.copy=function(){return Vo(t,e,n,r)};return i()}function Xo(t,e){return Ka.rebind(t,e,"range","rangeRound","interpolate","clamp")}function Go(t,e){return qo(t,Uo($o(t,e)[2]))}function $o(t,e){null==e&&(e=10);var n=Ro(t),r=n[1]-n[0],i=Math.pow(10,Math.floor(Math.log(r/e)/Math.LN10)),o=e/r*i;.15>=o?i*=10:.35>=o?i*=5:.75>=o&&(i*=2);n[0]=Math.ceil(n[0]/i)*i;n[1]=Math.floor(n[1]/i)*i+.5*i;n[2]=i;return n}function Yo(t,e){return Ka.range.apply(Ka,$o(t,e))}function Jo(t,e,n){var r=$o(t,e);if(n){var i=il.exec(n);i.shift();if("s"===i[8]){var o=Ka.formatPrefix(Math.max(fs(r[0]),fs(r[1])));i[7]||(i[7]="."+Ko(o.scale(r[2])));i[8]="f";n=Ka.format(i.join(""));return function(t){return n(o.scale(t))+o.symbol}}i[7]||(i[7]="."+Zo(i[8],r));n=i.join("")}else n=",."+Ko(r[2])+"f";return Ka.format(n)}function Ko(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}function Zo(t,e){var n=Ko(e[2]);return t in vu?Math.abs(n-Ko(Math.max(fs(e[0]),fs(e[1]))))+ +("e"!==t):n-2*("%"===t)}function Qo(t,e,n,r){function i(t){return(n?Math.log(0>t?0:t):-Math.log(t>0?0:-t))/Math.log(e)}function o(t){return n?Math.pow(e,t):-Math.pow(e,-t)}function a(e){return t(i(e))}a.invert=function(e){return o(t.invert(e))};a.domain=function(e){if(!arguments.length)return r;n=e[0]>=0;t.domain((r=e.map(Number)).map(i));return a};a.base=function(n){if(!arguments.length)return e;e=+n;t.domain(r.map(i));return a};a.nice=function(){var e=qo(r.map(i),n?Math:bu);t.domain(e);r=e.map(o);return a};a.ticks=function(){var t=Ro(r),a=[],s=t[0],l=t[1],u=Math.floor(i(s)),c=Math.ceil(i(l)),f=e%1?2:e;if(isFinite(c-u)){if(n){for(;c>u;u++)for(var h=1;f>h;h++)a.push(o(u)*h);a.push(o(u))}else{a.push(o(u));for(;u++<c;)for(var h=f-1;h>0;h--)a.push(o(u)*h)}for(u=0;a[u]<s;u++);for(c=a.length;a[c-1]>l;c--);a=a.slice(u,c)}return a};a.tickFormat=function(t,e){if(!arguments.length)return yu;arguments.length<2?e=yu:"function"!=typeof e&&(e=Ka.format(e));var r,s=Math.max(.1,t/a.ticks().length),l=n?(r=1e-12,Math.ceil):(r=-1e-12,Math.floor);return function(t){return t/o(l(i(t)+r))<=s?e(t):""}};a.copy=function(){return Qo(t.copy(),e,n,r)};return Xo(a,t)}function ta(t,e,n){function r(e){return t(i(e))}var i=ea(e),o=ea(1/e);r.invert=function(e){return o(t.invert(e))};r.domain=function(e){if(!arguments.length)return n;t.domain((n=e.map(Number)).map(i));return r};r.ticks=function(t){return Yo(n,t)};r.tickFormat=function(t,e){return Jo(n,t,e)};r.nice=function(t){return r.domain(Go(n,t))};r.exponent=function(a){if(!arguments.length)return e;i=ea(e=a);o=ea(1/e);t.domain(n.map(i));return r};r.copy=function(){return ta(t.copy(),e,n)};return Xo(r,t)}function ea(t){return function(e){return 0>e?-Math.pow(-e,t):Math.pow(e,t)}}function na(t,e){function n(n){return o[((i.get(n)||("range"===e.t?i.set(n,t.push(n)):0/0))-1)%o.length]}function r(e,n){return Ka.range(t.length).map(function(t){return e+n*t})}var i,o,a;n.domain=function(r){if(!arguments.length)return t;t=[];i=new u;for(var o,a=-1,s=r.length;++a<s;)i.has(o=r[a])||i.set(o,t.push(o));return n[e.t].apply(n,e.a)};n.range=function(t){if(!arguments.length)return o;o=t;a=0;e={t:"range",a:arguments};return n};n.rangePoints=function(i,s){arguments.length<2&&(s=0);var l=i[0],u=i[1],c=(u-l)/(Math.max(1,t.length-1)+s);o=r(t.length<2?(l+u)/2:l+c*s/2,c);a=0;e={t:"rangePoints",a:arguments};return n};n.rangeBands=function(i,s,l){arguments.length<2&&(s=0);arguments.length<3&&(l=s);var u=i[1]<i[0],c=i[u-0],f=i[1-u],h=(f-c)/(t.length-s+2*l);o=r(c+h*l,h);u&&o.reverse();a=h*(1-s);e={t:"rangeBands",a:arguments};return n};n.rangeRoundBands=function(i,s,l){arguments.length<2&&(s=0);arguments.length<3&&(l=s);var u=i[1]<i[0],c=i[u-0],f=i[1-u],h=Math.floor((f-c)/(t.length-s+2*l)),d=f-c-(t.length-s)*h;o=r(c+Math.round(d/2),h);u&&o.reverse();a=Math.round(h*(1-s));e={t:"rangeRoundBands",a:arguments};return n};n.rangeBand=function(){return a};n.rangeExtent=function(){return Ro(e.a[0])};n.copy=function(){return na(t,e)};return n.domain(t)}function ra(t,n){function o(){var e=0,r=n.length;s=[];for(;++e<r;)s[e-1]=Ka.quantile(t,e/r);return a}function a(t){return isNaN(t=+t)?void 0:n[Ka.bisect(s,t)]}var s;a.domain=function(n){if(!arguments.length)return t;t=n.map(r).filter(i).sort(e);return o()};a.range=function(t){if(!arguments.length)return n;n=t;return o()};a.quantiles=function(){return s};a.invertExtent=function(e){e=n.indexOf(e);return 0>e?[0/0,0/0]:[e>0?s[e-1]:t[0],e<s.length?s[e]:t[t.length-1]]};a.copy=function(){return ra(t,n)};return o()}function ia(t,e,n){function r(e){return n[Math.max(0,Math.min(a,Math.floor(o*(e-t))))]}function i(){o=n.length/(e-t);a=n.length-1;return r}var o,a;r.domain=function(n){if(!arguments.length)return[t,e];t=+n[0];e=+n[n.length-1];return i()};r.range=function(t){if(!arguments.length)return n;n=t;return i()};r.invertExtent=function(e){e=n.indexOf(e);e=0>e?0/0:e/o+t;return[e,e+1/o]};r.copy=function(){return ia(t,e,n)};return i()}function oa(t,e){function n(n){return n>=n?e[Ka.bisect(t,n)]:void 0}n.domain=function(e){if(!arguments.length)return t;t=e;return n};n.range=function(t){if(!arguments.length)return e;e=t;return n};n.invertExtent=function(n){n=e.indexOf(n);return[t[n-1],t[n]]};n.copy=function(){return oa(t,e)};return n}function aa(t){function e(t){return+t}e.invert=e;e.domain=e.range=function(n){if(!arguments.length)return t;t=n.map(e);return e};e.ticks=function(e){return Yo(t,e)};e.tickFormat=function(e,n){return Jo(t,e,n)};e.copy=function(){return aa(t)};return e}function sa(t){return t.innerRadius}function la(t){return t.outerRadius}function ua(t){return t.startAngle}function ca(t){return t.endAngle}function fa(t){function e(e){function a(){u.push("M",o(t(c),s))}for(var l,u=[],c=[],f=-1,h=e.length,d=Me(n),p=Me(r);++f<h;)if(i.call(this,l=e[f],f))c.push([+d.call(this,l,f),+p.call(this,l,f)]);else if(c.length){a();c=[]}c.length&&a();return u.length?u.join(""):null}var n=Ar,r=Nr,i=An,o=ha,a=o.key,s=.7;e.x=function(t){if(!arguments.length)return n;n=t;return e};e.y=function(t){if(!arguments.length)return r;r=t;return e};e.defined=function(t){if(!arguments.length)return i;i=t;return e};e.interpolate=function(t){if(!arguments.length)return a;a="function"==typeof t?o=t:(o=ku.get(t)||ha).key;return e};e.tension=function(t){if(!arguments.length)return s;s=t;return e};return e}function ha(t){return t.join("L")}function da(t){return ha(t)+"Z"}function pa(t){for(var e=0,n=t.length,r=t[0],i=[r[0],",",r[1]];++e<n;)i.push("H",(r[0]+(r=t[e])[0])/2,"V",r[1]);n>1&&i.push("H",r[0]);return i.join("")}function ga(t){for(var e=0,n=t.length,r=t[0],i=[r[0],",",r[1]];++e<n;)i.push("V",(r=t[e])[1],"H",r[0]);return i.join("")}function ma(t){for(var e=0,n=t.length,r=t[0],i=[r[0],",",r[1]];++e<n;)i.push("H",(r=t[e])[0],"V",r[1]);return i.join("")}function va(t,e){return t.length<4?ha(t):t[1]+xa(t.slice(1,t.length-1),wa(t,e))}function ya(t,e){return t.length<3?ha(t):t[0]+xa((t.push(t[0]),t),wa([t[t.length-2]].concat(t,[t[1]]),e))}function ba(t,e){return t.length<3?ha(t):t[0]+xa(t,wa(t,e))}function xa(t,e){if(e.length<1||t.length!=e.length&&t.length!=e.length+2)return ha(t);var n=t.length!=e.length,r="",i=t[0],o=t[1],a=e[0],s=a,l=1;if(n){r+="Q"+(o[0]-2*a[0]/3)+","+(o[1]-2*a[1]/3)+","+o[0]+","+o[1];i=t[1];l=2}if(e.length>1){s=e[1];o=t[l];l++;r+="C"+(i[0]+a[0])+","+(i[1]+a[1])+","+(o[0]-s[0])+","+(o[1]-s[1])+","+o[0]+","+o[1];for(var u=2;u<e.length;u++,l++){o=t[l];s=e[u];r+="S"+(o[0]-s[0])+","+(o[1]-s[1])+","+o[0]+","+o[1]}}if(n){var c=t[l];r+="Q"+(o[0]+2*s[0]/3)+","+(o[1]+2*s[1]/3)+","+c[0]+","+c[1]}return r}function wa(t,e){for(var n,r=[],i=(1-e)/2,o=t[0],a=t[1],s=1,l=t.length;++s<l;){n=o;o=a;a=t[s];r.push([i*(a[0]-n[0]),i*(a[1]-n[1])])}return r}function Sa(t){if(t.length<3)return ha(t);var e=1,n=t.length,r=t[0],i=r[0],o=r[1],a=[i,i,i,(r=t[1])[0]],s=[o,o,o,r[1]],l=[i,",",o,"L",ka(Lu,a),",",ka(Lu,s)];t.push(t[n-1]);for(;++e<=n;){r=t[e];a.shift();a.push(r[0]);s.shift();s.push(r[1]);Ma(l,a,s)}t.pop();l.push("L",r);return l.join("")}function Ca(t){if(t.length<4)return ha(t);for(var e,n=[],r=-1,i=t.length,o=[0],a=[0];++r<3;){e=t[r];o.push(e[0]);a.push(e[1])}n.push(ka(Lu,o)+","+ka(Lu,a));--r;for(;++r<i;){e=t[r];o.shift();o.push(e[0]);a.shift();a.push(e[1]);Ma(n,o,a)}return n.join("")}function Ta(t){for(var e,n,r=-1,i=t.length,o=i+4,a=[],s=[];++r<4;){n=t[r%i];a.push(n[0]);s.push(n[1])}e=[ka(Lu,a),",",ka(Lu,s)];--r;for(;++r<o;){n=t[r%i];a.shift();a.push(n[0]);s.shift();s.push(n[1]);Ma(e,a,s)}return e.join("")}function _a(t,e){var n=t.length-1;if(n)for(var r,i,o=t[0][0],a=t[0][1],s=t[n][0]-o,l=t[n][1]-a,u=-1;++u<=n;){r=t[u];i=u/n;r[0]=e*r[0]+(1-e)*(o+i*s);r[1]=e*r[1]+(1-e)*(a+i*l)}return Sa(t)}function ka(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function Ma(t,e,n){t.push("C",ka(Mu,e),",",ka(Mu,n),",",ka(Du,e),",",ka(Du,n),",",ka(Lu,e),",",ka(Lu,n))}function Da(t,e){return(e[1]-t[1])/(e[0]-t[0])}function La(t){for(var e=0,n=t.length-1,r=[],i=t[0],o=t[1],a=r[0]=Da(i,o);++e<n;)r[e]=(a+(a=Da(i=o,o=t[e+1])))/2;r[e]=a;return r}function Aa(t){for(var e,n,r,i,o=[],a=La(t),s=-1,l=t.length-1;++s<l;){e=Da(t[s],t[s+1]);if(fs(e)<Es)a[s]=a[s+1]=0;else{n=a[s]/e;r=a[s+1]/e;i=n*n+r*r;if(i>9){i=3*e/Math.sqrt(i);a[s]=i*n;a[s+1]=i*r}}}s=-1;for(;++s<=l;){i=(t[Math.min(l,s+1)][0]-t[Math.max(0,s-1)][0])/(6*(1+a[s]*a[s]));o.push([i||0,a[s]*i||0])}return o}function Na(t){return t.length<3?ha(t):t[0]+xa(t,Aa(t))}function Ea(t){for(var e,n,r,i=-1,o=t.length;++i<o;){e=t[i];n=e[0];r=e[1]+Tu;e[0]=n*Math.cos(r);e[1]=n*Math.sin(r)}return t}function ja(t){function e(e){function l(){g.push("M",s(t(v),f),c,u(t(m.reverse()),f),"Z")}for(var h,d,p,g=[],m=[],v=[],y=-1,b=e.length,x=Me(n),w=Me(i),S=n===r?function(){return d}:Me(r),C=i===o?function(){return p}:Me(o);++y<b;)if(a.call(this,h=e[y],y)){m.push([d=+x.call(this,h,y),p=+w.call(this,h,y)]);v.push([+S.call(this,h,y),+C.call(this,h,y)])}else if(m.length){l();m=[];v=[]}m.length&&l();return g.length?g.join(""):null}var n=Ar,r=Ar,i=0,o=Nr,a=An,s=ha,l=s.key,u=s,c="L",f=.7;e.x=function(t){if(!arguments.length)return r;n=r=t;return e};e.x0=function(t){if(!arguments.length)return n;n=t;return e};e.x1=function(t){if(!arguments.length)return r;r=t;return e};e.y=function(t){if(!arguments.length)return o;i=o=t;return e};e.y0=function(t){if(!arguments.length)return i;i=t;return e};e.y1=function(t){if(!arguments.length)return o;o=t;return e};e.defined=function(t){if(!arguments.length)return a;a=t;return e};e.interpolate=function(t){if(!arguments.length)return l;l="function"==typeof t?s=t:(s=ku.get(t)||ha).key;u=s.reverse||s;c=s.closed?"M":"L";return e};e.tension=function(t){if(!arguments.length)return f;f=t;return e};return e}function Ia(t){return t.radius}function Pa(t){return[t.x,t.y]}function Ha(t){return function(){var e=t.apply(this,arguments),n=e[0],r=e[1]+Tu;return[n*Math.cos(r),n*Math.sin(r)]}}function Oa(){return 64}function Fa(){return"circle"}function Ra(t){var e=Math.sqrt(t/Ls);return"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+-e+"A"+e+","+e+" 0 1,1 0,"+e+"Z"}function Wa(t,e){ms(t,Pu);t.id=e;return t}function za(t,e,n,r){var i=t.id;return z(t,"function"==typeof n?function(t,o,a){t.__transition__[i].tween.set(e,r(n.call(t,t.__data__,o,a)))}:(n=r(n),function(t){t.__transition__[i].tween.set(e,n)}))}function qa(t){null==t&&(t="");return function(){this.textContent=t}}function Ua(t,e,n,r){var i=t.__transition__||(t.__transition__={active:0,count:0}),o=i[n];if(!o){var a=r.time;o=i[n]={tween:new u,time:a,ease:r.ease,delay:r.delay,duration:r.duration};++i.count;Ka.timer(function(r){function s(r){if(i.active>n)return u();i.active=n;o.event&&o.event.start.call(t,c,e);o.tween.forEach(function(n,r){(r=r.call(t,c,e))&&g.push(r)});Ka.timer(function(){p.c=l(r||1)?An:l;return 1},0,a)}function l(r){if(i.active!==n)return u();for(var a=r/d,s=f(a),l=g.length;l>0;)g[--l].call(t,s);if(a>=1){o.event&&o.event.end.call(t,c,e);return u()}}function u(){--i.count?delete i[n]:delete t.__transition__;return 1}var c=t.__data__,f=o.ease,h=o.delay,d=o.duration,p=el,g=[];p.t=h+a;if(r>=h)return s(r-h);p.c=s;return void 0},0,a)}}function Ba(t,e,n){t.attr("transform",function(t){var r=e(t);return"translate("+(isFinite(r)?r:n(t))+",0)"})}function Va(t,e,n){t.attr("transform",function(t){var r=e(t);return"translate(0,"+(isFinite(r)?r:n(t))+")"})}function Xa(t){return t.toISOString()}function Ga(t,e,n){function r(e){return t(e)}function i(t,n){var r=t[1]-t[0],i=r/n,o=Ka.bisect(Bu,i);return o==Bu.length?[e.year,$o(t.map(function(t){return t/31536e6}),n)[2]]:o?e[i/Bu[o-1]<Bu[o]/i?o-1:o]:[Gu,$o(t,n)[2]]}r.invert=function(e){return $a(t.invert(e))};r.domain=function(e){if(!arguments.length)return t.domain().map($a);t.domain(e);return r};r.nice=function(t,e){function n(n){return!isNaN(n)&&!t.range(n,$a(+n+1),e).length}var o=r.domain(),a=Ro(o),s=null==t?i(a,10):"number"==typeof t&&i(a,t);s&&(t=s[0],e=s[1]);return r.domain(qo(o,e>1?{floor:function(e){for(;n(e=t.floor(e));)e=$a(e-1);return e},ceil:function(e){for(;n(e=t.ceil(e));)e=$a(+e+1);return e}}:t))};r.ticks=function(t,e){var n=Ro(r.domain()),o=null==t?i(n,10):"number"==typeof t?i(n,t):!t.range&&[{range:t},e];o&&(t=o[0],e=o[1]);return t.range(n[0],$a(+n[1]+1),1>e?1:e)};r.tickFormat=function(){return n};r.copy=function(){return Ga(t.copy(),e,n)};return Xo(r,t)}function $a(t){return new Date(t)}function Ya(t){return JSON.parse(t.responseText)}function Ja(t){var e=ts.createRange();e.selectNode(ts.body);return e.createContextualFragment(t.responseText)}var Ka={version:"3.4.13"};Date.now||(Date.now=function(){return+new Date});var Za=[].slice,Qa=function(t){return Za.call(t)},ts=document,es=ts.documentElement,ns=window;try{Qa(es.childNodes)[0].nodeType}catch(rs){Qa=function(t){for(var e=t.length,n=new Array(e);e--;)n[e]=t[e];return n}}try{ts.createElement("div").style.setProperty("opacity",0,"")}catch(is){var os=ns.Element.prototype,as=os.setAttribute,ss=os.setAttributeNS,ls=ns.CSSStyleDeclaration.prototype,us=ls.setProperty;os.setAttribute=function(t,e){as.call(this,t,e+"")};os.setAttributeNS=function(t,e,n){ss.call(this,t,e,n+"")};ls.setProperty=function(t,e,n){us.call(this,t,e+"",n)}}Ka.ascending=e;Ka.descending=function(t,e){return t>e?-1:e>t?1:e>=t?0:0/0};Ka.min=function(t,e){var n,r,i=-1,o=t.length;if(1===arguments.length){for(;++i<o&&!(null!=(n=t[i])&&n>=n);)n=void 0;
for(;++i<o;)null!=(r=t[i])&&n>r&&(n=r)}else{for(;++i<o&&!(null!=(n=e.call(t,t[i],i))&&n>=n);)n=void 0;for(;++i<o;)null!=(r=e.call(t,t[i],i))&&n>r&&(n=r)}return n};Ka.max=function(t,e){var n,r,i=-1,o=t.length;if(1===arguments.length){for(;++i<o&&!(null!=(n=t[i])&&n>=n);)n=void 0;for(;++i<o;)null!=(r=t[i])&&r>n&&(n=r)}else{for(;++i<o&&!(null!=(n=e.call(t,t[i],i))&&n>=n);)n=void 0;for(;++i<o;)null!=(r=e.call(t,t[i],i))&&r>n&&(n=r)}return n};Ka.extent=function(t,e){var n,r,i,o=-1,a=t.length;if(1===arguments.length){for(;++o<a&&!(null!=(n=i=t[o])&&n>=n);)n=i=void 0;for(;++o<a;)if(null!=(r=t[o])){n>r&&(n=r);r>i&&(i=r)}}else{for(;++o<a&&!(null!=(n=i=e.call(t,t[o],o))&&n>=n);)n=void 0;for(;++o<a;)if(null!=(r=e.call(t,t[o],o))){n>r&&(n=r);r>i&&(i=r)}}return[n,i]};Ka.sum=function(t,e){var n,r=0,o=t.length,a=-1;if(1===arguments.length)for(;++a<o;)i(n=+t[a])&&(r+=n);else for(;++a<o;)i(n=+e.call(t,t[a],a))&&(r+=n);return r};Ka.mean=function(t,e){var n,o=0,a=t.length,s=-1,l=a;if(1===arguments.length)for(;++s<a;)i(n=r(t[s]))?o+=n:--l;else for(;++s<a;)i(n=r(e.call(t,t[s],s)))?o+=n:--l;return l?o/l:void 0};Ka.quantile=function(t,e){var n=(t.length-1)*e+1,r=Math.floor(n),i=+t[r-1],o=n-r;return o?i+o*(t[r]-i):i};Ka.median=function(t,n){var o,a=[],s=t.length,l=-1;if(1===arguments.length)for(;++l<s;)i(o=r(t[l]))&&a.push(o);else for(;++l<s;)i(o=r(n.call(t,t[l],l)))&&a.push(o);return a.length?Ka.quantile(a.sort(e),.5):void 0};var cs=o(e);Ka.bisectLeft=cs.left;Ka.bisect=Ka.bisectRight=cs.right;Ka.bisector=function(t){return o(1===t.length?function(n,r){return e(t(n),r)}:t)};Ka.shuffle=function(t){for(var e,n,r=t.length;r;){n=Math.random()*r--|0;e=t[r],t[r]=t[n],t[n]=e}return t};Ka.permute=function(t,e){for(var n=e.length,r=new Array(n);n--;)r[n]=t[e[n]];return r};Ka.pairs=function(t){for(var e,n=0,r=t.length-1,i=t[0],o=new Array(0>r?0:r);r>n;)o[n]=[e=i,i=t[++n]];return o};Ka.zip=function(){if(!(r=arguments.length))return[];for(var t=-1,e=Ka.min(arguments,a),n=new Array(e);++t<e;)for(var r,i=-1,o=n[t]=new Array(r);++i<r;)o[i]=arguments[i][t];return n};Ka.transpose=function(t){return Ka.zip.apply(Ka,t)};Ka.keys=function(t){var e=[];for(var n in t)e.push(n);return e};Ka.values=function(t){var e=[];for(var n in t)e.push(t[n]);return e};Ka.entries=function(t){var e=[];for(var n in t)e.push({key:n,value:t[n]});return e};Ka.merge=function(t){for(var e,n,r,i=t.length,o=-1,a=0;++o<i;)a+=t[o].length;n=new Array(a);for(;--i>=0;){r=t[i];e=r.length;for(;--e>=0;)n[--a]=r[e]}return n};var fs=Math.abs;Ka.range=function(t,e,n){if(arguments.length<3){n=1;if(arguments.length<2){e=t;t=0}}if((e-t)/n===1/0)throw new Error("infinite range");var r,i=[],o=s(fs(n)),a=-1;t*=o,e*=o,n*=o;if(0>n)for(;(r=t+n*++a)>e;)i.push(r/o);else for(;(r=t+n*++a)<e;)i.push(r/o);return i};Ka.map=function(t){var e=new u;if(t instanceof u)t.forEach(function(t,n){e.set(t,n)});else for(var n in t)e.set(n,t[n]);return e};var hs="__proto__",ds="\x00";l(u,{has:h,get:function(t){return this._[c(t)]},set:function(t,e){return this._[c(t)]=e},remove:d,keys:p,values:function(){var t=[];for(var e in this._)t.push(this._[e]);return t},entries:function(){var t=[];for(var e in this._)t.push({key:f(e),value:this._[e]});return t},size:g,empty:m,forEach:function(t){for(var e in this._)t.call(this,f(e),this._[e])}});Ka.nest=function(){function t(e,a,s){if(s>=o.length)return r?r.call(i,a):n?a.sort(n):a;for(var l,c,f,h,d=-1,p=a.length,g=o[s++],m=new u;++d<p;)(h=m.get(l=g(c=a[d])))?h.push(c):m.set(l,[c]);if(e){c=e();f=function(n,r){c.set(n,t(e,r,s))}}else{c={};f=function(n,r){c[n]=t(e,r,s)}}m.forEach(f);return c}function e(t,n){if(n>=o.length)return t;var r=[],i=a[n++];t.forEach(function(t,i){r.push({key:t,values:e(i,n)})});return i?r.sort(function(t,e){return i(t.key,e.key)}):r}var n,r,i={},o=[],a=[];i.map=function(e,n){return t(n,e,0)};i.entries=function(n){return e(t(Ka.map,n,0),0)};i.key=function(t){o.push(t);return i};i.sortKeys=function(t){a[o.length-1]=t;return i};i.sortValues=function(t){n=t;return i};i.rollup=function(t){r=t;return i};return i};Ka.set=function(t){var e=new v;if(t)for(var n=0,r=t.length;r>n;++n)e.add(t[n]);return e};l(v,{has:h,add:function(t){this._[c(t+="")]=!0;return t},remove:d,values:p,size:g,empty:m,forEach:function(t){for(var e in this._)t.call(this,f(e))}});Ka.behavior={};Ka.rebind=function(t,e){for(var n,r=1,i=arguments.length;++r<i;)t[n=arguments[r]]=y(t,e,e[n]);return t};var ps=["webkit","ms","moz","Moz","o","O"];Ka.dispatch=function(){for(var t=new w,e=-1,n=arguments.length;++e<n;)t[arguments[e]]=S(t);return t};w.prototype.on=function(t,e){var n=t.indexOf("."),r="";if(n>=0){r=t.slice(n+1);t=t.slice(0,n)}if(t)return arguments.length<2?this[t].on(r):this[t].on(r,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(r,null);return this}};Ka.event=null;Ka.requote=function(t){return t.replace(gs,"\\$&")};var gs=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,ms={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var n in e)t[n]=e[n]},vs=function(t,e){return e.querySelector(t)},ys=function(t,e){return e.querySelectorAll(t)},bs=es.matches||es[b(es,"matchesSelector")],xs=function(t,e){return bs.call(t,e)};if("function"==typeof Sizzle){vs=function(t,e){return Sizzle(t,e)[0]||null};ys=Sizzle;xs=Sizzle.matchesSelector}Ka.selection=function(){return Ts};var ws=Ka.selection.prototype=[];ws.select=function(t){var e,n,r,i,o=[];t=M(t);for(var a=-1,s=this.length;++a<s;){o.push(e=[]);e.parentNode=(r=this[a]).parentNode;for(var l=-1,u=r.length;++l<u;)if(i=r[l]){e.push(n=t.call(i,i.__data__,l,a));n&&"__data__"in i&&(n.__data__=i.__data__)}else e.push(null)}return k(o)};ws.selectAll=function(t){var e,n,r=[];t=D(t);for(var i=-1,o=this.length;++i<o;)for(var a=this[i],s=-1,l=a.length;++s<l;)if(n=a[s]){r.push(e=Qa(t.call(n,n.__data__,s,i)));e.parentNode=n}return k(r)};var Ss={svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};Ka.ns={prefix:Ss,qualify:function(t){var e=t.indexOf(":"),n=t;if(e>=0){n=t.slice(0,e);t=t.slice(e+1)}return Ss.hasOwnProperty(n)?{space:Ss[n],local:t}:t}};ws.attr=function(t,e){if(arguments.length<2){if("string"==typeof t){var n=this.node();t=Ka.ns.qualify(t);return t.local?n.getAttributeNS(t.space,t.local):n.getAttribute(t)}for(e in t)this.each(L(e,t[e]));return this}return this.each(L(t,e))};ws.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var n=this.node(),r=(t=E(t)).length,i=-1;if(e=n.classList){for(;++i<r;)if(!e.contains(t[i]))return!1}else{e=n.getAttribute("class");for(;++i<r;)if(!N(t[i]).test(e))return!1}return!0}for(e in t)this.each(j(e,t[e]));return this}return this.each(j(t,e))};ws.style=function(t,e,n){var r=arguments.length;if(3>r){if("string"!=typeof t){2>r&&(e="");for(n in t)this.each(P(n,t[n],e));return this}if(2>r)return ns.getComputedStyle(this.node(),null).getPropertyValue(t);n=""}return this.each(P(t,e,n))};ws.property=function(t,e){if(arguments.length<2){if("string"==typeof t)return this.node()[t];for(e in t)this.each(H(e,t[e]));return this}return this.each(H(t,e))};ws.text=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.textContent=null==e?"":e}:null==t?function(){this.textContent=""}:function(){this.textContent=t}):this.node().textContent};ws.html=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.innerHTML=null==e?"":e}:null==t?function(){this.innerHTML=""}:function(){this.innerHTML=t}):this.node().innerHTML};ws.append=function(t){t=O(t);return this.select(function(){return this.appendChild(t.apply(this,arguments))})};ws.insert=function(t,e){t=O(t);e=M(e);return this.select(function(){return this.insertBefore(t.apply(this,arguments),e.apply(this,arguments)||null)})};ws.remove=function(){return this.each(function(){var t=this.parentNode;t&&t.removeChild(this)})};ws.data=function(t,e){function n(t,n){var r,i,o,a=t.length,f=n.length,h=Math.min(a,f),d=new Array(f),p=new Array(f),g=new Array(a);if(e){var m,v=new u,y=new Array(a);for(r=-1;++r<a;){v.has(m=e.call(i=t[r],i.__data__,r))?g[r]=i:v.set(m,i);y[r]=m}for(r=-1;++r<f;){if(i=v.get(m=e.call(n,o=n[r],r))){if(i!==!0){d[r]=i;i.__data__=o}}else p[r]=F(o);v.set(m,!0)}for(r=-1;++r<a;)v.get(y[r])!==!0&&(g[r]=t[r])}else{for(r=-1;++r<h;){i=t[r];o=n[r];if(i){i.__data__=o;d[r]=i}else p[r]=F(o)}for(;f>r;++r)p[r]=F(n[r]);for(;a>r;++r)g[r]=t[r]}p.update=d;p.parentNode=d.parentNode=g.parentNode=t.parentNode;s.push(p);l.push(d);c.push(g)}var r,i,o=-1,a=this.length;if(!arguments.length){t=new Array(a=(r=this[0]).length);for(;++o<a;)(i=r[o])&&(t[o]=i.__data__);return t}var s=q([]),l=k([]),c=k([]);if("function"==typeof t)for(;++o<a;)n(r=this[o],t.call(r,r.parentNode.__data__,o));else for(;++o<a;)n(r=this[o],t);l.enter=function(){return s};l.exit=function(){return c};return l};ws.datum=function(t){return arguments.length?this.property("__data__",t):this.property("__data__")};ws.filter=function(t){var e,n,r,i=[];"function"!=typeof t&&(t=R(t));for(var o=0,a=this.length;a>o;o++){i.push(e=[]);e.parentNode=(n=this[o]).parentNode;for(var s=0,l=n.length;l>s;s++)(r=n[s])&&t.call(r,r.__data__,s,o)&&e.push(r)}return k(i)};ws.order=function(){for(var t=-1,e=this.length;++t<e;)for(var n,r=this[t],i=r.length-1,o=r[i];--i>=0;)if(n=r[i]){o&&o!==n.nextSibling&&o.parentNode.insertBefore(n,o);o=n}return this};ws.sort=function(t){t=W.apply(this,arguments);for(var e=-1,n=this.length;++e<n;)this[e].sort(t);return this.order()};ws.each=function(t){return z(this,function(e,n,r){t.call(e,e.__data__,n,r)})};ws.call=function(t){var e=Qa(arguments);t.apply(e[0]=this,e);return this};ws.empty=function(){return!this.node()};ws.node=function(){for(var t=0,e=this.length;e>t;t++)for(var n=this[t],r=0,i=n.length;i>r;r++){var o=n[r];if(o)return o}return null};ws.size=function(){var t=0;z(this,function(){++t});return t};var Cs=[];Ka.selection.enter=q;Ka.selection.enter.prototype=Cs;Cs.append=ws.append;Cs.empty=ws.empty;Cs.node=ws.node;Cs.call=ws.call;Cs.size=ws.size;Cs.select=function(t){for(var e,n,r,i,o,a=[],s=-1,l=this.length;++s<l;){r=(i=this[s]).update;a.push(e=[]);e.parentNode=i.parentNode;for(var u=-1,c=i.length;++u<c;)if(o=i[u]){e.push(r[u]=n=t.call(i.parentNode,o.__data__,u,s));n.__data__=o.__data__}else e.push(null)}return k(a)};Cs.insert=function(t,e){arguments.length<2&&(e=U(this));return ws.insert.call(this,t,e)};ws.transition=function(){for(var t,e,n=Nu||++Hu,r=[],i=Eu||{time:Date.now(),ease:ki,delay:0,duration:250},o=-1,a=this.length;++o<a;){r.push(t=[]);for(var s=this[o],l=-1,u=s.length;++l<u;){(e=s[l])&&Ua(e,l,n,i);t.push(e)}}return Wa(r,n)};ws.interrupt=function(){return this.each(B)};Ka.select=function(t){var e=["string"==typeof t?vs(t,ts):t];e.parentNode=es;return k([e])};Ka.selectAll=function(t){var e=Qa("string"==typeof t?ys(t,ts):t);e.parentNode=es;return k([e])};var Ts=Ka.select(es);ws.on=function(t,e,n){var r=arguments.length;if(3>r){if("string"!=typeof t){2>r&&(e=!1);for(n in t)this.each(V(n,t[n],e));return this}if(2>r)return(r=this.node()["__on"+t])&&r._;n=!1}return this.each(V(t,e,n))};var _s=Ka.map({mouseenter:"mouseover",mouseleave:"mouseout"});_s.forEach(function(t){"on"+t in ts&&_s.remove(t)});var ks="onselectstart"in ts?null:b(es.style,"userSelect"),Ms=0;Ka.mouse=function(t){return Y(t,T())};var Ds=/WebKit/.test(ns.navigator.userAgent)?-1:0;Ka.touch=function(t,e,n){arguments.length<3&&(n=e,e=T().changedTouches);if(e)for(var r,i=0,o=e.length;o>i;++i)if((r=e[i]).identifier===n)return Y(t,r)};Ka.behavior.drag=function(){function t(){this.on("mousedown.drag",i).on("touchstart.drag",o)}function e(t,e,i,o,a){return function(){function s(){var t,n,r=e(h,g);if(r){t=r[0]-b[0];n=r[1]-b[1];p|=t|n;b=r;d({type:"drag",x:r[0]+u[0],y:r[1]+u[1],dx:t,dy:n})}}function l(){if(e(h,g)){v.on(o+m,null).on(a+m,null);y(p&&Ka.event.target===f);d({type:"dragend"})}}var u,c=this,f=Ka.event.target,h=c.parentNode,d=n.of(c,arguments),p=0,g=t(),m=".drag"+(null==g?"":"-"+g),v=Ka.select(i()).on(o+m,s).on(a+m,l),y=$(),b=e(h,g);if(r){u=r.apply(c,arguments);u=[u.x-b[0],u.y-b[1]]}else u=[0,0];d({type:"dragstart"})}}var n=_(t,"drag","dragstart","dragend"),r=null,i=e(x,Ka.mouse,Z,"mousemove","mouseup"),o=e(J,Ka.touch,K,"touchmove","touchend");t.origin=function(e){if(!arguments.length)return r;r=e;return t};return Ka.rebind(t,n,"on")};Ka.touches=function(t,e){arguments.length<2&&(e=T().touches);return e?Qa(e).map(function(e){var n=Y(t,e);n.identifier=e.identifier;return n}):[]};var Ls=Math.PI,As=2*Ls,Ns=Ls/2,Es=1e-6,js=Es*Es,Is=Ls/180,Ps=180/Ls,Hs=Math.SQRT2,Os=2,Fs=4;Ka.interpolateZoom=function(t,e){function n(t){var e=t*y;if(v){var n=ie(g),a=o/(Os*h)*(n*oe(Hs*e+g)-re(g));return[r+a*u,i+a*c,o*n/ie(Hs*e+g)]}return[r+t*u,i+t*c,o*Math.exp(Hs*e)]}var r=t[0],i=t[1],o=t[2],a=e[0],s=e[1],l=e[2],u=a-r,c=s-i,f=u*u+c*c,h=Math.sqrt(f),d=(l*l-o*o+Fs*f)/(2*o*Os*h),p=(l*l-o*o-Fs*f)/(2*l*Os*h),g=Math.log(Math.sqrt(d*d+1)-d),m=Math.log(Math.sqrt(p*p+1)-p),v=m-g,y=(v||Math.log(l/o))/Hs;n.duration=1e3*y;return n};Ka.behavior.zoom=function(){function t(t){t.on(M,u).on(zs+".zoom",f).on("dblclick.zoom",h).on(A,c)}function e(t){return[(t[0]-S.x)/S.k,(t[1]-S.y)/S.k]}function n(t){return[t[0]*S.k+S.x,t[1]*S.k+S.y]}function r(t){S.k=Math.max(k[0],Math.min(k[1],t))}function i(t,e){e=n(e);S.x+=t[0]-e[0];S.y+=t[1]-e[1]}function o(){b&&b.domain(y.range().map(function(t){return(t-S.x)/S.k}).map(y.invert));w&&w.domain(x.range().map(function(t){return(t-S.y)/S.k}).map(x.invert))}function a(t){t({type:"zoomstart"})}function s(t){o();t({type:"zoom",scale:S.k,translate:[S.x,S.y]})}function l(t){t({type:"zoomend"})}function u(){function t(){c=1;i(Ka.mouse(r),h);s(u)}function n(){f.on(D,null).on(L,null);d(c&&Ka.event.target===o);l(u)}var r=this,o=Ka.event.target,u=N.of(r,arguments),c=0,f=Ka.select(ns).on(D,t).on(L,n),h=e(Ka.mouse(r)),d=$();B.call(r);a(u)}function c(){function t(){var t=Ka.touches(d);h=S.k;t.forEach(function(t){t.identifier in g&&(g[t.identifier]=e(t))});return t}function n(){var e=Ka.event.target;Ka.select(e).on(b,o).on(x,f);w.push(e);for(var n=Ka.event.changedTouches,a=0,l=n.length;l>a;++a)g[n[a].identifier]=null;var u=t(),c=Date.now();if(1===u.length){if(500>c-v){var h=u[0],d=g[h.identifier];r(2*S.k);i(h,d);C();s(p)}v=c}else if(u.length>1){var h=u[0],y=u[1],T=h[0]-y[0],_=h[1]-y[1];m=T*T+_*_}}function o(){for(var t,e,n,o,a=Ka.touches(d),l=0,u=a.length;u>l;++l,o=null){n=a[l];if(o=g[n.identifier]){if(e)break;t=n,e=o}}if(o){var c=(c=n[0]-t[0])*c+(c=n[1]-t[1])*c,f=m&&Math.sqrt(c/m);t=[(t[0]+n[0])/2,(t[1]+n[1])/2];e=[(e[0]+o[0])/2,(e[1]+o[1])/2];r(f*h)}v=null;i(t,e);s(p)}function f(){if(Ka.event.touches.length){for(var e=Ka.event.changedTouches,n=0,r=e.length;r>n;++n)delete g[e[n].identifier];for(var i in g)return void t()}Ka.selectAll(w).on(y,null);T.on(M,u).on(A,c);_();l(p)}var h,d=this,p=N.of(d,arguments),g={},m=0,y=".zoom-"+Ka.event.changedTouches[0].identifier,b="touchmove"+y,x="touchend"+y,w=[],T=Ka.select(d),_=$();B.call(d);n();a(p);T.on(M,null).on(A,n)}function f(){var t=N.of(this,arguments);m?clearTimeout(m):(d=e(p=g||Ka.mouse(this)),B.call(this),a(t));m=setTimeout(function(){m=null;l(t)},50);C();r(Math.pow(2,.002*Rs())*S.k);i(p,d);s(t)}function h(){var t=N.of(this,arguments),n=Ka.mouse(this),o=e(n),u=Math.log(S.k)/Math.LN2;a(t);r(Math.pow(2,Ka.event.shiftKey?Math.ceil(u)-1:Math.floor(u)+1));i(n,o);s(t);l(t)}var d,p,g,m,v,y,b,x,w,S={x:0,y:0,k:1},T=[960,500],k=Ws,M="mousedown.zoom",D="mousemove.zoom",L="mouseup.zoom",A="touchstart.zoom",N=_(t,"zoomstart","zoom","zoomend");t.event=function(t){t.each(function(){var t=N.of(this,arguments),e=S;if(Nu)Ka.select(this).transition().each("start.zoom",function(){S=this.__chart__||{x:0,y:0,k:1};a(t)}).tween("zoom:zoom",function(){var n=T[0],r=T[1],i=n/2,o=r/2,a=Ka.interpolateZoom([(i-S.x)/S.k,(o-S.y)/S.k,n/S.k],[(i-e.x)/e.k,(o-e.y)/e.k,n/e.k]);return function(e){var r=a(e),l=n/r[2];this.__chart__=S={x:i-r[0]*l,y:o-r[1]*l,k:l};s(t)}}).each("end.zoom",function(){l(t)});else{this.__chart__=S;a(t);s(t);l(t)}})};t.translate=function(e){if(!arguments.length)return[S.x,S.y];S={x:+e[0],y:+e[1],k:S.k};o();return t};t.scale=function(e){if(!arguments.length)return S.k;S={x:S.x,y:S.y,k:+e};o();return t};t.scaleExtent=function(e){if(!arguments.length)return k;k=null==e?Ws:[+e[0],+e[1]];return t};t.center=function(e){if(!arguments.length)return g;g=e&&[+e[0],+e[1]];return t};t.size=function(e){if(!arguments.length)return T;T=e&&[+e[0],+e[1]];return t};t.x=function(e){if(!arguments.length)return b;b=e;y=e.copy();S={x:0,y:0,k:1};return t};t.y=function(e){if(!arguments.length)return w;w=e;x=e.copy();S={x:0,y:0,k:1};return t};return Ka.rebind(t,N,"on")};var Rs,Ws=[0,1/0],zs="onwheel"in ts?(Rs=function(){return-Ka.event.deltaY*(Ka.event.deltaMode?120:1)},"wheel"):"onmousewheel"in ts?(Rs=function(){return Ka.event.wheelDelta},"mousewheel"):(Rs=function(){return-Ka.event.detail},"MozMousePixelScroll");Ka.color=se;se.prototype.toString=function(){return this.rgb()+""};Ka.hsl=le;var qs=le.prototype=new se;qs.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);return new le(this.h,this.s,this.l/t)};qs.darker=function(t){t=Math.pow(.7,arguments.length?t:1);return new le(this.h,this.s,t*this.l)};qs.rgb=function(){return ue(this.h,this.s,this.l)};Ka.hcl=ce;var Us=ce.prototype=new se;Us.brighter=function(t){return new ce(this.h,this.c,Math.min(100,this.l+Bs*(arguments.length?t:1)))};Us.darker=function(t){return new ce(this.h,this.c,Math.max(0,this.l-Bs*(arguments.length?t:1)))};Us.rgb=function(){return fe(this.h,this.c,this.l).rgb()};Ka.lab=he;var Bs=18,Vs=.95047,Xs=1,Gs=1.08883,$s=he.prototype=new se;$s.brighter=function(t){return new he(Math.min(100,this.l+Bs*(arguments.length?t:1)),this.a,this.b)};$s.darker=function(t){return new he(Math.max(0,this.l-Bs*(arguments.length?t:1)),this.a,this.b)};$s.rgb=function(){return de(this.l,this.a,this.b)};Ka.rgb=ye;var Ys=ye.prototype=new se;Ys.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,n=this.g,r=this.b,i=30;if(!e&&!n&&!r)return new ye(i,i,i);e&&i>e&&(e=i);n&&i>n&&(n=i);r&&i>r&&(r=i);return new ye(Math.min(255,e/t),Math.min(255,n/t),Math.min(255,r/t))};Ys.darker=function(t){t=Math.pow(.7,arguments.length?t:1);return new ye(t*this.r,t*this.g,t*this.b)};Ys.hsl=function(){return Ce(this.r,this.g,this.b)};Ys.toString=function(){return"#"+we(this.r)+we(this.g)+we(this.b)};var Js=Ka.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});Js.forEach(function(t,e){Js.set(t,be(e))});Ka.functor=Me;Ka.xhr=Le(De);Ka.dsv=function(t,e){function n(t,n,o){arguments.length<3&&(o=n,n=null);var a=Ae(t,e,null==n?r:i(n),o);a.row=function(t){return arguments.length?a.response(null==(n=t)?r:i(t)):n};return a}function r(t){return n.parse(t.responseText)}function i(t){return function(e){return n.parse(e.responseText,t)}}function o(e){return e.map(a).join(t)}function a(t){return s.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}var s=new RegExp('["'+t+"\n]"),l=t.charCodeAt(0);n.parse=function(t,e){var r;return n.parseRows(t,function(t,n){if(r)return r(t,n-1);var i=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");r=e?function(t,n){return e(i(t),n)}:i})};n.parseRows=function(t,e){function n(){if(c>=u)return a;if(i)return i=!1,o;var e=c;if(34===t.charCodeAt(e)){for(var n=e;n++<u;)if(34===t.charCodeAt(n)){if(34!==t.charCodeAt(n+1))break;++n}c=n+2;var r=t.charCodeAt(n+1);if(13===r){i=!0;10===t.charCodeAt(n+2)&&++c}else 10===r&&(i=!0);return t.slice(e+1,n).replace(/""/g,'"')}for(;u>c;){var r=t.charCodeAt(c++),s=1;if(10===r)i=!0;else if(13===r){i=!0;10===t.charCodeAt(c)&&(++c,++s)}else if(r!==l)continue;return t.slice(e,c-s)}return t.slice(e)}for(var r,i,o={},a={},s=[],u=t.length,c=0,f=0;(r=n())!==a;){for(var h=[];r!==o&&r!==a;){h.push(r);r=n()}e&&null==(h=e(h,f++))||s.push(h)}return s};n.format=function(e){if(Array.isArray(e[0]))return n.formatRows(e);var r=new v,i=[];e.forEach(function(t){for(var e in t)r.has(e)||i.push(r.add(e))});return[i.map(a).join(t)].concat(e.map(function(e){return i.map(function(t){return a(e[t])}).join(t)})).join("\n")};n.formatRows=function(t){return t.map(o).join("\n")};return n};Ka.csv=Ka.dsv(",","text/csv");Ka.tsv=Ka.dsv(" ","text/tab-separated-values");var Ks,Zs,Qs,tl,el,nl=ns[b(ns,"requestAnimationFrame")]||function(t){setTimeout(t,17)};Ka.timer=function(t,e,n){var r=arguments.length;2>r&&(e=0);3>r&&(n=Date.now());var i=n+e,o={c:t,t:i,f:!1,n:null};Zs?Zs.n=o:Ks=o;Zs=o;if(!Qs){tl=clearTimeout(tl);Qs=1;nl(je)}};Ka.timer.flush=function(){Ie();Pe()};Ka.round=function(t,e){return e?Math.round(t*(e=Math.pow(10,e)))/e:Math.round(t)};var rl=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"].map(Oe);Ka.formatPrefix=function(t,e){var n=0;if(t){0>t&&(t*=-1);e&&(t=Ka.round(t,He(t,e)));n=1+Math.floor(1e-12+Math.log(t)/Math.LN10);n=Math.max(-24,Math.min(24,3*Math.floor((n-1)/3)))}return rl[8+n/3]};var il=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,ol=Ka.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(t,e){return(t=Ka.round(t,He(t,e))).toFixed(Math.max(0,Math.min(20,He(t*(1+1e-15),e))))}}),al=Ka.time={},sl=Date;We.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){ll.setUTCDate.apply(this._,arguments)},setDay:function(){ll.setUTCDay.apply(this._,arguments)},setFullYear:function(){ll.setUTCFullYear.apply(this._,arguments)},setHours:function(){ll.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){ll.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){ll.setUTCMinutes.apply(this._,arguments)},setMonth:function(){ll.setUTCMonth.apply(this._,arguments)},setSeconds:function(){ll.setUTCSeconds.apply(this._,arguments)},setTime:function(){ll.setTime.apply(this._,arguments)}};var ll=Date.prototype;al.year=ze(function(t){t=al.day(t);t.setMonth(0,1);return t},function(t,e){t.setFullYear(t.getFullYear()+e)},function(t){return t.getFullYear()});al.years=al.year.range;al.years.utc=al.year.utc.range;al.day=ze(function(t){var e=new sl(2e3,0);e.setFullYear(t.getFullYear(),t.getMonth(),t.getDate());return e},function(t,e){t.setDate(t.getDate()+e)},function(t){return t.getDate()-1});al.days=al.day.range;al.days.utc=al.day.utc.range;al.dayOfYear=function(t){var e=al.year(t);return Math.floor((t-e-6e4*(t.getTimezoneOffset()-e.getTimezoneOffset()))/864e5)};["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(t,e){e=7-e;var n=al[t]=ze(function(t){(t=al.day(t)).setDate(t.getDate()-(t.getDay()+e)%7);return t},function(t,e){t.setDate(t.getDate()+7*Math.floor(e))},function(t){var n=al.year(t).getDay();return Math.floor((al.dayOfYear(t)+(n+e)%7)/7)-(n!==e)});al[t+"s"]=n.range;al[t+"s"].utc=n.utc.range;al[t+"OfYear"]=function(t){var n=al.year(t).getDay();return Math.floor((al.dayOfYear(t)+(n+e)%7)/7)}});al.week=al.sunday;al.weeks=al.sunday.range;al.weeks.utc=al.sunday.utc.range;al.weekOfYear=al.sundayOfYear;var ul={"-":"",_:" ",0:"0"},cl=/^\s*\d+/,fl=/^%/;Ka.locale=function(t){return{numberFormat:Fe(t),timeFormat:Ue(t)}};var hl=Ka.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});Ka.format=hl.numberFormat;Ka.geo={};fn.prototype={s:0,t:0,add:function(t){hn(t,this.t,dl);hn(dl.s,this.s,this);this.s?this.t+=dl.t:this.s=dl.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var dl=new fn;Ka.geo.stream=function(t,e){t&&pl.hasOwnProperty(t.type)?pl[t.type](t,e):dn(t,e)};var pl={Feature:function(t,e){dn(t.geometry,e)},FeatureCollection:function(t,e){for(var n=t.features,r=-1,i=n.length;++r<i;)dn(n[r].geometry,e)}},gl={Sphere:function(t,e){e.sphere()},Point:function(t,e){t=t.coordinates;e.point(t[0],t[1],t[2])},MultiPoint:function(t,e){for(var n=t.coordinates,r=-1,i=n.length;++r<i;)t=n[r],e.point(t[0],t[1],t[2])},LineString:function(t,e){pn(t.coordinates,e,0)},MultiLineString:function(t,e){for(var n=t.coordinates,r=-1,i=n.length;++r<i;)pn(n[r],e,0)},Polygon:function(t,e){gn(t.coordinates,e)},MultiPolygon:function(t,e){for(var n=t.coordinates,r=-1,i=n.length;++r<i;)gn(n[r],e)},GeometryCollection:function(t,e){for(var n=t.geometries,r=-1,i=n.length;++r<i;)dn(n[r],e)}};Ka.geo.area=function(t){ml=0;Ka.geo.stream(t,yl);return ml};var ml,vl=new fn,yl={sphere:function(){ml+=4*Ls},point:x,lineStart:x,lineEnd:x,polygonStart:function(){vl.reset();yl.lineStart=mn},polygonEnd:function(){var t=2*vl;ml+=0>t?4*Ls+t:t;yl.lineStart=yl.lineEnd=yl.point=x}};Ka.geo.bounds=function(){function t(t,e){b.push(x=[c=t,h=t]);f>e&&(f=e);e>d&&(d=e)}function e(e,n){var r=vn([e*Is,n*Is]);if(v){var i=bn(v,r),o=[i[1],-i[0],0],a=bn(o,i);Sn(a);a=Cn(a);var l=e-p,u=l>0?1:-1,g=a[0]*Ps*u,m=fs(l)>180;if(m^(g>u*p&&u*e>g)){var y=a[1]*Ps;y>d&&(d=y)}else if(g=(g+360)%360-180,m^(g>u*p&&u*e>g)){var y=-a[1]*Ps;f>y&&(f=y)}else{f>n&&(f=n);n>d&&(d=n)}if(m)p>e?s(c,e)>s(c,h)&&(h=e):s(e,h)>s(c,h)&&(c=e);else if(h>=c){c>e&&(c=e);e>h&&(h=e)}else e>p?s(c,e)>s(c,h)&&(h=e):s(e,h)>s(c,h)&&(c=e)}else t(e,n);v=r,p=e}function n(){w.point=e}function r(){x[0]=c,x[1]=h;w.point=t;v=null}function i(t,n){if(v){var r=t-p;y+=fs(r)>180?r+(r>0?360:-360):r}else g=t,m=n;yl.point(t,n);e(t,n)}function o(){yl.lineStart()}function a(){i(g,m);yl.lineEnd();fs(y)>Es&&(c=-(h=180));x[0]=c,x[1]=h;v=null}function s(t,e){return(e-=t)<0?e+360:e}function l(t,e){return t[0]-e[0]}function u(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:t<e[0]||e[1]<t}var c,f,h,d,p,g,m,v,y,b,x,w={point:t,lineStart:n,lineEnd:r,polygonStart:function(){w.point=i;w.lineStart=o;w.lineEnd=a;y=0;yl.polygonStart()},polygonEnd:function(){yl.polygonEnd();w.point=t;w.lineStart=n;w.lineEnd=r;0>vl?(c=-(h=180),f=-(d=90)):y>Es?d=90:-Es>y&&(f=-90);x[0]=c,x[1]=h}};return function(t){d=h=-(c=f=1/0);b=[];Ka.geo.stream(t,w);var e=b.length;if(e){b.sort(l);for(var n,r=1,i=b[0],o=[i];e>r;++r){n=b[r];if(u(n[0],i)||u(n[1],i)){s(i[0],n[1])>s(i[0],i[1])&&(i[1]=n[1]);s(n[0],i[1])>s(i[0],i[1])&&(i[0]=n[0])}else o.push(i=n)}for(var a,n,p=-1/0,e=o.length-1,r=0,i=o[e];e>=r;i=n,++r){n=o[r];(a=s(i[1],n[0]))>p&&(p=a,c=n[0],h=i[1])}}b=x=null;return 1/0===c||1/0===f?[[0/0,0/0],[0/0,0/0]]:[[c,f],[h,d]]}}();Ka.geo.centroid=function(t){bl=xl=wl=Sl=Cl=Tl=_l=kl=Ml=Dl=Ll=0;Ka.geo.stream(t,Al);var e=Ml,n=Dl,r=Ll,i=e*e+n*n+r*r;if(js>i){e=Tl,n=_l,r=kl;Es>xl&&(e=wl,n=Sl,r=Cl);i=e*e+n*n+r*r;if(js>i)return[0/0,0/0]}return[Math.atan2(n,e)*Ps,ne(r/Math.sqrt(i))*Ps]};var bl,xl,wl,Sl,Cl,Tl,_l,kl,Ml,Dl,Ll,Al={sphere:x,point:_n,lineStart:Mn,lineEnd:Dn,polygonStart:function(){Al.lineStart=Ln},polygonEnd:function(){Al.lineStart=Mn}},Nl=In(An,Fn,Wn,[-Ls,-Ls/2]),El=1e9;Ka.geo.clipExtent=function(){var t,e,n,r,i,o,a={stream:function(t){i&&(i.valid=!1);i=o(t);i.valid=!0;return i},extent:function(s){if(!arguments.length)return[[t,e],[n,r]];o=Bn(t=+s[0][0],e=+s[0][1],n=+s[1][0],r=+s[1][1]);i&&(i.valid=!1,i=null);return a}};return a.extent([[0,0],[960,500]])};(Ka.geo.conicEqualArea=function(){return Xn(Gn)}).raw=Gn;Ka.geo.albers=function(){return Ka.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)};Ka.geo.albersUsa=function(){function t(t){var o=t[0],a=t[1];e=null;(n(o,a),e)||(r(o,a),e)||i(o,a);return e}var e,n,r,i,o=Ka.geo.albers(),a=Ka.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s=Ka.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(t,n){e=[t,n]}};t.invert=function(t){var e=o.scale(),n=o.translate(),r=(t[0]-n[0])/e,i=(t[1]-n[1])/e;return(i>=.12&&.234>i&&r>=-.425&&-.214>r?a:i>=.166&&.234>i&&r>=-.214&&-.115>r?s:o).invert(t)};t.stream=function(t){var e=o.stream(t),n=a.stream(t),r=s.stream(t);return{point:function(t,i){e.point(t,i);n.point(t,i);r.point(t,i)},sphere:function(){e.sphere();n.sphere();r.sphere()},lineStart:function(){e.lineStart();n.lineStart();r.lineStart()},lineEnd:function(){e.lineEnd();n.lineEnd();r.lineEnd()},polygonStart:function(){e.polygonStart();n.polygonStart();r.polygonStart()},polygonEnd:function(){e.polygonEnd();n.polygonEnd();r.polygonEnd()}}};t.precision=function(e){if(!arguments.length)return o.precision();o.precision(e);a.precision(e);s.precision(e);return t};t.scale=function(e){if(!arguments.length)return o.scale();
o.scale(e);a.scale(.35*e);s.scale(e);return t.translate(o.translate())};t.translate=function(e){if(!arguments.length)return o.translate();var u=o.scale(),c=+e[0],f=+e[1];n=o.translate(e).clipExtent([[c-.455*u,f-.238*u],[c+.455*u,f+.238*u]]).stream(l).point;r=a.translate([c-.307*u,f+.201*u]).clipExtent([[c-.425*u+Es,f+.12*u+Es],[c-.214*u-Es,f+.234*u-Es]]).stream(l).point;i=s.translate([c-.205*u,f+.212*u]).clipExtent([[c-.214*u+Es,f+.166*u+Es],[c-.115*u-Es,f+.234*u-Es]]).stream(l).point;return t};return t.scale(1070)};var jl,Il,Pl,Hl,Ol,Fl,Rl={point:x,lineStart:x,lineEnd:x,polygonStart:function(){Il=0;Rl.lineStart=$n},polygonEnd:function(){Rl.lineStart=Rl.lineEnd=Rl.point=x;jl+=fs(Il/2)}},Wl={point:Yn,lineStart:x,lineEnd:x,polygonStart:x,polygonEnd:x},zl={point:Zn,lineStart:Qn,lineEnd:tr,polygonStart:function(){zl.lineStart=er},polygonEnd:function(){zl.point=Zn;zl.lineStart=Qn;zl.lineEnd=tr}};Ka.geo.path=function(){function t(t){if(t){"function"==typeof s&&o.pointRadius(+s.apply(this,arguments));a&&a.valid||(a=i(o));Ka.geo.stream(t,a)}return o.result()}function e(){a=null;return t}var n,r,i,o,a,s=4.5;t.area=function(t){jl=0;Ka.geo.stream(t,i(Rl));return jl};t.centroid=function(t){wl=Sl=Cl=Tl=_l=kl=Ml=Dl=Ll=0;Ka.geo.stream(t,i(zl));return Ll?[Ml/Ll,Dl/Ll]:kl?[Tl/kl,_l/kl]:Cl?[wl/Cl,Sl/Cl]:[0/0,0/0]};t.bounds=function(t){Ol=Fl=-(Pl=Hl=1/0);Ka.geo.stream(t,i(Wl));return[[Pl,Hl],[Ol,Fl]]};t.projection=function(t){if(!arguments.length)return n;i=(n=t)?t.stream||ir(t):De;return e()};t.context=function(t){if(!arguments.length)return r;o=null==(r=t)?new Jn:new nr(t);"function"!=typeof s&&o.pointRadius(s);return e()};t.pointRadius=function(e){if(!arguments.length)return s;s="function"==typeof e?e:(o.pointRadius(+e),+e);return t};return t.projection(Ka.geo.albersUsa()).context(null)};Ka.geo.transform=function(t){return{stream:function(e){var n=new or(e);for(var r in t)n[r]=t[r];return n}}};or.prototype={point:function(t,e){this.stream.point(t,e)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};Ka.geo.projection=sr;Ka.geo.projectionMutator=lr;(Ka.geo.equirectangular=function(){return sr(cr)}).raw=cr.invert=cr;Ka.geo.rotation=function(t){function e(e){e=t(e[0]*Is,e[1]*Is);return e[0]*=Ps,e[1]*=Ps,e}t=hr(t[0]%360*Is,t[1]*Is,t.length>2?t[2]*Is:0);e.invert=function(e){e=t.invert(e[0]*Is,e[1]*Is);return e[0]*=Ps,e[1]*=Ps,e};return e};fr.invert=cr;Ka.geo.circle=function(){function t(){var t="function"==typeof r?r.apply(this,arguments):r,e=hr(-t[0]*Is,-t[1]*Is,0).invert,i=[];n(null,null,1,{point:function(t,n){i.push(t=e(t,n));t[0]*=Ps,t[1]*=Ps}});return{type:"Polygon",coordinates:[i]}}var e,n,r=[0,0],i=6;t.origin=function(e){if(!arguments.length)return r;r=e;return t};t.angle=function(r){if(!arguments.length)return e;n=mr((e=+r)*Is,i*Is);return t};t.precision=function(r){if(!arguments.length)return i;n=mr(e*Is,(i=+r)*Is);return t};return t.angle(90)};Ka.geo.distance=function(t,e){var n,r=(e[0]-t[0])*Is,i=t[1]*Is,o=e[1]*Is,a=Math.sin(r),s=Math.cos(r),l=Math.sin(i),u=Math.cos(i),c=Math.sin(o),f=Math.cos(o);return Math.atan2(Math.sqrt((n=f*a)*n+(n=u*c-l*f*s)*n),l*c+u*f*s)};Ka.geo.graticule=function(){function t(){return{type:"MultiLineString",coordinates:e()}}function e(){return Ka.range(Math.ceil(o/m)*m,i,m).map(h).concat(Ka.range(Math.ceil(u/v)*v,l,v).map(d)).concat(Ka.range(Math.ceil(r/p)*p,n,p).filter(function(t){return fs(t%m)>Es}).map(c)).concat(Ka.range(Math.ceil(s/g)*g,a,g).filter(function(t){return fs(t%v)>Es}).map(f))}var n,r,i,o,a,s,l,u,c,f,h,d,p=10,g=p,m=90,v=360,y=2.5;t.lines=function(){return e().map(function(t){return{type:"LineString",coordinates:t}})};t.outline=function(){return{type:"Polygon",coordinates:[h(o).concat(d(l).slice(1),h(i).reverse().slice(1),d(u).reverse().slice(1))]}};t.extent=function(e){return arguments.length?t.majorExtent(e).minorExtent(e):t.minorExtent()};t.majorExtent=function(e){if(!arguments.length)return[[o,u],[i,l]];o=+e[0][0],i=+e[1][0];u=+e[0][1],l=+e[1][1];o>i&&(e=o,o=i,i=e);u>l&&(e=u,u=l,l=e);return t.precision(y)};t.minorExtent=function(e){if(!arguments.length)return[[r,s],[n,a]];r=+e[0][0],n=+e[1][0];s=+e[0][1],a=+e[1][1];r>n&&(e=r,r=n,n=e);s>a&&(e=s,s=a,a=e);return t.precision(y)};t.step=function(e){return arguments.length?t.majorStep(e).minorStep(e):t.minorStep()};t.majorStep=function(e){if(!arguments.length)return[m,v];m=+e[0],v=+e[1];return t};t.minorStep=function(e){if(!arguments.length)return[p,g];p=+e[0],g=+e[1];return t};t.precision=function(e){if(!arguments.length)return y;y=+e;c=yr(s,a,90);f=br(r,n,y);h=yr(u,l,90);d=br(o,i,y);return t};return t.majorExtent([[-180,-90+Es],[180,90-Es]]).minorExtent([[-180,-80-Es],[180,80+Es]])};Ka.geo.greatArc=function(){function t(){return{type:"LineString",coordinates:[e||r.apply(this,arguments),n||i.apply(this,arguments)]}}var e,n,r=xr,i=wr;t.distance=function(){return Ka.geo.distance(e||r.apply(this,arguments),n||i.apply(this,arguments))};t.source=function(n){if(!arguments.length)return r;r=n,e="function"==typeof n?null:n;return t};t.target=function(e){if(!arguments.length)return i;i=e,n="function"==typeof e?null:e;return t};t.precision=function(){return arguments.length?t:0};return t};Ka.geo.interpolate=function(t,e){return Sr(t[0]*Is,t[1]*Is,e[0]*Is,e[1]*Is)};Ka.geo.length=function(t){ql=0;Ka.geo.stream(t,Ul);return ql};var ql,Ul={sphere:x,point:x,lineStart:Cr,lineEnd:x,polygonStart:x,polygonEnd:x},Bl=Tr(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(Ka.geo.azimuthalEqualArea=function(){return sr(Bl)}).raw=Bl;var Vl=Tr(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},De);(Ka.geo.azimuthalEquidistant=function(){return sr(Vl)}).raw=Vl;(Ka.geo.conicConformal=function(){return Xn(_r)}).raw=_r;(Ka.geo.conicEquidistant=function(){return Xn(kr)}).raw=kr;var Xl=Tr(function(t){return 1/t},Math.atan);(Ka.geo.gnomonic=function(){return sr(Xl)}).raw=Xl;Mr.invert=function(t,e){return[t,2*Math.atan(Math.exp(e))-Ns]};(Ka.geo.mercator=function(){return Dr(Mr)}).raw=Mr;var Gl=Tr(function(){return 1},Math.asin);(Ka.geo.orthographic=function(){return sr(Gl)}).raw=Gl;var $l=Tr(function(t){return 1/(1+t)},function(t){return 2*Math.atan(t)});(Ka.geo.stereographic=function(){return sr($l)}).raw=$l;Lr.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-Ns]};(Ka.geo.transverseMercator=function(){var t=Dr(Lr),e=t.center,n=t.rotate;t.center=function(t){return t?e([-t[1],t[0]]):(t=e(),[t[1],-t[0]])};t.rotate=function(t){return t?n([t[0],t[1],t.length>2?t[2]+90:90]):(t=n(),[t[0],t[1],t[2]-90])};return n([0,0,90])}).raw=Lr;Ka.geom={};Ka.geom.hull=function(t){function e(t){if(t.length<3)return[];var e,i=Me(n),o=Me(r),a=t.length,s=[],l=[];for(e=0;a>e;e++)s.push([+i.call(this,t[e],e),+o.call(this,t[e],e),e]);s.sort(jr);for(e=0;a>e;e++)l.push([s[e][0],-s[e][1]]);var u=Er(s),c=Er(l),f=c[0]===u[0],h=c[c.length-1]===u[u.length-1],d=[];for(e=u.length-1;e>=0;--e)d.push(t[s[u[e]][2]]);for(e=+f;e<c.length-h;++e)d.push(t[s[c[e]][2]]);return d}var n=Ar,r=Nr;if(arguments.length)return e(t);e.x=function(t){return arguments.length?(n=t,e):n};e.y=function(t){return arguments.length?(r=t,e):r};return e};Ka.geom.polygon=function(t){ms(t,Yl);return t};var Yl=Ka.geom.polygon.prototype=[];Yl.area=function(){for(var t,e=-1,n=this.length,r=this[n-1],i=0;++e<n;){t=r;r=this[e];i+=t[1]*r[0]-t[0]*r[1]}return.5*i};Yl.centroid=function(t){var e,n,r=-1,i=this.length,o=0,a=0,s=this[i-1];arguments.length||(t=-1/(6*this.area()));for(;++r<i;){e=s;s=this[r];n=e[0]*s[1]-s[0]*e[1];o+=(e[0]+s[0])*n;a+=(e[1]+s[1])*n}return[o*t,a*t]};Yl.clip=function(t){for(var e,n,r,i,o,a,s=Hr(t),l=-1,u=this.length-Hr(this),c=this[u-1];++l<u;){e=t.slice();t.length=0;i=this[l];o=e[(r=e.length-s)-1];n=-1;for(;++n<r;){a=e[n];if(Ir(a,c,i)){Ir(o,c,i)||t.push(Pr(o,a,c,i));t.push(a)}else Ir(o,c,i)&&t.push(Pr(o,a,c,i));o=a}s&&t.push(t[0]);c=i}return t};var Jl,Kl,Zl,Ql,tu,eu=[],nu=[];Br.prototype.prepare=function(){for(var t,e=this.edges,n=e.length;n--;){t=e[n].edge;t.b&&t.a||e.splice(n,1)}e.sort(Xr);return e.length};ni.prototype={start:function(){return this.edge.l===this.site?this.edge.a:this.edge.b},end:function(){return this.edge.l===this.site?this.edge.b:this.edge.a}};ri.prototype={insert:function(t,e){var n,r,i;if(t){e.P=t;e.N=t.N;t.N&&(t.N.P=e);t.N=e;if(t.R){t=t.R;for(;t.L;)t=t.L;t.L=e}else t.R=e;n=t}else if(this._){t=si(this._);e.P=null;e.N=t;t.P=t.L=e;n=t}else{e.P=e.N=null;this._=e;n=null}e.L=e.R=null;e.U=n;e.C=!0;t=e;for(;n&&n.C;){r=n.U;if(n===r.L){i=r.R;if(i&&i.C){n.C=i.C=!1;r.C=!0;t=r}else{if(t===n.R){oi(this,n);t=n;n=t.U}n.C=!1;r.C=!0;ai(this,r)}}else{i=r.L;if(i&&i.C){n.C=i.C=!1;r.C=!0;t=r}else{if(t===n.L){ai(this,n);t=n;n=t.U}n.C=!1;r.C=!0;oi(this,r)}}n=t.U}this._.C=!1},remove:function(t){t.N&&(t.N.P=t.P);t.P&&(t.P.N=t.N);t.N=t.P=null;var e,n,r,i=t.U,o=t.L,a=t.R;n=o?a?si(a):o:a;i?i.L===t?i.L=n:i.R=n:this._=n;if(o&&a){r=n.C;n.C=t.C;n.L=o;o.U=n;if(n!==a){i=n.U;n.U=t.U;t=n.R;i.L=t;n.R=a;a.U=n}else{n.U=i;i=n;t=n.R}}else{r=t.C;t=n}t&&(t.U=i);if(!r)if(t&&t.C)t.C=!1;else{do{if(t===this._)break;if(t===i.L){e=i.R;if(e.C){e.C=!1;i.C=!0;oi(this,i);e=i.R}if(e.L&&e.L.C||e.R&&e.R.C){if(!e.R||!e.R.C){e.L.C=!1;e.C=!0;ai(this,e);e=i.R}e.C=i.C;i.C=e.R.C=!1;oi(this,i);t=this._;break}}else{e=i.L;if(e.C){e.C=!1;i.C=!0;ai(this,i);e=i.L}if(e.L&&e.L.C||e.R&&e.R.C){if(!e.L||!e.L.C){e.R.C=!1;e.C=!0;oi(this,e);e=i.L}e.C=i.C;i.C=e.L.C=!1;ai(this,i);t=this._;break}}e.C=!0;t=i;i=i.U}while(!t.C);t&&(t.C=!1)}}};Ka.geom.voronoi=function(t){function e(t){var e=new Array(t.length),r=s[0][0],i=s[0][1],o=s[1][0],a=s[1][1];li(n(t),s).cells.forEach(function(n,s){var l=n.edges,u=n.site,c=e[s]=l.length?l.map(function(t){var e=t.start();return[e.x,e.y]}):u.x>=r&&u.x<=o&&u.y>=i&&u.y<=a?[[r,a],[o,a],[o,i],[r,i]]:[];c.point=t[s]});return e}function n(t){return t.map(function(t,e){return{x:Math.round(o(t,e)/Es)*Es,y:Math.round(a(t,e)/Es)*Es,i:e}})}var r=Ar,i=Nr,o=r,a=i,s=ru;if(t)return e(t);e.links=function(t){return li(n(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})};e.triangles=function(t){var e=[];li(n(t)).cells.forEach(function(n,r){for(var i,o,a=n.site,s=n.edges.sort(Xr),l=-1,u=s.length,c=s[u-1].edge,f=c.l===a?c.r:c.l;++l<u;){i=c;o=f;c=s[l].edge;f=c.l===a?c.r:c.l;r<o.i&&r<f.i&&ci(a,o,f)<0&&e.push([t[r],t[o.i],t[f.i]])}});return e};e.x=function(t){return arguments.length?(o=Me(r=t),e):r};e.y=function(t){return arguments.length?(a=Me(i=t),e):i};e.clipExtent=function(t){if(!arguments.length)return s===ru?null:s;s=null==t?ru:t;return e};e.size=function(t){return arguments.length?e.clipExtent(t&&[[0,0],t]):s===ru?null:s&&s[1]};return e};var ru=[[-1e6,-1e6],[1e6,1e6]];Ka.geom.delaunay=function(t){return Ka.geom.voronoi().triangles(t)};Ka.geom.quadtree=function(t,e,n,r,i){function o(t){function o(t,e,n,r,i,o,a,s){if(!isNaN(n)&&!isNaN(r))if(t.leaf){var l=t.x,c=t.y;if(null!=l)if(fs(l-n)+fs(c-r)<.01)u(t,e,n,r,i,o,a,s);else{var f=t.point;t.x=t.y=t.point=null;u(t,f,l,c,i,o,a,s);u(t,e,n,r,i,o,a,s)}else t.x=n,t.y=r,t.point=e}else u(t,e,n,r,i,o,a,s)}function u(t,e,n,r,i,a,s,l){var u=.5*(i+s),c=.5*(a+l),f=n>=u,h=r>=c,d=(h<<1)+f;t.leaf=!1;t=t.nodes[d]||(t.nodes[d]=di());f?i=u:s=u;h?a=c:l=c;o(t,e,n,r,i,a,s,l)}var c,f,h,d,p,g,m,v,y,b=Me(s),x=Me(l);if(null!=e)g=e,m=n,v=r,y=i;else{v=y=-(g=m=1/0);f=[],h=[];p=t.length;if(a)for(d=0;p>d;++d){c=t[d];c.x<g&&(g=c.x);c.y<m&&(m=c.y);c.x>v&&(v=c.x);c.y>y&&(y=c.y);f.push(c.x);h.push(c.y)}else for(d=0;p>d;++d){var w=+b(c=t[d],d),S=+x(c,d);g>w&&(g=w);m>S&&(m=S);w>v&&(v=w);S>y&&(y=S);f.push(w);h.push(S)}}var C=v-g,T=y-m;C>T?y=m+C:v=g+T;var _=di();_.add=function(t){o(_,t,+b(t,++d),+x(t,d),g,m,v,y)};_.visit=function(t){pi(t,_,g,m,v,y)};d=-1;if(null==e){for(;++d<p;)o(_,t[d],f[d],h[d],g,m,v,y);--d}else t.forEach(_.add);f=h=t=c=null;return _}var a,s=Ar,l=Nr;if(a=arguments.length){s=fi;l=hi;if(3===a){i=n;r=e;n=e=0}return o(t)}o.x=function(t){return arguments.length?(s=t,o):s};o.y=function(t){return arguments.length?(l=t,o):l};o.extent=function(t){if(!arguments.length)return null==e?null:[[e,n],[r,i]];null==t?e=n=r=i=null:(e=+t[0][0],n=+t[0][1],r=+t[1][0],i=+t[1][1]);return o};o.size=function(t){if(!arguments.length)return null==e?null:[r-e,i-n];null==t?e=n=r=i=null:(e=n=0,r=+t[0],i=+t[1]);return o};return o};Ka.interpolateRgb=gi;Ka.interpolateObject=mi;Ka.interpolateNumber=vi;Ka.interpolateString=yi;var iu=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,ou=new RegExp(iu.source,"g");Ka.interpolate=bi;Ka.interpolators=[function(t,e){var n=typeof e;return("string"===n?Js.has(e)||/^(#|rgb\(|hsl\()/.test(e)?gi:yi:e instanceof se?gi:Array.isArray(e)?xi:"object"===n&&isNaN(e)?mi:vi)(t,e)}];Ka.interpolateArray=xi;var au=function(){return De},su=Ka.map({linear:au,poly:Mi,quad:function(){return Ti},cubic:function(){return _i},sin:function(){return Di},exp:function(){return Li},circle:function(){return Ai},elastic:Ni,back:Ei,bounce:function(){return ji}}),lu=Ka.map({"in":De,out:Si,"in-out":Ci,"out-in":function(t){return Ci(Si(t))}});Ka.ease=function(t){var e=t.indexOf("-"),n=e>=0?t.slice(0,e):t,r=e>=0?t.slice(e+1):"in";n=su.get(n)||au;r=lu.get(r)||De;return wi(r(n.apply(null,Za.call(arguments,1))))};Ka.interpolateHcl=Ii;Ka.interpolateHsl=Pi;Ka.interpolateLab=Hi;Ka.interpolateRound=Oi;Ka.transform=function(t){var e=ts.createElementNS(Ka.ns.prefix.svg,"g");return(Ka.transform=function(t){if(null!=t){e.setAttribute("transform",t);var n=e.transform.baseVal.consolidate()}return new Fi(n?n.matrix:uu)})(t)};Fi.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var uu={a:1,b:0,c:0,d:1,e:0,f:0};Ka.interpolateTransform=qi;Ka.layout={};Ka.layout.bundle=function(){return function(t){for(var e=[],n=-1,r=t.length;++n<r;)e.push(Vi(t[n]));return e}};Ka.layout.chord=function(){function t(){var t,u,f,h,d,p={},g=[],m=Ka.range(o),v=[];n=[];r=[];t=0,h=-1;for(;++h<o;){u=0,d=-1;for(;++d<o;)u+=i[h][d];g.push(u);v.push(Ka.range(o));t+=u}a&&m.sort(function(t,e){return a(g[t],g[e])});s&&v.forEach(function(t,e){t.sort(function(t,n){return s(i[e][t],i[e][n])})});t=(As-c*o)/t;u=0,h=-1;for(;++h<o;){f=u,d=-1;for(;++d<o;){var y=m[h],b=v[y][d],x=i[y][b],w=u,S=u+=x*t;p[y+"-"+b]={index:y,subindex:b,startAngle:w,endAngle:S,value:x}}r[y]={index:y,startAngle:f,endAngle:u,value:(u-f)/t};u+=c}h=-1;for(;++h<o;){d=h-1;for(;++d<o;){var C=p[h+"-"+d],T=p[d+"-"+h];(C.value||T.value)&&n.push(C.value<T.value?{source:T,target:C}:{source:C,target:T})}}l&&e()}function e(){n.sort(function(t,e){return l((t.source.value+t.target.value)/2,(e.source.value+e.target.value)/2)})}var n,r,i,o,a,s,l,u={},c=0;u.matrix=function(t){if(!arguments.length)return i;o=(i=t)&&i.length;n=r=null;return u};u.padding=function(t){if(!arguments.length)return c;c=t;n=r=null;return u};u.sortGroups=function(t){if(!arguments.length)return a;a=t;n=r=null;return u};u.sortSubgroups=function(t){if(!arguments.length)return s;s=t;n=null;return u};u.sortChords=function(t){if(!arguments.length)return l;l=t;n&&e();return u};u.chords=function(){n||t();return n};u.groups=function(){r||t();return r};return u};Ka.layout.force=function(){function t(t){return function(e,n,r,i){if(e.point!==t){var o=e.cx-t.x,a=e.cy-t.y,s=i-n,l=o*o+a*a;if(l>s*s/m){if(p>l){var u=e.charge/l;t.px-=o*u;t.py-=a*u}return!0}if(e.point&&l&&p>l){var u=e.pointCharge/l;t.px-=o*u;t.py-=a*u}}return!e.charge}}function e(t){t.px=Ka.event.x,t.py=Ka.event.y;s.resume()}var n,r,i,o,a,s={},l=Ka.dispatch("start","tick","end"),u=[1,1],c=.9,f=cu,h=fu,d=-30,p=hu,g=.1,m=.64,v=[],y=[];s.tick=function(){if((r*=.99)<.005){l.end({type:"end",alpha:r=0});return!0}var e,n,s,f,h,p,m,b,x,w=v.length,S=y.length;for(n=0;S>n;++n){s=y[n];f=s.source;h=s.target;b=h.x-f.x;x=h.y-f.y;if(p=b*b+x*x){p=r*o[n]*((p=Math.sqrt(p))-i[n])/p;b*=p;x*=p;h.x-=b*(m=f.weight/(h.weight+f.weight));h.y-=x*m;f.x+=b*(m=1-m);f.y+=x*m}}if(m=r*g){b=u[0]/2;x=u[1]/2;n=-1;if(m)for(;++n<w;){s=v[n];s.x+=(b-s.x)*m;s.y+=(x-s.y)*m}}if(d){Zi(e=Ka.geom.quadtree(v),r,a);n=-1;for(;++n<w;)(s=v[n]).fixed||e.visit(t(s))}n=-1;for(;++n<w;){s=v[n];if(s.fixed){s.x=s.px;s.y=s.py}else{s.x-=(s.px-(s.px=s.x))*c;s.y-=(s.py-(s.py=s.y))*c}}l.tick({type:"tick",alpha:r})};s.nodes=function(t){if(!arguments.length)return v;v=t;return s};s.links=function(t){if(!arguments.length)return y;y=t;return s};s.size=function(t){if(!arguments.length)return u;u=t;return s};s.linkDistance=function(t){if(!arguments.length)return f;f="function"==typeof t?t:+t;return s};s.distance=s.linkDistance;s.linkStrength=function(t){if(!arguments.length)return h;h="function"==typeof t?t:+t;return s};s.friction=function(t){if(!arguments.length)return c;c=+t;return s};s.charge=function(t){if(!arguments.length)return d;d="function"==typeof t?t:+t;return s};s.chargeDistance=function(t){if(!arguments.length)return Math.sqrt(p);p=t*t;return s};s.gravity=function(t){if(!arguments.length)return g;g=+t;return s};s.theta=function(t){if(!arguments.length)return Math.sqrt(m);m=t*t;return s};s.alpha=function(t){if(!arguments.length)return r;t=+t;if(r)r=t>0?t:0;else if(t>0){l.start({type:"start",alpha:r=t});Ka.timer(s.tick)}return s};s.start=function(){function t(t,r){if(!n){n=new Array(l);for(s=0;l>s;++s)n[s]=[];for(s=0;u>s;++s){var i=y[s];n[i.source.index].push(i.target);n[i.target.index].push(i.source)}}for(var o,a=n[e],s=-1,u=a.length;++s<u;)if(!isNaN(o=a[s][t]))return o;return Math.random()*r}var e,n,r,l=v.length,c=y.length,p=u[0],g=u[1];for(e=0;l>e;++e){(r=v[e]).index=e;r.weight=0}for(e=0;c>e;++e){r=y[e];"number"==typeof r.source&&(r.source=v[r.source]);"number"==typeof r.target&&(r.target=v[r.target]);++r.source.weight;++r.target.weight}for(e=0;l>e;++e){r=v[e];isNaN(r.x)&&(r.x=t("x",p));isNaN(r.y)&&(r.y=t("y",g));isNaN(r.px)&&(r.px=r.x);isNaN(r.py)&&(r.py=r.y)}i=[];if("function"==typeof f)for(e=0;c>e;++e)i[e]=+f.call(this,y[e],e);else for(e=0;c>e;++e)i[e]=f;o=[];if("function"==typeof h)for(e=0;c>e;++e)o[e]=+h.call(this,y[e],e);else for(e=0;c>e;++e)o[e]=h;a=[];if("function"==typeof d)for(e=0;l>e;++e)a[e]=+d.call(this,v[e],e);else for(e=0;l>e;++e)a[e]=d;return s.resume()};s.resume=function(){return s.alpha(.1)};s.stop=function(){return s.alpha(0)};s.drag=function(){n||(n=Ka.behavior.drag().origin(De).on("dragstart.force",$i).on("drag.force",e).on("dragend.force",Yi));if(!arguments.length)return n;this.on("mouseover.force",Ji).on("mouseout.force",Ki).call(n);return void 0};return Ka.rebind(s,l,"on")};var cu=20,fu=1,hu=1/0;Ka.layout.hierarchy=function(){function t(i){var o,a=[i],s=[];i.depth=0;for(;null!=(o=a.pop());){s.push(o);if((u=n.call(t,o,o.depth))&&(l=u.length)){for(var l,u,c;--l>=0;){a.push(c=u[l]);c.parent=o;c.depth=o.depth+1}r&&(o.value=0);o.children=u}else{r&&(o.value=+r.call(t,o,o.depth)||0);delete o.children}}eo(i,function(t){var n,i;e&&(n=t.children)&&n.sort(e);r&&(i=t.parent)&&(i.value+=t.value)});return s}var e=io,n=no,r=ro;t.sort=function(n){if(!arguments.length)return e;e=n;return t};t.children=function(e){if(!arguments.length)return n;n=e;return t};t.value=function(e){if(!arguments.length)return r;r=e;return t};t.revalue=function(e){if(r){to(e,function(t){t.children&&(t.value=0)});eo(e,function(e){var n;e.children||(e.value=+r.call(t,e,e.depth)||0);(n=e.parent)&&(n.value+=e.value)})}return e};return t};Ka.layout.partition=function(){function t(e,n,r,i){var o=e.children;e.x=n;e.y=e.depth*i;e.dx=r;e.dy=i;if(o&&(a=o.length)){var a,s,l,u=-1;r=e.value?r/e.value:0;for(;++u<a;){t(s=o[u],n,l=s.value*r,i);n+=l}}}function e(t){var n=t.children,r=0;if(n&&(i=n.length))for(var i,o=-1;++o<i;)r=Math.max(r,e(n[o]));return 1+r}function n(n,o){var a=r.call(this,n,o);t(a[0],0,i[0],i[1]/e(a[0]));return a}var r=Ka.layout.hierarchy(),i=[1,1];n.size=function(t){if(!arguments.length)return i;i=t;return n};return Qi(n,r)};Ka.layout.pie=function(){function t(o){var a=o.map(function(n,r){return+e.call(t,n,r)}),s=+("function"==typeof r?r.apply(this,arguments):r),l=(("function"==typeof i?i.apply(this,arguments):i)-s)/Ka.sum(a),u=Ka.range(o.length);null!=n&&u.sort(n===du?function(t,e){return a[e]-a[t]}:function(t,e){return n(o[t],o[e])});var c=[];u.forEach(function(t){var e;c[t]={data:o[t],value:e=a[t],startAngle:s,endAngle:s+=e*l}});return c}var e=Number,n=du,r=0,i=As;t.value=function(n){if(!arguments.length)return e;e=n;return t};t.sort=function(e){if(!arguments.length)return n;n=e;return t};t.startAngle=function(e){if(!arguments.length)return r;r=e;return t};t.endAngle=function(e){if(!arguments.length)return i;i=e;return t};return t};var du={};Ka.layout.stack=function(){function t(s,l){if(!(h=s.length))return s;var u=s.map(function(n,r){return e.call(t,n,r)}),c=u.map(function(e){return e.map(function(e,n){return[o.call(t,e,n),a.call(t,e,n)]})}),f=n.call(t,c,l);u=Ka.permute(u,f);c=Ka.permute(c,f);var h,d,p,g,m=r.call(t,c,l),v=u[0].length;for(p=0;v>p;++p){i.call(t,u[0][p],g=m[p],c[0][p][1]);for(d=1;h>d;++d)i.call(t,u[d][p],g+=c[d-1][p][1],c[d][p][1])}return s}var e=De,n=uo,r=co,i=lo,o=ao,a=so;t.values=function(n){if(!arguments.length)return e;e=n;return t};t.order=function(e){if(!arguments.length)return n;n="function"==typeof e?e:pu.get(e)||uo;return t};t.offset=function(e){if(!arguments.length)return r;r="function"==typeof e?e:gu.get(e)||co;return t};t.x=function(e){if(!arguments.length)return o;o=e;return t};t.y=function(e){if(!arguments.length)return a;a=e;return t};t.out=function(e){if(!arguments.length)return i;i=e;return t};return t};var pu=Ka.map({"inside-out":function(t){var e,n,r=t.length,i=t.map(fo),o=t.map(ho),a=Ka.range(r).sort(function(t,e){return i[t]-i[e]}),s=0,l=0,u=[],c=[];for(e=0;r>e;++e){n=a[e];if(l>s){s+=o[n];u.push(n)}else{l+=o[n];c.push(n)}}return c.reverse().concat(u)},reverse:function(t){return Ka.range(t.length).reverse()},"default":uo}),gu=Ka.map({silhouette:function(t){var e,n,r,i=t.length,o=t[0].length,a=[],s=0,l=[];for(n=0;o>n;++n){for(e=0,r=0;i>e;e++)r+=t[e][n][1];r>s&&(s=r);a.push(r)}for(n=0;o>n;++n)l[n]=(s-a[n])/2;return l},wiggle:function(t){var e,n,r,i,o,a,s,l,u,c=t.length,f=t[0],h=f.length,d=[];d[0]=l=u=0;for(n=1;h>n;++n){for(e=0,i=0;c>e;++e)i+=t[e][n][1];for(e=0,o=0,s=f[n][0]-f[n-1][0];c>e;++e){for(r=0,a=(t[e][n][1]-t[e][n-1][1])/(2*s);e>r;++r)a+=(t[r][n][1]-t[r][n-1][1])/s;o+=a*t[e][n][1]}d[n]=l-=i?o/i*s:0;u>l&&(u=l)}for(n=0;h>n;++n)d[n]-=u;return d},expand:function(t){var e,n,r,i=t.length,o=t[0].length,a=1/i,s=[];for(n=0;o>n;++n){for(e=0,r=0;i>e;e++)r+=t[e][n][1];if(r)for(e=0;i>e;e++)t[e][n][1]/=r;else for(e=0;i>e;e++)t[e][n][1]=a}for(n=0;o>n;++n)s[n]=0;return s},zero:co});Ka.layout.histogram=function(){function t(t,o){for(var a,s,l=[],u=t.map(n,this),c=r.call(this,u,o),f=i.call(this,c,u,o),o=-1,h=u.length,d=f.length-1,p=e?1:1/h;++o<d;){a=l[o]=[];a.dx=f[o+1]-(a.x=f[o]);a.y=0}if(d>0){o=-1;for(;++o<h;){s=u[o];if(s>=c[0]&&s<=c[1]){a=l[Ka.bisect(f,s,1,d)-1];a.y+=p;a.push(t[o])}}}return l}var e=!0,n=Number,r=vo,i=go;t.value=function(e){if(!arguments.length)return n;n=e;return t};t.range=function(e){if(!arguments.length)return r;r=Me(e);return t};t.bins=function(e){if(!arguments.length)return i;i="number"==typeof e?function(t){return mo(t,e)}:Me(e);return t};t.frequency=function(n){if(!arguments.length)return e;e=!!n;return t};return t};Ka.layout.pack=function(){function t(t,o){var a=n.call(this,t,o),s=a[0],l=i[0],u=i[1],c=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};s.x=s.y=0;eo(s,function(t){t.r=+c(t.value)});eo(s,So);if(r){var f=r*(e?1:Math.max(2*s.r/l,2*s.r/u))/2;eo(s,function(t){t.r+=f});eo(s,So);eo(s,function(t){t.r-=f})}_o(s,l/2,u/2,e?1:1/Math.max(2*s.r/l,2*s.r/u));return a}var e,n=Ka.layout.hierarchy().sort(yo),r=0,i=[1,1];t.size=function(e){if(!arguments.length)return i;i=e;return t};t.radius=function(n){if(!arguments.length)return e;e=null==n||"function"==typeof n?n:+n;return t};t.padding=function(e){if(!arguments.length)return r;r=+e;return t};return Qi(t,n)};Ka.layout.tree=function(){function t(t,i){var c=a.call(this,t,i),f=c[0],h=e(f);eo(h,n),h.parent.m=-h.z;to(h,r);if(u)to(f,o);else{var d=f,p=f,g=f;to(f,function(t){t.x<d.x&&(d=t);t.x>p.x&&(p=t);t.depth>g.depth&&(g=t)});var m=s(d,p)/2-d.x,v=l[0]/(p.x+s(p,d)/2+m),y=l[1]/(g.depth||1);to(f,function(t){t.x=(t.x+m)*v;t.y=t.depth*y})}return c}function e(t){for(var e,n={A:null,children:[t]},r=[n];null!=(e=r.pop());)for(var i,o=e.children,a=0,s=o.length;s>a;++a)r.push((o[a]=i={_:o[a],parent:e,children:(i=o[a].children)&&i.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:a}).a=i);return n.children[0]}function n(t){var e=t.children,n=t.parent.children,r=t.i?n[t.i-1]:null;if(e.length){No(t);var o=(e[0].z+e[e.length-1].z)/2;if(r){t.z=r.z+s(t._,r._);t.m=t.z-o}else t.z=o}else r&&(t.z=r.z+s(t._,r._));t.parent.A=i(t,r,t.parent.A||n[0])}function r(t){t._.x=t.z+t.parent.m;t.m+=t.parent.m}function i(t,e,n){if(e){for(var r,i=t,o=t,a=e,l=i.parent.children[0],u=i.m,c=o.m,f=a.m,h=l.m;a=Lo(a),i=Do(i),a&&i;){l=Do(l);o=Lo(o);o.a=t;r=a.z+f-i.z-u+s(a._,i._);if(r>0){Ao(Eo(a,t,n),t,r);u+=r;c+=r}f+=a.m;u+=i.m;h+=l.m;c+=o.m}if(a&&!Lo(o)){o.t=a;o.m+=f-c}if(i&&!Do(l)){l.t=i;l.m+=u-h;n=t}}return n}function o(t){t.x*=l[0];t.y=t.depth*l[1]}var a=Ka.layout.hierarchy().sort(null).value(null),s=Mo,l=[1,1],u=null;t.separation=function(e){if(!arguments.length)return s;s=e;return t};t.size=function(e){if(!arguments.length)return u?null:l;u=null==(l=e)?o:null;return t};t.nodeSize=function(e){if(!arguments.length)return u?l:null;u=null==(l=e)?null:o;return t};return Qi(t,a)};Ka.layout.cluster=function(){function t(t,o){var a,s=e.call(this,t,o),l=s[0],u=0;eo(l,function(t){var e=t.children;if(e&&e.length){t.x=Io(e);t.y=jo(e)}else{t.x=a?u+=n(t,a):0;t.y=0;a=t}});var c=Po(l),f=Ho(l),h=c.x-n(c,f)/2,d=f.x+n(f,c)/2;eo(l,i?function(t){t.x=(t.x-l.x)*r[0];t.y=(l.y-t.y)*r[1]}:function(t){t.x=(t.x-h)/(d-h)*r[0];t.y=(1-(l.y?t.y/l.y:1))*r[1]});return s}var e=Ka.layout.hierarchy().sort(null).value(null),n=Mo,r=[1,1],i=!1;t.separation=function(e){if(!arguments.length)return n;n=e;return t};t.size=function(e){if(!arguments.length)return i?null:r;i=null==(r=e);return t};t.nodeSize=function(e){if(!arguments.length)return i?r:null;i=null!=(r=e);return t};return Qi(t,e)};Ka.layout.treemap=function(){function t(t,e){for(var n,r,i=-1,o=t.length;++i<o;){r=(n=t[i]).value*(0>e?0:e);n.area=isNaN(r)||0>=r?0:r}}function e(n){var o=n.children;if(o&&o.length){var a,s,l,u=f(n),c=[],h=o.slice(),p=1/0,g="slice"===d?u.dx:"dice"===d?u.dy:"slice-dice"===d?1&n.depth?u.dy:u.dx:Math.min(u.dx,u.dy);t(h,u.dx*u.dy/n.value);c.area=0;for(;(l=h.length)>0;){c.push(a=h[l-1]);c.area+=a.area;if("squarify"!==d||(s=r(c,g))<=p){h.pop();p=s}else{c.area-=c.pop().area;i(c,g,u,!1);g=Math.min(u.dx,u.dy);c.length=c.area=0;p=1/0}}if(c.length){i(c,g,u,!0);c.length=c.area=0}o.forEach(e)}}function n(e){var r=e.children;if(r&&r.length){var o,a=f(e),s=r.slice(),l=[];t(s,a.dx*a.dy/e.value);l.area=0;for(;o=s.pop();){l.push(o);l.area+=o.area;if(null!=o.z){i(l,o.z?a.dx:a.dy,a,!s.length);l.length=l.area=0}}r.forEach(n)}}function r(t,e){for(var n,r=t.area,i=0,o=1/0,a=-1,s=t.length;++a<s;)if(n=t[a].area){o>n&&(o=n);n>i&&(i=n)}r*=r;e*=e;return r?Math.max(e*i*p/r,r/(e*o*p)):1/0}function i(t,e,n,r){var i,o=-1,a=t.length,s=n.x,u=n.y,c=e?l(t.area/e):0;if(e==n.dx){(r||c>n.dy)&&(c=n.dy);for(;++o<a;){i=t[o];i.x=s;i.y=u;i.dy=c;s+=i.dx=Math.min(n.x+n.dx-s,c?l(i.area/c):0)}i.z=!0;i.dx+=n.x+n.dx-s;n.y+=c;n.dy-=c}else{(r||c>n.dx)&&(c=n.dx);for(;++o<a;){i=t[o];i.x=s;i.y=u;i.dx=c;u+=i.dy=Math.min(n.y+n.dy-u,c?l(i.area/c):0)}i.z=!1;i.dy+=n.y+n.dy-u;n.x+=c;n.dx-=c}}function o(r){var i=a||s(r),o=i[0];o.x=0;o.y=0;o.dx=u[0];o.dy=u[1];a&&s.revalue(o);t([o],o.dx*o.dy/o.value);(a?n:e)(o);h&&(a=i);return i}var a,s=Ka.layout.hierarchy(),l=Math.round,u=[1,1],c=null,f=Oo,h=!1,d="squarify",p=.5*(1+Math.sqrt(5));o.size=function(t){if(!arguments.length)return u;u=t;return o};o.padding=function(t){function e(e){var n=t.call(o,e,e.depth);return null==n?Oo(e):Fo(e,"number"==typeof n?[n,n,n,n]:n)}function n(e){return Fo(e,t)}if(!arguments.length)return c;var r;f=null==(c=t)?Oo:"function"==(r=typeof t)?e:"number"===r?(t=[t,t,t,t],n):n;return o};o.round=function(t){if(!arguments.length)return l!=Number;l=t?Math.round:Number;return o};o.sticky=function(t){if(!arguments.length)return h;h=t;a=null;return o};o.ratio=function(t){if(!arguments.length)return p;p=t;return o};o.mode=function(t){if(!arguments.length)return d;d=t+"";return o};return Qi(o,s)};Ka.random={normal:function(t,e){var n=arguments.length;2>n&&(e=1);1>n&&(t=0);return function(){var n,r,i;do{n=2*Math.random()-1;r=2*Math.random()-1;i=n*n+r*r}while(!i||i>1);return t+e*n*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var t=Ka.random.normal.apply(Ka,arguments);return function(){return Math.exp(t())}},bates:function(t){var e=Ka.random.irwinHall(t);return function(){return e()/t}},irwinHall:function(t){return function(){for(var e=0,n=0;t>n;n++)e+=Math.random();return e}}};Ka.scale={};var mu={floor:De,ceil:De};Ka.scale.linear=function(){return Vo([0,1],[0,1],bi,!1)};var vu={s:1,g:1,p:1,r:1,e:1};Ka.scale.log=function(){return Qo(Ka.scale.linear().domain([0,1]),10,!0,[1,10])};var yu=Ka.format(".0e"),bu={floor:function(t){return-Math.ceil(-t)},ceil:function(t){return-Math.floor(-t)}};Ka.scale.pow=function(){return ta(Ka.scale.linear(),1,[0,1])};Ka.scale.sqrt=function(){return Ka.scale.pow().exponent(.5)};Ka.scale.ordinal=function(){return na([],{t:"range",a:[[]]})};Ka.scale.category10=function(){return Ka.scale.ordinal().range(xu)};Ka.scale.category20=function(){return Ka.scale.ordinal().range(wu)};Ka.scale.category20b=function(){return Ka.scale.ordinal().range(Su)};Ka.scale.category20c=function(){return Ka.scale.ordinal().range(Cu)};var xu=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(xe),wu=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(xe),Su=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(xe),Cu=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(xe);Ka.scale.quantile=function(){return ra([],[])};Ka.scale.quantize=function(){return ia(0,1,[0,1])};Ka.scale.threshold=function(){return oa([.5],[0,1])};Ka.scale.identity=function(){return aa([0,1])};Ka.svg={};Ka.svg.arc=function(){function t(){var t=e.apply(this,arguments),o=n.apply(this,arguments),a=r.apply(this,arguments)+Tu,s=i.apply(this,arguments)+Tu,l=(a>s&&(l=a,a=s,s=l),s-a),u=Ls>l?"0":"1",c=Math.cos(a),f=Math.sin(a),h=Math.cos(s),d=Math.sin(s);return l>=_u?t?"M0,"+o+"A"+o+","+o+" 0 1,1 0,"+-o+"A"+o+","+o+" 0 1,1 0,"+o+"M0,"+t+"A"+t+","+t+" 0 1,0 0,"+-t+"A"+t+","+t+" 0 1,0 0,"+t+"Z":"M0,"+o+"A"+o+","+o+" 0 1,1 0,"+-o+"A"+o+","+o+" 0 1,1 0,"+o+"Z":t?"M"+o*c+","+o*f+"A"+o+","+o+" 0 "+u+",1 "+o*h+","+o*d+"L"+t*h+","+t*d+"A"+t+","+t+" 0 "+u+",0 "+t*c+","+t*f+"Z":"M"+o*c+","+o*f+"A"+o+","+o+" 0 "+u+",1 "+o*h+","+o*d+"L0,0Z"}var e=sa,n=la,r=ua,i=ca;t.innerRadius=function(n){if(!arguments.length)return e;e=Me(n);return t};t.outerRadius=function(e){if(!arguments.length)return n;n=Me(e);return t};t.startAngle=function(e){if(!arguments.length)return r;r=Me(e);return t};t.endAngle=function(e){if(!arguments.length)return i;i=Me(e);return t};t.centroid=function(){var t=(e.apply(this,arguments)+n.apply(this,arguments))/2,o=(r.apply(this,arguments)+i.apply(this,arguments))/2+Tu;return[Math.cos(o)*t,Math.sin(o)*t]};return t};var Tu=-Ns,_u=As-Es;Ka.svg.line=function(){return fa(De)};var ku=Ka.map({linear:ha,"linear-closed":da,step:pa,"step-before":ga,"step-after":ma,basis:Sa,"basis-open":Ca,"basis-closed":Ta,bundle:_a,cardinal:ba,"cardinal-open":va,"cardinal-closed":ya,monotone:Na});ku.forEach(function(t,e){e.key=t;e.closed=/-closed$/.test(t)});var Mu=[0,2/3,1/3,0],Du=[0,1/3,2/3,0],Lu=[0,1/6,2/3,1/6];
Ka.svg.line.radial=function(){var t=fa(Ea);t.radius=t.x,delete t.x;t.angle=t.y,delete t.y;return t};ga.reverse=ma;ma.reverse=ga;Ka.svg.area=function(){return ja(De)};Ka.svg.area.radial=function(){var t=ja(Ea);t.radius=t.x,delete t.x;t.innerRadius=t.x0,delete t.x0;t.outerRadius=t.x1,delete t.x1;t.angle=t.y,delete t.y;t.startAngle=t.y0,delete t.y0;t.endAngle=t.y1,delete t.y1;return t};Ka.svg.chord=function(){function t(t,s){var l=e(this,o,t,s),u=e(this,a,t,s);return"M"+l.p0+r(l.r,l.p1,l.a1-l.a0)+(n(l,u)?i(l.r,l.p1,l.r,l.p0):i(l.r,l.p1,u.r,u.p0)+r(u.r,u.p1,u.a1-u.a0)+i(u.r,u.p1,l.r,l.p0))+"Z"}function e(t,e,n,r){var i=e.call(t,n,r),o=s.call(t,i,r),a=l.call(t,i,r)+Tu,c=u.call(t,i,r)+Tu;return{r:o,a0:a,a1:c,p0:[o*Math.cos(a),o*Math.sin(a)],p1:[o*Math.cos(c),o*Math.sin(c)]}}function n(t,e){return t.a0==e.a0&&t.a1==e.a1}function r(t,e,n){return"A"+t+","+t+" 0 "+ +(n>Ls)+",1 "+e}function i(t,e,n,r){return"Q 0,0 "+r}var o=xr,a=wr,s=Ia,l=ua,u=ca;t.radius=function(e){if(!arguments.length)return s;s=Me(e);return t};t.source=function(e){if(!arguments.length)return o;o=Me(e);return t};t.target=function(e){if(!arguments.length)return a;a=Me(e);return t};t.startAngle=function(e){if(!arguments.length)return l;l=Me(e);return t};t.endAngle=function(e){if(!arguments.length)return u;u=Me(e);return t};return t};Ka.svg.diagonal=function(){function t(t,i){var o=e.call(this,t,i),a=n.call(this,t,i),s=(o.y+a.y)/2,l=[o,{x:o.x,y:s},{x:a.x,y:s},a];l=l.map(r);return"M"+l[0]+"C"+l[1]+" "+l[2]+" "+l[3]}var e=xr,n=wr,r=Pa;t.source=function(n){if(!arguments.length)return e;e=Me(n);return t};t.target=function(e){if(!arguments.length)return n;n=Me(e);return t};t.projection=function(e){if(!arguments.length)return r;r=e;return t};return t};Ka.svg.diagonal.radial=function(){var t=Ka.svg.diagonal(),e=Pa,n=t.projection;t.projection=function(t){return arguments.length?n(Ha(e=t)):e};return t};Ka.svg.symbol=function(){function t(t,r){return(Au.get(e.call(this,t,r))||Ra)(n.call(this,t,r))}var e=Fa,n=Oa;t.type=function(n){if(!arguments.length)return e;e=Me(n);return t};t.size=function(e){if(!arguments.length)return n;n=Me(e);return t};return t};var Au=Ka.map({circle:Ra,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*Iu)),n=e*Iu;return"M0,"+-e+"L"+n+",0 0,"+e+" "+-n+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/ju),n=e*ju/2;return"M0,"+n+"L"+e+","+-n+" "+-e+","+-n+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/ju),n=e*ju/2;return"M0,"+-n+"L"+e+","+n+" "+-e+","+n+"Z"}});Ka.svg.symbolTypes=Au.keys();var Nu,Eu,ju=Math.sqrt(3),Iu=Math.tan(30*Is),Pu=[],Hu=0;Pu.call=ws.call;Pu.empty=ws.empty;Pu.node=ws.node;Pu.size=ws.size;Ka.transition=function(t){return arguments.length?Nu?t.transition():t:Ts.transition()};Ka.transition.prototype=Pu;Pu.select=function(t){var e,n,r,i=this.id,o=[];t=M(t);for(var a=-1,s=this.length;++a<s;){o.push(e=[]);for(var l=this[a],u=-1,c=l.length;++u<c;)if((r=l[u])&&(n=t.call(r,r.__data__,u,a))){"__data__"in r&&(n.__data__=r.__data__);Ua(n,u,i,r.__transition__[i]);e.push(n)}else e.push(null)}return Wa(o,i)};Pu.selectAll=function(t){var e,n,r,i,o,a=this.id,s=[];t=D(t);for(var l=-1,u=this.length;++l<u;)for(var c=this[l],f=-1,h=c.length;++f<h;)if(r=c[f]){o=r.__transition__[a];n=t.call(r,r.__data__,f,l);s.push(e=[]);for(var d=-1,p=n.length;++d<p;){(i=n[d])&&Ua(i,d,a,o);e.push(i)}}return Wa(s,a)};Pu.filter=function(t){var e,n,r,i=[];"function"!=typeof t&&(t=R(t));for(var o=0,a=this.length;a>o;o++){i.push(e=[]);for(var n=this[o],s=0,l=n.length;l>s;s++)(r=n[s])&&t.call(r,r.__data__,s,o)&&e.push(r)}return Wa(i,this.id)};Pu.tween=function(t,e){var n=this.id;return arguments.length<2?this.node().__transition__[n].tween.get(t):z(this,null==e?function(e){e.__transition__[n].tween.remove(t)}:function(r){r.__transition__[n].tween.set(t,e)})};Pu.attr=function(t,e){function n(){this.removeAttribute(s)}function r(){this.removeAttributeNS(s.space,s.local)}function i(t){return null==t?n:(t+="",function(){var e,n=this.getAttribute(s);return n!==t&&(e=a(n,t),function(t){this.setAttribute(s,e(t))})})}function o(t){return null==t?r:(t+="",function(){var e,n=this.getAttributeNS(s.space,s.local);return n!==t&&(e=a(n,t),function(t){this.setAttributeNS(s.space,s.local,e(t))})})}if(arguments.length<2){for(e in t)this.attr(e,t[e]);return this}var a="transform"==t?qi:bi,s=Ka.ns.qualify(t);return za(this,"attr."+t,e,s.local?o:i)};Pu.attrTween=function(t,e){function n(t,n){var r=e.call(this,t,n,this.getAttribute(i));return r&&function(t){this.setAttribute(i,r(t))}}function r(t,n){var r=e.call(this,t,n,this.getAttributeNS(i.space,i.local));return r&&function(t){this.setAttributeNS(i.space,i.local,r(t))}}var i=Ka.ns.qualify(t);return this.tween("attr."+t,i.local?r:n)};Pu.style=function(t,e,n){function r(){this.style.removeProperty(t)}function i(e){return null==e?r:(e+="",function(){var r,i=ns.getComputedStyle(this,null).getPropertyValue(t);return i!==e&&(r=bi(i,e),function(e){this.style.setProperty(t,r(e),n)})})}var o=arguments.length;if(3>o){if("string"!=typeof t){2>o&&(e="");for(n in t)this.style(n,t[n],e);return this}n=""}return za(this,"style."+t,e,i)};Pu.styleTween=function(t,e,n){function r(r,i){var o=e.call(this,r,i,ns.getComputedStyle(this,null).getPropertyValue(t));return o&&function(e){this.style.setProperty(t,o(e),n)}}arguments.length<3&&(n="");return this.tween("style."+t,r)};Pu.text=function(t){return za(this,"text",t,qa)};Pu.remove=function(){return this.each("end.transition",function(){var t;this.__transition__.count<2&&(t=this.parentNode)&&t.removeChild(this)})};Pu.ease=function(t){var e=this.id;if(arguments.length<1)return this.node().__transition__[e].ease;"function"!=typeof t&&(t=Ka.ease.apply(Ka,arguments));return z(this,function(n){n.__transition__[e].ease=t})};Pu.delay=function(t){var e=this.id;return arguments.length<1?this.node().__transition__[e].delay:z(this,"function"==typeof t?function(n,r,i){n.__transition__[e].delay=+t.call(n,n.__data__,r,i)}:(t=+t,function(n){n.__transition__[e].delay=t}))};Pu.duration=function(t){var e=this.id;return arguments.length<1?this.node().__transition__[e].duration:z(this,"function"==typeof t?function(n,r,i){n.__transition__[e].duration=Math.max(1,t.call(n,n.__data__,r,i))}:(t=Math.max(1,t),function(n){n.__transition__[e].duration=t}))};Pu.each=function(t,e){var n=this.id;if(arguments.length<2){var r=Eu,i=Nu;Nu=n;z(this,function(e,r,i){Eu=e.__transition__[n];t.call(e,e.__data__,r,i)});Eu=r;Nu=i}else z(this,function(r){var i=r.__transition__[n];(i.event||(i.event=Ka.dispatch("start","end"))).on(t,e)});return this};Pu.transition=function(){for(var t,e,n,r,i=this.id,o=++Hu,a=[],s=0,l=this.length;l>s;s++){a.push(t=[]);for(var e=this[s],u=0,c=e.length;c>u;u++){if(n=e[u]){r=Object.create(n.__transition__[i]);r.delay+=r.duration;Ua(n,u,o,r)}t.push(n)}}return Wa(a,o)};Ka.svg.axis=function(){function t(t){t.each(function(){var t,u=Ka.select(this),c=this.__chart__||n,f=this.__chart__=n.copy(),h=null==l?f.ticks?f.ticks.apply(f,s):f.domain():l,d=null==e?f.tickFormat?f.tickFormat.apply(f,s):De:e,p=u.selectAll(".tick").data(h,f),g=p.enter().insert("g",".domain").attr("class","tick").style("opacity",Es),m=Ka.transition(p.exit()).style("opacity",Es).remove(),v=Ka.transition(p.order()).style("opacity",1),y=Math.max(i,0)+a,b=Wo(f),x=u.selectAll(".domain").data([0]),w=(x.enter().append("path").attr("class","domain"),Ka.transition(x));g.append("line");g.append("text");var S,C,T,_,k=g.select("line"),M=v.select("line"),D=p.select("text").text(d),L=g.select("text"),A=v.select("text"),N="top"===r||"left"===r?-1:1;if("bottom"===r||"top"===r){t=Ba,S="x",T="y",C="x2",_="y2";D.attr("dy",0>N?"0em":".71em").style("text-anchor","middle");w.attr("d","M"+b[0]+","+N*o+"V0H"+b[1]+"V"+N*o)}else{t=Va,S="y",T="x",C="y2",_="x2";D.attr("dy",".32em").style("text-anchor",0>N?"end":"start");w.attr("d","M"+N*o+","+b[0]+"H0V"+b[1]+"H"+N*o)}k.attr(_,N*i);L.attr(T,N*y);M.attr(C,0).attr(_,N*i);A.attr(S,0).attr(T,N*y);if(f.rangeBand){var E=f,j=E.rangeBand()/2;c=f=function(t){return E(t)+j}}else c.rangeBand?c=f:m.call(t,f,c);g.call(t,c,f);v.call(t,f,f)})}var e,n=Ka.scale.linear(),r=Ou,i=6,o=6,a=3,s=[10],l=null;t.scale=function(e){if(!arguments.length)return n;n=e;return t};t.orient=function(e){if(!arguments.length)return r;r=e in Fu?e+"":Ou;return t};t.ticks=function(){if(!arguments.length)return s;s=arguments;return t};t.tickValues=function(e){if(!arguments.length)return l;l=e;return t};t.tickFormat=function(n){if(!arguments.length)return e;e=n;return t};t.tickSize=function(e){var n=arguments.length;if(!n)return i;i=+e;o=+arguments[n-1];return t};t.innerTickSize=function(e){if(!arguments.length)return i;i=+e;return t};t.outerTickSize=function(e){if(!arguments.length)return o;o=+e;return t};t.tickPadding=function(e){if(!arguments.length)return a;a=+e;return t};t.tickSubdivide=function(){return arguments.length&&t};return t};var Ou="bottom",Fu={top:1,right:1,bottom:1,left:1};Ka.svg.brush=function(){function t(o){o.each(function(){var o=Ka.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",i).on("touchstart.brush",i),a=o.selectAll(".background").data([0]);a.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair");o.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var s=o.selectAll(".resize").data(p,De);s.exit().remove();s.enter().append("g").attr("class",function(t){return"resize "+t}).style("cursor",function(t){return Ru[t]}).append("rect").attr("x",function(t){return/[ew]$/.test(t)?-3:null}).attr("y",function(t){return/^[ns]/.test(t)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden");s.style("display",t.empty()?"none":null);var c,f=Ka.transition(o),h=Ka.transition(a);if(l){c=Wo(l);h.attr("x",c[0]).attr("width",c[1]-c[0]);n(f)}if(u){c=Wo(u);h.attr("y",c[0]).attr("height",c[1]-c[0]);r(f)}e(f)})}function e(t){t.selectAll(".resize").attr("transform",function(t){return"translate("+c[+/e$/.test(t)]+","+f[+/^s/.test(t)]+")"})}function n(t){t.select(".extent").attr("x",c[0]);t.selectAll(".extent,.n>rect,.s>rect").attr("width",c[1]-c[0])}function r(t){t.select(".extent").attr("y",f[0]);t.selectAll(".extent,.e>rect,.w>rect").attr("height",f[1]-f[0])}function i(){function i(){if(32==Ka.event.keyCode){if(!D){y=null;A[0]-=c[1];A[1]-=f[1];D=2}C()}}function p(){if(32==Ka.event.keyCode&&2==D){A[0]+=c[1];A[1]+=f[1];D=0;C()}}function g(){var t=Ka.mouse(x),i=!1;if(b){t[0]+=b[0];t[1]+=b[1]}if(!D)if(Ka.event.altKey){y||(y=[(c[0]+c[1])/2,(f[0]+f[1])/2]);A[0]=c[+(t[0]<y[0])];A[1]=f[+(t[1]<y[1])]}else y=null;if(k&&m(t,l,0)){n(T);i=!0}if(M&&m(t,u,1)){r(T);i=!0}if(i){e(T);S({type:"brush",mode:D?"move":"resize"})}}function m(t,e,n){var r,i,s=Wo(e),l=s[0],u=s[1],p=A[n],g=n?f:c,m=g[1]-g[0];if(D){l-=p;u-=m+p}r=(n?d:h)?Math.max(l,Math.min(u,t[n])):t[n];if(D)i=(r+=p)+m;else{y&&(p=Math.max(l,Math.min(u,2*y[n]-r)));if(r>p){i=r;r=p}else i=p}if(g[0]!=r||g[1]!=i){n?a=null:o=null;g[0]=r;g[1]=i;return!0}}function v(){g();T.style("pointer-events","all").selectAll(".resize").style("display",t.empty()?"none":null);Ka.select("body").style("cursor",null);N.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null);L();S({type:"brushend"})}var y,b,x=this,w=Ka.select(Ka.event.target),S=s.of(x,arguments),T=Ka.select(x),_=w.datum(),k=!/^(n|s)$/.test(_)&&l,M=!/^(e|w)$/.test(_)&&u,D=w.classed("extent"),L=$(),A=Ka.mouse(x),N=Ka.select(ns).on("keydown.brush",i).on("keyup.brush",p);Ka.event.changedTouches?N.on("touchmove.brush",g).on("touchend.brush",v):N.on("mousemove.brush",g).on("mouseup.brush",v);T.interrupt().selectAll("*").interrupt();if(D){A[0]=c[0]-A[0];A[1]=f[0]-A[1]}else if(_){var E=+/w$/.test(_),j=+/^n/.test(_);b=[c[1-E]-A[0],f[1-j]-A[1]];A[0]=c[E];A[1]=f[j]}else Ka.event.altKey&&(y=A.slice());T.style("pointer-events","none").selectAll(".resize").style("display",null);Ka.select("body").style("cursor",w.style("cursor"));S({type:"brushstart"});g()}var o,a,s=_(t,"brushstart","brush","brushend"),l=null,u=null,c=[0,0],f=[0,0],h=!0,d=!0,p=Wu[0];t.event=function(t){t.each(function(){var t=s.of(this,arguments),e={x:c,y:f,i:o,j:a},n=this.__chart__||e;this.__chart__=e;if(Nu)Ka.select(this).transition().each("start.brush",function(){o=n.i;a=n.j;c=n.x;f=n.y;t({type:"brushstart"})}).tween("brush:brush",function(){var n=xi(c,e.x),r=xi(f,e.y);o=a=null;return function(i){c=e.x=n(i);f=e.y=r(i);t({type:"brush",mode:"resize"})}}).each("end.brush",function(){o=e.i;a=e.j;t({type:"brush",mode:"resize"});t({type:"brushend"})});else{t({type:"brushstart"});t({type:"brush",mode:"resize"});t({type:"brushend"})}})};t.x=function(e){if(!arguments.length)return l;l=e;p=Wu[!l<<1|!u];return t};t.y=function(e){if(!arguments.length)return u;u=e;p=Wu[!l<<1|!u];return t};t.clamp=function(e){if(!arguments.length)return l&&u?[h,d]:l?h:u?d:null;l&&u?(h=!!e[0],d=!!e[1]):l?h=!!e:u&&(d=!!e);return t};t.extent=function(e){var n,r,i,s,h;if(!arguments.length){if(l)if(o)n=o[0],r=o[1];else{n=c[0],r=c[1];l.invert&&(n=l.invert(n),r=l.invert(r));n>r&&(h=n,n=r,r=h)}if(u)if(a)i=a[0],s=a[1];else{i=f[0],s=f[1];u.invert&&(i=u.invert(i),s=u.invert(s));i>s&&(h=i,i=s,s=h)}return l&&u?[[n,i],[r,s]]:l?[n,r]:u&&[i,s]}if(l){n=e[0],r=e[1];u&&(n=n[0],r=r[0]);o=[n,r];l.invert&&(n=l(n),r=l(r));n>r&&(h=n,n=r,r=h);(n!=c[0]||r!=c[1])&&(c=[n,r])}if(u){i=e[0],s=e[1];l&&(i=i[1],s=s[1]);a=[i,s];u.invert&&(i=u(i),s=u(s));i>s&&(h=i,i=s,s=h);(i!=f[0]||s!=f[1])&&(f=[i,s])}return t};t.clear=function(){if(!t.empty()){c=[0,0],f=[0,0];o=a=null}return t};t.empty=function(){return!!l&&c[0]==c[1]||!!u&&f[0]==f[1]};return Ka.rebind(t,s,"on")};var Ru={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Wu=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],zu=al.format=hl.timeFormat,qu=zu.utc,Uu=qu("%Y-%m-%dT%H:%M:%S.%LZ");zu.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Xa:Uu;Xa.parse=function(t){var e=new Date(t);return isNaN(e)?null:e};Xa.toString=Uu.toString;al.second=ze(function(t){return new sl(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()});al.seconds=al.second.range;al.seconds.utc=al.second.utc.range;al.minute=ze(function(t){return new sl(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()});al.minutes=al.minute.range;al.minutes.utc=al.minute.utc.range;al.hour=ze(function(t){var e=t.getTimezoneOffset()/60;return new sl(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()});al.hours=al.hour.range;al.hours.utc=al.hour.utc.range;al.month=ze(function(t){t=al.day(t);t.setDate(1);return t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()});al.months=al.month.range;al.months.utc=al.month.utc.range;var Bu=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],Vu=[[al.second,1],[al.second,5],[al.second,15],[al.second,30],[al.minute,1],[al.minute,5],[al.minute,15],[al.minute,30],[al.hour,1],[al.hour,3],[al.hour,6],[al.hour,12],[al.day,1],[al.day,2],[al.week,1],[al.month,1],[al.month,3],[al.year,1]],Xu=zu.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",An]]),Gu={range:function(t,e,n){return Ka.range(Math.ceil(t/n)*n,+e,n).map($a)},floor:De,ceil:De};Vu.year=al.year;al.scale=function(){return Ga(Ka.scale.linear(),Vu,Xu)};var $u=Vu.map(function(t){return[t[0].utc,t[1]]}),Yu=qu.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",An]]);$u.year=al.year.utc;al.scale.utc=function(){return Ga(Ka.scale.linear(),$u,Yu)};Ka.text=Le(function(t){return t.responseText});Ka.json=function(t,e){return Ae(t,"application/json",Ya,e)};Ka.html=function(t,e){return Ae(t,"text/html",Ja,e)};Ka.xml=Le(function(t){return t.responseXML});"function"==typeof t&&t.amd?t(Ka):"object"==typeof n&&n.exports&&(n.exports=Ka);this.d3=Ka}()},{}],13:[function(t){var e=t("jquery");(function(t,e){function n(e,n){var i,o,a,s=e.nodeName.toLowerCase();if("area"===s){i=e.parentNode;o=i.name;if(!e.href||!o||"map"!==i.nodeName.toLowerCase())return!1;a=t("img[usemap=#"+o+"]")[0];return!!a&&r(a)}return(/input|select|textarea|button|object/.test(s)?!e.disabled:"a"===s?e.href||n:n)&&r(e)}function r(e){return t.expr.filters.visible(e)&&!t(e).parents().addBack().filter(function(){return"hidden"===t.css(this,"visibility")}).length}var i=0,o=/^ui-id-\d+$/;t.ui=t.ui||{};t.extend(t.ui,{version:"1.10.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}});t.fn.extend({focus:function(e){return function(n,r){return"number"==typeof n?this.each(function(){var e=this;setTimeout(function(){t(e).focus();r&&r.call(e)},n)}):e.apply(this,arguments)}}(t.fn.focus),scrollParent:function(){var e;e=t.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(t.css(this,"position"))&&/(auto|scroll)/.test(t.css(this,"overflow")+t.css(this,"overflow-y")+t.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(t.css(this,"overflow")+t.css(this,"overflow-y")+t.css(this,"overflow-x"))}).eq(0);return/fixed/.test(this.css("position"))||!e.length?t(document):e},zIndex:function(n){if(n!==e)return this.css("zIndex",n);if(this.length)for(var r,i,o=t(this[0]);o.length&&o[0]!==document;){r=o.css("position");if("absolute"===r||"relative"===r||"fixed"===r){i=parseInt(o.css("zIndex"),10);if(!isNaN(i)&&0!==i)return i}o=o.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++i)})},removeUniqueId:function(){return this.each(function(){o.test(this.id)&&t(this).removeAttr("id")})}});t.extend(t.expr[":"],{data:t.expr.createPseudo?t.expr.createPseudo(function(e){return function(n){return!!t.data(n,e)}}):function(e,n,r){return!!t.data(e,r[3])},focusable:function(e){return n(e,!isNaN(t.attr(e,"tabindex")))},tabbable:function(e){var r=t.attr(e,"tabindex"),i=isNaN(r);return(i||r>=0)&&n(e,!i)}});t("<a>").outerWidth(1).jquery||t.each(["Width","Height"],function(n,r){function i(e,n,r,i){t.each(o,function(){n-=parseFloat(t.css(e,"padding"+this))||0;r&&(n-=parseFloat(t.css(e,"border"+this+"Width"))||0);i&&(n-=parseFloat(t.css(e,"margin"+this))||0)});return n}var o="Width"===r?["Left","Right"]:["Top","Bottom"],a=r.toLowerCase(),s={innerWidth:t.fn.innerWidth,innerHeight:t.fn.innerHeight,outerWidth:t.fn.outerWidth,outerHeight:t.fn.outerHeight};t.fn["inner"+r]=function(n){return n===e?s["inner"+r].call(this):this.each(function(){t(this).css(a,i(this,n)+"px")})};t.fn["outer"+r]=function(e,n){return"number"!=typeof e?s["outer"+r].call(this,e):this.each(function(){t(this).css(a,i(this,e,!0,n)+"px")})}});t.fn.addBack||(t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))});t("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(t.fn.removeData=function(e){return function(n){return arguments.length?e.call(this,t.camelCase(n)):e.call(this)}}(t.fn.removeData));t.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());t.support.selectstart="onselectstart"in document.createElement("div");t.fn.extend({disableSelection:function(){return this.bind((t.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(t){t.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}});t.extend(t.ui,{plugin:{add:function(e,n,r){var i,o=t.ui[e].prototype;for(i in r){o.plugins[i]=o.plugins[i]||[];o.plugins[i].push([n,r[i]])}},call:function(t,e,n){var r,i=t.plugins[e];if(i&&t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType)for(r=0;r<i.length;r++)t.options[i[r][0]]&&i[r][1].apply(t.element,n)}},hasScroll:function(e,n){if("hidden"===t(e).css("overflow"))return!1;var r=n&&"left"===n?"scrollLeft":"scrollTop",i=!1;if(e[r]>0)return!0;e[r]=1;i=e[r]>0;e[r]=0;return i}})})(e)},{jquery:17}],14:[function(t){var e=t("jquery");t("./widget");(function(t){var e=!1;t(document).mouseup(function(){e=!1});t.widget("ui.mouse",{version:"1.10.4",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.bind("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).bind("click."+this.widgetName,function(n){if(!0===t.data(n.target,e.widgetName+".preventClickEvent")){t.removeData(n.target,e.widgetName+".preventClickEvent");n.stopImmediatePropagation();return!1}});this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);this._mouseMoveDelegate&&t(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(n){if(!e){this._mouseStarted&&this._mouseUp(n);this._mouseDownEvent=n;var r=this,i=1===n.which,o="string"==typeof this.options.cancel&&n.target.nodeName?t(n.target).closest(this.options.cancel).length:!1;if(!i||o||!this._mouseCapture(n))return!0;this.mouseDelayMet=!this.options.delay;this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){r.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(n)&&this._mouseDelayMet(n)){this._mouseStarted=this._mouseStart(n)!==!1;if(!this._mouseStarted){n.preventDefault();return!0}}!0===t.data(n.target,this.widgetName+".preventClickEvent")&&t.removeData(n.target,this.widgetName+".preventClickEvent");this._mouseMoveDelegate=function(t){return r._mouseMove(t)};this._mouseUpDelegate=function(t){return r._mouseUp(t)};t(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);n.preventDefault();e=!0;return!0}},_mouseMove:function(e){if(t.ui.ie&&(!document.documentMode||document.documentMode<9)&&!e.button)return this._mouseUp(e);if(this._mouseStarted){this._mouseDrag(e);return e.preventDefault()}if(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)){this._mouseStarted=this._mouseStart(this._mouseDownEvent,e)!==!1;this._mouseStarted?this._mouseDrag(e):this._mouseUp(e)}return!this._mouseStarted},_mouseUp:function(e){t(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=!1;e.target===this._mouseDownEvent.target&&t.data(e.target,this.widgetName+".preventClickEvent",!0);this._mouseStop(e)}return!1},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})})(e)},{"./widget":16,jquery:17}],15:[function(t){var e=t("jquery");t("./core");t("./mouse");t("./widget");(function(t){function e(t,e,n){return t>e&&e+n>t}function n(t){return/left|right/.test(t.css("float"))||/inline|table-cell/.test(t.css("display"))}t.widget("ui.sortable",t.ui.mouse,{version:"1.10.4",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_create:function(){var t=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?"x"===t.axis||n(this.items[0].item):!1;this.offset=this.element.offset();this._mouseInit();this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled");this._mouseDestroy();for(var t=this.items.length-1;t>=0;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_setOption:function(e,n){if("disabled"===e){this.options[e]=n;this.widget().toggleClass("ui-sortable-disabled",!!n)}else t.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(e,n){var r=null,i=!1,o=this;if(this.reverting)return!1;if(this.options.disabled||"static"===this.options.type)return!1;this._refreshItems(e);t(e.target).parents().each(function(){if(t.data(this,o.widgetName+"-item")===o){r=t(this);return!1}});t.data(e.target,o.widgetName+"-item")===o&&(r=t(e.target));if(!r)return!1;if(this.options.handle&&!n){t(this.options.handle,r).find("*").addBack().each(function(){this===e.target&&(i=!0)});if(!i)return!1}this.currentItem=r;this._removeCurrentsFromItems();return!0},_mouseStart:function(e,n,r){var i,o,a=this.options;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(e);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");this.originalPosition=this._generatePosition(e);this.originalPageX=e.pageX;this.originalPageY=e.pageY;a.cursorAt&&this._adjustOffsetFromHelper(a.cursorAt);this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};this.helper[0]!==this.currentItem[0]&&this.currentItem.hide();this._createPlaceholder();a.containment&&this._setContainment();if(a.cursor&&"auto"!==a.cursor){o=this.document.find("body");this.storedCursor=o.css("cursor");o.css("cursor",a.cursor);this.storedStylesheet=t("<style>*{ cursor: "+a.cursor+" !important; }</style>").appendTo(o)}if(a.opacity){this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity"));this.helper.css("opacity",a.opacity)}if(a.zIndex){this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex"));this.helper.css("zIndex",a.zIndex)}this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset());this._trigger("start",e,this._uiHash());this._preserveHelperProportions||this._cacheHelperProportions();if(!r)for(i=this.containers.length-1;i>=0;i--)this.containers[i]._trigger("activate",e,this._uiHash(this));t.ui.ddmanager&&(t.ui.ddmanager.current=this);t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e);this.dragging=!0;this.helper.addClass("ui-sortable-helper");this._mouseDrag(e);return!0},_mouseDrag:function(e){var n,r,i,o,a=this.options,s=!1;this.position=this._generatePosition(e);this.positionAbs=this._convertPositionTo("absolute");this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs);if(this.options.scroll){if(this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName){this.overflowOffset.top+this.scrollParent[0].offsetHeight-e.pageY<a.scrollSensitivity?this.scrollParent[0].scrollTop=s=this.scrollParent[0].scrollTop+a.scrollSpeed:e.pageY-this.overflowOffset.top<a.scrollSensitivity&&(this.scrollParent[0].scrollTop=s=this.scrollParent[0].scrollTop-a.scrollSpeed);this.overflowOffset.left+this.scrollParent[0].offsetWidth-e.pageX<a.scrollSensitivity?this.scrollParent[0].scrollLeft=s=this.scrollParent[0].scrollLeft+a.scrollSpeed:e.pageX-this.overflowOffset.left<a.scrollSensitivity&&(this.scrollParent[0].scrollLeft=s=this.scrollParent[0].scrollLeft-a.scrollSpeed)}else{e.pageY-t(document).scrollTop()<a.scrollSensitivity?s=t(document).scrollTop(t(document).scrollTop()-a.scrollSpeed):t(window).height()-(e.pageY-t(document).scrollTop())<a.scrollSensitivity&&(s=t(document).scrollTop(t(document).scrollTop()+a.scrollSpeed));e.pageX-t(document).scrollLeft()<a.scrollSensitivity?s=t(document).scrollLeft(t(document).scrollLeft()-a.scrollSpeed):t(window).width()-(e.pageX-t(document).scrollLeft())<a.scrollSensitivity&&(s=t(document).scrollLeft(t(document).scrollLeft()+a.scrollSpeed))}s!==!1&&t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e)}this.positionAbs=this._convertPositionTo("absolute");this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px");this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px");for(n=this.items.length-1;n>=0;n--){r=this.items[n];i=r.item[0];o=this._intersectsWithPointer(r);if(o&&r.instance===this.currentContainer&&i!==this.currentItem[0]&&this.placeholder[1===o?"next":"prev"]()[0]!==i&&!t.contains(this.placeholder[0],i)&&("semi-dynamic"===this.options.type?!t.contains(this.element[0],i):!0)){this.direction=1===o?"down":"up";if("pointer"!==this.options.tolerance&&!this._intersectsWithSides(r))break;this._rearrange(e,r);this._trigger("change",e,this._uiHash());break}}this._contactContainers(e);t.ui.ddmanager&&t.ui.ddmanager.drag(this,e);this._trigger("sort",e,this._uiHash());this.lastPositionAbs=this.positionAbs;return!1},_mouseStop:function(e,n){if(e){t.ui.ddmanager&&!this.options.dropBehaviour&&t.ui.ddmanager.drop(this,e);if(this.options.revert){var r=this,i=this.placeholder.offset(),o=this.options.axis,a={};o&&"x"!==o||(a.left=i.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft));o&&"y"!==o||(a.top=i.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop));this.reverting=!0;t(this.helper).animate(a,parseInt(this.options.revert,10)||500,function(){r._clear(e)})}else this._clear(e,n);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null});"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var e=this.containers.length-1;e>=0;e--){this.containers[e]._trigger("deactivate",null,this._uiHash(this));if(this.containers[e].containerCache.over){this.containers[e]._trigger("out",null,this._uiHash(this));this.containers[e].containerCache.over=0}}}if(this.placeholder){this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]);"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove();t.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null});this.domPosition.prev?t(this.domPosition.prev).after(this.currentItem):t(this.domPosition.parent).prepend(this.currentItem)}return this},serialize:function(e){var n=this._getItemsAsjQuery(e&&e.connected),r=[];e=e||{};t(n).each(function(){var n=(t(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);n&&r.push((e.key||n[1]+"[]")+"="+(e.key&&e.expression?n[1]:n[2]))
});!r.length&&e.key&&r.push(e.key+"=");return r.join("&")},toArray:function(e){var n=this._getItemsAsjQuery(e&&e.connected),r=[];e=e||{};n.each(function(){r.push(t(e.item||this).attr(e.attribute||"id")||"")});return r},_intersectsWith:function(t){var e=this.positionAbs.left,n=e+this.helperProportions.width,r=this.positionAbs.top,i=r+this.helperProportions.height,o=t.left,a=o+t.width,s=t.top,l=s+t.height,u=this.offset.click.top,c=this.offset.click.left,f="x"===this.options.axis||r+u>s&&l>r+u,h="y"===this.options.axis||e+c>o&&a>e+c,d=f&&h;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?d:o<e+this.helperProportions.width/2&&n-this.helperProportions.width/2<a&&s<r+this.helperProportions.height/2&&i-this.helperProportions.height/2<l},_intersectsWithPointer:function(t){var n="x"===this.options.axis||e(this.positionAbs.top+this.offset.click.top,t.top,t.height),r="y"===this.options.axis||e(this.positionAbs.left+this.offset.click.left,t.left,t.width),i=n&&r,o=this._getDragVerticalDirection(),a=this._getDragHorizontalDirection();return i?this.floating?a&&"right"===a||"down"===o?2:1:o&&("down"===o?2:1):!1},_intersectsWithSides:function(t){var n=e(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),r=e(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),i=this._getDragVerticalDirection(),o=this._getDragHorizontalDirection();return this.floating&&o?"right"===o&&r||"left"===o&&!r:i&&("down"===i&&n||"up"===i&&!n)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!==t&&(t>0?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!==t&&(t>0?"right":"left")},refresh:function(t){this._refreshItems(t);this.refreshPositions();return this},_connectWith:function(){var t=this.options;return t.connectWith.constructor===String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(e){function n(){s.push(this)}var r,i,o,a,s=[],l=[],u=this._connectWith();if(u&&e)for(r=u.length-1;r>=0;r--){o=t(u[r]);for(i=o.length-1;i>=0;i--){a=t.data(o[i],this.widgetFullName);a&&a!==this&&!a.options.disabled&&l.push([t.isFunction(a.options.items)?a.options.items.call(a.element):t(a.options.items,a.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),a])}}l.push([t.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):t(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(r=l.length-1;r>=0;r--)l[r][0].each(n);return t(s)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=t.grep(this.items,function(t){for(var n=0;n<e.length;n++)if(e[n]===t.item[0])return!1;return!0})},_refreshItems:function(e){this.items=[];this.containers=[this];var n,r,i,o,a,s,l,u,c=this.items,f=[[t.isFunction(this.options.items)?this.options.items.call(this.element[0],e,{item:this.currentItem}):t(this.options.items,this.element),this]],h=this._connectWith();if(h&&this.ready)for(n=h.length-1;n>=0;n--){i=t(h[n]);for(r=i.length-1;r>=0;r--){o=t.data(i[r],this.widgetFullName);if(o&&o!==this&&!o.options.disabled){f.push([t.isFunction(o.options.items)?o.options.items.call(o.element[0],e,{item:this.currentItem}):t(o.options.items,o.element),o]);this.containers.push(o)}}}for(n=f.length-1;n>=0;n--){a=f[n][1];s=f[n][0];for(r=0,u=s.length;u>r;r++){l=t(s[r]);l.data(this.widgetName+"-item",a);c.push({item:l,instance:a,width:0,height:0,left:0,top:0})}}},refreshPositions:function(e){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var n,r,i,o;for(n=this.items.length-1;n>=0;n--){r=this.items[n];if(r.instance===this.currentContainer||!this.currentContainer||r.item[0]===this.currentItem[0]){i=this.options.toleranceElement?t(this.options.toleranceElement,r.item):r.item;if(!e){r.width=i.outerWidth();r.height=i.outerHeight()}o=i.offset();r.left=o.left;r.top=o.top}}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(n=this.containers.length-1;n>=0;n--){o=this.containers[n].element.offset();this.containers[n].containerCache.left=o.left;this.containers[n].containerCache.top=o.top;this.containers[n].containerCache.width=this.containers[n].element.outerWidth();this.containers[n].containerCache.height=this.containers[n].element.outerHeight()}return this},_createPlaceholder:function(e){e=e||this;var n,r=e.options;if(!r.placeholder||r.placeholder.constructor===String){n=r.placeholder;r.placeholder={element:function(){var r=e.currentItem[0].nodeName.toLowerCase(),i=t("<"+r+">",e.document[0]).addClass(n||e.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");"tr"===r?e.currentItem.children().each(function(){t("<td> </td>",e.document[0]).attr("colspan",t(this).attr("colspan")||1).appendTo(i)}):"img"===r&&i.attr("src",e.currentItem.attr("src"));n||i.css("visibility","hidden");return i},update:function(t,i){if(!n||r.forcePlaceholderSize){i.height()||i.height(e.currentItem.innerHeight()-parseInt(e.currentItem.css("paddingTop")||0,10)-parseInt(e.currentItem.css("paddingBottom")||0,10));i.width()||i.width(e.currentItem.innerWidth()-parseInt(e.currentItem.css("paddingLeft")||0,10)-parseInt(e.currentItem.css("paddingRight")||0,10))}}}}e.placeholder=t(r.placeholder.element.call(e.element,e.currentItem));e.currentItem.after(e.placeholder);r.placeholder.update(e,e.placeholder)},_contactContainers:function(r){var i,o,a,s,l,u,c,f,h,d,p=null,g=null;for(i=this.containers.length-1;i>=0;i--)if(!t.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(p&&t.contains(this.containers[i].element[0],p.element[0]))continue;p=this.containers[i];g=i}else if(this.containers[i].containerCache.over){this.containers[i]._trigger("out",r,this._uiHash(this));this.containers[i].containerCache.over=0}if(p)if(1===this.containers.length){if(!this.containers[g].containerCache.over){this.containers[g]._trigger("over",r,this._uiHash(this));this.containers[g].containerCache.over=1}}else{a=1e4;s=null;d=p.floating||n(this.currentItem);l=d?"left":"top";u=d?"width":"height";c=this.positionAbs[l]+this.offset.click[l];for(o=this.items.length-1;o>=0;o--)if(t.contains(this.containers[g].element[0],this.items[o].item[0])&&this.items[o].item[0]!==this.currentItem[0]&&(!d||e(this.positionAbs.top+this.offset.click.top,this.items[o].top,this.items[o].height))){f=this.items[o].item.offset()[l];h=!1;if(Math.abs(f-c)>Math.abs(f+this.items[o][u]-c)){h=!0;f+=this.items[o][u]}if(Math.abs(f-c)<a){a=Math.abs(f-c);s=this.items[o];this.direction=h?"up":"down"}}if(!s&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[g])return;s?this._rearrange(r,s,null,!0):this._rearrange(r,null,this.containers[g].element,!0);this._trigger("change",r,this._uiHash());this.containers[g]._trigger("change",r,this._uiHash(this));this.currentContainer=this.containers[g];this.options.placeholder.update(this.currentContainer,this.placeholder);this.containers[g]._trigger("over",r,this._uiHash(this));this.containers[g].containerCache.over=1}},_createHelper:function(e){var n=this.options,r=t.isFunction(n.helper)?t(n.helper.apply(this.element[0],[e,this.currentItem])):"clone"===n.helper?this.currentItem.clone():this.currentItem;r.parents("body").length||t("parent"!==n.appendTo?n.appendTo:this.currentItem[0].parentNode)[0].appendChild(r[0]);r[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")});(!r[0].style.width||n.forceHelperSize)&&r.width(this.currentItem.width());(!r[0].style.height||n.forceHelperSize)&&r.height(this.currentItem.height());return r},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" "));t.isArray(e)&&(e={left:+e[0],top:+e[1]||0});"left"in e&&(this.offset.click.left=e.left+this.margins.left);"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left);"top"in e&&(this.offset.click.top=e.top+this.margins.top);"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();if("absolute"===this.cssPosition&&this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])){e.left+=this.scrollParent.scrollLeft();e.top+=this.scrollParent.scrollTop()}(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0});return{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,n,r,i=this.options;"parent"===i.containment&&(i.containment=this.helper[0].parentNode);("document"===i.containment||"window"===i.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,t("document"===i.containment?document:window).width()-this.helperProportions.width-this.margins.left,(t("document"===i.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]);if(!/^(document|window|parent)$/.test(i.containment)){e=t(i.containment)[0];n=t(i.containment).offset();r="hidden"!==t(e).css("overflow");this.containment=[n.left+(parseInt(t(e).css("borderLeftWidth"),10)||0)+(parseInt(t(e).css("paddingLeft"),10)||0)-this.margins.left,n.top+(parseInt(t(e).css("borderTopWidth"),10)||0)+(parseInt(t(e).css("paddingTop"),10)||0)-this.margins.top,n.left+(r?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(t(e).css("borderLeftWidth"),10)||0)-(parseInt(t(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,n.top+(r?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(t(e).css("borderTopWidth"),10)||0)-(parseInt(t(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(e,n){n||(n=this.position);var r="absolute"===e?1:-1,i="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(i[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:i.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:i.scrollLeft())*r}},_generatePosition:function(e){var n,r,i=this.options,o=e.pageX,a=e.pageY,s="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,l=/(html|body)/i.test(s[0].tagName);"relative"!==this.cssPosition||this.scrollParent[0]!==document&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset());if(this.originalPosition){if(this.containment){e.pageX-this.offset.click.left<this.containment[0]&&(o=this.containment[0]+this.offset.click.left);e.pageY-this.offset.click.top<this.containment[1]&&(a=this.containment[1]+this.offset.click.top);e.pageX-this.offset.click.left>this.containment[2]&&(o=this.containment[2]+this.offset.click.left);e.pageY-this.offset.click.top>this.containment[3]&&(a=this.containment[3]+this.offset.click.top)}if(i.grid){n=this.originalPageY+Math.round((a-this.originalPageY)/i.grid[1])*i.grid[1];a=this.containment?n-this.offset.click.top>=this.containment[1]&&n-this.offset.click.top<=this.containment[3]?n:n-this.offset.click.top>=this.containment[1]?n-i.grid[1]:n+i.grid[1]:n;r=this.originalPageX+Math.round((o-this.originalPageX)/i.grid[0])*i.grid[0];o=this.containment?r-this.offset.click.left>=this.containment[0]&&r-this.offset.click.left<=this.containment[2]?r:r-this.offset.click.left>=this.containment[0]?r-i.grid[0]:r+i.grid[0]:r}}return{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():l?0:s.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():l?0:s.scrollLeft())}},_rearrange:function(t,e,n,r){n?n[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling);this.counter=this.counter?++this.counter:1;var i=this.counter;this._delay(function(){i===this.counter&&this.refreshPositions(!r)})},_clear:function(t,e){function n(t,e,n){return function(r){n._trigger(t,r,e._uiHash(e))}}this.reverting=!1;var r,i=[];!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem);this._noFinalSort=null;if(this.helper[0]===this.currentItem[0]){for(r in this._storedCSS)("auto"===this._storedCSS[r]||"static"===this._storedCSS[r])&&(this._storedCSS[r]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!e&&i.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))});!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||i.push(function(t){this._trigger("update",t,this._uiHash())});if(this!==this.currentContainer&&!e){i.push(function(t){this._trigger("remove",t,this._uiHash())});i.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer));i.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer))}for(r=this.containers.length-1;r>=0;r--){e||i.push(n("deactivate",this,this.containers[r]));if(this.containers[r].containerCache.over){i.push(n("out",this,this.containers[r]));this.containers[r].containerCache.over=0}}if(this.storedCursor){this.document.find("body").css("cursor",this.storedCursor);this.storedStylesheet.remove()}this._storedOpacity&&this.helper.css("opacity",this._storedOpacity);this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex);this.dragging=!1;if(this.cancelHelperRemoval){if(!e){this._trigger("beforeStop",t,this._uiHash());for(r=0;r<i.length;r++)i[r].call(this,t);this._trigger("stop",t,this._uiHash())}this.fromOutside=!1;return!1}e||this._trigger("beforeStop",t,this._uiHash());this.placeholder[0].parentNode.removeChild(this.placeholder[0]);this.helper[0]!==this.currentItem[0]&&this.helper.remove();this.helper=null;if(!e){for(r=0;r<i.length;r++)i[r].call(this,t);this._trigger("stop",t,this._uiHash())}this.fromOutside=!1;return!0},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var n=e||this;return{helper:n.helper,placeholder:n.placeholder||t([]),position:n.position,originalPosition:n.originalPosition,offset:n.positionAbs,item:n.currentItem,sender:e?e.element:null}}})})(e)},{"./core":13,"./mouse":14,"./widget":16,jquery:17}],16:[function(t){var e=t("jquery");(function(t,e){var n=0,r=Array.prototype.slice,i=t.cleanData;t.cleanData=function(e){for(var n,r=0;null!=(n=e[r]);r++)try{t(n).triggerHandler("remove")}catch(o){}i(e)};t.widget=function(e,n,r){var i,o,a,s,l={},u=e.split(".")[0];e=e.split(".")[1];i=u+"-"+e;if(!r){r=n;n=t.Widget}t.expr[":"][i.toLowerCase()]=function(e){return!!t.data(e,i)};t[u]=t[u]||{};o=t[u][e];a=t[u][e]=function(t,e){if(!this._createWidget)return new a(t,e);arguments.length&&this._createWidget(t,e);return void 0};t.extend(a,o,{version:r.version,_proto:t.extend({},r),_childConstructors:[]});s=new n;s.options=t.widget.extend({},s.options);t.each(r,function(e,r){l[e]=t.isFunction(r)?function(){var t=function(){return n.prototype[e].apply(this,arguments)},i=function(t){return n.prototype[e].apply(this,t)};return function(){var e,n=this._super,o=this._superApply;this._super=t;this._superApply=i;e=r.apply(this,arguments);this._super=n;this._superApply=o;return e}}():r});a.prototype=t.widget.extend(s,{widgetEventPrefix:o?s.widgetEventPrefix||e:e},l,{constructor:a,namespace:u,widgetName:e,widgetFullName:i});if(o){t.each(o._childConstructors,function(e,n){var r=n.prototype;t.widget(r.namespace+"."+r.widgetName,a,n._proto)});delete o._childConstructors}else n._childConstructors.push(a);t.widget.bridge(e,a)};t.widget.extend=function(n){for(var i,o,a=r.call(arguments,1),s=0,l=a.length;l>s;s++)for(i in a[s]){o=a[s][i];a[s].hasOwnProperty(i)&&o!==e&&(n[i]=t.isPlainObject(o)?t.isPlainObject(n[i])?t.widget.extend({},n[i],o):t.widget.extend({},o):o)}return n};t.widget.bridge=function(n,i){var o=i.prototype.widgetFullName||n;t.fn[n]=function(a){var s="string"==typeof a,l=r.call(arguments,1),u=this;a=!s&&l.length?t.widget.extend.apply(null,[a].concat(l)):a;this.each(s?function(){var r,i=t.data(this,o);if(!i)return t.error("cannot call methods on "+n+" prior to initialization; attempted to call method '"+a+"'");if(!t.isFunction(i[a])||"_"===a.charAt(0))return t.error("no such method '"+a+"' for "+n+" widget instance");r=i[a].apply(i,l);if(r!==i&&r!==e){u=r&&r.jquery?u.pushStack(r.get()):r;return!1}}:function(){var e=t.data(this,o);e?e.option(a||{})._init():t.data(this,o,new i(a,this))});return u}};t.Widget=function(){};t.Widget._childConstructors=[];t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(e,r){r=t(r||this.defaultElement||this)[0];this.element=t(r);this.uuid=n++;this.eventNamespace="."+this.widgetName+this.uuid;this.options=t.widget.extend({},this.options,this._getCreateOptions(),e);this.bindings=t();this.hoverable=t();this.focusable=t();if(r!==this){t.data(r,this.widgetFullName,this);this._on(!0,this.element,{remove:function(t){t.target===r&&this.destroy()}});this.document=t(r.style?r.ownerDocument:r.document||r);this.window=t(this.document[0].defaultView||this.document[0].parentWindow)}this._create();this._trigger("create",null,this._getCreateEventData());this._init()},_getCreateOptions:t.noop,_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){this._destroy();this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(t.camelCase(this.widgetFullName));this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled ui-state-disabled");this.bindings.unbind(this.eventNamespace);this.hoverable.removeClass("ui-state-hover");this.focusable.removeClass("ui-state-focus")},_destroy:t.noop,widget:function(){return this.element},option:function(n,r){var i,o,a,s=n;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof n){s={};i=n.split(".");n=i.shift();if(i.length){o=s[n]=t.widget.extend({},this.options[n]);for(a=0;a<i.length-1;a++){o[i[a]]=o[i[a]]||{};o=o[i[a]]}n=i.pop();if(1===arguments.length)return o[n]===e?null:o[n];o[n]=r}else{if(1===arguments.length)return this.options[n]===e?null:this.options[n];s[n]=r}}this._setOptions(s);return this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){this.options[t]=e;if("disabled"===t){this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!e).attr("aria-disabled",e);this.hoverable.removeClass("ui-state-hover");this.focusable.removeClass("ui-state-focus")}return this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(e,n,r){var i,o=this;if("boolean"!=typeof e){r=n;n=e;e=!1}if(r){n=i=t(n);this.bindings=this.bindings.add(n)}else{r=n;n=this.element;i=this.widget()}t.each(r,function(r,a){function s(){return e||o.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof a?o[a]:a).apply(o,arguments):void 0}"string"!=typeof a&&(s.guid=a.guid=a.guid||s.guid||t.guid++);var l=r.match(/^(\w+)\s*(.*)$/),u=l[1]+o.eventNamespace,c=l[2];c?i.delegate(c,u,s):n.bind(u,s)})},_off:function(t,e){e=(e||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace;t.unbind(e).undelegate(e)},_delay:function(t,e){function n(){return("string"==typeof t?r[t]:t).apply(r,arguments)}var r=this;return setTimeout(n,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e);this._on(e,{mouseenter:function(e){t(e.currentTarget).addClass("ui-state-hover")},mouseleave:function(e){t(e.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e);this._on(e,{focusin:function(e){t(e.currentTarget).addClass("ui-state-focus")},focusout:function(e){t(e.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(e,n,r){var i,o,a=this.options[e];r=r||{};n=t.Event(n);n.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase();n.target=this.element[0];o=n.originalEvent;if(o)for(i in o)i in n||(n[i]=o[i]);this.element.trigger(n,r);return!(t.isFunction(a)&&a.apply(this.element[0],[n].concat(r))===!1||n.isDefaultPrevented())}};t.each({show:"fadeIn",hide:"fadeOut"},function(e,n){t.Widget.prototype["_"+e]=function(r,i,o){"string"==typeof i&&(i={effect:i});var a,s=i?i===!0||"number"==typeof i?n:i.effect||n:e;i=i||{};"number"==typeof i&&(i={duration:i});a=!t.isEmptyObject(i);i.complete=o;i.delay&&r.delay(i.delay);a&&t.effects&&t.effects.effect[s]?r[e](i):s!==e&&r[s]?r[s](i.duration,i.easing,o):r.queue(function(n){t(this)[e]();o&&o.call(r[0]);n()})}})})(e)},{jquery:17}],17:[function(e,n){(function(t,e){"object"==typeof n&&"object"==typeof n.exports?n.exports=t.document?e(t,!0):function(t){if(!t.document)throw new Error("jQuery requires a window with a document");return e(t)}:e(t)})("undefined"!=typeof window?window:this,function(e,n){function r(t){var e=t.length,n=oe.type(t);return"function"===n||oe.isWindow(t)?!1:1===t.nodeType&&e?!0:"array"===n||0===e||"number"==typeof e&&e>0&&e-1 in t}function i(t,e,n){if(oe.isFunction(e))return oe.grep(t,function(t,r){return!!e.call(t,r,t)!==n});if(e.nodeType)return oe.grep(t,function(t){return t===e!==n});if("string"==typeof e){if(de.test(e))return oe.filter(e,t,n);e=oe.filter(e,t)}return oe.grep(t,function(t){return oe.inArray(t,e)>=0!==n})}function o(t,e){do t=t[e];while(t&&1!==t.nodeType);return t}function a(t){var e=we[t]={};oe.each(t.match(xe)||[],function(t,n){e[n]=!0});return e}function s(){if(ge.addEventListener){ge.removeEventListener("DOMContentLoaded",l,!1);e.removeEventListener("load",l,!1)}else{ge.detachEvent("onreadystatechange",l);e.detachEvent("onload",l)}}function l(){if(ge.addEventListener||"load"===event.type||"complete"===ge.readyState){s();oe.ready()}}function u(t,e,n){if(void 0===n&&1===t.nodeType){var r="data-"+e.replace(ke,"-$1").toLowerCase();n=t.getAttribute(r);if("string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:_e.test(n)?oe.parseJSON(n):n}catch(i){}oe.data(t,e,n)}else n=void 0}return n}function c(t){var e;for(e in t)if(("data"!==e||!oe.isEmptyObject(t[e]))&&"toJSON"!==e)return!1;return!0}function f(t,e,n,r){if(oe.acceptData(t)){var i,o,a=oe.expando,s=t.nodeType,l=s?oe.cache:t,u=s?t[a]:t[a]&&a;if(u&&l[u]&&(r||l[u].data)||void 0!==n||"string"!=typeof e){u||(u=s?t[a]=Y.pop()||oe.guid++:a);l[u]||(l[u]=s?{}:{toJSON:oe.noop});("object"==typeof e||"function"==typeof e)&&(r?l[u]=oe.extend(l[u],e):l[u].data=oe.extend(l[u].data,e));o=l[u];if(!r){o.data||(o.data={});o=o.data}void 0!==n&&(o[oe.camelCase(e)]=n);if("string"==typeof e){i=o[e];null==i&&(i=o[oe.camelCase(e)])}else i=o;return i}}}function h(t,e,n){if(oe.acceptData(t)){var r,i,o=t.nodeType,a=o?oe.cache:t,s=o?t[oe.expando]:oe.expando;if(a[s]){if(e){r=n?a[s]:a[s].data;if(r){if(oe.isArray(e))e=e.concat(oe.map(e,oe.camelCase));else if(e in r)e=[e];else{e=oe.camelCase(e);e=e in r?[e]:e.split(" ")}i=e.length;for(;i--;)delete r[e[i]];if(n?!c(r):!oe.isEmptyObject(r))return}}if(!n){delete a[s].data;if(!c(a[s]))return}o?oe.cleanData([t],!0):re.deleteExpando||a!=a.window?delete a[s]:a[s]=null}}}function d(){return!0}function p(){return!1}function g(){try{return ge.activeElement}catch(t){}}function m(t){var e=Oe.split("|"),n=t.createDocumentFragment();if(n.createElement)for(;e.length;)n.createElement(e.pop());return n}function v(t,e){var n,r,i=0,o=typeof t.getElementsByTagName!==Te?t.getElementsByTagName(e||"*"):typeof t.querySelectorAll!==Te?t.querySelectorAll(e||"*"):void 0;if(!o)for(o=[],n=t.childNodes||t;null!=(r=n[i]);i++)!e||oe.nodeName(r,e)?o.push(r):oe.merge(o,v(r,e));return void 0===e||e&&oe.nodeName(t,e)?oe.merge([t],o):o}function y(t){Ne.test(t.type)&&(t.defaultChecked=t.checked)}function b(t,e){return oe.nodeName(t,"table")&&oe.nodeName(11!==e.nodeType?e:e.firstChild,"tr")?t.getElementsByTagName("tbody")[0]||t.appendChild(t.ownerDocument.createElement("tbody")):t}function x(t){t.type=(null!==oe.find.attr(t,"type"))+"/"+t.type;return t}function w(t){var e=$e.exec(t.type);e?t.type=e[1]:t.removeAttribute("type");return t}function S(t,e){for(var n,r=0;null!=(n=t[r]);r++)oe._data(n,"globalEval",!e||oe._data(e[r],"globalEval"))}function C(t,e){if(1===e.nodeType&&oe.hasData(t)){var n,r,i,o=oe._data(t),a=oe._data(e,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++)oe.event.add(e,n,s[n][r])}a.data&&(a.data=oe.extend({},a.data))}}function T(t,e){var n,r,i;if(1===e.nodeType){n=e.nodeName.toLowerCase();if(!re.noCloneEvent&&e[oe.expando]){i=oe._data(e);for(r in i.events)oe.removeEvent(e,r,i.handle);e.removeAttribute(oe.expando)}if("script"===n&&e.text!==t.text){x(e).text=t.text;w(e)}else if("object"===n){e.parentNode&&(e.outerHTML=t.outerHTML);re.html5Clone&&t.innerHTML&&!oe.trim(e.innerHTML)&&(e.innerHTML=t.innerHTML)}else if("input"===n&&Ne.test(t.type)){e.defaultChecked=e.checked=t.checked;e.value!==t.value&&(e.value=t.value)}else"option"===n?e.defaultSelected=e.selected=t.defaultSelected:("input"===n||"textarea"===n)&&(e.defaultValue=t.defaultValue)}}function _(t,n){var r,i=oe(n.createElement(t)).appendTo(n.body),o=e.getDefaultComputedStyle&&(r=e.getDefaultComputedStyle(i[0]))?r.display:oe.css(i[0],"display");i.detach();return o}function k(t){var e=ge,n=tn[t];if(!n){n=_(t,e);if("none"===n||!n){Qe=(Qe||oe("<iframe frameborder='0' width='0' height='0'/>")).appendTo(e.documentElement);e=(Qe[0].contentWindow||Qe[0].contentDocument).document;e.write();e.close();n=_(t,e);Qe.detach()}tn[t]=n}return n}function M(t,e){return{get:function(){var n=t();if(null!=n){if(!n)return(this.get=e).apply(this,arguments);delete this.get}}}}function D(t,e){if(e in t)return e;for(var n=e.charAt(0).toUpperCase()+e.slice(1),r=e,i=pn.length;i--;){e=pn[i]+n;if(e in t)return e}return r}function L(t,e){for(var n,r,i,o=[],a=0,s=t.length;s>a;a++){r=t[a];if(r.style){o[a]=oe._data(r,"olddisplay");n=r.style.display;if(e){o[a]||"none"!==n||(r.style.display="");""===r.style.display&&Le(r)&&(o[a]=oe._data(r,"olddisplay",k(r.nodeName)))}else{i=Le(r);(n&&"none"!==n||!i)&&oe._data(r,"olddisplay",i?n:oe.css(r,"display"))}}}for(a=0;s>a;a++){r=t[a];r.style&&(e&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=e?o[a]||"":"none"))}return t}function A(t,e,n){var r=cn.exec(e);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):e}function N(t,e,n,r,i){for(var o=n===(r?"border":"content")?4:"width"===e?1:0,a=0;4>o;o+=2){"margin"===n&&(a+=oe.css(t,n+De[o],!0,i));if(r){"content"===n&&(a-=oe.css(t,"padding"+De[o],!0,i));"margin"!==n&&(a-=oe.css(t,"border"+De[o]+"Width",!0,i))}else{a+=oe.css(t,"padding"+De[o],!0,i);"padding"!==n&&(a+=oe.css(t,"border"+De[o]+"Width",!0,i))}}return a}function E(t,e,n){var r=!0,i="width"===e?t.offsetWidth:t.offsetHeight,o=en(t),a=re.boxSizing&&"border-box"===oe.css(t,"boxSizing",!1,o);if(0>=i||null==i){i=nn(t,e,o);(0>i||null==i)&&(i=t.style[e]);if(on.test(i))return i;r=a&&(re.boxSizingReliable()||i===t.style[e]);i=parseFloat(i)||0}return i+N(t,e,n||(a?"border":"content"),r,o)+"px"}function j(t,e,n,r,i){return new j.prototype.init(t,e,n,r,i)}function I(){setTimeout(function(){gn=void 0});return gn=oe.now()}function P(t,e){var n,r={height:t},i=0;e=e?1:0;for(;4>i;i+=2-e){n=De[i];r["margin"+n]=r["padding"+n]=t}e&&(r.opacity=r.width=t);return r}function H(t,e,n){for(var r,i=(wn[e]||[]).concat(wn["*"]),o=0,a=i.length;a>o;o++)if(r=i[o].call(n,e,t))return r}function O(t,e,n){var r,i,o,a,s,l,u,c,f=this,h={},d=t.style,p=t.nodeType&&Le(t),g=oe._data(t,"fxshow");if(!n.queue){s=oe._queueHooks(t,"fx");if(null==s.unqueued){s.unqueued=0;l=s.empty.fire;s.empty.fire=function(){s.unqueued||l()}}s.unqueued++;f.always(function(){f.always(function(){s.unqueued--;oe.queue(t,"fx").length||s.empty.fire()})})}if(1===t.nodeType&&("height"in e||"width"in e)){n.overflow=[d.overflow,d.overflowX,d.overflowY];u=oe.css(t,"display");c="none"===u?oe._data(t,"olddisplay")||k(t.nodeName):u;"inline"===c&&"none"===oe.css(t,"float")&&(re.inlineBlockNeedsLayout&&"inline"!==k(t.nodeName)?d.zoom=1:d.display="inline-block")}if(n.overflow){d.overflow="hidden";re.shrinkWrapBlocks()||f.always(function(){d.overflow=n.overflow[0];d.overflowX=n.overflow[1];d.overflowY=n.overflow[2]})}for(r in e){i=e[r];if(vn.exec(i)){delete e[r];o=o||"toggle"===i;if(i===(p?"hide":"show")){if("show"!==i||!g||void 0===g[r])continue;p=!0}h[r]=g&&g[r]||oe.style(t,r)}else u=void 0}if(oe.isEmptyObject(h))"inline"===("none"===u?k(t.nodeName):u)&&(d.display=u);else{g?"hidden"in g&&(p=g.hidden):g=oe._data(t,"fxshow",{});o&&(g.hidden=!p);p?oe(t).show():f.done(function(){oe(t).hide()});f.done(function(){var e;oe._removeData(t,"fxshow");for(e in h)oe.style(t,e,h[e])});for(r in h){a=H(p?g[r]:0,r,f);if(!(r in g)){g[r]=a.start;if(p){a.end=a.start;a.start="width"===r||"height"===r?1:0}}}}}function F(t,e){var n,r,i,o,a;for(n in t){r=oe.camelCase(n);i=e[r];o=t[n];if(oe.isArray(o)){i=o[1];o=t[n]=o[0]}if(n!==r){t[r]=o;delete t[n]}a=oe.cssHooks[r];if(a&&"expand"in a){o=a.expand(o);delete t[r];for(n in o)if(!(n in t)){t[n]=o[n];e[n]=i}}else e[r]=i}}function R(t,e,n){var r,i,o=0,a=xn.length,s=oe.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;for(var e=gn||I(),n=Math.max(0,u.startTime+u.duration-e),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;l>a;a++)u.tweens[a].run(o);s.notifyWith(t,[u,o,n]);if(1>o&&l)return n;s.resolveWith(t,[u]);return!1},u=s.promise({elem:t,props:oe.extend({},e),opts:oe.extend(!0,{specialEasing:{}},n),originalProperties:e,originalOptions:n,startTime:gn||I(),duration:n.duration,tweens:[],createTween:function(e,n){var r=oe.Tween(t,u.opts,e,n,u.opts.specialEasing[e]||u.opts.easing);u.tweens.push(r);return r},stop:function(e){var n=0,r=e?u.tweens.length:0;if(i)return this;i=!0;for(;r>n;n++)u.tweens[n].run(1);e?s.resolveWith(t,[u,e]):s.rejectWith(t,[u,e]);return this}}),c=u.props;F(c,u.opts.specialEasing);for(;a>o;o++){r=xn[o].call(u,t,c,u.opts);if(r)return r}oe.map(c,H,u);oe.isFunction(u.opts.start)&&u.opts.start.call(t,u);oe.fx.timer(oe.extend(l,{elem:t,anim:u,queue:u.opts.queue}));return u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)
}function W(t){return function(e,n){if("string"!=typeof e){n=e;e="*"}var r,i=0,o=e.toLowerCase().match(xe)||[];if(oe.isFunction(n))for(;r=o[i++];)if("+"===r.charAt(0)){r=r.slice(1)||"*";(t[r]=t[r]||[]).unshift(n)}else(t[r]=t[r]||[]).push(n)}}function z(t,e,n,r){function i(s){var l;o[s]=!0;oe.each(t[s]||[],function(t,s){var u=s(e,n,r);if("string"==typeof u&&!a&&!o[u]){e.dataTypes.unshift(u);i(u);return!1}return a?!(l=u):void 0});return l}var o={},a=t===Vn;return i(e.dataTypes[0])||!o["*"]&&i("*")}function q(t,e){var n,r,i=oe.ajaxSettings.flatOptions||{};for(r in e)void 0!==e[r]&&((i[r]?t:n||(n={}))[r]=e[r]);n&&oe.extend(!0,t,n);return t}function U(t,e,n){for(var r,i,o,a,s=t.contents,l=t.dataTypes;"*"===l[0];){l.shift();void 0===i&&(i=t.mimeType||e.getResponseHeader("Content-Type"))}if(i)for(a in s)if(s[a]&&s[a].test(i)){l.unshift(a);break}if(l[0]in n)o=l[0];else{for(a in n){if(!l[0]||t.converters[a+" "+l[0]]){o=a;break}r||(r=a)}o=o||r}if(o){o!==l[0]&&l.unshift(o);return n[o]}}function B(t,e,n,r){var i,o,a,s,l,u={},c=t.dataTypes.slice();if(c[1])for(a in t.converters)u[a.toLowerCase()]=t.converters[a];o=c.shift();for(;o;){t.responseFields[o]&&(n[t.responseFields[o]]=e);!l&&r&&t.dataFilter&&(e=t.dataFilter(e,t.dataType));l=o;o=c.shift();if(o)if("*"===o)o=l;else if("*"!==l&&l!==o){a=u[l+" "+o]||u["* "+o];if(!a)for(i in u){s=i.split(" ");if(s[1]===o){a=u[l+" "+s[0]]||u["* "+s[0]];if(a){if(a===!0)a=u[i];else if(u[i]!==!0){o=s[0];c.unshift(s[1])}break}}}if(a!==!0)if(a&&t["throws"])e=a(e);else try{e=a(e)}catch(f){return{state:"parsererror",error:a?f:"No conversion from "+l+" to "+o}}}}return{state:"success",data:e}}function V(t,e,n,r){var i;if(oe.isArray(e))oe.each(e,function(e,i){n||Yn.test(t)?r(t,i):V(t+"["+("object"==typeof i?e:"")+"]",i,n,r)});else if(n||"object"!==oe.type(e))r(t,e);else for(i in e)V(t+"["+i+"]",e[i],n,r)}function X(){try{return new e.XMLHttpRequest}catch(t){}}function G(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $(t){return oe.isWindow(t)?t:9===t.nodeType?t.defaultView||t.parentWindow:!1}var Y=[],J=Y.slice,K=Y.concat,Z=Y.push,Q=Y.indexOf,te={},ee=te.toString,ne=te.hasOwnProperty,re={},ie="1.11.1",oe=function(t,e){return new oe.fn.init(t,e)},ae=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,se=/^-ms-/,le=/-([\da-z])/gi,ue=function(t,e){return e.toUpperCase()};oe.fn=oe.prototype={jquery:ie,constructor:oe,selector:"",length:0,toArray:function(){return J.call(this)},get:function(t){return null!=t?0>t?this[t+this.length]:this[t]:J.call(this)},pushStack:function(t){var e=oe.merge(this.constructor(),t);e.prevObject=this;e.context=this.context;return e},each:function(t,e){return oe.each(this,t,e)},map:function(t){return this.pushStack(oe.map(this,function(e,n){return t.call(e,n,e)}))},slice:function(){return this.pushStack(J.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(t){var e=this.length,n=+t+(0>t?e:0);return this.pushStack(n>=0&&e>n?[this[n]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Z,sort:Y.sort,splice:Y.splice};oe.extend=oe.fn.extend=function(){var t,e,n,r,i,o,a=arguments[0]||{},s=1,l=arguments.length,u=!1;if("boolean"==typeof a){u=a;a=arguments[s]||{};s++}"object"==typeof a||oe.isFunction(a)||(a={});if(s===l){a=this;s--}for(;l>s;s++)if(null!=(i=arguments[s]))for(r in i){t=a[r];n=i[r];if(a!==n)if(u&&n&&(oe.isPlainObject(n)||(e=oe.isArray(n)))){if(e){e=!1;o=t&&oe.isArray(t)?t:[]}else o=t&&oe.isPlainObject(t)?t:{};a[r]=oe.extend(u,o,n)}else void 0!==n&&(a[r]=n)}return a};oe.extend({expando:"jQuery"+(ie+Math.random()).replace(/\D/g,""),isReady:!0,error:function(t){throw new Error(t)},noop:function(){},isFunction:function(t){return"function"===oe.type(t)},isArray:Array.isArray||function(t){return"array"===oe.type(t)},isWindow:function(t){return null!=t&&t==t.window},isNumeric:function(t){return!oe.isArray(t)&&t-parseFloat(t)>=0},isEmptyObject:function(t){var e;for(e in t)return!1;return!0},isPlainObject:function(t){var e;if(!t||"object"!==oe.type(t)||t.nodeType||oe.isWindow(t))return!1;try{if(t.constructor&&!ne.call(t,"constructor")&&!ne.call(t.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}if(re.ownLast)for(e in t)return ne.call(t,e);for(e in t);return void 0===e||ne.call(t,e)},type:function(t){return null==t?t+"":"object"==typeof t||"function"==typeof t?te[ee.call(t)]||"object":typeof t},globalEval:function(t){t&&oe.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(t){return t.replace(se,"ms-").replace(le,ue)},nodeName:function(t,e){return t.nodeName&&t.nodeName.toLowerCase()===e.toLowerCase()},each:function(t,e,n){var i,o=0,a=t.length,s=r(t);if(n)if(s)for(;a>o;o++){i=e.apply(t[o],n);if(i===!1)break}else for(o in t){i=e.apply(t[o],n);if(i===!1)break}else if(s)for(;a>o;o++){i=e.call(t[o],o,t[o]);if(i===!1)break}else for(o in t){i=e.call(t[o],o,t[o]);if(i===!1)break}return t},trim:function(t){return null==t?"":(t+"").replace(ae,"")},makeArray:function(t,e){var n=e||[];null!=t&&(r(Object(t))?oe.merge(n,"string"==typeof t?[t]:t):Z.call(n,t));return n},inArray:function(t,e,n){var r;if(e){if(Q)return Q.call(e,t,n);r=e.length;n=n?0>n?Math.max(0,r+n):n:0;for(;r>n;n++)if(n in e&&e[n]===t)return n}return-1},merge:function(t,e){for(var n=+e.length,r=0,i=t.length;n>r;)t[i++]=e[r++];if(n!==n)for(;void 0!==e[r];)t[i++]=e[r++];t.length=i;return t},grep:function(t,e,n){for(var r,i=[],o=0,a=t.length,s=!n;a>o;o++){r=!e(t[o],o);r!==s&&i.push(t[o])}return i},map:function(t,e,n){var i,o=0,a=t.length,s=r(t),l=[];if(s)for(;a>o;o++){i=e(t[o],o,n);null!=i&&l.push(i)}else for(o in t){i=e(t[o],o,n);null!=i&&l.push(i)}return K.apply([],l)},guid:1,proxy:function(t,e){var n,r,i;if("string"==typeof e){i=t[e];e=t;t=i}if(!oe.isFunction(t))return void 0;n=J.call(arguments,2);r=function(){return t.apply(e||this,n.concat(J.call(arguments)))};r.guid=t.guid=t.guid||oe.guid++;return r},now:function(){return+new Date},support:re});oe.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(t,e){te["[object "+e+"]"]=e.toLowerCase()});var ce=function(t){function e(t,e,n,r){var i,o,a,s,l,u,f,d,p,g;(e?e.ownerDocument||e:W)!==E&&N(e);e=e||E;n=n||[];if(!t||"string"!=typeof t)return n;if(1!==(s=e.nodeType)&&9!==s)return[];if(I&&!r){if(i=ye.exec(t))if(a=i[1]){if(9===s){o=e.getElementById(a);if(!o||!o.parentNode)return n;if(o.id===a){n.push(o);return n}}else if(e.ownerDocument&&(o=e.ownerDocument.getElementById(a))&&F(e,o)&&o.id===a){n.push(o);return n}}else{if(i[2]){Q.apply(n,e.getElementsByTagName(t));return n}if((a=i[3])&&w.getElementsByClassName&&e.getElementsByClassName){Q.apply(n,e.getElementsByClassName(a));return n}}if(w.qsa&&(!P||!P.test(t))){d=f=R;p=e;g=9===s&&t;if(1===s&&"object"!==e.nodeName.toLowerCase()){u=_(t);(f=e.getAttribute("id"))?d=f.replace(xe,"\\$&"):e.setAttribute("id",d);d="[id='"+d+"'] ";l=u.length;for(;l--;)u[l]=d+h(u[l]);p=be.test(t)&&c(e.parentNode)||e;g=u.join(",")}if(g)try{Q.apply(n,p.querySelectorAll(g));return n}catch(m){}finally{f||e.removeAttribute("id")}}}return M(t.replace(le,"$1"),e,n,r)}function n(){function t(n,r){e.push(n+" ")>S.cacheLength&&delete t[e.shift()];return t[n+" "]=r}var e=[];return t}function r(t){t[R]=!0;return t}function i(t){var e=E.createElement("div");try{return!!t(e)}catch(n){return!1}finally{e.parentNode&&e.parentNode.removeChild(e);e=null}}function o(t,e){for(var n=t.split("|"),r=t.length;r--;)S.attrHandle[n[r]]=e}function a(t,e){var n=e&&t,r=n&&1===t.nodeType&&1===e.nodeType&&(~e.sourceIndex||$)-(~t.sourceIndex||$);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===e)return-1;return t?1:-1}function s(t){return function(e){var n=e.nodeName.toLowerCase();return"input"===n&&e.type===t}}function l(t){return function(e){var n=e.nodeName.toLowerCase();return("input"===n||"button"===n)&&e.type===t}}function u(t){return r(function(e){e=+e;return r(function(n,r){for(var i,o=t([],n.length,e),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function c(t){return t&&typeof t.getElementsByTagName!==G&&t}function f(){}function h(t){for(var e=0,n=t.length,r="";n>e;e++)r+=t[e].value;return r}function d(t,e,n){var r=e.dir,i=n&&"parentNode"===r,o=q++;return e.first?function(e,n,o){for(;e=e[r];)if(1===e.nodeType||i)return t(e,n,o)}:function(e,n,a){var s,l,u=[z,o];if(a){for(;e=e[r];)if((1===e.nodeType||i)&&t(e,n,a))return!0}else for(;e=e[r];)if(1===e.nodeType||i){l=e[R]||(e[R]={});if((s=l[r])&&s[0]===z&&s[1]===o)return u[2]=s[2];l[r]=u;if(u[2]=t(e,n,a))return!0}}}function p(t){return t.length>1?function(e,n,r){for(var i=t.length;i--;)if(!t[i](e,n,r))return!1;return!0}:t[0]}function g(t,n,r){for(var i=0,o=n.length;o>i;i++)e(t,n[i],r);return r}function m(t,e,n,r,i){for(var o,a=[],s=0,l=t.length,u=null!=e;l>s;s++)if((o=t[s])&&(!n||n(o,r,i))){a.push(o);u&&e.push(s)}return a}function v(t,e,n,i,o,a){i&&!i[R]&&(i=v(i));o&&!o[R]&&(o=v(o,a));return r(function(r,a,s,l){var u,c,f,h=[],d=[],p=a.length,v=r||g(e||"*",s.nodeType?[s]:s,[]),y=!t||!r&&e?v:m(v,h,t,s,l),b=n?o||(r?t:p||i)?[]:a:y;n&&n(y,b,s,l);if(i){u=m(b,d);i(u,[],s,l);c=u.length;for(;c--;)(f=u[c])&&(b[d[c]]=!(y[d[c]]=f))}if(r){if(o||t){if(o){u=[];c=b.length;for(;c--;)(f=b[c])&&u.push(y[c]=f);o(null,b=[],u,l)}c=b.length;for(;c--;)(f=b[c])&&(u=o?ee.call(r,f):h[c])>-1&&(r[u]=!(a[u]=f))}}else{b=m(b===a?b.splice(p,b.length):b);o?o(null,a,b,l):Q.apply(a,b)}})}function y(t){for(var e,n,r,i=t.length,o=S.relative[t[0].type],a=o||S.relative[" "],s=o?1:0,l=d(function(t){return t===e},a,!0),u=d(function(t){return ee.call(e,t)>-1},a,!0),c=[function(t,n,r){return!o&&(r||n!==D)||((e=n).nodeType?l(t,n,r):u(t,n,r))}];i>s;s++)if(n=S.relative[t[s].type])c=[d(p(c),n)];else{n=S.filter[t[s].type].apply(null,t[s].matches);if(n[R]){r=++s;for(;i>r&&!S.relative[t[r].type];r++);return v(s>1&&p(c),s>1&&h(t.slice(0,s-1).concat({value:" "===t[s-2].type?"*":""})).replace(le,"$1"),n,r>s&&y(t.slice(s,r)),i>r&&y(t=t.slice(r)),i>r&&h(t))}c.push(n)}return p(c)}function b(t,n){var i=n.length>0,o=t.length>0,a=function(r,a,s,l,u){var c,f,h,d=0,p="0",g=r&&[],v=[],y=D,b=r||o&&S.find.TAG("*",u),x=z+=null==y?1:Math.random()||.1,w=b.length;u&&(D=a!==E&&a);for(;p!==w&&null!=(c=b[p]);p++){if(o&&c){f=0;for(;h=t[f++];)if(h(c,a,s)){l.push(c);break}u&&(z=x)}if(i){(c=!h&&c)&&d--;r&&g.push(c)}}d+=p;if(i&&p!==d){f=0;for(;h=n[f++];)h(g,v,a,s);if(r){if(d>0)for(;p--;)g[p]||v[p]||(v[p]=K.call(l));v=m(v)}Q.apply(l,v);u&&!r&&v.length>0&&d+n.length>1&&e.uniqueSort(l)}if(u){z=x;D=y}return g};return i?r(a):a}var x,w,S,C,T,_,k,M,D,L,A,N,E,j,I,P,H,O,F,R="sizzle"+-new Date,W=t.document,z=0,q=0,U=n(),B=n(),V=n(),X=function(t,e){t===e&&(A=!0);return 0},G="undefined",$=1<<31,Y={}.hasOwnProperty,J=[],K=J.pop,Z=J.push,Q=J.push,te=J.slice,ee=J.indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(this[e]===t)return e;return-1},ne="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",re="[\\x20\\t\\r\\n\\f]",ie="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",oe=ie.replace("w","w#"),ae="\\["+re+"*("+ie+")(?:"+re+"*([*^$|!~]?=)"+re+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+oe+"))|)"+re+"*\\]",se=":("+ie+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+ae+")*)|.*)\\)|)",le=new RegExp("^"+re+"+|((?:^|[^\\\\])(?:\\\\.)*)"+re+"+$","g"),ue=new RegExp("^"+re+"*,"+re+"*"),ce=new RegExp("^"+re+"*([>+~]|"+re+")"+re+"*"),fe=new RegExp("="+re+"*([^\\]'\"]*?)"+re+"*\\]","g"),he=new RegExp(se),de=new RegExp("^"+oe+"$"),pe={ID:new RegExp("^#("+ie+")"),CLASS:new RegExp("^\\.("+ie+")"),TAG:new RegExp("^("+ie.replace("w","w*")+")"),ATTR:new RegExp("^"+ae),PSEUDO:new RegExp("^"+se),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+re+"*(even|odd|(([+-]|)(\\d*)n|)"+re+"*(?:([+-]|)"+re+"*(\\d+)|))"+re+"*\\)|)","i"),bool:new RegExp("^(?:"+ne+")$","i"),needsContext:new RegExp("^"+re+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+re+"*((?:-\\d)?\\d*)"+re+"*\\)|)(?=[^-]|$)","i")},ge=/^(?:input|select|textarea|button)$/i,me=/^h\d$/i,ve=/^[^{]+\{\s*\[native \w/,ye=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,be=/[+~]/,xe=/'|\\/g,we=new RegExp("\\\\([\\da-f]{1,6}"+re+"?|("+re+")|.)","ig"),Se=function(t,e,n){var r="0x"+e-65536;return r!==r||n?e:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)};try{Q.apply(J=te.call(W.childNodes),W.childNodes);J[W.childNodes.length].nodeType}catch(Ce){Q={apply:J.length?function(t,e){Z.apply(t,te.call(e))}:function(t,e){for(var n=t.length,r=0;t[n++]=e[r++];);t.length=n-1}}}w=e.support={};T=e.isXML=function(t){var e=t&&(t.ownerDocument||t).documentElement;return e?"HTML"!==e.nodeName:!1};N=e.setDocument=function(t){var e,n=t?t.ownerDocument||t:W,r=n.defaultView;if(n===E||9!==n.nodeType||!n.documentElement)return E;E=n;j=n.documentElement;I=!T(n);r&&r!==r.top&&(r.addEventListener?r.addEventListener("unload",function(){N()},!1):r.attachEvent&&r.attachEvent("onunload",function(){N()}));w.attributes=i(function(t){t.className="i";return!t.getAttribute("className")});w.getElementsByTagName=i(function(t){t.appendChild(n.createComment(""));return!t.getElementsByTagName("*").length});w.getElementsByClassName=ve.test(n.getElementsByClassName)&&i(function(t){t.innerHTML="<div class='a'></div><div class='a i'></div>";t.firstChild.className="i";return 2===t.getElementsByClassName("i").length});w.getById=i(function(t){j.appendChild(t).id=R;return!n.getElementsByName||!n.getElementsByName(R).length});if(w.getById){S.find.ID=function(t,e){if(typeof e.getElementById!==G&&I){var n=e.getElementById(t);return n&&n.parentNode?[n]:[]}};S.filter.ID=function(t){var e=t.replace(we,Se);return function(t){return t.getAttribute("id")===e}}}else{delete S.find.ID;S.filter.ID=function(t){var e=t.replace(we,Se);return function(t){var n=typeof t.getAttributeNode!==G&&t.getAttributeNode("id");return n&&n.value===e}}}S.find.TAG=w.getElementsByTagName?function(t,e){return typeof e.getElementsByTagName!==G?e.getElementsByTagName(t):void 0}:function(t,e){var n,r=[],i=0,o=e.getElementsByTagName(t);if("*"===t){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o};S.find.CLASS=w.getElementsByClassName&&function(t,e){return typeof e.getElementsByClassName!==G&&I?e.getElementsByClassName(t):void 0};H=[];P=[];if(w.qsa=ve.test(n.querySelectorAll)){i(function(t){t.innerHTML="<select msallowclip=''><option selected=''></option></select>";t.querySelectorAll("[msallowclip^='']").length&&P.push("[*^$]="+re+"*(?:''|\"\")");t.querySelectorAll("[selected]").length||P.push("\\["+re+"*(?:value|"+ne+")");t.querySelectorAll(":checked").length||P.push(":checked")});i(function(t){var e=n.createElement("input");e.setAttribute("type","hidden");t.appendChild(e).setAttribute("name","D");t.querySelectorAll("[name=d]").length&&P.push("name"+re+"*[*^$|!~]?=");t.querySelectorAll(":enabled").length||P.push(":enabled",":disabled");t.querySelectorAll("*,:x");P.push(",.*:")})}(w.matchesSelector=ve.test(O=j.matches||j.webkitMatchesSelector||j.mozMatchesSelector||j.oMatchesSelector||j.msMatchesSelector))&&i(function(t){w.disconnectedMatch=O.call(t,"div");O.call(t,"[s!='']:x");H.push("!=",se)});P=P.length&&new RegExp(P.join("|"));H=H.length&&new RegExp(H.join("|"));e=ve.test(j.compareDocumentPosition);F=e||ve.test(j.contains)?function(t,e){var n=9===t.nodeType?t.documentElement:t,r=e&&e.parentNode;return t===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):t.compareDocumentPosition&&16&t.compareDocumentPosition(r)))}:function(t,e){if(e)for(;e=e.parentNode;)if(e===t)return!0;return!1};X=e?function(t,e){if(t===e){A=!0;return 0}var r=!t.compareDocumentPosition-!e.compareDocumentPosition;if(r)return r;r=(t.ownerDocument||t)===(e.ownerDocument||e)?t.compareDocumentPosition(e):1;return 1&r||!w.sortDetached&&e.compareDocumentPosition(t)===r?t===n||t.ownerDocument===W&&F(W,t)?-1:e===n||e.ownerDocument===W&&F(W,e)?1:L?ee.call(L,t)-ee.call(L,e):0:4&r?-1:1}:function(t,e){if(t===e){A=!0;return 0}var r,i=0,o=t.parentNode,s=e.parentNode,l=[t],u=[e];if(!o||!s)return t===n?-1:e===n?1:o?-1:s?1:L?ee.call(L,t)-ee.call(L,e):0;if(o===s)return a(t,e);r=t;for(;r=r.parentNode;)l.unshift(r);r=e;for(;r=r.parentNode;)u.unshift(r);for(;l[i]===u[i];)i++;return i?a(l[i],u[i]):l[i]===W?-1:u[i]===W?1:0};return n};e.matches=function(t,n){return e(t,null,null,n)};e.matchesSelector=function(t,n){(t.ownerDocument||t)!==E&&N(t);n=n.replace(fe,"='$1']");if(!(!w.matchesSelector||!I||H&&H.test(n)||P&&P.test(n)))try{var r=O.call(t,n);if(r||w.disconnectedMatch||t.document&&11!==t.document.nodeType)return r}catch(i){}return e(n,E,null,[t]).length>0};e.contains=function(t,e){(t.ownerDocument||t)!==E&&N(t);return F(t,e)};e.attr=function(t,e){(t.ownerDocument||t)!==E&&N(t);var n=S.attrHandle[e.toLowerCase()],r=n&&Y.call(S.attrHandle,e.toLowerCase())?n(t,e,!I):void 0;return void 0!==r?r:w.attributes||!I?t.getAttribute(e):(r=t.getAttributeNode(e))&&r.specified?r.value:null};e.error=function(t){throw new Error("Syntax error, unrecognized expression: "+t)};e.uniqueSort=function(t){var e,n=[],r=0,i=0;A=!w.detectDuplicates;L=!w.sortStable&&t.slice(0);t.sort(X);if(A){for(;e=t[i++];)e===t[i]&&(r=n.push(i));for(;r--;)t.splice(n[r],1)}L=null;return t};C=e.getText=function(t){var e,n="",r=0,i=t.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof t.textContent)return t.textContent;for(t=t.firstChild;t;t=t.nextSibling)n+=C(t)}else if(3===i||4===i)return t.nodeValue}else for(;e=t[r++];)n+=C(e);return n};S=e.selectors={cacheLength:50,createPseudo:r,match:pe,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(t){t[1]=t[1].replace(we,Se);t[3]=(t[3]||t[4]||t[5]||"").replace(we,Se);"~="===t[2]&&(t[3]=" "+t[3]+" ");return t.slice(0,4)},CHILD:function(t){t[1]=t[1].toLowerCase();if("nth"===t[1].slice(0,3)){t[3]||e.error(t[0]);t[4]=+(t[4]?t[5]+(t[6]||1):2*("even"===t[3]||"odd"===t[3]));t[5]=+(t[7]+t[8]||"odd"===t[3])}else t[3]&&e.error(t[0]);return t},PSEUDO:function(t){var e,n=!t[6]&&t[2];if(pe.CHILD.test(t[0]))return null;if(t[3])t[2]=t[4]||t[5]||"";else if(n&&he.test(n)&&(e=_(n,!0))&&(e=n.indexOf(")",n.length-e)-n.length)){t[0]=t[0].slice(0,e);t[2]=n.slice(0,e)}return t.slice(0,3)}},filter:{TAG:function(t){var e=t.replace(we,Se).toLowerCase();return"*"===t?function(){return!0}:function(t){return t.nodeName&&t.nodeName.toLowerCase()===e}},CLASS:function(t){var e=U[t+" "];return e||(e=new RegExp("(^|"+re+")"+t+"("+re+"|$)"))&&U(t,function(t){return e.test("string"==typeof t.className&&t.className||typeof t.getAttribute!==G&&t.getAttribute("class")||"")})},ATTR:function(t,n,r){return function(i){var o=e.attr(i,t);if(null==o)return"!="===n;if(!n)return!0;o+="";return"="===n?o===r:"!="===n?o!==r:"^="===n?r&&0===o.indexOf(r):"*="===n?r&&o.indexOf(r)>-1:"$="===n?r&&o.slice(-r.length)===r:"~="===n?(" "+o+" ").indexOf(r)>-1:"|="===n?o===r||o.slice(0,r.length+1)===r+"-":!1}},CHILD:function(t,e,n,r,i){var o="nth"!==t.slice(0,3),a="last"!==t.slice(-4),s="of-type"===e;return 1===r&&0===i?function(t){return!!t.parentNode}:function(e,n,l){var u,c,f,h,d,p,g=o!==a?"nextSibling":"previousSibling",m=e.parentNode,v=s&&e.nodeName.toLowerCase(),y=!l&&!s;if(m){if(o){for(;g;){f=e;for(;f=f[g];)if(s?f.nodeName.toLowerCase()===v:1===f.nodeType)return!1;p=g="only"===t&&!p&&"nextSibling"}return!0}p=[a?m.firstChild:m.lastChild];if(a&&y){c=m[R]||(m[R]={});u=c[t]||[];d=u[0]===z&&u[1];h=u[0]===z&&u[2];f=d&&m.childNodes[d];for(;f=++d&&f&&f[g]||(h=d=0)||p.pop();)if(1===f.nodeType&&++h&&f===e){c[t]=[z,d,h];break}}else if(y&&(u=(e[R]||(e[R]={}))[t])&&u[0]===z)h=u[1];else for(;f=++d&&f&&f[g]||(h=d=0)||p.pop();)if((s?f.nodeName.toLowerCase()===v:1===f.nodeType)&&++h){y&&((f[R]||(f[R]={}))[t]=[z,h]);if(f===e)break}h-=i;return h===r||h%r===0&&h/r>=0}}},PSEUDO:function(t,n){var i,o=S.pseudos[t]||S.setFilters[t.toLowerCase()]||e.error("unsupported pseudo: "+t);if(o[R])return o(n);if(o.length>1){i=[t,t,"",n];return S.setFilters.hasOwnProperty(t.toLowerCase())?r(function(t,e){for(var r,i=o(t,n),a=i.length;a--;){r=ee.call(t,i[a]);t[r]=!(e[r]=i[a])}}):function(t){return o(t,0,i)}}return o}},pseudos:{not:r(function(t){var e=[],n=[],i=k(t.replace(le,"$1"));return i[R]?r(function(t,e,n,r){for(var o,a=i(t,null,r,[]),s=t.length;s--;)(o=a[s])&&(t[s]=!(e[s]=o))}):function(t,r,o){e[0]=t;i(e,null,o,n);return!n.pop()}}),has:r(function(t){return function(n){return e(t,n).length>0}}),contains:r(function(t){return function(e){return(e.textContent||e.innerText||C(e)).indexOf(t)>-1}}),lang:r(function(t){de.test(t||"")||e.error("unsupported lang: "+t);t=t.replace(we,Se).toLowerCase();return function(e){var n;do if(n=I?e.lang:e.getAttribute("xml:lang")||e.getAttribute("lang")){n=n.toLowerCase();return n===t||0===n.indexOf(t+"-")}while((e=e.parentNode)&&1===e.nodeType);return!1}}),target:function(e){var n=t.location&&t.location.hash;return n&&n.slice(1)===e.id},root:function(t){return t===j},focus:function(t){return t===E.activeElement&&(!E.hasFocus||E.hasFocus())&&!!(t.type||t.href||~t.tabIndex)},enabled:function(t){return t.disabled===!1},disabled:function(t){return t.disabled===!0},checked:function(t){var e=t.nodeName.toLowerCase();return"input"===e&&!!t.checked||"option"===e&&!!t.selected},selected:function(t){t.parentNode&&t.parentNode.selectedIndex;return t.selected===!0},empty:function(t){for(t=t.firstChild;t;t=t.nextSibling)if(t.nodeType<6)return!1;return!0},parent:function(t){return!S.pseudos.empty(t)},header:function(t){return me.test(t.nodeName)},input:function(t){return ge.test(t.nodeName)},button:function(t){var e=t.nodeName.toLowerCase();return"input"===e&&"button"===t.type||"button"===e},text:function(t){var e;return"input"===t.nodeName.toLowerCase()&&"text"===t.type&&(null==(e=t.getAttribute("type"))||"text"===e.toLowerCase())},first:u(function(){return[0]}),last:u(function(t,e){return[e-1]}),eq:u(function(t,e,n){return[0>n?n+e:n]}),even:u(function(t,e){for(var n=0;e>n;n+=2)t.push(n);return t}),odd:u(function(t,e){for(var n=1;e>n;n+=2)t.push(n);return t}),lt:u(function(t,e,n){for(var r=0>n?n+e:n;--r>=0;)t.push(r);return t}),gt:u(function(t,e,n){for(var r=0>n?n+e:n;++r<e;)t.push(r);return t})}};S.pseudos.nth=S.pseudos.eq;for(x in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})S.pseudos[x]=s(x);for(x in{submit:!0,reset:!0})S.pseudos[x]=l(x);f.prototype=S.filters=S.pseudos;S.setFilters=new f;_=e.tokenize=function(t,n){var r,i,o,a,s,l,u,c=B[t+" "];if(c)return n?0:c.slice(0);s=t;l=[];u=S.preFilter;for(;s;){if(!r||(i=ue.exec(s))){i&&(s=s.slice(i[0].length)||s);l.push(o=[])}r=!1;if(i=ce.exec(s)){r=i.shift();o.push({value:r,type:i[0].replace(le," ")});s=s.slice(r.length)}for(a in S.filter)if((i=pe[a].exec(s))&&(!u[a]||(i=u[a](i)))){r=i.shift();o.push({value:r,type:a,matches:i});s=s.slice(r.length)}if(!r)break}return n?s.length:s?e.error(t):B(t,l).slice(0)};k=e.compile=function(t,e){var n,r=[],i=[],o=V[t+" "];if(!o){e||(e=_(t));n=e.length;for(;n--;){o=y(e[n]);o[R]?r.push(o):i.push(o)}o=V(t,b(i,r));o.selector=t}return o};M=e.select=function(t,e,n,r){var i,o,a,s,l,u="function"==typeof t&&t,f=!r&&_(t=u.selector||t);n=n||[];if(1===f.length){o=f[0]=f[0].slice(0);if(o.length>2&&"ID"===(a=o[0]).type&&w.getById&&9===e.nodeType&&I&&S.relative[o[1].type]){e=(S.find.ID(a.matches[0].replace(we,Se),e)||[])[0];if(!e)return n;u&&(e=e.parentNode);t=t.slice(o.shift().value.length)}i=pe.needsContext.test(t)?0:o.length;for(;i--;){a=o[i];if(S.relative[s=a.type])break;if((l=S.find[s])&&(r=l(a.matches[0].replace(we,Se),be.test(o[0].type)&&c(e.parentNode)||e))){o.splice(i,1);t=r.length&&h(o);if(!t){Q.apply(n,r);return n}break}}}(u||k(t,f))(r,e,!I,n,be.test(t)&&c(e.parentNode)||e);return n};w.sortStable=R.split("").sort(X).join("")===R;w.detectDuplicates=!!A;N();w.sortDetached=i(function(t){return 1&t.compareDocumentPosition(E.createElement("div"))});i(function(t){t.innerHTML="<a href='#'></a>";return"#"===t.firstChild.getAttribute("href")})||o("type|href|height|width",function(t,e,n){return n?void 0:t.getAttribute(e,"type"===e.toLowerCase()?1:2)});w.attributes&&i(function(t){t.innerHTML="<input/>";t.firstChild.setAttribute("value","");return""===t.firstChild.getAttribute("value")})||o("value",function(t,e,n){return n||"input"!==t.nodeName.toLowerCase()?void 0:t.defaultValue});i(function(t){return null==t.getAttribute("disabled")})||o(ne,function(t,e,n){var r;return n?void 0:t[e]===!0?e.toLowerCase():(r=t.getAttributeNode(e))&&r.specified?r.value:null});return e}(e);oe.find=ce;oe.expr=ce.selectors;oe.expr[":"]=oe.expr.pseudos;oe.unique=ce.uniqueSort;oe.text=ce.getText;oe.isXMLDoc=ce.isXML;oe.contains=ce.contains;var fe=oe.expr.match.needsContext,he=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,de=/^.[^:#\[\.,]*$/;oe.filter=function(t,e,n){var r=e[0];n&&(t=":not("+t+")");return 1===e.length&&1===r.nodeType?oe.find.matchesSelector(r,t)?[r]:[]:oe.find.matches(t,oe.grep(e,function(t){return 1===t.nodeType}))};oe.fn.extend({find:function(t){var e,n=[],r=this,i=r.length;if("string"!=typeof t)return this.pushStack(oe(t).filter(function(){for(e=0;i>e;e++)if(oe.contains(r[e],this))return!0}));for(e=0;i>e;e++)oe.find(t,r[e],n);n=this.pushStack(i>1?oe.unique(n):n);n.selector=this.selector?this.selector+" "+t:t;return n},filter:function(t){return this.pushStack(i(this,t||[],!1))},not:function(t){return this.pushStack(i(this,t||[],!0))},is:function(t){return!!i(this,"string"==typeof t&&fe.test(t)?oe(t):t||[],!1).length}});var pe,ge=e.document,me=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,ve=oe.fn.init=function(t,e){var n,r;if(!t)return this;if("string"==typeof t){n="<"===t.charAt(0)&&">"===t.charAt(t.length-1)&&t.length>=3?[null,t,null]:me.exec(t);if(!n||!n[1]&&e)return!e||e.jquery?(e||pe).find(t):this.constructor(e).find(t);if(n[1]){e=e instanceof oe?e[0]:e;oe.merge(this,oe.parseHTML(n[1],e&&e.nodeType?e.ownerDocument||e:ge,!0));if(he.test(n[1])&&oe.isPlainObject(e))for(n in e)oe.isFunction(this[n])?this[n](e[n]):this.attr(n,e[n]);return this}r=ge.getElementById(n[2]);if(r&&r.parentNode){if(r.id!==n[2])return pe.find(t);this.length=1;this[0]=r}this.context=ge;this.selector=t;return this}if(t.nodeType){this.context=this[0]=t;this.length=1;return this}if(oe.isFunction(t))return"undefined"!=typeof pe.ready?pe.ready(t):t(oe);if(void 0!==t.selector){this.selector=t.selector;this.context=t.context}return oe.makeArray(t,this)};ve.prototype=oe.fn;pe=oe(ge);var ye=/^(?:parents|prev(?:Until|All))/,be={children:!0,contents:!0,next:!0,prev:!0};oe.extend({dir:function(t,e,n){for(var r=[],i=t[e];i&&9!==i.nodeType&&(void 0===n||1!==i.nodeType||!oe(i).is(n));){1===i.nodeType&&r.push(i);i=i[e]}return r},sibling:function(t,e){for(var n=[];t;t=t.nextSibling)1===t.nodeType&&t!==e&&n.push(t);return n}});oe.fn.extend({has:function(t){var e,n=oe(t,this),r=n.length;return this.filter(function(){for(e=0;r>e;e++)if(oe.contains(this,n[e]))return!0})},closest:function(t,e){for(var n,r=0,i=this.length,o=[],a=fe.test(t)||"string"!=typeof t?oe(t,e||this.context):0;i>r;r++)for(n=this[r];n&&n!==e;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&oe.find.matchesSelector(n,t))){o.push(n);break}return this.pushStack(o.length>1?oe.unique(o):o)},index:function(t){return t?"string"==typeof t?oe.inArray(this[0],oe(t)):oe.inArray(t.jquery?t[0]:t,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(t,e){return this.pushStack(oe.unique(oe.merge(this.get(),oe(t,e))))},addBack:function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}});oe.each({parent:function(t){var e=t.parentNode;return e&&11!==e.nodeType?e:null},parents:function(t){return oe.dir(t,"parentNode")},parentsUntil:function(t,e,n){return oe.dir(t,"parentNode",n)},next:function(t){return o(t,"nextSibling")},prev:function(t){return o(t,"previousSibling")},nextAll:function(t){return oe.dir(t,"nextSibling")},prevAll:function(t){return oe.dir(t,"previousSibling")},nextUntil:function(t,e,n){return oe.dir(t,"nextSibling",n)},prevUntil:function(t,e,n){return oe.dir(t,"previousSibling",n)},siblings:function(t){return oe.sibling((t.parentNode||{}).firstChild,t)},children:function(t){return oe.sibling(t.firstChild)},contents:function(t){return oe.nodeName(t,"iframe")?t.contentDocument||t.contentWindow.document:oe.merge([],t.childNodes)}},function(t,e){oe.fn[t]=function(n,r){var i=oe.map(this,e,n);"Until"!==t.slice(-5)&&(r=n);r&&"string"==typeof r&&(i=oe.filter(r,i));if(this.length>1){be[t]||(i=oe.unique(i));ye.test(t)&&(i=i.reverse())}return this.pushStack(i)}});var xe=/\S+/g,we={};oe.Callbacks=function(t){t="string"==typeof t?we[t]||a(t):oe.extend({},t);var e,n,r,i,o,s,l=[],u=!t.once&&[],c=function(a){n=t.memory&&a;r=!0;o=s||0;s=0;i=l.length;e=!0;for(;l&&i>o;o++)if(l[o].apply(a[0],a[1])===!1&&t.stopOnFalse){n=!1;break}e=!1;l&&(u?u.length&&c(u.shift()):n?l=[]:f.disable())},f={add:function(){if(l){var r=l.length;(function o(e){oe.each(e,function(e,n){var r=oe.type(n);"function"===r?t.unique&&f.has(n)||l.push(n):n&&n.length&&"string"!==r&&o(n)})})(arguments);if(e)i=l.length;else if(n){s=r;c(n)}}return this},remove:function(){l&&oe.each(arguments,function(t,n){for(var r;(r=oe.inArray(n,l,r))>-1;){l.splice(r,1);if(e){i>=r&&i--;o>=r&&o--}}});return this},has:function(t){return t?oe.inArray(t,l)>-1:!(!l||!l.length)},empty:function(){l=[];i=0;return this},disable:function(){l=u=n=void 0;return this},disabled:function(){return!l},lock:function(){u=void 0;n||f.disable();return this},locked:function(){return!u},fireWith:function(t,n){if(l&&(!r||u)){n=n||[];n=[t,n.slice?n.slice():n];e?u.push(n):c(n)}return this},fire:function(){f.fireWith(this,arguments);return this},fired:function(){return!!r}};return f};oe.extend({Deferred:function(t){var e=[["resolve","done",oe.Callbacks("once memory"),"resolved"],["reject","fail",oe.Callbacks("once memory"),"rejected"],["notify","progress",oe.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){i.done(arguments).fail(arguments);return this},then:function(){var t=arguments;return oe.Deferred(function(n){oe.each(e,function(e,o){var a=oe.isFunction(t[e])&&t[e];i[o[1]](function(){var t=a&&a.apply(this,arguments);t&&oe.isFunction(t.promise)?t.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[o[0]+"With"](this===r?n.promise():this,a?[t]:arguments)})});t=null}).promise()},promise:function(t){return null!=t?oe.extend(t,r):r}},i={};r.pipe=r.then;oe.each(e,function(t,o){var a=o[2],s=o[3];r[o[1]]=a.add;s&&a.add(function(){n=s},e[1^t][2].disable,e[2][2].lock);i[o[0]]=function(){i[o[0]+"With"](this===i?r:this,arguments);return this};i[o[0]+"With"]=a.fireWith});r.promise(i);t&&t.call(i,i);return i},when:function(t){var e,n,r,i=0,o=J.call(arguments),a=o.length,s=1!==a||t&&oe.isFunction(t.promise)?a:0,l=1===s?t:oe.Deferred(),u=function(t,n,r){return function(i){n[t]=this;r[t]=arguments.length>1?J.call(arguments):i;r===e?l.notifyWith(n,r):--s||l.resolveWith(n,r)}};if(a>1){e=new Array(a);n=new Array(a);r=new Array(a);for(;a>i;i++)o[i]&&oe.isFunction(o[i].promise)?o[i].promise().done(u(i,r,o)).fail(l.reject).progress(u(i,n,e)):--s}s||l.resolveWith(r,o);return l.promise()}});var Se;oe.fn.ready=function(t){oe.ready.promise().done(t);return this};oe.extend({isReady:!1,readyWait:1,holdReady:function(t){t?oe.readyWait++:oe.ready(!0)},ready:function(t){if(t===!0?!--oe.readyWait:!oe.isReady){if(!ge.body)return setTimeout(oe.ready);oe.isReady=!0;if(!(t!==!0&&--oe.readyWait>0)){Se.resolveWith(ge,[oe]);if(oe.fn.triggerHandler){oe(ge).triggerHandler("ready");oe(ge).off("ready")}}}}});oe.ready.promise=function(t){if(!Se){Se=oe.Deferred();if("complete"===ge.readyState)setTimeout(oe.ready);else if(ge.addEventListener){ge.addEventListener("DOMContentLoaded",l,!1);e.addEventListener("load",l,!1)}else{ge.attachEvent("onreadystatechange",l);e.attachEvent("onload",l);var n=!1;try{n=null==e.frameElement&&ge.documentElement}catch(r){}n&&n.doScroll&&function i(){if(!oe.isReady){try{n.doScroll("left")}catch(t){return setTimeout(i,50)}s();oe.ready()}}()}}return Se.promise(t)
};var Ce,Te="undefined";for(Ce in oe(re))break;re.ownLast="0"!==Ce;re.inlineBlockNeedsLayout=!1;oe(function(){var t,e,n,r;n=ge.getElementsByTagName("body")[0];if(n&&n.style){e=ge.createElement("div");r=ge.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";n.appendChild(r).appendChild(e);if(typeof e.style.zoom!==Te){e.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";re.inlineBlockNeedsLayout=t=3===e.offsetWidth;t&&(n.style.zoom=1)}n.removeChild(r)}});(function(){var t=ge.createElement("div");if(null==re.deleteExpando){re.deleteExpando=!0;try{delete t.test}catch(e){re.deleteExpando=!1}}t=null})();oe.acceptData=function(t){var e=oe.noData[(t.nodeName+" ").toLowerCase()],n=+t.nodeType||1;return 1!==n&&9!==n?!1:!e||e!==!0&&t.getAttribute("classid")===e};var _e=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,ke=/([A-Z])/g;oe.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(t){t=t.nodeType?oe.cache[t[oe.expando]]:t[oe.expando];return!!t&&!c(t)},data:function(t,e,n){return f(t,e,n)},removeData:function(t,e){return h(t,e)},_data:function(t,e,n){return f(t,e,n,!0)},_removeData:function(t,e){return h(t,e,!0)}});oe.fn.extend({data:function(t,e){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===t){if(this.length){i=oe.data(o);if(1===o.nodeType&&!oe._data(o,"parsedAttrs")){n=a.length;for(;n--;)if(a[n]){r=a[n].name;if(0===r.indexOf("data-")){r=oe.camelCase(r.slice(5));u(o,r,i[r])}}oe._data(o,"parsedAttrs",!0)}}return i}return"object"==typeof t?this.each(function(){oe.data(this,t)}):arguments.length>1?this.each(function(){oe.data(this,t,e)}):o?u(o,t,oe.data(o,t)):void 0},removeData:function(t){return this.each(function(){oe.removeData(this,t)})}});oe.extend({queue:function(t,e,n){var r;if(t){e=(e||"fx")+"queue";r=oe._data(t,e);n&&(!r||oe.isArray(n)?r=oe._data(t,e,oe.makeArray(n)):r.push(n));return r||[]}},dequeue:function(t,e){e=e||"fx";var n=oe.queue(t,e),r=n.length,i=n.shift(),o=oe._queueHooks(t,e),a=function(){oe.dequeue(t,e)};if("inprogress"===i){i=n.shift();r--}if(i){"fx"===e&&n.unshift("inprogress");delete o.stop;i.call(t,a,o)}!r&&o&&o.empty.fire()},_queueHooks:function(t,e){var n=e+"queueHooks";return oe._data(t,n)||oe._data(t,n,{empty:oe.Callbacks("once memory").add(function(){oe._removeData(t,e+"queue");oe._removeData(t,n)})})}});oe.fn.extend({queue:function(t,e){var n=2;if("string"!=typeof t){e=t;t="fx";n--}return arguments.length<n?oe.queue(this[0],t):void 0===e?this:this.each(function(){var n=oe.queue(this,t,e);oe._queueHooks(this,t);"fx"===t&&"inprogress"!==n[0]&&oe.dequeue(this,t)})},dequeue:function(t){return this.each(function(){oe.dequeue(this,t)})},clearQueue:function(t){return this.queue(t||"fx",[])},promise:function(t,e){var n,r=1,i=oe.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};if("string"!=typeof t){e=t;t=void 0}t=t||"fx";for(;a--;){n=oe._data(o[a],t+"queueHooks");if(n&&n.empty){r++;n.empty.add(s)}}s();return i.promise(e)}});var Me=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,De=["Top","Right","Bottom","Left"],Le=function(t,e){t=e||t;return"none"===oe.css(t,"display")||!oe.contains(t.ownerDocument,t)},Ae=oe.access=function(t,e,n,r,i,o,a){var s=0,l=t.length,u=null==n;if("object"===oe.type(n)){i=!0;for(s in n)oe.access(t,e,s,n[s],!0,o,a)}else if(void 0!==r){i=!0;oe.isFunction(r)||(a=!0);if(u)if(a){e.call(t,r);e=null}else{u=e;e=function(t,e,n){return u.call(oe(t),n)}}if(e)for(;l>s;s++)e(t[s],n,a?r:r.call(t[s],s,e(t[s],n)))}return i?t:u?e.call(t):l?e(t[0],n):o},Ne=/^(?:checkbox|radio)$/i;(function(){var t=ge.createElement("input"),e=ge.createElement("div"),n=ge.createDocumentFragment();e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";re.leadingWhitespace=3===e.firstChild.nodeType;re.tbody=!e.getElementsByTagName("tbody").length;re.htmlSerialize=!!e.getElementsByTagName("link").length;re.html5Clone="<:nav></:nav>"!==ge.createElement("nav").cloneNode(!0).outerHTML;t.type="checkbox";t.checked=!0;n.appendChild(t);re.appendChecked=t.checked;e.innerHTML="<textarea>x</textarea>";re.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue;n.appendChild(e);e.innerHTML="<input type='radio' checked='checked' name='t'/>";re.checkClone=e.cloneNode(!0).cloneNode(!0).lastChild.checked;re.noCloneEvent=!0;if(e.attachEvent){e.attachEvent("onclick",function(){re.noCloneEvent=!1});e.cloneNode(!0).click()}if(null==re.deleteExpando){re.deleteExpando=!0;try{delete e.test}catch(r){re.deleteExpando=!1}}})();(function(){var t,n,r=ge.createElement("div");for(t in{submit:!0,change:!0,focusin:!0}){n="on"+t;if(!(re[t+"Bubbles"]=n in e)){r.setAttribute(n,"t");re[t+"Bubbles"]=r.attributes[n].expando===!1}}r=null})();var Ee=/^(?:input|select|textarea)$/i,je=/^key/,Ie=/^(?:mouse|pointer|contextmenu)|click/,Pe=/^(?:focusinfocus|focusoutblur)$/,He=/^([^.]*)(?:\.(.+)|)$/;oe.event={global:{},add:function(t,e,n,r,i){var o,a,s,l,u,c,f,h,d,p,g,m=oe._data(t);if(m){if(n.handler){l=n;n=l.handler;i=l.selector}n.guid||(n.guid=oe.guid++);(a=m.events)||(a=m.events={});if(!(c=m.handle)){c=m.handle=function(t){return typeof oe===Te||t&&oe.event.triggered===t.type?void 0:oe.event.dispatch.apply(c.elem,arguments)};c.elem=t}e=(e||"").match(xe)||[""];s=e.length;for(;s--;){o=He.exec(e[s])||[];d=g=o[1];p=(o[2]||"").split(".").sort();if(d){u=oe.event.special[d]||{};d=(i?u.delegateType:u.bindType)||d;u=oe.event.special[d]||{};f=oe.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&oe.expr.match.needsContext.test(i),namespace:p.join(".")},l);if(!(h=a[d])){h=a[d]=[];h.delegateCount=0;u.setup&&u.setup.call(t,r,p,c)!==!1||(t.addEventListener?t.addEventListener(d,c,!1):t.attachEvent&&t.attachEvent("on"+d,c))}if(u.add){u.add.call(t,f);f.handler.guid||(f.handler.guid=n.guid)}i?h.splice(h.delegateCount++,0,f):h.push(f);oe.event.global[d]=!0}}t=null}},remove:function(t,e,n,r,i){var o,a,s,l,u,c,f,h,d,p,g,m=oe.hasData(t)&&oe._data(t);if(m&&(c=m.events)){e=(e||"").match(xe)||[""];u=e.length;for(;u--;){s=He.exec(e[u])||[];d=g=s[1];p=(s[2]||"").split(".").sort();if(d){f=oe.event.special[d]||{};d=(r?f.delegateType:f.bindType)||d;h=c[d]||[];s=s[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)");l=o=h.length;for(;o--;){a=h[o];if(!(!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector))){h.splice(o,1);a.selector&&h.delegateCount--;f.remove&&f.remove.call(t,a)}}if(l&&!h.length){f.teardown&&f.teardown.call(t,p,m.handle)!==!1||oe.removeEvent(t,d,m.handle);delete c[d]}}else for(d in c)oe.event.remove(t,d+e[u],n,r,!0)}if(oe.isEmptyObject(c)){delete m.handle;oe._removeData(t,"events")}}},trigger:function(t,n,r,i){var o,a,s,l,u,c,f,h=[r||ge],d=ne.call(t,"type")?t.type:t,p=ne.call(t,"namespace")?t.namespace.split("."):[];s=c=r=r||ge;if(3!==r.nodeType&&8!==r.nodeType&&!Pe.test(d+oe.event.triggered)){if(d.indexOf(".")>=0){p=d.split(".");d=p.shift();p.sort()}a=d.indexOf(":")<0&&"on"+d;t=t[oe.expando]?t:new oe.Event(d,"object"==typeof t&&t);t.isTrigger=i?2:3;t.namespace=p.join(".");t.namespace_re=t.namespace?new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;t.result=void 0;t.target||(t.target=r);n=null==n?[t]:oe.makeArray(n,[t]);u=oe.event.special[d]||{};if(i||!u.trigger||u.trigger.apply(r,n)!==!1){if(!i&&!u.noBubble&&!oe.isWindow(r)){l=u.delegateType||d;Pe.test(l+d)||(s=s.parentNode);for(;s;s=s.parentNode){h.push(s);c=s}c===(r.ownerDocument||ge)&&h.push(c.defaultView||c.parentWindow||e)}f=0;for(;(s=h[f++])&&!t.isPropagationStopped();){t.type=f>1?l:u.bindType||d;o=(oe._data(s,"events")||{})[t.type]&&oe._data(s,"handle");o&&o.apply(s,n);o=a&&s[a];if(o&&o.apply&&oe.acceptData(s)){t.result=o.apply(s,n);t.result===!1&&t.preventDefault()}}t.type=d;if(!i&&!t.isDefaultPrevented()&&(!u._default||u._default.apply(h.pop(),n)===!1)&&oe.acceptData(r)&&a&&r[d]&&!oe.isWindow(r)){c=r[a];c&&(r[a]=null);oe.event.triggered=d;try{r[d]()}catch(g){}oe.event.triggered=void 0;c&&(r[a]=c)}return t.result}}},dispatch:function(t){t=oe.event.fix(t);var e,n,r,i,o,a=[],s=J.call(arguments),l=(oe._data(this,"events")||{})[t.type]||[],u=oe.event.special[t.type]||{};s[0]=t;t.delegateTarget=this;if(!u.preDispatch||u.preDispatch.call(this,t)!==!1){a=oe.event.handlers.call(this,t,l);e=0;for(;(i=a[e++])&&!t.isPropagationStopped();){t.currentTarget=i.elem;o=0;for(;(r=i.handlers[o++])&&!t.isImmediatePropagationStopped();)if(!t.namespace_re||t.namespace_re.test(r.namespace)){t.handleObj=r;t.data=r.data;n=((oe.event.special[r.origType]||{}).handle||r.handler).apply(i.elem,s);if(void 0!==n&&(t.result=n)===!1){t.preventDefault();t.stopPropagation()}}}u.postDispatch&&u.postDispatch.call(this,t);return t.result}},handlers:function(t,e){var n,r,i,o,a=[],s=e.delegateCount,l=t.target;if(s&&l.nodeType&&(!t.button||"click"!==t.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==t.type)){i=[];for(o=0;s>o;o++){r=e[o];n=r.selector+" ";void 0===i[n]&&(i[n]=r.needsContext?oe(n,this).index(l)>=0:oe.find(n,this,null,[l]).length);i[n]&&i.push(r)}i.length&&a.push({elem:l,handlers:i})}s<e.length&&a.push({elem:this,handlers:e.slice(s)});return a},fix:function(t){if(t[oe.expando])return t;var e,n,r,i=t.type,o=t,a=this.fixHooks[i];a||(this.fixHooks[i]=a=Ie.test(i)?this.mouseHooks:je.test(i)?this.keyHooks:{});r=a.props?this.props.concat(a.props):this.props;t=new oe.Event(o);e=r.length;for(;e--;){n=r[e];t[n]=o[n]}t.target||(t.target=o.srcElement||ge);3===t.target.nodeType&&(t.target=t.target.parentNode);t.metaKey=!!t.metaKey;return a.filter?a.filter(t,o):t},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(t,e){null==t.which&&(t.which=null!=e.charCode?e.charCode:e.keyCode);return t}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(t,e){var n,r,i,o=e.button,a=e.fromElement;if(null==t.pageX&&null!=e.clientX){r=t.target.ownerDocument||ge;i=r.documentElement;n=r.body;t.pageX=e.clientX+(i&&i.scrollLeft||n&&n.scrollLeft||0)-(i&&i.clientLeft||n&&n.clientLeft||0);t.pageY=e.clientY+(i&&i.scrollTop||n&&n.scrollTop||0)-(i&&i.clientTop||n&&n.clientTop||0)}!t.relatedTarget&&a&&(t.relatedTarget=a===t.target?e.toElement:a);t.which||void 0===o||(t.which=1&o?1:2&o?3:4&o?2:0);return t}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==g()&&this.focus)try{this.focus();return!1}catch(t){}},delegateType:"focusin"},blur:{trigger:function(){if(this===g()&&this.blur){this.blur();return!1}},delegateType:"focusout"},click:{trigger:function(){if(oe.nodeName(this,"input")&&"checkbox"===this.type&&this.click){this.click();return!1}},_default:function(t){return oe.nodeName(t.target,"a")}},beforeunload:{postDispatch:function(t){void 0!==t.result&&t.originalEvent&&(t.originalEvent.returnValue=t.result)}}},simulate:function(t,e,n,r){var i=oe.extend(new oe.Event,n,{type:t,isSimulated:!0,originalEvent:{}});r?oe.event.trigger(i,null,e):oe.event.dispatch.call(e,i);i.isDefaultPrevented()&&n.preventDefault()}};oe.removeEvent=ge.removeEventListener?function(t,e,n){t.removeEventListener&&t.removeEventListener(e,n,!1)}:function(t,e,n){var r="on"+e;if(t.detachEvent){typeof t[r]===Te&&(t[r]=null);t.detachEvent(r,n)}};oe.Event=function(t,e){if(!(this instanceof oe.Event))return new oe.Event(t,e);if(t&&t.type){this.originalEvent=t;this.type=t.type;this.isDefaultPrevented=t.defaultPrevented||void 0===t.defaultPrevented&&t.returnValue===!1?d:p}else this.type=t;e&&oe.extend(this,e);this.timeStamp=t&&t.timeStamp||oe.now();this[oe.expando]=!0};oe.Event.prototype={isDefaultPrevented:p,isPropagationStopped:p,isImmediatePropagationStopped:p,preventDefault:function(){var t=this.originalEvent;this.isDefaultPrevented=d;t&&(t.preventDefault?t.preventDefault():t.returnValue=!1)},stopPropagation:function(){var t=this.originalEvent;this.isPropagationStopped=d;if(t){t.stopPropagation&&t.stopPropagation();t.cancelBubble=!0}},stopImmediatePropagation:function(){var t=this.originalEvent;this.isImmediatePropagationStopped=d;t&&t.stopImmediatePropagation&&t.stopImmediatePropagation();this.stopPropagation()}};oe.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(t,e){oe.event.special[t]={delegateType:e,bindType:e,handle:function(t){var n,r=this,i=t.relatedTarget,o=t.handleObj;if(!i||i!==r&&!oe.contains(r,i)){t.type=o.origType;n=o.handler.apply(this,arguments);t.type=e}return n}}});re.submitBubbles||(oe.event.special.submit={setup:function(){if(oe.nodeName(this,"form"))return!1;oe.event.add(this,"click._submit keypress._submit",function(t){var e=t.target,n=oe.nodeName(e,"input")||oe.nodeName(e,"button")?e.form:void 0;if(n&&!oe._data(n,"submitBubbles")){oe.event.add(n,"submit._submit",function(t){t._submit_bubble=!0});oe._data(n,"submitBubbles",!0)}});return void 0},postDispatch:function(t){if(t._submit_bubble){delete t._submit_bubble;this.parentNode&&!t.isTrigger&&oe.event.simulate("submit",this.parentNode,t,!0)}},teardown:function(){if(oe.nodeName(this,"form"))return!1;oe.event.remove(this,"._submit");return void 0}});re.changeBubbles||(oe.event.special.change={setup:function(){if(Ee.test(this.nodeName)){if("checkbox"===this.type||"radio"===this.type){oe.event.add(this,"propertychange._change",function(t){"checked"===t.originalEvent.propertyName&&(this._just_changed=!0)});oe.event.add(this,"click._change",function(t){this._just_changed&&!t.isTrigger&&(this._just_changed=!1);oe.event.simulate("change",this,t,!0)})}return!1}oe.event.add(this,"beforeactivate._change",function(t){var e=t.target;if(Ee.test(e.nodeName)&&!oe._data(e,"changeBubbles")){oe.event.add(e,"change._change",function(t){!this.parentNode||t.isSimulated||t.isTrigger||oe.event.simulate("change",this.parentNode,t,!0)});oe._data(e,"changeBubbles",!0)}})},handle:function(t){var e=t.target;return this!==e||t.isSimulated||t.isTrigger||"radio"!==e.type&&"checkbox"!==e.type?t.handleObj.handler.apply(this,arguments):void 0},teardown:function(){oe.event.remove(this,"._change");return!Ee.test(this.nodeName)}});re.focusinBubbles||oe.each({focus:"focusin",blur:"focusout"},function(t,e){var n=function(t){oe.event.simulate(e,t.target,oe.event.fix(t),!0)};oe.event.special[e]={setup:function(){var r=this.ownerDocument||this,i=oe._data(r,e);i||r.addEventListener(t,n,!0);oe._data(r,e,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=oe._data(r,e)-1;if(i)oe._data(r,e,i);else{r.removeEventListener(t,n,!0);oe._removeData(r,e)}}}});oe.fn.extend({on:function(t,e,n,r,i){var o,a;if("object"==typeof t){if("string"!=typeof e){n=n||e;e=void 0}for(o in t)this.on(o,e,n,t[o],i);return this}if(null==n&&null==r){r=e;n=e=void 0}else if(null==r)if("string"==typeof e){r=n;n=void 0}else{r=n;n=e;e=void 0}if(r===!1)r=p;else if(!r)return this;if(1===i){a=r;r=function(t){oe().off(t);return a.apply(this,arguments)};r.guid=a.guid||(a.guid=oe.guid++)}return this.each(function(){oe.event.add(this,t,r,n,e)})},one:function(t,e,n,r){return this.on(t,e,n,r,1)},off:function(t,e,n){var r,i;if(t&&t.preventDefault&&t.handleObj){r=t.handleObj;oe(t.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler);return this}if("object"==typeof t){for(i in t)this.off(i,e,t[i]);return this}if(e===!1||"function"==typeof e){n=e;e=void 0}n===!1&&(n=p);return this.each(function(){oe.event.remove(this,t,n,e)})},trigger:function(t,e){return this.each(function(){oe.event.trigger(t,e,this)})},triggerHandler:function(t,e){var n=this[0];return n?oe.event.trigger(t,e,n,!0):void 0}});var Oe="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Fe=/ jQuery\d+="(?:null|\d+)"/g,Re=new RegExp("<(?:"+Oe+")[\\s/>]","i"),We=/^\s+/,ze=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,qe=/<([\w:]+)/,Ue=/<tbody/i,Be=/<|&#?\w+;/,Ve=/<(?:script|style|link)/i,Xe=/checked\s*(?:[^=]|=\s*.checked.)/i,Ge=/^$|\/(?:java|ecma)script/i,$e=/^true\/(.*)/,Ye=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Je={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:re.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Ke=m(ge),Ze=Ke.appendChild(ge.createElement("div"));Je.optgroup=Je.option;Je.tbody=Je.tfoot=Je.colgroup=Je.caption=Je.thead;Je.th=Je.td;oe.extend({clone:function(t,e,n){var r,i,o,a,s,l=oe.contains(t.ownerDocument,t);if(re.html5Clone||oe.isXMLDoc(t)||!Re.test("<"+t.nodeName+">"))o=t.cloneNode(!0);else{Ze.innerHTML=t.outerHTML;Ze.removeChild(o=Ze.firstChild)}if(!(re.noCloneEvent&&re.noCloneChecked||1!==t.nodeType&&11!==t.nodeType||oe.isXMLDoc(t))){r=v(o);s=v(t);for(a=0;null!=(i=s[a]);++a)r[a]&&T(i,r[a])}if(e)if(n){s=s||v(t);r=r||v(o);for(a=0;null!=(i=s[a]);a++)C(i,r[a])}else C(t,o);r=v(o,"script");r.length>0&&S(r,!l&&v(t,"script"));r=s=i=null;return o},buildFragment:function(t,e,n,r){for(var i,o,a,s,l,u,c,f=t.length,h=m(e),d=[],p=0;f>p;p++){o=t[p];if(o||0===o)if("object"===oe.type(o))oe.merge(d,o.nodeType?[o]:o);else if(Be.test(o)){s=s||h.appendChild(e.createElement("div"));l=(qe.exec(o)||["",""])[1].toLowerCase();c=Je[l]||Je._default;s.innerHTML=c[1]+o.replace(ze,"<$1></$2>")+c[2];i=c[0];for(;i--;)s=s.lastChild;!re.leadingWhitespace&&We.test(o)&&d.push(e.createTextNode(We.exec(o)[0]));if(!re.tbody){o="table"!==l||Ue.test(o)?"<table>"!==c[1]||Ue.test(o)?0:s:s.firstChild;i=o&&o.childNodes.length;for(;i--;)oe.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}oe.merge(d,s.childNodes);s.textContent="";for(;s.firstChild;)s.removeChild(s.firstChild);s=h.lastChild}else d.push(e.createTextNode(o))}s&&h.removeChild(s);re.appendChecked||oe.grep(v(d,"input"),y);p=0;for(;o=d[p++];)if(!r||-1===oe.inArray(o,r)){a=oe.contains(o.ownerDocument,o);s=v(h.appendChild(o),"script");a&&S(s);if(n){i=0;for(;o=s[i++];)Ge.test(o.type||"")&&n.push(o)}}s=null;return h},cleanData:function(t,e){for(var n,r,i,o,a=0,s=oe.expando,l=oe.cache,u=re.deleteExpando,c=oe.event.special;null!=(n=t[a]);a++)if(e||oe.acceptData(n)){i=n[s];o=i&&l[i];if(o){if(o.events)for(r in o.events)c[r]?oe.event.remove(n,r):oe.removeEvent(n,r,o.handle);if(l[i]){delete l[i];u?delete n[s]:typeof n.removeAttribute!==Te?n.removeAttribute(s):n[s]=null;Y.push(i)}}}}});oe.fn.extend({text:function(t){return Ae(this,function(t){return void 0===t?oe.text(this):this.empty().append((this[0]&&this[0].ownerDocument||ge).createTextNode(t))},null,t,arguments.length)},append:function(){return this.domManip(arguments,function(t){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var e=b(this,t);e.appendChild(t)}})},prepend:function(){return this.domManip(arguments,function(t){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var e=b(this,t);e.insertBefore(t,e.firstChild)}})},before:function(){return this.domManip(arguments,function(t){this.parentNode&&this.parentNode.insertBefore(t,this)})},after:function(){return this.domManip(arguments,function(t){this.parentNode&&this.parentNode.insertBefore(t,this.nextSibling)})},remove:function(t,e){for(var n,r=t?oe.filter(t,this):this,i=0;null!=(n=r[i]);i++){e||1!==n.nodeType||oe.cleanData(v(n));if(n.parentNode){e&&oe.contains(n.ownerDocument,n)&&S(v(n,"script"));n.parentNode.removeChild(n)}}return this},empty:function(){for(var t,e=0;null!=(t=this[e]);e++){1===t.nodeType&&oe.cleanData(v(t,!1));for(;t.firstChild;)t.removeChild(t.firstChild);t.options&&oe.nodeName(t,"select")&&(t.options.length=0)}return this},clone:function(t,e){t=null==t?!1:t;e=null==e?t:e;return this.map(function(){return oe.clone(this,t,e)})},html:function(t){return Ae(this,function(t){var e=this[0]||{},n=0,r=this.length;if(void 0===t)return 1===e.nodeType?e.innerHTML.replace(Fe,""):void 0;if(!("string"!=typeof t||Ve.test(t)||!re.htmlSerialize&&Re.test(t)||!re.leadingWhitespace&&We.test(t)||Je[(qe.exec(t)||["",""])[1].toLowerCase()])){t=t.replace(ze,"<$1></$2>");try{for(;r>n;n++){e=this[n]||{};if(1===e.nodeType){oe.cleanData(v(e,!1));e.innerHTML=t}}e=0}catch(i){}}e&&this.empty().append(t)},null,t,arguments.length)},replaceWith:function(){var t=arguments[0];this.domManip(arguments,function(e){t=this.parentNode;oe.cleanData(v(this));t&&t.replaceChild(e,this)});return t&&(t.length||t.nodeType)?this:this.remove()},detach:function(t){return this.remove(t,!0)},domManip:function(t,e){t=K.apply([],t);var n,r,i,o,a,s,l=0,u=this.length,c=this,f=u-1,h=t[0],d=oe.isFunction(h);if(d||u>1&&"string"==typeof h&&!re.checkClone&&Xe.test(h))return this.each(function(n){var r=c.eq(n);d&&(t[0]=h.call(this,n,r.html()));r.domManip(t,e)});if(u){s=oe.buildFragment(t,this[0].ownerDocument,!1,this);n=s.firstChild;1===s.childNodes.length&&(s=n);if(n){o=oe.map(v(s,"script"),x);i=o.length;for(;u>l;l++){r=s;if(l!==f){r=oe.clone(r,!0,!0);i&&oe.merge(o,v(r,"script"))}e.call(this[l],r,l)}if(i){a=o[o.length-1].ownerDocument;oe.map(o,w);for(l=0;i>l;l++){r=o[l];Ge.test(r.type||"")&&!oe._data(r,"globalEval")&&oe.contains(a,r)&&(r.src?oe._evalUrl&&oe._evalUrl(r.src):oe.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Ye,"")))}}s=n=null}}return this}});oe.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(t,e){oe.fn[t]=function(t){for(var n,r=0,i=[],o=oe(t),a=o.length-1;a>=r;r++){n=r===a?this:this.clone(!0);oe(o[r])[e](n);Z.apply(i,n.get())}return this.pushStack(i)}});var Qe,tn={};(function(){var t;re.shrinkWrapBlocks=function(){if(null!=t)return t;t=!1;var e,n,r;n=ge.getElementsByTagName("body")[0];if(n&&n.style){e=ge.createElement("div");r=ge.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";n.appendChild(r).appendChild(e);if(typeof e.style.zoom!==Te){e.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";e.appendChild(ge.createElement("div")).style.width="5px";t=3!==e.offsetWidth}n.removeChild(r);return t}}})();var en,nn,rn=/^margin/,on=new RegExp("^("+Me+")(?!px)[a-z%]+$","i"),an=/^(top|right|bottom|left)$/;if(e.getComputedStyle){en=function(t){return t.ownerDocument.defaultView.getComputedStyle(t,null)};nn=function(t,e,n){var r,i,o,a,s=t.style;n=n||en(t);a=n?n.getPropertyValue(e)||n[e]:void 0;if(n){""!==a||oe.contains(t.ownerDocument,t)||(a=oe.style(t,e));if(on.test(a)&&rn.test(e)){r=s.width;i=s.minWidth;o=s.maxWidth;s.minWidth=s.maxWidth=s.width=a;a=n.width;s.width=r;s.minWidth=i;s.maxWidth=o}}return void 0===a?a:a+""}}else if(ge.documentElement.currentStyle){en=function(t){return t.currentStyle};nn=function(t,e,n){var r,i,o,a,s=t.style;n=n||en(t);a=n?n[e]:void 0;null==a&&s&&s[e]&&(a=s[e]);if(on.test(a)&&!an.test(e)){r=s.left;i=t.runtimeStyle;o=i&&i.left;o&&(i.left=t.currentStyle.left);s.left="fontSize"===e?"1em":a;a=s.pixelLeft+"px";s.left=r;o&&(i.left=o)}return void 0===a?a:a+""||"auto"}}(function(){function t(){var t,n,r,i;n=ge.getElementsByTagName("body")[0];if(n&&n.style){t=ge.createElement("div");r=ge.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";n.appendChild(r).appendChild(t);t.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute";o=a=!1;l=!0;if(e.getComputedStyle){o="1%"!==(e.getComputedStyle(t,null)||{}).top;a="4px"===(e.getComputedStyle(t,null)||{width:"4px"}).width;i=t.appendChild(ge.createElement("div"));i.style.cssText=t.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";t.style.width="1px";l=!parseFloat((e.getComputedStyle(i,null)||{}).marginRight)}t.innerHTML="<table><tr><td></td><td>t</td></tr></table>";i=t.getElementsByTagName("td");i[0].style.cssText="margin:0;border:0;padding:0;display:none";s=0===i[0].offsetHeight;if(s){i[0].style.display="";i[1].style.display="none";s=0===i[0].offsetHeight}n.removeChild(r)}}var n,r,i,o,a,s,l;n=ge.createElement("div");n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";i=n.getElementsByTagName("a")[0];r=i&&i.style;if(r){r.cssText="float:left;opacity:.5";re.opacity="0.5"===r.opacity;re.cssFloat=!!r.cssFloat;n.style.backgroundClip="content-box";n.cloneNode(!0).style.backgroundClip="";re.clearCloneStyle="content-box"===n.style.backgroundClip;re.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing;oe.extend(re,{reliableHiddenOffsets:function(){null==s&&t();return s},boxSizingReliable:function(){null==a&&t();return a},pixelPosition:function(){null==o&&t();return o},reliableMarginRight:function(){null==l&&t();return l}})}})();oe.swap=function(t,e,n,r){var i,o,a={};for(o in e){a[o]=t.style[o];t.style[o]=e[o]}i=n.apply(t,r||[]);for(o in e)t.style[o]=a[o];return i};var sn=/alpha\([^)]*\)/i,ln=/opacity\s*=\s*([^)]*)/,un=/^(none|table(?!-c[ea]).+)/,cn=new RegExp("^("+Me+")(.*)$","i"),fn=new RegExp("^([+-])=("+Me+")","i"),hn={position:"absolute",visibility:"hidden",display:"block"},dn={letterSpacing:"0",fontWeight:"400"},pn=["Webkit","O","Moz","ms"];oe.extend({cssHooks:{opacity:{get:function(t,e){if(e){var n=nn(t,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":re.cssFloat?"cssFloat":"styleFloat"},style:function(t,e,n,r){if(t&&3!==t.nodeType&&8!==t.nodeType&&t.style){var i,o,a,s=oe.camelCase(e),l=t.style;e=oe.cssProps[s]||(oe.cssProps[s]=D(l,s));a=oe.cssHooks[e]||oe.cssHooks[s];if(void 0===n)return a&&"get"in a&&void 0!==(i=a.get(t,!1,r))?i:l[e];o=typeof n;if("string"===o&&(i=fn.exec(n))){n=(i[1]+1)*i[2]+parseFloat(oe.css(t,e));o="number"}if(null!=n&&n===n){"number"!==o||oe.cssNumber[s]||(n+="px");re.clearCloneStyle||""!==n||0!==e.indexOf("background")||(l[e]="inherit");if(!(a&&"set"in a&&void 0===(n=a.set(t,n,r))))try{l[e]=n}catch(u){}}}},css:function(t,e,n,r){var i,o,a,s=oe.camelCase(e);e=oe.cssProps[s]||(oe.cssProps[s]=D(t.style,s));a=oe.cssHooks[e]||oe.cssHooks[s];a&&"get"in a&&(o=a.get(t,!0,n));void 0===o&&(o=nn(t,e,r));"normal"===o&&e in dn&&(o=dn[e]);if(""===n||n){i=parseFloat(o);return n===!0||oe.isNumeric(i)?i||0:o}return o}});oe.each(["height","width"],function(t,e){oe.cssHooks[e]={get:function(t,n,r){return n?un.test(oe.css(t,"display"))&&0===t.offsetWidth?oe.swap(t,hn,function(){return E(t,e,r)}):E(t,e,r):void 0},set:function(t,n,r){var i=r&&en(t);return A(t,n,r?N(t,e,r,re.boxSizing&&"border-box"===oe.css(t,"boxSizing",!1,i),i):0)}}});re.opacity||(oe.cssHooks.opacity={get:function(t,e){return ln.test((e&&t.currentStyle?t.currentStyle.filter:t.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":e?"1":""},set:function(t,e){var n=t.style,r=t.currentStyle,i=oe.isNumeric(e)?"alpha(opacity="+100*e+")":"",o=r&&r.filter||n.filter||"";n.zoom=1;if((e>=1||""===e)&&""===oe.trim(o.replace(sn,""))&&n.removeAttribute){n.removeAttribute("filter");if(""===e||r&&!r.filter)return}n.filter=sn.test(o)?o.replace(sn,i):o+" "+i}});oe.cssHooks.marginRight=M(re.reliableMarginRight,function(t,e){return e?oe.swap(t,{display:"inline-block"},nn,[t,"marginRight"]):void 0});oe.each({margin:"",padding:"",border:"Width"},function(t,e){oe.cssHooks[t+e]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[t+De[r]+e]=o[r]||o[r-2]||o[0];return i}};rn.test(t)||(oe.cssHooks[t+e].set=A)});oe.fn.extend({css:function(t,e){return Ae(this,function(t,e,n){var r,i,o={},a=0;if(oe.isArray(e)){r=en(t);i=e.length;for(;i>a;a++)o[e[a]]=oe.css(t,e[a],!1,r);return o}return void 0!==n?oe.style(t,e,n):oe.css(t,e)},t,e,arguments.length>1)},show:function(){return L(this,!0)},hide:function(){return L(this)},toggle:function(t){return"boolean"==typeof t?t?this.show():this.hide():this.each(function(){Le(this)?oe(this).show():oe(this).hide()})}});oe.Tween=j;j.prototype={constructor:j,init:function(t,e,n,r,i,o){this.elem=t;this.prop=n;this.easing=i||"swing";this.options=e;this.start=this.now=this.cur();this.end=r;this.unit=o||(oe.cssNumber[n]?"":"px")},cur:function(){var t=j.propHooks[this.prop];return t&&t.get?t.get(this):j.propHooks._default.get(this)},run:function(t){var e,n=j.propHooks[this.prop];this.pos=e=this.options.duration?oe.easing[this.easing](t,this.options.duration*t,0,1,this.options.duration):t;this.now=(this.end-this.start)*e+this.start;this.options.step&&this.options.step.call(this.elem,this.now,this);n&&n.set?n.set(this):j.propHooks._default.set(this);return this}};j.prototype.init.prototype=j.prototype;j.propHooks={_default:{get:function(t){var e;if(null!=t.elem[t.prop]&&(!t.elem.style||null==t.elem.style[t.prop]))return t.elem[t.prop];e=oe.css(t.elem,t.prop,"");return e&&"auto"!==e?e:0},set:function(t){oe.fx.step[t.prop]?oe.fx.step[t.prop](t):t.elem.style&&(null!=t.elem.style[oe.cssProps[t.prop]]||oe.cssHooks[t.prop])?oe.style(t.elem,t.prop,t.now+t.unit):t.elem[t.prop]=t.now}}};j.propHooks.scrollTop=j.propHooks.scrollLeft={set:function(t){t.elem.nodeType&&t.elem.parentNode&&(t.elem[t.prop]=t.now)}};oe.easing={linear:function(t){return t},swing:function(t){return.5-Math.cos(t*Math.PI)/2}};oe.fx=j.prototype.init;oe.fx.step={};var gn,mn,vn=/^(?:toggle|show|hide)$/,yn=new RegExp("^(?:([+-])=|)("+Me+")([a-z%]*)$","i"),bn=/queueHooks$/,xn=[O],wn={"*":[function(t,e){var n=this.createTween(t,e),r=n.cur(),i=yn.exec(e),o=i&&i[3]||(oe.cssNumber[t]?"":"px"),a=(oe.cssNumber[t]||"px"!==o&&+r)&&yn.exec(oe.css(n.elem,t)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3];i=i||[];a=+r||1;do{s=s||".5";a/=s;oe.style(n.elem,t,a+o)}while(s!==(s=n.cur()/r)&&1!==s&&--l)}if(i){a=n.start=+a||+r||0;n.unit=o;n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]}return n}]};oe.Animation=oe.extend(R,{tweener:function(t,e){if(oe.isFunction(t)){e=t;t=["*"]}else t=t.split(" ");for(var n,r=0,i=t.length;i>r;r++){n=t[r];wn[n]=wn[n]||[];wn[n].unshift(e)}},prefilter:function(t,e){e?xn.unshift(t):xn.push(t)}});oe.speed=function(t,e,n){var r=t&&"object"==typeof t?oe.extend({},t):{complete:n||!n&&e||oe.isFunction(t)&&t,duration:t,easing:n&&e||e&&!oe.isFunction(e)&&e};r.duration=oe.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in oe.fx.speeds?oe.fx.speeds[r.duration]:oe.fx.speeds._default;(null==r.queue||r.queue===!0)&&(r.queue="fx");r.old=r.complete;r.complete=function(){oe.isFunction(r.old)&&r.old.call(this);r.queue&&oe.dequeue(this,r.queue)};return r};oe.fn.extend({fadeTo:function(t,e,n,r){return this.filter(Le).css("opacity",0).show().end().animate({opacity:e},t,n,r)},animate:function(t,e,n,r){var i=oe.isEmptyObject(t),o=oe.speed(e,n,r),a=function(){var e=R(this,oe.extend({},t),o);(i||oe._data(this,"finish"))&&e.stop(!0)};a.finish=a;return i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(t,e,n){var r=function(t){var e=t.stop;delete t.stop;e(n)};if("string"!=typeof t){n=e;e=t;t=void 0}e&&t!==!1&&this.queue(t||"fx",[]);return this.each(function(){var e=!0,i=null!=t&&t+"queueHooks",o=oe.timers,a=oe._data(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&bn.test(i)&&r(a[i]);for(i=o.length;i--;)if(o[i].elem===this&&(null==t||o[i].queue===t)){o[i].anim.stop(n);e=!1;o.splice(i,1)}(e||!n)&&oe.dequeue(this,t)})},finish:function(t){t!==!1&&(t=t||"fx");return this.each(function(){var e,n=oe._data(this),r=n[t+"queue"],i=n[t+"queueHooks"],o=oe.timers,a=r?r.length:0;n.finish=!0;oe.queue(this,t,[]);i&&i.stop&&i.stop.call(this,!0);
for(e=o.length;e--;)if(o[e].elem===this&&o[e].queue===t){o[e].anim.stop(!0);o.splice(e,1)}for(e=0;a>e;e++)r[e]&&r[e].finish&&r[e].finish.call(this);delete n.finish})}});oe.each(["toggle","show","hide"],function(t,e){var n=oe.fn[e];oe.fn[e]=function(t,r,i){return null==t||"boolean"==typeof t?n.apply(this,arguments):this.animate(P(e,!0),t,r,i)}});oe.each({slideDown:P("show"),slideUp:P("hide"),slideToggle:P("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(t,e){oe.fn[t]=function(t,n,r){return this.animate(e,t,n,r)}});oe.timers=[];oe.fx.tick=function(){var t,e=oe.timers,n=0;gn=oe.now();for(;n<e.length;n++){t=e[n];t()||e[n]!==t||e.splice(n--,1)}e.length||oe.fx.stop();gn=void 0};oe.fx.timer=function(t){oe.timers.push(t);t()?oe.fx.start():oe.timers.pop()};oe.fx.interval=13;oe.fx.start=function(){mn||(mn=setInterval(oe.fx.tick,oe.fx.interval))};oe.fx.stop=function(){clearInterval(mn);mn=null};oe.fx.speeds={slow:600,fast:200,_default:400};oe.fn.delay=function(t,e){t=oe.fx?oe.fx.speeds[t]||t:t;e=e||"fx";return this.queue(e,function(e,n){var r=setTimeout(e,t);n.stop=function(){clearTimeout(r)}})};(function(){var t,e,n,r,i;e=ge.createElement("div");e.setAttribute("className","t");e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";r=e.getElementsByTagName("a")[0];n=ge.createElement("select");i=n.appendChild(ge.createElement("option"));t=e.getElementsByTagName("input")[0];r.style.cssText="top:1px";re.getSetAttribute="t"!==e.className;re.style=/top/.test(r.getAttribute("style"));re.hrefNormalized="/a"===r.getAttribute("href");re.checkOn=!!t.value;re.optSelected=i.selected;re.enctype=!!ge.createElement("form").enctype;n.disabled=!0;re.optDisabled=!i.disabled;t=ge.createElement("input");t.setAttribute("value","");re.input=""===t.getAttribute("value");t.value="t";t.setAttribute("type","radio");re.radioValue="t"===t.value})();var Sn=/\r/g;oe.fn.extend({val:function(t){var e,n,r,i=this[0];if(arguments.length){r=oe.isFunction(t);return this.each(function(n){var i;if(1===this.nodeType){i=r?t.call(this,n,oe(this).val()):t;null==i?i="":"number"==typeof i?i+="":oe.isArray(i)&&(i=oe.map(i,function(t){return null==t?"":t+""}));e=oe.valHooks[this.type]||oe.valHooks[this.nodeName.toLowerCase()];e&&"set"in e&&void 0!==e.set(this,i,"value")||(this.value=i)}})}if(i){e=oe.valHooks[i.type]||oe.valHooks[i.nodeName.toLowerCase()];if(e&&"get"in e&&void 0!==(n=e.get(i,"value")))return n;n=i.value;return"string"==typeof n?n.replace(Sn,""):null==n?"":n}}});oe.extend({valHooks:{option:{get:function(t){var e=oe.find.attr(t,"value");return null!=e?e:oe.trim(oe.text(t))}},select:{get:function(t){for(var e,n,r=t.options,i=t.selectedIndex,o="select-one"===t.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;s>l;l++){n=r[l];if(!(!n.selected&&l!==i||(re.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&oe.nodeName(n.parentNode,"optgroup"))){e=oe(n).val();if(o)return e;a.push(e)}}return a},set:function(t,e){for(var n,r,i=t.options,o=oe.makeArray(e),a=i.length;a--;){r=i[a];if(oe.inArray(oe.valHooks.option.get(r),o)>=0)try{r.selected=n=!0}catch(s){r.scrollHeight}else r.selected=!1}n||(t.selectedIndex=-1);return i}}}});oe.each(["radio","checkbox"],function(){oe.valHooks[this]={set:function(t,e){return oe.isArray(e)?t.checked=oe.inArray(oe(t).val(),e)>=0:void 0}};re.checkOn||(oe.valHooks[this].get=function(t){return null===t.getAttribute("value")?"on":t.value})});var Cn,Tn,_n=oe.expr.attrHandle,kn=/^(?:checked|selected)$/i,Mn=re.getSetAttribute,Dn=re.input;oe.fn.extend({attr:function(t,e){return Ae(this,oe.attr,t,e,arguments.length>1)},removeAttr:function(t){return this.each(function(){oe.removeAttr(this,t)})}});oe.extend({attr:function(t,e,n){var r,i,o=t.nodeType;if(t&&3!==o&&8!==o&&2!==o){if(typeof t.getAttribute===Te)return oe.prop(t,e,n);if(1!==o||!oe.isXMLDoc(t)){e=e.toLowerCase();r=oe.attrHooks[e]||(oe.expr.match.bool.test(e)?Tn:Cn)}if(void 0===n){if(r&&"get"in r&&null!==(i=r.get(t,e)))return i;i=oe.find.attr(t,e);return null==i?void 0:i}if(null!==n){if(r&&"set"in r&&void 0!==(i=r.set(t,n,e)))return i;t.setAttribute(e,n+"");return n}oe.removeAttr(t,e)}},removeAttr:function(t,e){var n,r,i=0,o=e&&e.match(xe);if(o&&1===t.nodeType)for(;n=o[i++];){r=oe.propFix[n]||n;oe.expr.match.bool.test(n)?Dn&&Mn||!kn.test(n)?t[r]=!1:t[oe.camelCase("default-"+n)]=t[r]=!1:oe.attr(t,n,"");t.removeAttribute(Mn?n:r)}},attrHooks:{type:{set:function(t,e){if(!re.radioValue&&"radio"===e&&oe.nodeName(t,"input")){var n=t.value;t.setAttribute("type",e);n&&(t.value=n);return e}}}}});Tn={set:function(t,e,n){e===!1?oe.removeAttr(t,n):Dn&&Mn||!kn.test(n)?t.setAttribute(!Mn&&oe.propFix[n]||n,n):t[oe.camelCase("default-"+n)]=t[n]=!0;return n}};oe.each(oe.expr.match.bool.source.match(/\w+/g),function(t,e){var n=_n[e]||oe.find.attr;_n[e]=Dn&&Mn||!kn.test(e)?function(t,e,r){var i,o;if(!r){o=_n[e];_n[e]=i;i=null!=n(t,e,r)?e.toLowerCase():null;_n[e]=o}return i}:function(t,e,n){return n?void 0:t[oe.camelCase("default-"+e)]?e.toLowerCase():null}});Dn&&Mn||(oe.attrHooks.value={set:function(t,e,n){if(!oe.nodeName(t,"input"))return Cn&&Cn.set(t,e,n);t.defaultValue=e;return void 0}});if(!Mn){Cn={set:function(t,e,n){var r=t.getAttributeNode(n);r||t.setAttributeNode(r=t.ownerDocument.createAttribute(n));r.value=e+="";return"value"===n||e===t.getAttribute(n)?e:void 0}};_n.id=_n.name=_n.coords=function(t,e,n){var r;return n?void 0:(r=t.getAttributeNode(e))&&""!==r.value?r.value:null};oe.valHooks.button={get:function(t,e){var n=t.getAttributeNode(e);return n&&n.specified?n.value:void 0},set:Cn.set};oe.attrHooks.contenteditable={set:function(t,e,n){Cn.set(t,""===e?!1:e,n)}};oe.each(["width","height"],function(t,e){oe.attrHooks[e]={set:function(t,n){if(""===n){t.setAttribute(e,"auto");return n}}}})}re.style||(oe.attrHooks.style={get:function(t){return t.style.cssText||void 0},set:function(t,e){return t.style.cssText=e+""}});var Ln=/^(?:input|select|textarea|button|object)$/i,An=/^(?:a|area)$/i;oe.fn.extend({prop:function(t,e){return Ae(this,oe.prop,t,e,arguments.length>1)},removeProp:function(t){t=oe.propFix[t]||t;return this.each(function(){try{this[t]=void 0;delete this[t]}catch(e){}})}});oe.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(t,e,n){var r,i,o,a=t.nodeType;if(t&&3!==a&&8!==a&&2!==a){o=1!==a||!oe.isXMLDoc(t);if(o){e=oe.propFix[e]||e;i=oe.propHooks[e]}return void 0!==n?i&&"set"in i&&void 0!==(r=i.set(t,n,e))?r:t[e]=n:i&&"get"in i&&null!==(r=i.get(t,e))?r:t[e]}},propHooks:{tabIndex:{get:function(t){var e=oe.find.attr(t,"tabindex");return e?parseInt(e,10):Ln.test(t.nodeName)||An.test(t.nodeName)&&t.href?0:-1}}}});re.hrefNormalized||oe.each(["href","src"],function(t,e){oe.propHooks[e]={get:function(t){return t.getAttribute(e,4)}}});re.optSelected||(oe.propHooks.selected={get:function(t){var e=t.parentNode;if(e){e.selectedIndex;e.parentNode&&e.parentNode.selectedIndex}return null}});oe.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){oe.propFix[this.toLowerCase()]=this});re.enctype||(oe.propFix.enctype="encoding");var Nn=/[\t\r\n\f]/g;oe.fn.extend({addClass:function(t){var e,n,r,i,o,a,s=0,l=this.length,u="string"==typeof t&&t;if(oe.isFunction(t))return this.each(function(e){oe(this).addClass(t.call(this,e,this.className))});if(u){e=(t||"").match(xe)||[];for(;l>s;s++){n=this[s];r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Nn," "):" ");if(r){o=0;for(;i=e[o++];)r.indexOf(" "+i+" ")<0&&(r+=i+" ");a=oe.trim(r);n.className!==a&&(n.className=a)}}}return this},removeClass:function(t){var e,n,r,i,o,a,s=0,l=this.length,u=0===arguments.length||"string"==typeof t&&t;if(oe.isFunction(t))return this.each(function(e){oe(this).removeClass(t.call(this,e,this.className))});if(u){e=(t||"").match(xe)||[];for(;l>s;s++){n=this[s];r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(Nn," "):"");if(r){o=0;for(;i=e[o++];)for(;r.indexOf(" "+i+" ")>=0;)r=r.replace(" "+i+" "," ");a=t?oe.trim(r):"";n.className!==a&&(n.className=a)}}}return this},toggleClass:function(t,e){var n=typeof t;return"boolean"==typeof e&&"string"===n?e?this.addClass(t):this.removeClass(t):this.each(oe.isFunction(t)?function(n){oe(this).toggleClass(t.call(this,n,this.className,e),e)}:function(){if("string"===n)for(var e,r=0,i=oe(this),o=t.match(xe)||[];e=o[r++];)i.hasClass(e)?i.removeClass(e):i.addClass(e);else if(n===Te||"boolean"===n){this.className&&oe._data(this,"__className__",this.className);this.className=this.className||t===!1?"":oe._data(this,"__className__")||""}})},hasClass:function(t){for(var e=" "+t+" ",n=0,r=this.length;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(Nn," ").indexOf(e)>=0)return!0;return!1}});oe.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(t,e){oe.fn[e]=function(t,n){return arguments.length>0?this.on(e,null,t,n):this.trigger(e)}});oe.fn.extend({hover:function(t,e){return this.mouseenter(t).mouseleave(e||t)},bind:function(t,e,n){return this.on(t,null,e,n)},unbind:function(t,e){return this.off(t,null,e)},delegate:function(t,e,n,r){return this.on(e,t,n,r)},undelegate:function(t,e,n){return 1===arguments.length?this.off(t,"**"):this.off(e,t||"**",n)}});var En=oe.now(),jn=/\?/,In=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;oe.parseJSON=function(t){if(e.JSON&&e.JSON.parse)return e.JSON.parse(t+"");var n,r=null,i=oe.trim(t+"");return i&&!oe.trim(i.replace(In,function(t,e,i,o){n&&e&&(r=0);if(0===r)return t;n=i||e;r+=!o-!i;return""}))?Function("return "+i)():oe.error("Invalid JSON: "+t)};oe.parseXML=function(t){var n,r;if(!t||"string"!=typeof t)return null;try{if(e.DOMParser){r=new DOMParser;n=r.parseFromString(t,"text/xml")}else{n=new ActiveXObject("Microsoft.XMLDOM");n.async="false";n.loadXML(t)}}catch(i){n=void 0}n&&n.documentElement&&!n.getElementsByTagName("parsererror").length||oe.error("Invalid XML: "+t);return n};var Pn,Hn,On=/#.*$/,Fn=/([?&])_=[^&]*/,Rn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Wn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,zn=/^(?:GET|HEAD)$/,qn=/^\/\//,Un=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Bn={},Vn={},Xn="*/".concat("*");try{Hn=location.href}catch(Gn){Hn=ge.createElement("a");Hn.href="";Hn=Hn.href}Pn=Un.exec(Hn.toLowerCase())||[];oe.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Hn,type:"GET",isLocal:Wn.test(Pn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Xn,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":oe.parseJSON,"text xml":oe.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(t,e){return e?q(q(t,oe.ajaxSettings),e):q(oe.ajaxSettings,t)},ajaxPrefilter:W(Bn),ajaxTransport:W(Vn),ajax:function(t,e){function n(t,e,n,r){var i,c,v,y,x,S=e;if(2!==b){b=2;s&&clearTimeout(s);u=void 0;a=r||"";w.readyState=t>0?4:0;i=t>=200&&300>t||304===t;n&&(y=U(f,w,n));y=B(f,y,w,i);if(i){if(f.ifModified){x=w.getResponseHeader("Last-Modified");x&&(oe.lastModified[o]=x);x=w.getResponseHeader("etag");x&&(oe.etag[o]=x)}if(204===t||"HEAD"===f.type)S="nocontent";else if(304===t)S="notmodified";else{S=y.state;c=y.data;v=y.error;i=!v}}else{v=S;if(t||!S){S="error";0>t&&(t=0)}}w.status=t;w.statusText=(e||S)+"";i?p.resolveWith(h,[c,S,w]):p.rejectWith(h,[w,S,v]);w.statusCode(m);m=void 0;l&&d.trigger(i?"ajaxSuccess":"ajaxError",[w,f,i?c:v]);g.fireWith(h,[w,S]);if(l){d.trigger("ajaxComplete",[w,f]);--oe.active||oe.event.trigger("ajaxStop")}}}if("object"==typeof t){e=t;t=void 0}e=e||{};var r,i,o,a,s,l,u,c,f=oe.ajaxSetup({},e),h=f.context||f,d=f.context&&(h.nodeType||h.jquery)?oe(h):oe.event,p=oe.Deferred(),g=oe.Callbacks("once memory"),m=f.statusCode||{},v={},y={},b=0,x="canceled",w={readyState:0,getResponseHeader:function(t){var e;if(2===b){if(!c){c={};for(;e=Rn.exec(a);)c[e[1].toLowerCase()]=e[2]}e=c[t.toLowerCase()]}return null==e?null:e},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(t,e){var n=t.toLowerCase();if(!b){t=y[n]=y[n]||t;v[t]=e}return this},overrideMimeType:function(t){b||(f.mimeType=t);return this},statusCode:function(t){var e;if(t)if(2>b)for(e in t)m[e]=[m[e],t[e]];else w.always(t[w.status]);return this},abort:function(t){var e=t||x;u&&u.abort(e);n(0,e);return this}};p.promise(w).complete=g.add;w.success=w.done;w.error=w.fail;f.url=((t||f.url||Hn)+"").replace(On,"").replace(qn,Pn[1]+"//");f.type=e.method||e.type||f.method||f.type;f.dataTypes=oe.trim(f.dataType||"*").toLowerCase().match(xe)||[""];if(null==f.crossDomain){r=Un.exec(f.url.toLowerCase());f.crossDomain=!(!r||r[1]===Pn[1]&&r[2]===Pn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(Pn[3]||("http:"===Pn[1]?"80":"443")))}f.data&&f.processData&&"string"!=typeof f.data&&(f.data=oe.param(f.data,f.traditional));z(Bn,f,e,w);if(2===b)return w;l=f.global;l&&0===oe.active++&&oe.event.trigger("ajaxStart");f.type=f.type.toUpperCase();f.hasContent=!zn.test(f.type);o=f.url;if(!f.hasContent){if(f.data){o=f.url+=(jn.test(o)?"&":"?")+f.data;delete f.data}f.cache===!1&&(f.url=Fn.test(o)?o.replace(Fn,"$1_="+En++):o+(jn.test(o)?"&":"?")+"_="+En++)}if(f.ifModified){oe.lastModified[o]&&w.setRequestHeader("If-Modified-Since",oe.lastModified[o]);oe.etag[o]&&w.setRequestHeader("If-None-Match",oe.etag[o])}(f.data&&f.hasContent&&f.contentType!==!1||e.contentType)&&w.setRequestHeader("Content-Type",f.contentType);w.setRequestHeader("Accept",f.dataTypes[0]&&f.accepts[f.dataTypes[0]]?f.accepts[f.dataTypes[0]]+("*"!==f.dataTypes[0]?", "+Xn+"; q=0.01":""):f.accepts["*"]);for(i in f.headers)w.setRequestHeader(i,f.headers[i]);if(f.beforeSend&&(f.beforeSend.call(h,w,f)===!1||2===b))return w.abort();x="abort";for(i in{success:1,error:1,complete:1})w[i](f[i]);u=z(Vn,f,e,w);if(u){w.readyState=1;l&&d.trigger("ajaxSend",[w,f]);f.async&&f.timeout>0&&(s=setTimeout(function(){w.abort("timeout")},f.timeout));try{b=1;u.send(v,n)}catch(S){if(!(2>b))throw S;n(-1,S)}}else n(-1,"No Transport");return w},getJSON:function(t,e,n){return oe.get(t,e,n,"json")},getScript:function(t,e){return oe.get(t,void 0,e,"script")}});oe.each(["get","post"],function(t,e){oe[e]=function(t,n,r,i){if(oe.isFunction(n)){i=i||r;r=n;n=void 0}return oe.ajax({url:t,type:e,dataType:i,data:n,success:r})}});oe.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(t,e){oe.fn[e]=function(t){return this.on(e,t)}});oe._evalUrl=function(t){return oe.ajax({url:t,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})};oe.fn.extend({wrapAll:function(t){if(oe.isFunction(t))return this.each(function(e){oe(this).wrapAll(t.call(this,e))});if(this[0]){var e=oe(t,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&e.insertBefore(this[0]);e.map(function(){for(var t=this;t.firstChild&&1===t.firstChild.nodeType;)t=t.firstChild;return t}).append(this)}return this},wrapInner:function(t){return this.each(oe.isFunction(t)?function(e){oe(this).wrapInner(t.call(this,e))}:function(){var e=oe(this),n=e.contents();n.length?n.wrapAll(t):e.append(t)})},wrap:function(t){var e=oe.isFunction(t);return this.each(function(n){oe(this).wrapAll(e?t.call(this,n):t)})},unwrap:function(){return this.parent().each(function(){oe.nodeName(this,"body")||oe(this).replaceWith(this.childNodes)}).end()}});oe.expr.filters.hidden=function(t){return t.offsetWidth<=0&&t.offsetHeight<=0||!re.reliableHiddenOffsets()&&"none"===(t.style&&t.style.display||oe.css(t,"display"))};oe.expr.filters.visible=function(t){return!oe.expr.filters.hidden(t)};var $n=/%20/g,Yn=/\[\]$/,Jn=/\r?\n/g,Kn=/^(?:submit|button|image|reset|file)$/i,Zn=/^(?:input|select|textarea|keygen)/i;oe.param=function(t,e){var n,r=[],i=function(t,e){e=oe.isFunction(e)?e():null==e?"":e;r[r.length]=encodeURIComponent(t)+"="+encodeURIComponent(e)};void 0===e&&(e=oe.ajaxSettings&&oe.ajaxSettings.traditional);if(oe.isArray(t)||t.jquery&&!oe.isPlainObject(t))oe.each(t,function(){i(this.name,this.value)});else for(n in t)V(n,t[n],e,i);return r.join("&").replace($n,"+")};oe.fn.extend({serialize:function(){return oe.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var t=oe.prop(this,"elements");return t?oe.makeArray(t):this}).filter(function(){var t=this.type;return this.name&&!oe(this).is(":disabled")&&Zn.test(this.nodeName)&&!Kn.test(t)&&(this.checked||!Ne.test(t))}).map(function(t,e){var n=oe(this).val();return null==n?null:oe.isArray(n)?oe.map(n,function(t){return{name:e.name,value:t.replace(Jn,"\r\n")}}):{name:e.name,value:n.replace(Jn,"\r\n")}}).get()}});oe.ajaxSettings.xhr=void 0!==e.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&X()||G()}:X;var Qn=0,tr={},er=oe.ajaxSettings.xhr();e.ActiveXObject&&oe(e).on("unload",function(){for(var t in tr)tr[t](void 0,!0)});re.cors=!!er&&"withCredentials"in er;er=re.ajax=!!er;er&&oe.ajaxTransport(function(t){if(!t.crossDomain||re.cors){var e;return{send:function(n,r){var i,o=t.xhr(),a=++Qn;o.open(t.type,t.url,t.async,t.username,t.password);if(t.xhrFields)for(i in t.xhrFields)o[i]=t.xhrFields[i];t.mimeType&&o.overrideMimeType&&o.overrideMimeType(t.mimeType);t.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(i in n)void 0!==n[i]&&o.setRequestHeader(i,n[i]+"");o.send(t.hasContent&&t.data||null);e=function(n,i){var s,l,u;if(e&&(i||4===o.readyState)){delete tr[a];e=void 0;o.onreadystatechange=oe.noop;if(i)4!==o.readyState&&o.abort();else{u={};s=o.status;"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText}catch(c){l=""}s||!t.isLocal||t.crossDomain?1223===s&&(s=204):s=u.text?200:404}}u&&r(s,l,u,o.getAllResponseHeaders())};t.async?4===o.readyState?setTimeout(e):o.onreadystatechange=tr[a]=e:e()},abort:function(){e&&e(void 0,!0)}}}});oe.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(t){oe.globalEval(t);return t}}});oe.ajaxPrefilter("script",function(t){void 0===t.cache&&(t.cache=!1);if(t.crossDomain){t.type="GET";t.global=!1}});oe.ajaxTransport("script",function(t){if(t.crossDomain){var e,n=ge.head||oe("head")[0]||ge.documentElement;return{send:function(r,i){e=ge.createElement("script");e.async=!0;t.scriptCharset&&(e.charset=t.scriptCharset);e.src=t.url;e.onload=e.onreadystatechange=function(t,n){if(n||!e.readyState||/loaded|complete/.test(e.readyState)){e.onload=e.onreadystatechange=null;e.parentNode&&e.parentNode.removeChild(e);e=null;n||i(200,"success")}};n.insertBefore(e,n.firstChild)},abort:function(){e&&e.onload(void 0,!0)}}}});var nr=[],rr=/(=)\?(?=&|$)|\?\?/;oe.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var t=nr.pop()||oe.expando+"_"+En++;this[t]=!0;return t}});oe.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,a,s=t.jsonp!==!1&&(rr.test(t.url)?"url":"string"==typeof t.data&&!(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&rr.test(t.data)&&"data");if(s||"jsonp"===t.dataTypes[0]){i=t.jsonpCallback=oe.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback;s?t[s]=t[s].replace(rr,"$1"+i):t.jsonp!==!1&&(t.url+=(jn.test(t.url)?"&":"?")+t.jsonp+"="+i);t.converters["script json"]=function(){a||oe.error(i+" was not called");return a[0]};t.dataTypes[0]="json";o=e[i];e[i]=function(){a=arguments};r.always(function(){e[i]=o;if(t[i]){t.jsonpCallback=n.jsonpCallback;nr.push(i)}a&&oe.isFunction(o)&&o(a[0]);a=o=void 0});return"script"}});oe.parseHTML=function(t,e,n){if(!t||"string"!=typeof t)return null;if("boolean"==typeof e){n=e;e=!1}e=e||ge;var r=he.exec(t),i=!n&&[];if(r)return[e.createElement(r[1])];r=oe.buildFragment([t],e,i);i&&i.length&&oe(i).remove();return oe.merge([],r.childNodes)};var ir=oe.fn.load;oe.fn.load=function(t,e,n){if("string"!=typeof t&&ir)return ir.apply(this,arguments);var r,i,o,a=this,s=t.indexOf(" ");if(s>=0){r=oe.trim(t.slice(s,t.length));t=t.slice(0,s)}if(oe.isFunction(e)){n=e;e=void 0}else e&&"object"==typeof e&&(o="POST");a.length>0&&oe.ajax({url:t,type:o,dataType:"html",data:e}).done(function(t){i=arguments;a.html(r?oe("<div>").append(oe.parseHTML(t)).find(r):t)}).complete(n&&function(t,e){a.each(n,i||[t.responseText,e,t])});return this};oe.expr.filters.animated=function(t){return oe.grep(oe.timers,function(e){return t===e.elem}).length};var or=e.document.documentElement;oe.offset={setOffset:function(t,e,n){var r,i,o,a,s,l,u,c=oe.css(t,"position"),f=oe(t),h={};"static"===c&&(t.style.position="relative");s=f.offset();o=oe.css(t,"top");l=oe.css(t,"left");u=("absolute"===c||"fixed"===c)&&oe.inArray("auto",[o,l])>-1;if(u){r=f.position();a=r.top;i=r.left}else{a=parseFloat(o)||0;i=parseFloat(l)||0}oe.isFunction(e)&&(e=e.call(t,n,s));null!=e.top&&(h.top=e.top-s.top+a);null!=e.left&&(h.left=e.left-s.left+i);"using"in e?e.using.call(t,h):f.css(h)}};oe.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){oe.offset.setOffset(this,t,e)});var e,n,r={top:0,left:0},i=this[0],o=i&&i.ownerDocument;if(o){e=o.documentElement;if(!oe.contains(e,i))return r;typeof i.getBoundingClientRect!==Te&&(r=i.getBoundingClientRect());n=$(o);return{top:r.top+(n.pageYOffset||e.scrollTop)-(e.clientTop||0),left:r.left+(n.pageXOffset||e.scrollLeft)-(e.clientLeft||0)}}},position:function(){if(this[0]){var t,e,n={top:0,left:0},r=this[0];if("fixed"===oe.css(r,"position"))e=r.getBoundingClientRect();else{t=this.offsetParent();e=this.offset();oe.nodeName(t[0],"html")||(n=t.offset());n.top+=oe.css(t[0],"borderTopWidth",!0);n.left+=oe.css(t[0],"borderLeftWidth",!0)}return{top:e.top-n.top-oe.css(r,"marginTop",!0),left:e.left-n.left-oe.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var t=this.offsetParent||or;t&&!oe.nodeName(t,"html")&&"static"===oe.css(t,"position");)t=t.offsetParent;return t||or})}});oe.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,e){var n=/Y/.test(e);oe.fn[t]=function(r){return Ae(this,function(t,r,i){var o=$(t);if(void 0===i)return o?e in o?o[e]:o.document.documentElement[r]:t[r];o?o.scrollTo(n?oe(o).scrollLeft():i,n?i:oe(o).scrollTop()):t[r]=i;return void 0},t,r,arguments.length,null)}});oe.each(["top","left"],function(t,e){oe.cssHooks[e]=M(re.pixelPosition,function(t,n){if(n){n=nn(t,e);return on.test(n)?oe(t).position()[e]+"px":n}})});oe.each({Height:"height",Width:"width"},function(t,e){oe.each({padding:"inner"+t,content:e,"":"outer"+t},function(n,r){oe.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),a=n||(r===!0||i===!0?"margin":"border");return Ae(this,function(e,n,r){var i;if(oe.isWindow(e))return e.document.documentElement["client"+t];if(9===e.nodeType){i=e.documentElement;return Math.max(e.body["scroll"+t],i["scroll"+t],e.body["offset"+t],i["offset"+t],i["client"+t])}return void 0===r?oe.css(e,n,a):oe.style(e,n,r,a)},e,o?r:void 0,o,null)}})});oe.fn.size=function(){return this.length};oe.fn.andSelf=oe.fn.addBack;"function"==typeof t&&t.amd&&t("jquery",[],function(){return oe});var ar=e.jQuery,sr=e.$;oe.noConflict=function(t){e.$===oe&&(e.$=sr);t&&e.jQuery===oe&&(e.jQuery=ar);return oe};typeof n===Te&&(e.jQuery=e.$=oe);return oe})},{}],18:[function(e,n,r){(function(){(function(i){if("object"==typeof r&&"object"==typeof n)return i(e("jquery"));if("function"==typeof t&&t.amd)return t(["jquery"],i);i(jQuery);return void 0})(function(t){var e;e=t;return e.pivotUtilities.d3_renderers={Treemap:function(t,n){var r,i,o,a,s,l,u,c,f,h,d,p,g,m;o={localeStrings:{}};n=e.extend(o,n);l=e("<div style='width: 100%; height: 100%;'>");c={name:"All",children:[]};r=function(t,e,n){var i,o,a,s,l,u,c;if(0!==e.length){null==(u=t.children)&&(t.children=[]);a=e.shift();c=t.children;for(s=0,l=c.length;l>s;s++){i=c[s];if(i.name===a){r(i,e,n);return}}o={name:a};r(o,e,n);return t.children.push(o)}t.value=n};m=t.getRowKeys();for(p=0,g=m.length;g>p;p++){u=m[p];h=t.getAggregator(u,[]).value();null!=h&&r(c,u,h)}i=d3.scale.category10();d=e(window).width()/1.4;a=e(window).height()/1.4;s=10;f=d3.layout.treemap().size([d,a]).sticky(!0).value(function(t){return t.size});d3.select(l[0]).append("div").style("position","relative").style("width",d+2*s+"px").style("height",a+2*s+"px").style("left",s+"px").style("top",s+"px").datum(c).selectAll(".node").data(f.padding([15,0,0,0]).value(function(t){return t.value}).nodes).enter().append("div").attr("class","node").style("background",function(t){return null!=t.children?"lightgrey":i(t.name)}).text(function(t){return t.name}).call(function(){this.style("left",function(t){return t.x+"px"}).style("top",function(t){return t.y+"px"}).style("width",function(t){return Math.max(0,t.dx-1)+"px"}).style("height",function(t){return Math.max(0,t.dy-1)+"px"})});return l}}})}).call(this)},{jquery:17}],19:[function(e,n,r){(function(){(function(i){if("object"==typeof r&&"object"==typeof n)return i(e("jquery"));if("function"==typeof t&&t.amd)return t(["jquery"],i);i(jQuery);return void 0})(function(t){var e,n;e=t;n=function(t,n){return function(r,i){var o,a,s,l,u,c,f,h,d,p,g,m,v,y,b,x,w,S,C,T,_,k,M,D,L;c={localeStrings:{vs:"vs",by:"by"}};i=e.extend(c,i);w=r.getRowKeys();0===w.length&&w.push([]);s=r.getColKeys();0===s.length&&s.push([]);p=function(){var t,e,n;n=[];for(t=0,e=w.length;e>t;t++){h=w[t];n.push(h.join("-"))}return n}();p.unshift("");m=0;l=[p];for(k=0,D=s.length;D>k;k++){a=s[k];b=[a.join("-")];m+=b[0].length;for(M=0,L=w.length;L>M;M++){x=w[M];o=r.getAggregator(x,a);b.push(null!=o.value()?o.value():null)}l.push(b)}S=T=r.aggregatorName+(r.valAttrs.length?"("+r.valAttrs.join(", ")+")":"");d=r.colAttrs.join("-");""!==d&&(S+=" "+i.localeStrings.vs+" "+d);f=r.rowAttrs.join("-");""!==f&&(S+=" "+i.localeStrings.by+" "+f);v={width:e(window).width()/1.4,height:e(window).height()/1.4,title:S,hAxis:{title:d,slantedText:m>50},vAxis:{title:T}};2===l[0].length&&""===l[0][1]&&(v.legend={position:"none"});for(g in n){C=n[g];v[g]=C}u=google.visualization.arrayToDataTable(l);y=e("<div style='width: 100%; height: 100%;'>");_=new google.visualization.ChartWrapper({dataTable:u,chartType:t,options:v});_.draw(y[0]);y.bind("dblclick",function(){var t;t=new google.visualization.ChartEditor;google.visualization.events.addListener(t,"ok",function(){return t.getChartWrapper().draw(y[0])});return t.openDialog(_)});return y}};return e.pivotUtilities.gchart_renderers={"Line Chart":n("LineChart"),"Bar Chart":n("ColumnChart"),"Stacked Bar Chart":n("ColumnChart",{isStacked:!0}),"Area Chart":n("AreaChart",{isStacked:!0})}})}).call(this)},{jquery:17}],20:[function(e,n,r){(function(){var i=[].indexOf||function(t){for(var e=0,n=this.length;n>e;e++)if(e in this&&this[e]===t)return e;return-1},o=[].slice,a=function(t,e){return function(){return t.apply(e,arguments)}},s={}.hasOwnProperty;(function(i){if("object"==typeof r&&"object"==typeof n)return i(e("jquery"));if("function"==typeof t&&t.amd)return t(["jquery"],i);i(jQuery);return void 0})(function(t){var e,n,r,l,u,c,f,h,d,p,g,m,v,y,b,x,w;e=t;r=function(t,e,n){var r,i,o,a;t+="";i=t.split(".");o=i[0];a=i.length>1?n+i[1]:"";r=/(\d+)(\d{3})/;for(;r.test(o);)o=o.replace(r,"$1"+e+"$2");return o+a};g=function(t){var n;n={digitsAfterDecimal:2,scaler:1,thousandsSep:",",decimalSep:".",prefix:"",suffix:"",showZero:!1};t=e.extend(n,t);return function(e){var n;if(isNaN(e)||!isFinite(e))return"";if(0===e&&!t.showZero)return"";n=r((t.scaler*e).toFixed(t.digitsAfterDecimal),t.thousandsSep,t.decimalSep);return""+t.prefix+n+t.suffix}};y=g();b=g({digitsAfterDecimal:0});x=g({digitsAfterDecimal:1,scaler:100,suffix:"%"});l={count:function(t){null==t&&(t=b);return function(){return function(){return{count:0,push:function(){return this.count++},value:function(){return this.count},format:t}}}},countUnique:function(t){null==t&&(t=b);return function(e){var n;n=e[0];return function(){return{uniq:[],push:function(t){var e;return e=t[n],i.call(this.uniq,e)<0?this.uniq.push(t[n]):void 0},value:function(){return this.uniq.length},format:t,numInputs:null!=n?0:1}}}},listUnique:function(t){return function(e){var n;n=e[0];return function(){return{uniq:[],push:function(t){var e;return e=t[n],i.call(this.uniq,e)<0?this.uniq.push(t[n]):void 0},value:function(){return this.uniq.join(t)},format:function(t){return t},numInputs:null!=n?0:1}}}},sum:function(t){null==t&&(t=y);return function(e){var n;n=e[0];return function(){return{sum:0,push:function(t){return isNaN(parseFloat(t[n]))?void 0:this.sum+=parseFloat(t[n])},value:function(){return this.sum},format:t,numInputs:null!=n?0:1}}}},average:function(t){null==t&&(t=y);return function(e){var n;n=e[0];return function(){return{sum:0,len:0,push:function(t){if(!isNaN(parseFloat(t[n]))){this.sum+=parseFloat(t[n]);return this.len++}},value:function(){return this.sum/this.len},format:t,numInputs:null!=n?0:1}}}},sumOverSum:function(t){null==t&&(t=y);return function(e){var n,r;r=e[0],n=e[1];return function(){return{sumNum:0,sumDenom:0,push:function(t){isNaN(parseFloat(t[r]))||(this.sumNum+=parseFloat(t[r]));return isNaN(parseFloat(t[n]))?void 0:this.sumDenom+=parseFloat(t[n])},value:function(){return this.sumNum/this.sumDenom},format:t,numInputs:null!=r&&null!=n?0:2}}}},sumOverSumBound80:function(t,e){null==t&&(t=!0);null==e&&(e=y);return function(n){var r,i;i=n[0],r=n[1];return function(){return{sumNum:0,sumDenom:0,push:function(t){isNaN(parseFloat(t[i]))||(this.sumNum+=parseFloat(t[i]));return isNaN(parseFloat(t[r]))?void 0:this.sumDenom+=parseFloat(t[r])},value:function(){var e;e=t?1:-1;return(.821187207574908/this.sumDenom+this.sumNum/this.sumDenom+1.2815515655446004*e*Math.sqrt(.410593603787454/(this.sumDenom*this.sumDenom)+this.sumNum*(1-this.sumNum/this.sumDenom)/(this.sumDenom*this.sumDenom)))/(1+1.642374415149816/this.sumDenom)},format:e,numInputs:null!=i&&null!=r?0:2}}}},fractionOf:function(t,e,n){null==e&&(e="total");null==n&&(n=x);return function(){var r;r=1<=arguments.length?o.call(arguments,0):[];return function(i,o,a){return{selector:{total:[[],[]],row:[o,[]],col:[[],a]}[e],inner:t.apply(null,r)(i,o,a),push:function(t){return this.inner.push(t)},format:n,value:function(){return this.inner.value()/i.getAggregator.apply(i,this.selector).inner.value()},numInputs:t.apply(null,r)().numInputs}}}}};u=function(t){return{Count:t.count(b),"Count Unique Values":t.countUnique(b),"List Unique Values":t.listUnique(", "),Sum:t.sum(y),"Integer Sum":t.sum(b),Average:t.average(y),"Sum over Sum":t.sumOverSum(y),"80% Upper Bound":t.sumOverSumBound80(!0,y),"80% Lower Bound":t.sumOverSumBound80(!1,y),"Sum as Fraction of Total":t.fractionOf(t.sum(),"total",x),"Sum as Fraction of Rows":t.fractionOf(t.sum(),"row",x),"Sum as Fraction of Columns":t.fractionOf(t.sum(),"col",x),"Count as Fraction of Total":t.fractionOf(t.count(),"total",x),"Count as Fraction of Rows":t.fractionOf(t.count(),"row",x),"Count as Fraction of Columns":t.fractionOf(t.count(),"col",x)}}(l);v={Table:function(t,e){return m(t,e)},"Table Barchart":function(t,n){return e(m(t,n)).barchart()},Heatmap:function(t,n){return e(m(t,n)).heatmap()},"Row Heatmap":function(t,n){return e(m(t,n)).heatmap("rowheatmap")},"Col Heatmap":function(t,n){return e(m(t,n)).heatmap("colheatmap")}};h={en:{aggregators:u,renderers:v,localeStrings:{renderError:"An error occurred rendering the PivotTable results.",computeError:"An error occurred computing the PivotTable results.",uiRenderError:"An error occurred rendering the PivotTable UI.",selectAll:"Select All",selectNone:"Select None",tooMany:"(too many to list)",filterResults:"Filter results",totals:"Totals",vs:"vs",by:"by"}}};
d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];c=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];w=function(t){return("0"+t).substr(-2,2)};f={bin:function(t,e){return function(n){return n[t]-n[t]%e}},dateFormat:function(t,e,n,r){null==n&&(n=d);null==r&&(r=c);return function(i){var o;o=new Date(Date.parse(i[t]));return isNaN(o)?"":e.replace(/%(.)/g,function(t,e){switch(e){case"y":return o.getFullYear();case"m":return w(o.getMonth()+1);case"n":return n[o.getMonth()];case"d":return w(o.getDate());case"w":return r[o.getDay()];case"x":return o.getDay();case"H":return w(o.getHours());case"M":return w(o.getMinutes());case"S":return w(o.getSeconds());default:return"%"+e}})}}};p=function(t,e){var n,r,i,o,a,s,l;s=/(\d+)|(\D+)/g;a=/\d/;l=/^0/;if("number"==typeof t||"number"==typeof e)return isNaN(t)?1:isNaN(e)?-1:t-e;n=String(t).toLowerCase();i=String(e).toLowerCase();if(n===i)return 0;if(!a.test(n)||!a.test(i))return n>i?1:-1;n=n.match(s);i=i.match(s);for(;n.length&&i.length;){r=n.shift();o=i.shift();if(r!==o)return a.test(r)&&a.test(o)?r.replace(l,".0")-o.replace(l,".0"):r>o?1:-1}return n.length-i.length};e.pivotUtilities={aggregatorTemplates:l,aggregators:u,renderers:v,derivers:f,locales:h,naturalSort:p,numberFormat:g};n=function(){function n(t,e){this.getAggregator=a(this.getAggregator,this);this.getRowKeys=a(this.getRowKeys,this);this.getColKeys=a(this.getColKeys,this);this.sortKeys=a(this.sortKeys,this);this.arrSort=a(this.arrSort,this);this.natSort=a(this.natSort,this);var r=this;this.aggregator=e.aggregator;this.aggregatorName=e.aggregatorName;this.colAttrs=e.cols;this.rowAttrs=e.rows;this.valAttrs=e.vals;this.tree={};this.rowKeys=[];this.colKeys=[];this.rowTotals={};this.colTotals={};this.allTotal=this.aggregator(this,[],[]);this.sorted=!1;n.forEachRecord(t,e.derivedAttributes,function(t){return e.filter(t)?r.processRecord(t):void 0})}n.forEachRecord=function(n,r,i){var o,a,l,u,c,f,h,d,p,g,m,v;o=e.isEmptyObject(r)?i:function(t){var e,n,o;for(e in r){n=r[e];t[e]=null!=(o=n(t))?o:t[e]}return i(t)};if(e.isFunction(n))return n(o);if(e.isArray(n)){if(e.isArray(n[0])){m=[];for(l in n)if(s.call(n,l)){a=n[l];if(l>0){f={};g=n[0];for(u in g)if(s.call(g,u)){c=g[u];f[c]=a[u]}m.push(o(f))}}return m}v=[];for(d=0,p=n.length;p>d;d++){f=n[d];v.push(o(f))}return v}if(n instanceof t){h=[];e("thead > tr > th",n).each(function(){return h.push(e(this).text())});return e("tbody > tr",n).each(function(){f={};e("td",this).each(function(t){return f[h[t]]=e(this).text()});return o(f)})}throw new Error("unknown input format")};n.convertToArray=function(t){var e;e=[];n.forEachRecord(t,{},function(t){return e.push(t)});return e};n.prototype.natSort=function(t,e){return p(t,e)};n.prototype.arrSort=function(t,e){return this.natSort(t.join(),e.join())};n.prototype.sortKeys=function(){if(!this.sorted){this.rowKeys.sort(this.arrSort);this.colKeys.sort(this.arrSort)}return this.sorted=!0};n.prototype.getColKeys=function(){this.sortKeys();return this.colKeys};n.prototype.getRowKeys=function(){this.sortKeys();return this.rowKeys};n.prototype.processRecord=function(t){var e,n,r,i,o,a,s,l,u,c,f,h,d;e=[];i=[];c=this.colAttrs;for(a=0,l=c.length;l>a;a++){o=c[a];e.push(null!=(f=t[o])?f:"null")}h=this.rowAttrs;for(s=0,u=h.length;u>s;s++){o=h[s];i.push(null!=(d=t[o])?d:"null")}r=i.join(String.fromCharCode(0));n=e.join(String.fromCharCode(0));this.allTotal.push(t);if(0!==i.length){if(!this.rowTotals[r]){this.rowKeys.push(i);this.rowTotals[r]=this.aggregator(this,i,[])}this.rowTotals[r].push(t)}if(0!==e.length){if(!this.colTotals[n]){this.colKeys.push(e);this.colTotals[n]=this.aggregator(this,[],e)}this.colTotals[n].push(t)}if(0!==e.length&&0!==i.length){this.tree[r]||(this.tree[r]={});this.tree[r][n]||(this.tree[r][n]=this.aggregator(this,i,e));return this.tree[r][n].push(t)}};n.prototype.getAggregator=function(t,e){var n,r,i;i=t.join(String.fromCharCode(0));r=e.join(String.fromCharCode(0));n=0===t.length&&0===e.length?this.allTotal:0===t.length?this.colTotals[r]:0===e.length?this.rowTotals[i]:this.tree[i][r];return null!=n?n:{value:function(){return null},format:function(){return""}}};return n}();m=function(t,n){var r,i,o,a,l,u,c,f,h,d,p,g,m,v,y,b,x,w,S,C,T;u={localeStrings:{totals:"Totals"}};n=e.extend(u,n);o=t.colAttrs;p=t.rowAttrs;m=t.getRowKeys();l=t.getColKeys();d=document.createElement("table");d.className="pvtTable";v=function(t,e,n){var r,i,o,a,s,l;if(0!==e){i=!0;for(a=s=0;n>=0?n>=s:s>=n;a=n>=0?++s:--s)t[e-1][a]!==t[e][a]&&(i=!1);if(i)return-1}r=0;for(;e+r<t.length;){o=!1;for(a=l=0;n>=0?n>=l:l>=n;a=n>=0?++l:--l)t[e][a]!==t[e+r][a]&&(o=!0);if(o)break;r++}return r};for(f in o)if(s.call(o,f)){i=o[f];w=document.createElement("tr");if(0===parseInt(f)&&0!==p.length){b=document.createElement("th");b.setAttribute("colspan",p.length);b.setAttribute("rowspan",o.length);w.appendChild(b)}b=document.createElement("th");b.className="pvtAxisLabel";b.textContent=i;w.appendChild(b);for(c in l)if(s.call(l,c)){a=l[c];T=v(l,parseInt(c),parseInt(f));if(-1!==T){b=document.createElement("th");b.className="pvtColLabel";b.textContent=a[f];b.setAttribute("colspan",T);parseInt(f)===o.length-1&&0!==p.length&&b.setAttribute("rowspan",2);w.appendChild(b)}}if(0===parseInt(f)){b=document.createElement("th");b.className="pvtTotalLabel";b.innerHTML=n.localeStrings.totals;b.setAttribute("rowspan",o.length+(0===p.length?0:1));w.appendChild(b)}d.appendChild(w)}if(0!==p.length){w=document.createElement("tr");for(c in p)if(s.call(p,c)){h=p[c];b=document.createElement("th");b.className="pvtAxisLabel";b.textContent=h;w.appendChild(b)}b=document.createElement("th");if(0===o.length){b.className="pvtTotalLabel";b.innerHTML=n.localeStrings.totals}w.appendChild(b);d.appendChild(w)}for(c in m)if(s.call(m,c)){g=m[c];w=document.createElement("tr");for(f in g)if(s.call(g,f)){S=g[f];T=v(m,parseInt(c),parseInt(f));if(-1!==T){b=document.createElement("th");b.className="pvtRowLabel";b.textContent=S;b.setAttribute("rowspan",T);parseInt(f)===p.length-1&&0!==o.length&&b.setAttribute("colspan",2);w.appendChild(b)}}for(f in l)if(s.call(l,f)){a=l[f];r=t.getAggregator(g,a);C=r.value();y=document.createElement("td");y.className="pvtVal row"+c+" col"+f;y.innerHTML=r.format(C);y.setAttribute("data-value",C);w.appendChild(y)}x=t.getAggregator(g,[]);C=x.value();y=document.createElement("td");y.className="pvtTotal rowTotal";y.innerHTML=x.format(C);y.setAttribute("data-value",C);y.setAttribute("data-for","row"+c);w.appendChild(y);d.appendChild(w)}w=document.createElement("tr");b=document.createElement("th");b.className="pvtTotalLabel";b.innerHTML=n.localeStrings.totals;b.setAttribute("colspan",p.length+(0===o.length?0:1));w.appendChild(b);for(f in l)if(s.call(l,f)){a=l[f];x=t.getAggregator([],a);C=x.value();y=document.createElement("td");y.className="pvtTotal colTotal";y.innerHTML=x.format(C);y.setAttribute("data-value",C);y.setAttribute("data-for","col"+f);w.appendChild(y)}x=t.getAggregator([],[]);C=x.value();y=document.createElement("td");y.className="pvtGrandTotal";y.innerHTML=x.format(C);y.setAttribute("data-value",C);w.appendChild(y);d.appendChild(w);d.setAttribute("data-numrows",m.length);d.setAttribute("data-numcols",l.length);return d};e.fn.pivot=function(t,r){var i,o,a,s;i={cols:[],rows:[],filter:function(){return!0},aggregator:l.count()(),aggregatorName:"Count",derivedAttributes:{},renderer:m,rendererOptions:null,localeStrings:h.en.localeStrings};r=e.extend(i,r);a=null;try{o=new n(t,r);try{a=r.renderer(o,r.rendererOptions)}catch(u){"undefined"!=typeof console&&null!==console&&console.error(u.stack);a=e("<span>").html(r.localeStrings.renderError)}}catch(u){"undefined"!=typeof console&&null!==console&&console.error(u.stack);a=e("<span>").html(r.localeStrings.computeError)}s=this[0];for(;s.hasChildNodes();)s.removeChild(s.lastChild);return this.append(a)};e.fn.pivotUI=function(t,r,o,a){var l,u,c,f,d,g,m,v,y,b,x,w,S,C,T,_,k,M,D,L,A,N,E,j,I,P,H,O,F,R,W,z,q,U,B,V,X,G,$=this;null==o&&(o=!1);null==a&&(a="en");m={derivedAttributes:{},aggregators:h[a].aggregators,renderers:h[a].renderers,hiddenAttributes:[],menuLimit:200,cols:[],rows:[],vals:[],exclusions:{},unusedAttrsVertical:"auto",autoSortUnusedAttrs:!1,rendererOptions:{localeStrings:h[a].localeStrings},onRefresh:null,filter:function(){return!0},localeStrings:h[a].localeStrings};v=this.data("pivotUIOptions");w=null==v||o?e.extend(m,r):v;try{t=n.convertToArray(t);D=function(){var e,n;e=t[0];n=[];for(x in e)s.call(e,x)&&n.push(x);return n}();U=w.derivedAttributes;for(d in U)s.call(U,d)&&i.call(D,d)<0&&D.push(d);f={};for(P=0,R=D.length;R>P;P++){j=D[P];f[j]={}}n.forEachRecord(t,w.derivedAttributes,function(t){var e,n,r,i;i=[];for(x in t)if(s.call(t,x)){e=t[x];if(w.filter(t)){null==e&&(e="null");null==(r=(n=f[x])[e])&&(n[e]=0);i.push(f[x][e]++)}}return i});N=e("<table cellpadding='5'>");k=e("<td>");_=e("<select class='pvtRenderer'>").appendTo(k).bind("change",function(){return C()});B=w.renderers;for(j in B)s.call(B,j)&&e("<option>").val(j).html(j).appendTo(_);g=e("<td class='pvtAxisContainer pvtUnused'>");M=function(){var t,e,n;n=[];for(t=0,e=D.length;e>t;t++){d=D[t];i.call(w.hiddenAttributes,d)<0&&n.push(d)}return n}();E=!1;if("auto"===w.unusedAttrsVertical){c=0;for(H=0,W=M.length;W>H;H++){l=M[H];c+=l.length}E=c>120}g.addClass(w.unusedAttrsVertical===!0||E?"pvtVertList":"pvtHorizList");I=function(t){var n,r,o,a,s,l,u,c,h,d,m,v,b,S,T;u=function(){var e;e=[];for(x in f[t])e.push(x);return e}();l=!1;v=e("<div>").addClass("pvtFilterBox").hide();v.append(e("<h4>").text(""+t+" ("+u.length+")"));if(u.length>w.menuLimit)v.append(e("<p>").html(w.localeStrings.tooMany));else{r=e("<p>").appendTo(v);r.append(e("<button>").html(w.localeStrings.selectAll).bind("click",function(){return v.find("input:visible").prop("checked",!0)}));r.append(e("<button>").html(w.localeStrings.selectNone).bind("click",function(){return v.find("input:visible").prop("checked",!1)}));r.append(e("<input>").addClass("pvtSearch").attr("placeholder",w.localeStrings.filterResults).bind("keyup",function(){var t;t=e(this).val().toLowerCase();return e(this).parents(".pvtFilterBox").find("label span").each(function(){var n;n=e(this).text().toLowerCase().indexOf(t);return-1!==n?e(this).parent().show():e(this).parent().hide()})}));o=e("<div>").addClass("pvtCheckContainer").appendTo(v);T=u.sort(p);for(b=0,S=T.length;S>b;b++){x=T[b];m=f[t][x];a=e("<label>");s=w.exclusions[t]?i.call(w.exclusions[t],x)>=0:!1;l||(l=s);e("<input type='checkbox' class='pvtFilter'>").attr("checked",!s).data("filter",[t,x]).appendTo(a);a.append(e("<span>").text(""+x+" ("+m+")"));o.append(e("<p>").append(a))}}d=function(){var t;t=e(v).find("[type='checkbox']").length-e(v).find("[type='checkbox']:checked").length;t>0?n.addClass("pvtFilteredAttribute"):n.removeClass("pvtFilteredAttribute");return u.length>w.menuLimit?v.toggle():v.toggle(0,C)};e("<p>").appendTo(v).append(e("<button>").text("OK").bind("click",d));c=function(t){v.css({left:t.pageX,top:t.pageY}).toggle();e(".pvtSearch").val("");return e("label").show()};h=e("<span class='pvtTriangle'>").html(" ▾").bind("click",c);n=e("<li class='axis_"+y+"'>").append(e("<span class='pvtAttr'>").text(t).data("attrName",t).append(h));l&&n.addClass("pvtFilteredAttribute");g.append(n).append(v);return n.bind("dblclick",c)};for(y in M){d=M[y];I(d)}L=e("<tr>").appendTo(N);u=e("<select class='pvtAggregator'>").bind("change",function(){return C()});V=w.aggregators;for(j in V)s.call(V,j)&&u.append(e("<option>").val(j).html(j));e("<td class='pvtVals'>").appendTo(L).append(u).append(e("<br>"));e("<td class='pvtAxisContainer pvtHorizList pvtCols'>").appendTo(L);A=e("<tr>").appendTo(N);A.append(e("<td valign='top' class='pvtAxisContainer pvtRows'>"));S=e("<td valign='top' class='pvtRendererArea'>").appendTo(A);if(w.unusedAttrsVertical===!0||E){N.find("tr:nth-child(1)").prepend(k);N.find("tr:nth-child(2)").prepend(g)}else N.prepend(e("<tr>").append(k).append(g));this.html(N);X=w.cols;for(O=0,z=X.length;z>O;O++){j=X[O];this.find(".pvtCols").append(this.find(".axis_"+M.indexOf(j)))}G=w.rows;for(F=0,q=G.length;q>F;F++){j=G[F];this.find(".pvtRows").append(this.find(".axis_"+M.indexOf(j)))}null!=w.aggregatorName&&this.find(".pvtAggregator").val(w.aggregatorName);null!=w.rendererName&&this.find(".pvtRenderer").val(w.rendererName);b=!0;T=function(){var n,r,o,a,s,l,c,f,h,d,p,g,m,v;f={derivedAttributes:w.derivedAttributes,localeStrings:w.localeStrings,rendererOptions:w.rendererOptions,cols:[],rows:[]};s=null!=(v=w.aggregators[u.val()]([])().numInputs)?v:0;d=[];$.find(".pvtRows li span.pvtAttr").each(function(){return f.rows.push(e(this).data("attrName"))});$.find(".pvtCols li span.pvtAttr").each(function(){return f.cols.push(e(this).data("attrName"))});$.find(".pvtVals select.pvtAttrDropdown").each(function(){if(0===s)return e(this).remove();s--;return""!==e(this).val()?d.push(e(this).val()):void 0});if(0!==s){c=$.find(".pvtVals");for(j=g=0;s>=0?s>g:g>s;j=s>=0?++g:--g){a=e("<select class='pvtAttrDropdown'>").append(e("<option>")).bind("change",function(){return C()});for(m=0,p=M.length;p>m;m++){n=M[m];a.append(e("<option>").val(n).text(n))}c.append(a)}}if(b){d=w.vals;y=0;$.find(".pvtVals select.pvtAttrDropdown").each(function(){e(this).val(d[y]);return y++});b=!1}f.aggregatorName=u.val();f.vals=d;f.aggregator=w.aggregators[u.val()](d);f.renderer=w.renderers[_.val()];r={};$.find("input.pvtFilter").not(":checked").each(function(){var t;t=e(this).data("filter");return null!=r[t[0]]?r[t[0]].push(t[1]):r[t[0]]=[t[1]]});f.filter=function(t){var e,n;if(!w.filter(t))return!1;for(x in r){e=r[x];if(n=""+t[x],i.call(e,n)>=0)return!1}return!0};S.pivot(t,f);l=e.extend(w,{cols:f.cols,rows:f.rows,vals:d,exclusions:r,aggregatorName:u.val(),rendererName:_.val()});$.data("pivotUIOptions",l);if(w.autoSortUnusedAttrs){o=e.pivotUtilities.naturalSort;h=$.find("td.pvtUnused.pvtAxisContainer");e(h).children("li").sort(function(t,n){return o(e(t).text(),e(n).text())}).appendTo(h)}S.css("opacity",1);return null!=w.onRefresh?w.onRefresh(l):void 0};C=function(){S.css("opacity",.5);return setTimeout(T,10)};C();this.find(".pvtAxisContainer").sortable({update:function(t,e){return null==e.sender?C():void 0},connectWith:this.find(".pvtAxisContainer"),items:"li",placeholder:"pvtPlaceholder"})}catch(Y){"undefined"!=typeof console&&null!==console&&console.error(Y.stack);this.html(w.localeStrings.uiRenderError)}return this};e.fn.heatmap=function(t){var n,r,i,o,a,s,l,u,c=this;null==t&&(t="heatmap");s=this.data("numrows");a=this.data("numcols");n=function(t,e,n){var r;r=function(){switch(t){case"red":return function(t){return"ff"+t+t};case"green":return function(t){return""+t+"ff"+t};case"blue":return function(t){return""+t+t+"ff"}}}();return function(t){var i,o;o=255-Math.round(255*(t-e)/(n-e));i=o.toString(16).split(".")[0];1===i.length&&(i=0+i);return r(i)}};r=function(t,r){var i,o,a;o=function(n){return c.find(t).each(function(){var t;t=e(this).data("value");return null!=t&&isFinite(t)?n(t,e(this)):void 0})};a=[];o(function(t){return a.push(t)});i=n(r,Math.min.apply(Math,a),Math.max.apply(Math,a));return o(function(t,e){return e.css("background-color","#"+i(t))})};switch(t){case"heatmap":r(".pvtVal","red");break;case"rowheatmap":for(i=l=0;s>=0?s>l:l>s;i=s>=0?++l:--l)r(".pvtVal.row"+i,"red");break;case"colheatmap":for(o=u=0;a>=0?a>u:u>a;o=a>=0?++u:--u)r(".pvtVal.col"+o,"red")}r(".pvtTotal.rowTotal","red");r(".pvtTotal.colTotal","red");return this};return e.fn.barchart=function(){var t,n,r,i,o,a=this;i=this.data("numrows");r=this.data("numcols");t=function(t){var n,r,i,o;n=function(n){return a.find(t).each(function(){var t;t=e(this).data("value");return null!=t&&isFinite(t)?n(t,e(this)):void 0})};o=[];n(function(t){return o.push(t)});r=Math.max.apply(Math,o);i=function(t){return 100*t/(1.4*r)};return n(function(t,n){var r,o;r=n.text();o=e("<div>").css({position:"relative",height:"55px"});o.append(e("<div>").css({position:"absolute",bottom:0,left:0,right:0,height:i(t)+"%","background-color":"gray"}));o.append(e("<div>").text(r).css({position:"relative","padding-left":"5px","padding-right":"5px"}));return n.css({padding:0,"padding-top":"5px","text-align":"center"}).html(o)})};for(n=o=0;i>=0?i>o:o>i;n=i>=0?++o:--o)t(".pvtVal.row"+n);t(".pvtTotal.colTotal");return this}})}).call(this)},{jquery:17}],21:[function(e,n){(function(e){function r(){try{return l in e&&e[l]}catch(t){return!1}}function i(t){return t.replace(/^d/,"___$&").replace(p,"___")}var o,a={},s=e.document,l="localStorage",u="script";a.disabled=!1;a.version="1.3.17";a.set=function(){};a.get=function(){};a.has=function(t){return void 0!==a.get(t)};a.remove=function(){};a.clear=function(){};a.transact=function(t,e,n){if(null==n){n=e;e=null}null==e&&(e={});var r=a.get(t,e);n(r);a.set(t,r)};a.getAll=function(){};a.forEach=function(){};a.serialize=function(t){return JSON.stringify(t)};a.deserialize=function(t){if("string"!=typeof t)return void 0;try{return JSON.parse(t)}catch(e){return t||void 0}};if(r()){o=e[l];a.set=function(t,e){if(void 0===e)return a.remove(t);o.setItem(t,a.serialize(e));return e};a.get=function(t,e){var n=a.deserialize(o.getItem(t));return void 0===n?e:n};a.remove=function(t){o.removeItem(t)};a.clear=function(){o.clear()};a.getAll=function(){var t={};a.forEach(function(e,n){t[e]=n});return t};a.forEach=function(t){for(var e=0;e<o.length;e++){var n=o.key(e);t(n,a.get(n))}}}else if(s.documentElement.addBehavior){var c,f;try{f=new ActiveXObject("htmlfile");f.open();f.write("<"+u+">document.w=window</"+u+'><iframe src="/favicon.ico"></iframe>');f.close();c=f.w.frames[0].document;o=c.createElement("div")}catch(h){o=s.createElement("div");c=s.body}var d=function(t){return function(){var e=Array.prototype.slice.call(arguments,0);e.unshift(o);c.appendChild(o);o.addBehavior("#default#userData");o.load(l);var n=t.apply(a,e);c.removeChild(o);return n}},p=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");a.set=d(function(t,e,n){e=i(e);if(void 0===n)return a.remove(e);t.setAttribute(e,a.serialize(n));t.save(l);return n});a.get=d(function(t,e,n){e=i(e);var r=a.deserialize(t.getAttribute(e));return void 0===r?n:r});a.remove=d(function(t,e){e=i(e);t.removeAttribute(e);t.save(l)});a.clear=d(function(t){var e=t.XMLDocument.documentElement.attributes;t.load(l);for(var n,r=0;n=e[r];r++)t.removeAttribute(n.name);t.save(l)});a.getAll=function(){var t={};a.forEach(function(e,n){t[e]=n});return t};a.forEach=d(function(t,e){for(var n,r=t.XMLDocument.documentElement.attributes,i=0;n=r[i];++i)e(n.name,a.deserialize(t.getAttribute(n.name)))})}try{var g="__storejs__";a.set(g,g);a.get(g)!=g&&(a.disabled=!0);a.remove(g)}catch(h){a.disabled=!0}a.enabled=!a.disabled;"undefined"!=typeof n&&n.exports&&this.module!==n?n.exports=a:"function"==typeof t&&t.amd?t(a):e.store=a})(Function("return this")())},{}],22:[function(t,e){e.exports={name:"yasgui-utils",version:"1.4.2",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:"Laurens Rietveld",maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"}}},{}],23:[function(t,e){window.console=window.console||{log:function(){}};e.exports={storage:t("./storage.js"),svg:t("./svg.js"),version:{"yasgui-utils":t("../package.json").version}}},{"../package.json":22,"./storage.js":24,"./svg.js":25}],24:[function(t,e){{var n=t("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};e.exports={set:function(t,e,i){if(e){"string"==typeof i&&(i=r[i]());e.documentElement&&(e=(new XMLSerializer).serializeToString(e.documentElement));n.set(t,{val:e,exp:i,time:(new Date).getTime()})}},remove:function(t){n.remove(t)},get:function(t){var e=n.get(t);return e?e.exp&&(new Date).getTime()-e.time>e.exp?null:e.val:null}}}},{store:21}],25:[function(t,e){e.exports={draw:function(t,n,r){if(t){var i=e.exports.getElement(n,r);i&&(t.append?t.append(i):t.appendChild(i))}},getElement:function(t,e){e||(e={});if(t&&0==t.indexOf("<svg")){e.width||(e.width="100%");e.height||(e.height="100%");var n=new DOMParser,r=n.parseFromString(t,"text/xml"),i=r.documentElement,o=document.createElement("div");o.style.display="inline-block";o.style.width=e.width;o.style.height=e.height;o.appendChild(i);return o}return!1}}},{}],26:[function(t,e){e.exports={name:"yasgui-yasr",description:"Yet Another SPARQL Resultset GUI",version:"2.3.1",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasr.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasr.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"^0.3.11","gulp-notify":"^2.0.1","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^1.0.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.8",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","bootstrap-sass":"^3.3.1","browserify-transform-tools":"^1.2.1","gulp-cssimport":"^1.3.1","gulp-html-replace":"^1.4.1","browserify-shim":"^3.8.1"},bugs:"https://github.com/YASGUI/YASR/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASR.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.7.0","yasgui-utils":"^1.4.1",pivottable:"^1.2.2","jquery-ui":"^1.10.5",d3:"^3.4.13"},"browserify-shim":{google:"global:google"},browserify:{transform:["browserify-shim"]},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"},"../lib/DataTables/media/js/jquery.dataTables.js":{require:"datatables",global:"jQuery"}}}},{}],27:[function(t,e){"use strict";e.exports=function(t){var e='"',n=",",r="\n",i=t.head.vars,o=t.results.bindings,a=function(){for(var t=0;t<i.length;t++)u(i[t]);f+=r},s=function(){for(var t=0;t<o.length;t++){l(o[t]);f+=r}},l=function(t){for(var e=0;e<i.length;e++){var n=i[e];u(t.hasOwnProperty(n)?t[n].value:"")}},u=function(t){t.replace(e,e+e);c(t)&&(t=e+t+e);f+=" "+t+" "+n},c=function(t){var r=!1;t.match("[\\w|"+n+"|"+e+"]")&&(r=!0);return r},f="";a();s();return f}},{}],28:[function(t,e){"use strict";var n=t("jquery"),r=e.exports=function(e){var r=n("<div class='booleanResult'></div>"),i=function(){r.empty().appendTo(e.resultsContainer);var i=e.results.getBoolean(),o=null,a=null;if(i===!0){o="check";a="True"}else if(i===!1){o="cross";a="False"}else{r.width("140");a="Could not find boolean value in response"}o&&t("yasgui-utils").svg.draw(r,t("./imgs.js")[o],{width:25,height:25});n("<span></span>").text(a).appendTo(r)},o=function(){return e.results.getBoolean&&(e.results.getBoolean()===!0||0==e.results.getBoolean())};return{name:null,draw:i,hideFromSelection:!0,getPriority:10,canHandleResults:o}};r.version={"YASR-boolean":t("../package.json").version,jquery:n.fn.jquery}},{"../package.json":26,"./imgs.js":31,jquery:17,"yasgui-utils":23}],29:[function(t,e){"use strict";var n=t("jquery");e.exports={output:"table",outputPlugins:["table","error","boolean","rawResponse"],drawOutputSelector:!0,drawDownloadIcon:!0,getUsedPrefixes:null,persistency:{outputSelector:function(t){return"selector_"+n(t.container).closest("[id]").attr("id")},results:{id:function(t){return"results_"+n(t.container).closest("[id]").attr("id")},maxSize:1e5}}}},{jquery:17}],30:[function(t,e){"use strict";var n=t("jquery"),r=e.exports=function(t){var e=n("<div class='errorResult'></div>"),i=(n.extend(!0,{},r.defaults),function(){var r=t.results.getException();e.empty().appendTo(t.resultsContainer);var i="Error";r.statusText&&r.statusText.length<100&&(i=r.statusText);r.status&&(i+=" (#"+r.status+")");e.append(n("<span>",{"class":"exception"}).text(i));var o=null;r.responseText?o=r.responseText:"string"==typeof r&&(o=r);o&&e.append(n("<pre>").text(o))}),o=function(t){return t.results.getException()||!1};return{name:null,draw:i,getPriority:20,hideFromSelection:!0,canHandleResults:o}};r.defaults={}},{jquery:17}],31:[function(t,e){"use strict";e.exports={cross:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><g> <path d="M83.288,88.13c-2.114,2.112-5.575,2.112-7.689,0L53.659,66.188c-2.114-2.112-5.573-2.112-7.687,0L24.251,87.907 c-2.113,2.114-5.571,2.114-7.686,0l-4.693-4.691c-2.114-2.114-2.114-5.573,0-7.688l21.719-21.721c2.113-2.114,2.113-5.573,0-7.686 L11.872,24.4c-2.114-2.113-2.114-5.571,0-7.686l4.842-4.842c2.113-2.114,5.571-2.114,7.686,0L46.12,33.591 c2.114,2.114,5.572,2.114,7.688,0l21.721-21.719c2.114-2.114,5.573-2.114,7.687,0l4.695,4.695c2.111,2.113,2.111,5.571-0.003,7.686 L66.188,45.973c-2.112,2.114-2.112,5.573,0,7.686L88.13,75.602c2.112,2.111,2.112,5.572,0,7.687L83.288,88.13z"/></g></svg>',check:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path fill="#000000" d="M14.301,49.982l22.606,17.047L84.361,4.903c2.614-3.733,7.76-4.64,11.493-2.026l0.627,0.462 c3.732,2.614,4.64,7.758,2.025,11.492l-51.783,79.77c-1.955,2.791-3.896,3.762-7.301,3.988c-3.405,0.225-5.464-1.039-7.508-3.084 L2.447,61.814c-3.263-3.262-3.263-8.553,0-11.814l0.041-0.019C5.75,46.718,11.039,46.718,14.301,49.982z"/></svg>',unsorted:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path7-9" d="m 8.8748339,52.571766 16.9382111,-0.222584 4.050851,-0.06665 15.719154,-0.222166 0.27778,-0.04246 0.43276,0.0017 0.41632,-0.06121 0.37532,-0.0611 0.47132,-0.119342 0.27767,-0.08206 0.55244,-0.198047 0.19707,-0.08043 0.61095,-0.259721 0.0988,-0.05825 0.019,-0.01914 0.59303,-0.356548 0.11787,-0.0788 0.49125,-0.337892 0.17994,-0.139779 0.37317,-0.336871 0.21862,-0.219786 0.31311,-0.31479 0.21993,-0.259387 c 0.92402,-1.126057 1.55249,-2.512251 1.78961,-4.016904 l 0.0573,-0.25754 0.0195,-0.374113 0.0179,-0.454719 0.0175,-0.05874 -0.0169,-0.258049 -0.0225,-0.493503 -0.0398,-0.355569 -0.0619,-0.414201 -0.098,-0.414812 -0.083,-0.353334 L 53.23955,41.1484 53.14185,40.850967 52.93977,40.377742 52.84157,40.161628 34.38021,4.2507375 C 33.211567,1.9401875 31.035446,0.48226552 28.639484,0.11316952 l -0.01843,-0.01834 -0.671963,-0.07882 -0.236871,0.0042 L 27.335984,-4.7826577e-7 27.220736,0.00379952 l -0.398804,0.0025 -0.313848,0.04043 -0.594474,0.07724 -0.09611,0.02147 C 23.424549,0.60716252 21.216017,2.1142355 20.013025,4.4296865 L 0.93967491,40.894479 c -2.08310801,3.997178 -0.588125,8.835482 3.35080799,10.819749 1.165535,0.613495 2.43199,0.88731 3.675026,0.864202 l 0.49845,-0.02325 0.410875,0.01658 z M 9.1502369,43.934401 9.0136999,43.910011 27.164145,9.2564625 44.70942,43.42818 l -14.765289,0.214677 -4.031106,0.0468 -16.7627881,0.244744 z" /></svg>',sortDesc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,0.12823506 0.09753,0.02006 c 2.39093,0.458209 4.599455,1.96811104 5.80244,4.28639004 L 52.785897,40.894525 c 2.088044,4.002139 0.590949,8.836902 -3.348692,10.821875 -1.329078,0.688721 -2.766603,0.943695 -4.133174,0.841768 l -0.454018,0.02 L 27.910392,52.354171 23.855313,52.281851 8.14393,52.061827 7.862608,52.021477 7.429856,52.021738 7.014241,51.959818 6.638216,51.900838 6.164776,51.779369 5.889216,51.699439 5.338907,51.500691 5.139719,51.419551 4.545064,51.145023 4.430618,51.105123 4.410168,51.084563 3.817138,50.730843 3.693615,50.647783 3.207314,50.310611 3.028071,50.174369 2.652795,49.833957 2.433471,49.613462 2.140099,49.318523 1.901127,49.041407 C 0.97781,47.916059 0.347935,46.528448 0.11153,45.021676 L 0.05352,44.766255 0.05172,44.371683 0.01894,43.936017 0,43.877277 0.01836,43.62206 0.03666,43.122889 0.0765,42.765905 0.13912,42.352413 0.23568,41.940425 0.32288,41.588517 0.481021,41.151945 0.579391,40.853806 0.77369,40.381268 0.876097,40.162336 19.338869,4.2542801 c 1.172169,-2.308419 3.34759,-3.76846504 5.740829,-4.17716604 l 0.01975,0.01985 0.69605,-0.09573 0.218437,0.0225 0.490791,-0.02132 0.39809,0.0046 0.315972,0.03973 0.594462,0.08149 z" /></svg>',sortAsc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,0.70898699,-0.70898699,-0.70522156,97.988199,58.704807)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,113.65778 0.09753,-0.0201 c 2.39093,-0.45821 4.599455,-1.96811 5.80244,-4.28639 L 52.785897,72.891487 c 2.088044,-4.002139 0.590949,-8.836902 -3.348692,-10.821875 -1.329078,-0.688721 -2.766603,-0.943695 -4.133174,-0.841768 l -0.454018,-0.02 -16.939621,0.223997 -4.055079,0.07232 -15.711383,0.220024 -0.281322,0.04035 -0.432752,-2.61e-4 -0.415615,0.06192 -0.376025,0.05898 -0.47344,0.121469 -0.27556,0.07993 -0.550309,0.198748 -0.199188,0.08114 -0.594655,0.274528 -0.114446,0.0399 -0.02045,0.02056 -0.59303,0.35372 -0.123523,0.08306 -0.486301,0.337172 -0.179243,0.136242 -0.375276,0.340412 -0.219324,0.220495 -0.293372,0.294939 -0.238972,0.277116 C 0.97781,65.869953 0.347935,67.257564 0.11153,68.764336 L 0.05352,69.019757 0.05172,69.414329 0.01894,69.849995 0,69.908735 l 0.01836,0.255217 0.0183,0.499171 0.03984,0.356984 0.06262,0.413492 0.09656,0.411988 0.0872,0.351908 0.158141,0.436572 0.09837,0.298139 0.194299,0.472538 0.102407,0.218932 18.462772,35.908054 c 1.172169,2.30842 3.34759,3.76847 5.740829,4.17717 l 0.01975,-0.0199 0.69605,0.0957 0.218437,-0.0225 0.490791,0.0213 0.39809,-0.005 0.315972,-0.0397 0.594462,-0.0815 z" /></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g id="Captions"></g><g id="Your_Icon"> <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>',move:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_11656_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="753" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="287" inkscape:window-y="249" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><polygon points="33,83 50,100 67,83 54,83 54,17 67,17 50,0 33,17 46,17 46,83 " transform="translate(-7.962963,-10)" /><polygon points="83,67 100,50 83,33 83,46 17,46 17,33 0,50 17,67 17,54 83,54 " transform="translate(-7.962963,-10)" /></svg>',fullscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="640" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><path d="m -7.962963,-10 v 38.889 l 16.667,-16.667 16.667,16.667 5.555,-5.555 -16.667,-16.667 16.667,-16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 92.037037,-10 v 38.889 l -16.667,-16.667 -16.666,16.667 -5.556,-5.555 16.666,-16.667 -16.666,-16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M -7.962963,90 V 51.111 l 16.667,16.666 16.667,-16.666 5.555,5.556 -16.667,16.666 16.667,16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M 92.037037,90 V 51.111 l -16.667,16.666 -16.666,-16.666 -5.556,5.556 16.666,16.666 -16.666,16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>',smallscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Layer_1" /><path d="m 30.926037,28.889 0,-38.889 -16.667,16.667 -16.667,-16.667 -5.555,5.555 16.667,16.667 -16.667,16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,28.889 0,-38.889 16.667,16.667 16.666,-16.667 5.556,5.555 -16.666,16.667 16.666,16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 30.926037,51.111 0,38.889 -16.667,-16.666 -16.667,16.666 -5.555,-5.556 16.667,-16.666 -16.667,-16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,51.111 0,38.889 16.667,-16.666 16.666,16.666 5.556,-5.556 -16.666,-16.666 16.666,-16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>'}
},{}],32:[function(t,e){"use strict";var n=t("jquery"),r=t("yasgui-utils");console=console||{log:function(){}};var i=e.exports=function(e,s,l){var u={};u.options=n.extend(!0,{},i.defaults,s);u.container=n("<div class='yasr'></div>").appendTo(e);u.header=n("<div class='yasr_header'></div>").appendTo(u.container);u.resultsContainer=n("<div class='yasr_results'></div>").appendTo(u.container);u.plugins={};for(var c in i.plugins)u.plugins[c]=new i.plugins[c](u);u.draw=function(t){if(!u.results)return!1;t||(t=u.options.output);var e=null,r=-1,i=[];for(var o in u.plugins)if(u.plugins[o].canHandleResults(u)){var a=u.plugins[o].getPriority;"function"==typeof a&&(a=a(u));if(null!=a&&void 0!=a&&a>r){r=a;e=o}}else i.push(o);f(i);if(t in u.plugins&&u.plugins[t].canHandleResults(u)){n(u.resultsContainer).empty();u.plugins[t].draw();return!0}if(e){n(u.resultsContainer).empty();u.plugins[e].draw();return!0}return!1};var f=function(t){u.header.find(".yasr_btnGroup .yasr_btn").removeClass("disabled");t.forEach(function(t){u.header.find(".yasr_btnGroup .select_"+t).addClass("disabled")})};u.somethingDrawn=function(){return!u.resultsContainer.is(":empty")};u.setResponse=function(e,n,i){try{u.results=t("./parsers/wrapper.js")(e,n,i)}catch(o){u.results={getException:function(){return o}}}u.draw();if(u.options.persistency&&u.options.persistency.results){var a="string"==typeof u.options.persistency.results.id?u.options.persistency.results.id:u.options.persistency.results.id(u);u.results.getOriginalResponseAsString&&u.results.getOriginalResponseAsString().length<u.options.persistency.results.maxSize?r.storage.set(a,u.results.getAsStoreObject(),"month"):r.storage.remove(a)}};if(u.options.persistency&&u.options.persistency.outputSelector){var h="string"==typeof u.options.persistency.outputSelector?u.options.persistency.outputSelector:u.options.persistency.outputSelector(u);if(h){var d=r.storage.get(h);d&&(u.options.output=d)}}a(u);if(!l&&u.options.persistency&&u.options.persistency.results){var h="string"==typeof u.options.persistency.results.id?u.options.persistency.results.id:u.options.persistency.results.id(u),p=r.storage.get(h);p&&(n.isArray(p)?u.setResponse.apply(this,p):u.setResponse(p))}l&&u.setResponse(l);o(u);return u},o=function(t){var e=t.header.find(".yasr_downloadIcon");e.removeAttr("title");var n=t.plugins[t.options.output];if(n){var r=n.getDownloadInfo?n.getDownloadInfo():null;if(r){r.buttonTitle&&e.attr(r.buttonTitle);e.prop("disabled",!1);e.find("path").each(function(){this.style.fill="black"})}else{e.prop("disabled",!0).prop("title","Download not supported for this result representation");e.find("path").each(function(){this.style.fill="gray"})}}},a=function(e){var i=function(){var t=n('<div class="yasr_btnGroup"></div>');n.each(e.plugins,function(i,a){if(!a.hideFromSelection){var s=a.name||i,l=n("<button class='yasr_btn'></button>").text(s).addClass("select_"+i).click(function(){t.find("button.selected").removeClass("selected");n(this).addClass("selected");e.options.output=i;if(e.options.persistency&&e.options.persistency.outputSelector){var a="string"==typeof e.options.persistency.outputSelector?e.options.persistency.outputSelector:e.options.persistency.outputSelector(e);r.storage.set(a,e.options.output,"month")}e.draw();o(e)}).appendTo(t);e.options.output==i&&l.addClass("selected")}});t.children().length>1&&e.header.append(t)},a=function(){var r=function(t,e){var n=null,r=window.URL||window.webkitURL||window.mozURL||window.msURL;if(r&&Blob){var i=new Blob([t],{type:e});n=r.createObjectURL(i)}return n},i=n("<button class='yasr_btn yasr_downloadIcon btn_icon'></button>").append(t("yasgui-utils").svg.getElement(t("./imgs.js").download,{width:"15px",height:"15px"})).click(function(){var t=e.plugins[e.options.output];if(t&&t.getDownloadInfo){var i=t.getDownloadInfo(),o=r(i.getContent(),i.contentType?i.contentType:"text/plain"),a=n("<a></a>");a.attr("href",o);a.attr("download",i.filename);a.get(0).click()}});e.header.append(i)},s=function(){var r=n("<button class='yasr_btn btn_fullscreen btn_icon'></button>").append(t("yasgui-utils").svg.getElement(t("./imgs.js").fullscreen,{width:"15px",height:"15px"})).click(function(){e.container.addClass("yasr_fullscreen")});e.header.append(r)},l=function(){var r=n("<button class='yasr_btn btn_smallscreen btn_icon'></button>").append(t("yasgui-utils").svg.getElement(t("./imgs.js").smallscreen,{width:"15px",height:"15px"})).click(function(){e.container.removeClass("yasr_fullscreen")});e.header.append(r)};s();l();e.options.drawOutputSelector&&i();e.options.drawDownloadIcon&&a()};i.plugins={};i.registerOutput=function(t,e){i.plugins[t]=e};i.registerOutput("boolean",t("./boolean.js"));i.registerOutput("rawResponse",t("./rawResponse.js"));i.registerOutput("table",t("./table.js"));i.registerOutput("error",t("./error.js"));i.registerOutput("pivot",t("./pivot.js"));i.defaults=t("./defaults.js");i.version={YASR:t("../package.json").version,jquery:n.fn.jquery,"yasgui-utils":t("yasgui-utils").version};i.$=n},{"../package.json":26,"./boolean.js":28,"./defaults.js":29,"./error.js":30,"./imgs.js":31,"./parsers/wrapper.js":37,"./pivot.js":39,"./rawResponse.js":40,"./table.js":41,jquery:17,"yasgui-utils":23}],33:[function(t,e){"use strict";t("jquery"),e.exports=function(e){return t("./dlv.js")(e,",")}},{"./dlv.js":34,jquery:17}],34:[function(t,e){"use strict";var n=jQuery=t("jquery");t("../../lib/jquery.csv-0.71.js");e.exports=function(t,e){var r={},i=n.csv.toArrays(t,{separator:e}),o=function(t){return 0==t.indexOf("http")?"uri":null},a=function(){if(2==i.length&&1==i[0].length&&1==i[1].length&&"boolean"==i[0][0]&&("1"==i[1][0]||"0"==i[1][0])){r.boolean="1"==i[1][0]?!0:!1;return!0}return!1},s=function(){if(i.length>0&&i[0].length>0){r.head={vars:i[0]};return!0}return!1},l=function(){if(i.length>1){r.results={bindings:[]};for(var t=1;t<i.length;t++){for(var e={},n=0;n<i[t].length;n++){var a=r.head.vars[n];if(a){var s=i[t][n],l=o(s);e[a]={value:s};l&&(e[a].type=l)}}r.results.bindings.push(e)}r.head={vars:i[0]};return!0}return!1},u=a();if(!u){var c=s();c&&l()}return r}},{"../../lib/jquery.csv-0.71.js":3,jquery:17}],35:[function(t,e){"use strict";t("jquery"),e.exports=function(t){if("string"==typeof t)try{return JSON.parse(t)}catch(e){return!1}return"object"==typeof t&&t.constructor==={}.constructor?t:!1}},{jquery:17}],36:[function(t,e){"use strict";t("jquery"),e.exports=function(e){return t("./dlv.js")(e," ")}},{"./dlv.js":34,jquery:17}],37:[function(t,e){"use strict";t("jquery"),e.exports=function(e,n,r){var i={xml:t("./xml.js"),json:t("./json.js"),tsv:t("./tsv.js"),csv:t("./csv.js")},o=null,a=null,s=null,l=null,u=null,c=function(){if("object"==typeof e){if(e.exception)u=e.exception;else if(e.status&&e.status>=300){u={status:e.status};"string"==typeof r&&(u.errorString=r);e.responseText&&(u.responseText=e.responseText);e.statusText&&(u.statusText=e.statusText)}if(e.contentType)o=e.contentType.toLowerCase();else if(e.getResponseHeader&&e.getResponseHeader("content-type")){var t=e.getResponseHeader("content-type").trim().toLowerCase();t.length>0&&(o=t)}e.response?a=e.response:n||r||(a=e)}u||a||(a=e.responseText?e.responseText:e)},f=function(){if(s)return s;if(s===!1||u)return!1;var t=function(){if(o)if(o.indexOf("json")>-1){try{s=i.json(a)}catch(t){u=t}l="json"}else if(o.indexOf("xml")>-1){try{s=i.xml(a)}catch(t){u=t}l="xml"}else if(o.indexOf("csv")>-1){try{s=i.csv(a)}catch(t){u=t}l="csv"}else if(o.indexOf("tab-separated")>-1){try{s=i.tsv(a)}catch(t){u=t}l="tsv"}},e=function(){s=i.json(a);if(s)l="json";else try{s=i.xml(a);s&&(l="xml")}catch(t){}};t();s||e();s||(s=!1);return s},h=function(){var t=f();return t&&"head"in t?t.head.vars:null},d=function(){var t=f();return t&&"results"in t?t.results.bindings:null},p=function(){var t=f();return t&&"boolean"in t?t.boolean:null},g=function(){return a},m=function(){var t="";"string"==typeof a?t=a:"json"==l?t=JSON.stringify(a,void 0,2):"xml"==l&&(t=(new XMLSerializer).serializeToString(a));return t},v=function(){return u},y=function(){null==l&&f();return l},b=function(){var t={};if(e.status){t.status=e.status;t.responseText=e.responseText;t.statusText=e.statusText;t.contentType=o}else t=e;var i=n,a=void 0;"string"==typeof r&&(a=r);return[t,i,a]};c();s=f();return{getAsStoreObject:b,getAsJson:f,getOriginalResponse:g,getOriginalResponseAsString:m,getOriginalContentType:function(){return o},getVariables:h,getBindings:d,getBoolean:p,getType:y,getException:v}}},{"./csv.js":33,"./json.js":35,"./tsv.js":36,"./xml.js":38,jquery:17}],38:[function(t,e){"use strict";{var n=t("jquery");e.exports=function(t){var e=function(t){a.head={};for(var e=0;e<t.childNodes.length;e++){var n=t.childNodes[e];if("variable"==n.nodeName){a.head.vars||(a.head.vars=[]);var r=n.getAttribute("name");r&&a.head.vars.push(r)}}},r=function(t){a.results={};a.results.bindings=[];for(var e=0;e<t.childNodes.length;e++){for(var n=t.childNodes[e],r=null,i=0;i<n.childNodes.length;i++){var o=n.childNodes[i];if("binding"==o.nodeName){var s=o.getAttribute("name");if(s){r=r||{};r[s]={};for(var l=0;l<o.childNodes.length;l++){var u=o.childNodes[l],c=u.nodeName;if("#text"!=c){r[s].type=c;r[s].value=u.innerHTML;var f=u.getAttribute("datatype");f&&(r[s].datatype=f)}}}}}r&&a.results.bindings.push(r)}},i=function(t){a.boolean="true"==t.innerHTML?!0:!1},o=null;"string"==typeof t?o=n.parseXML(t):n.isXMLDoc(t)&&(o=t);var t=null;if(!(o.childNodes.length>0))return null;t=o.childNodes[0];for(var a={},s=0;s<t.childNodes.length;s++){var l=t.childNodes[s];"head"==l.nodeName&&e(l);"results"==l.nodeName&&r(l);"boolean"==l.nodeName&&i(l)}return a}}},{jquery:17}],39:[function(t,e){(function(n){"use strict";var r=t("jquery"),i=t("./utils.js"),o=t("yasgui-utils"),a=t("./imgs.js");t("jquery-ui/sortable");t("pivottable");var s=e.exports=function(e){var l=!1,u=!1,c=r.pivotUtilities.renderers,f=r.extend(!0,{},s.defaults);if(f.useD3Chart){try{{t("d3")}t("../node_modules/pivottable/dist/d3_renderers.js")}catch(h){}r.pivotUtilities.d3_renderers&&r.extend(!0,c,r.pivotUtilities.d3_renderers)}var d=function(){var e=function(){try{t("../node_modules/pivottable/dist/gchart_renderers.js");r.extend(!0,c,r.pivotUtilities.gchart_renderers)}catch(e){}u=!1;l&&x();l=!1};r.ajax({cache:!0,dataType:"script",url:"//google.com/jsapi"}).done(function(){var t="undefined"!=typeof window?window.google:"undefined"!=typeof n?n.google:null;t.load("visualization","1",{packages:["corechart","charteditor"],callback:e})}).fail(e)};if(f.useGChart&&!r.pivotUtilities.gchart_renderers){u=!0;d()}var p,g=function(t){var n=e.results.getVariables(),r=null;e.options.getUsedPrefixes&&(r="function"==typeof e.options.getUsedPrefixes?e.options.getUsedPrefixes(e):e.options.getUsedPrefixes);e.results.getBindings().forEach(function(e){var o={};n.forEach(function(t){if(t in e){var n=e[t].value;"uri"==e.type&&(n=i.uriToPrefixed(r,n));o[t]=n}else o[t]=null});t(o)})},m=null,v=function(){null===m&&(m="string"==typeof f.persistency?f.persistency:"function"==typeof f.persistency?f.persistency(e):!1);return m},y=function(t){if(v()){var e={cols:t.cols,rows:t.rows,rendererName:t.rendererName};o.storage.set(v(),e,"month")}},b=function(){var t=o.storage.get(v());if(t){var n=e.results.getVariables(),r=!0;t.cols.forEach(function(t){n.indexOf(t)<0&&(r=!1)});r&&t.rows.forEach(function(t){n.indexOf(t)<0&&(r=!1)});if(!r){t.cols=[];t.rows=[]}c[t.rendererName]||delete t.rendererName}else t={};return t},x=function(){if(u)l=!0;else{p=r("<div>",{"class":"pivotTable"}).appendTo(r(e.resultsContainer));var t=(r.pivotUtilities.renderers,r.extend(!0,{},b(),s.defaults.pivotTable));t.onRefresh=function(){var e=t.onRefresh;return function(t){y(t);e&&e(t)}}();window.pivot=p.pivotUI(g,t);var n=r(o.svg.getElement(a.move,{width:"14px",height:"14px"}));p.find(".pvtTriangle").replaceWith(n);r(".pvtCols").prepend(r("<div>",{"class":"containerHeader"}).text("Columns"));r(".pvtRows").prepend(r("<div>",{"class":"containerHeader"}).text("Rows"));r(".pvtUnused").prepend(r("<div>",{"class":"containerHeader"}).text("Available Variables"));r(".pvtVals").prepend(r("<div>",{"class":"containerHeader"}).text("Cells"))}},w=function(){return e.results&&e.results.getVariables&&e.results.getVariables()&&e.results.getVariables().length>0};return{draw:x,name:"Pivot Table",canHandleResults:w,getPriority:4}};s.defaults={useGChart:!0,useD3Chart:!0,persistency:function(t){return"yasr_pivot_"+r(t.container).closest("[id]").attr("id")},pivotTable:{}};s.version={"YASR-rawResponse":t("../package.json").version,jquery:r.fn.jquery}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../node_modules/pivottable/dist/d3_renderers.js":18,"../node_modules/pivottable/dist/gchart_renderers.js":19,"../package.json":26,"./imgs.js":31,"./utils.js":42,d3:12,jquery:17,"jquery-ui/sortable":15,pivottable:20,"yasgui-utils":23}],40:[function(t,e){"use strict";var n=t("jquery"),r=t("codemirror");t("codemirror/addon/fold/foldcode.js");t("codemirror/addon/fold/foldgutter.js");t("codemirror/addon/fold/xml-fold.js");t("codemirror/addon/fold/brace-fold.js");t("codemirror/addon/edit/matchbrackets.js");t("codemirror/mode/xml/xml.js");t("codemirror/mode/javascript/javascript.js");var i=e.exports=function(t){var e=n.extend(!0,{},i.defaults),o=null,a=function(){var n=e.CodeMirror;n.value=t.results.getOriginalResponseAsString();var i=t.results.getType();if(i){"json"==i&&(i={name:"javascript",json:!0});n.mode=i}o=r(t.resultsContainer.get()[0],n);o.on("fold",function(){o.refresh()});o.on("unfold",function(){o.refresh()})},s=function(){if(!t.results)return!1;if(!t.results.getOriginalResponseAsString)return!1;var e=t.results.getOriginalResponseAsString();return e&&0!=e.length||!t.results.getException()?!0:!1},l=function(){if(!t.results)return null;var e=t.results.getOriginalContentType(),n=t.results.getType();return{getContent:function(){return t.results.getOriginalResponse()},filename:"queryResults"+(n?"."+n:""),contentType:e?e:"text/plain",buttonTitle:"Download raw response"}};return{draw:a,name:"Raw Response",canHandleResults:s,getPriority:2,getDownloadInfo:l}};i.defaults={CodeMirror:{readOnly:!0,lineNumbers:!0,lineWrapping:!0,foldGutter:!0,gutters:["CodeMirror-linenumbers","CodeMirror-foldgutter"]}};i.version={"YASR-rawResponse":t("../package.json").version,jquery:n.fn.jquery,CodeMirror:r.version}},{"../package.json":26,codemirror:9,"codemirror/addon/edit/matchbrackets.js":4,"codemirror/addon/fold/brace-fold.js":5,"codemirror/addon/fold/foldcode.js":6,"codemirror/addon/fold/foldgutter.js":7,"codemirror/addon/fold/xml-fold.js":8,"codemirror/mode/javascript/javascript.js":10,"codemirror/mode/xml/xml.js":11,jquery:17}],41:[function(t,e){"use strict";var n=t("jquery"),r=t("yasgui-utils"),i=t("./imgs.js");t("../lib/DataTables/media/js/jquery.dataTables.js");var o=e.exports=function(e){var a=null,s={name:"Table",getPriority:10},u=s.options=n.extend(!0,{},o.defaults),c=function(){var t=[],n=e.results.getBindings(),r=e.results.getVariables(),i=null;e.options.getUsedPrefixes&&(i="function"==typeof e.options.getUsedPrefixes?e.options.getUsedPrefixes(e):e.options.getUsedPrefixes);for(var o=0;o<n.length;o++){var a=[];a.push("");for(var l=n[o],c=0;c<r.length;c++){var f=r[c];a.push(f in l?u.getCellContent?u.getCellContent(e,s,l,f,{rowId:o,colId:c,usedPrefixes:i}):"":"")}t.push(a)}return t},f=function(){a.on("order.dt",function(){h()});u.persistency&&u.persistency.tableLength&&a.on("length.dt",function(t,n,i){var o="string"==typeof u.persistency.tableLength?u.persistency.tableLength:u.persistency.tableLength(e);r.storage.set(o,i,"month")});n.extend(!0,u.callbacks,u.handlers);a.delegate("td","click",function(t){if(u.callbacks&&u.callbacks.onCellClick){var e=u.callbacks.onCellClick(this,t);if(e===!1)return!1}}).delegate("td","mouseenter",function(t){u.callbacks&&u.callbacks.onCellMouseEnter&&u.callbacks.onCellMouseEnter(this,t);var e=n(this);u.fetchTitlesFromPreflabel&&void 0===e.attr("title")&&0==e.text().trim().indexOf("http")&&l(e)}).delegate("td","mouseleave",function(t){u.callbacks&&u.callbacks.onCellMouseLeave&&u.callbacks.onCellMouseLeave(this,t)})};s.draw=function(){a=n('<table cellpadding="0" cellspacing="0" border="0" class="resultsTable"></table>');n(e.resultsContainer).html(a);var t=u.datatable;t.data=c();t.columns=u.getColumns(e,s);if(u.persistency&&u.persistency.tableLength){var i="string"==typeof u.persistency.tableLength?u.persistency.tableLength:u.persistency.tableLength(e),o=r.storage.get(i);o&&(t.pageLength=o)}a.DataTable(n.extend(!0,{},t));h();f();var l=e.header.outerHeight()-5;l>0&&e.resultsContainer.find(".dataTables_wrapper").css("position","relative").css("top","-"+l+"px").css("margin-bottom","-"+l+"px")};var h=function(){var t={sorting:"unsorted",sorting_asc:"sortAsc",sorting_desc:"sortDesc"};a.find(".sortIcons").remove();var e=8,o=13;for(var s in t){var l=n("<div class='sortIcons'></div>").css("float","right").css("margin-right","-12px").width(e).height(o);r.svg.draw(l,i[t[s]],{width:e+2,height:o+1});a.find("th."+s).append(l)}};s.canHandleResults=function(){return e.results&&e.results.getVariables&&e.results.getVariables()&&e.results.getVariables().length>0};s.getDownloadInfo=function(){return e.results?{getContent:function(){return t("./bindingsToCsv.js")(e.results.getAsJson())},filename:"queryResults.csv",contentType:"text/csv",buttonTitle:"Download as CSV"}:null};return s},a=function(t,e,n){var r=n.value;if(n["xml:lang"])r='"'+n.value+'"@'+n["xml:lang"];else if(n.datatype){var i="http://www.w3.org/2001/XMLSchema#",o=n.datatype;o=0==o.indexOf(i)?"xsd:"+o.substring(i.length):"<"+o+">";r='"'+r+'"^^'+o}return r},s=function(t,e,n,r,i){var o=n[r],s=null;if("uri"==o.type){var l=null,u=o.value,c=u;if(i.usedPrefixes)for(var f in i.usedPrefixes)if(0==c.indexOf(i.usedPrefixes[f])){c=f+":"+u.substring(i.usedPrefixes[f].length);break}if(e.options.mergeLabelsWithUris){var h="string"==typeof e.options.mergeLabelsWithUris?e.options.mergeLabelsWithUris:"Label";if(n[r+h]){c=a(t,e,n[r+h]);l=u}}s="<a "+(l?"title='"+u+"' ":"")+"class='uri' target='_blank' href='"+u+"'>"+c+"</a>"}else s="<span class='nonUri'>"+a(t,e,o)+"</span>";return s},l=function(t){var e=function(){t.attr("title","")};n.get("http://preflabel.org/api/v1/label/"+encodeURIComponent(t.text())+"?silent=true").success(function(n){"object"==typeof n&&n.label?t.attr("title",n.label):"string"==typeof n&&n.length>0?t.attr("title",n):e()}).fail(e)};o.defaults={getCellContent:s,persistency:{tableLength:function(t){return"tableLength_"+n(t.container).closest("[id]").attr("id")}},getColumns:function(t,e){var n=function(n){if(!e.options.mergeLabelsWithUris)return!0;var r="string"==typeof e.options.mergeLabelsWithUris?e.options.mergeLabelsWithUris:"Label";return-1!==n.indexOf(r,n.length-r.length)&&t.results.getVariables().indexOf(n.substring(0,n.length-r.length))>=0?!1:!0},r=[];r.push({title:""});t.results.getVariables().forEach(function(t){r.push({title:t,visible:n(t)})});return r},fetchTitlesFromPreflabel:!0,mergeLabelsWithUris:!1,callbacks:{onCellMouseEnter:null,onCellMouseLeave:null,onCellClick:null},datatable:{order:[],pageLength:50,lengthMenu:[[10,50,100,1e3,-1],[10,50,100,1e3,"All"]],lengthChange:!0,pagingType:"full_numbers",drawCallback:function(t){for(var e=0;e<t.aiDisplay.length;e++)n("td:eq(0)",t.aoData[t.aiDisplay[e]].nTr).html(e+1);var r=!1;n(t.nTableWrapper).find(".paginate_button").each(function(){-1==n(this).attr("class").indexOf("current")&&-1==n(this).attr("class").indexOf("disabled")&&(r=!0)});r?n(t.nTableWrapper).find(".dataTables_paginate").show():n(t.nTableWrapper).find(".dataTables_paginate").hide()},columnDefs:[{width:"12px",orderable:!1,targets:0}]}};o.version={"YASR-table":t("../package.json").version,jquery:n.fn.jquery,"jquery-datatables":n.fn.DataTable.version}},{"../lib/DataTables/media/js/jquery.dataTables.js":2,"../package.json":26,"./bindingsToCsv.js":27,"./imgs.js":31,jquery:17,"yasgui-utils":23}],42:[function(t,e){"use strict";t("jquery");e.exports={uriToPrefixed:function(t,e){if(t)for(var n in t)if(0==e.indexOf(t[n])){e=n+":"+e.substring(t[n].length);break}}}},{jquery:17}]},{},[1])(1)});
//# sourceMappingURL=yasr.bundled.min.js.map |
src/dumb/editor/custom_field/preview_templates/TypeSelectionPreviewTemplate.js | jeckhummer/wf-constructor | import React from 'react';
import {Form} from "semantic-ui-react";
export const TypeSelectionPreviewTemplate = ({label, items}) => {
const options = items.map((item, key) => ({
text: item || "[NO TEXT PROVIDED]",
value: key + "_" + item,
}));
return (
<Form>
<Form.Select
label={label || "[NO TEXT PROVIDED]"}
options={options}
placeholder="--"
/>
</Form>
);
}; |
app/components/Toolbox.js | ARMataTeam/ARMata | // @flow
import React, { Component } from 'react';
import { Sidebar, Button, Form, Header, Icon, Grid } from 'semantic-ui-react';
import ToolboxComponent from './ToolboxComponent';
import styles from './Toolbox.css'; // eslint-disable-line flowtype-errors/show-errors
export default class Toolbox extends Component {
props: {
dispatchButtonClick: (action: string) => void,
addResource: (resourceType: string) => void,
error: (errorMessage: string) => void,
isToolboxOpen: boolean
}
generateGrid() {
const types = [
{ type: 'Microsoft.AnalysisServices/servers', name: 'Analysis Services' },
{ type: 'Microsoft.ApiManagement/service', name: 'API Management' },
{ type: 'Microsoft.Authorization/locks', name: 'Authorization Lock' },
{ type: 'Microsoft.Automation/automationAccounts', name: 'Automation Account' },
{ type: 'Microsoft.Batch/batchAccounts', name: 'Batch Account' },
{ type: 'Microsoft.Cache/Redis', name: 'Redis Cache' },
{ type: 'Microsoft.Cdn/profiles', name: 'CDN' },
{ type: 'Microsoft.CertificateRegistration/certificateOrders', name: 'Certificate Registration' },
{ type: 'Microsoft.CognitiveServices/accounts', name: 'Cognitive Services' },
{ type: 'Microsoft.Compute/virtualMachines', name: 'Virtual Machine' },
{ type: 'Microsoft.ContainerInstance/containerGroups', name: 'Container Groups' },
{ type: 'Microsoft.ContainerRegistry/registries', name: 'Container Registry' },
{ type: 'Microsoft.ContainerService/containerServices', name: 'Container Services' },
{ type: 'Microsoft.DocumentDB/databaseAccounts', name: 'Document DB' },
{ type: 'Microsoft.CustomerInsights/hubs', name: 'Customer Insights' },
{ type: 'Microsoft.DataFactory/dataFactories', name: 'Data Factory' },
{ type: 'Microsoft.DataLakeAnalytics/accounts', name: 'Data Lake Analytics' },
{ type: 'Microsoft.DataLakeStore/accounts', name: 'Data Lake Store' },
{ type: 'Microsoft.Devices/IotHubs', name: 'IoT Hub' },
{ type: 'Microsoft.Devices/IotHubs/eventHubEndpoints/ConsumerGroups', name: 'IoT Hub Consumer Groups' },
{ type: 'Microsoft.DevTestLab/labs', name: 'DevTest Labs' },
{ type: 'Microsoft.DomainRegistration/domains', name: 'Domain Registration' },
{ type: 'Microsoft.EventHub/namespaces', name: 'Event Hub Namespace' },
{ type: 'Microsoft.HDInsight/clusters', name: 'HDInsight cluster' },
{ type: 'Microsoft.ImportExport/jobs', name: 'Import/Export' },
{ type: 'Microsoft.Insights/Components', name: 'Insights' },
{ type: 'Microsoft.KeyVault/vaults', name: 'Key Vault' },
{ type: 'Microsoft.Logic/integrationAccounts', name: 'Logic App' },
{ type: 'Microsoft.MachineLearning/commitmentPlans', name: 'Machine Learning Plan' },
{ type: 'Microsoft.Media/mediaservices', name: 'Media Services' },
{ type: 'Microsoft.Network/applicationGateways', name: 'Application Gateway' },
{ type: 'Microsoft.Network/connections', name: 'Network Connections' },
{ type: 'Microsoft.Network/loadBalancers', name: 'Load Balancer' },
{ type: 'Microsoft.Network/networkInterfaces', name: 'Network Interface' },
{ type: 'Microsoft.Network/virtualNetworks', name: 'Virtual Networks' },
{ type: 'Microsoft.NotificationHubs/namespaces', name: 'Notification Hub' },
{ type: 'Microsoft.StreamAnalytics/streamingjobs', name: 'Stream Analytics' },
{ type: 'Microsoft.StorSimple/managers', name: 'StorSimple' },
{ type: 'Microsoft.Storage/storageAccounts', name: 'Storage Account' },
{ type: 'Microsoft.Sql/servers', name: 'SQL Server' },
{ type: 'Microsoft.ServiceFabric/clusters', name: 'Service Fabric Cluster' },
{ type: 'Microsoft.ServiceBus/namespaces', name: 'Service Bus Namespace' },
{ type: 'Microsoft.ServerManagement/gateways', name: 'Server Management' },
{ type: 'Microsoft.Search/searchServices', name: 'Search Service' },
{ type: 'Microsoft.Scheduler/jobCollections', name: 'Scheduler' },
{ type: 'Microsoft.Relay/namespaces', name: 'Relay' },
{ type: 'Microsoft.Resources/deployments', name: 'Resources' },
{ type: 'Microsoft.RecoveryServices/vaults', name: 'Recovery Services' },
{ type: 'Microsoft.PowerBI/workspaceCollections', name: 'Power BI' },
{ type: 'Microsoft.Web/sites', name: 'App Service' },
];
// Sort data so toolbox is more intuitive
types.sort((a, b) => a.name.localeCompare(b.name));
const grid = [];
for (let i = 0; i <= types.length - 1; i += 2) {
grid.push(<Grid.Row columns={2} key={i}>
<Grid.Column>
<ToolboxComponent
resourceType={types[i].type}
addResource={(type) => this.props.addResource(type)}
error={(msg) => this.props.error(msg)}
/>
{types[i].name}
</Grid.Column>
<Grid.Column>
<ToolboxComponent
resourceType={types[i + 1].type}
addResource={(type) => this.props.addResource(type)}
error={(msg) => this.props.error(msg)}
/>
{types[i + 1].name}
</Grid.Column>
</Grid.Row>);
}
return grid;
}
render() {
return (<Sidebar as={Form} className={styles.toolbox} animation="overlay" width="wide" visible={this.props.isToolboxOpen} icon="labeled" inverted>
<Header as="h3" icon style={{ color: '#FFF' }}>
<Icon name="sitemap" />
Toolbox
<Header.Subheader style={{ color: '#FFF' }}>
Build & customize a template
</Header.Subheader>
</Header>
<Grid>
{this.generateGrid()}
</Grid>
<br />
<Form.Field><Button type="button" fluid onClick={() => this.props.dispatchButtonClick('CLOSE_TOOLBOX')}>Close</Button></Form.Field>
</Sidebar>);
}
}
|
lib/components/sidebar/panel-element-editor/attributes-editor/line-attributes-editor.js | vovance/3d-demo | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = undefined;
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _export = require('../../../style/export');
var _export2 = require('../../../../catalog/properties/export');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var tableStyle = {
width: '100%'
};
var firstTdStyle = {
width: '6em'
};
var inputStyle = {
textAlign: 'left'
};
function LineAttributesEditor(_ref, _ref2) {
var element = _ref.element,
_onUpdate = _ref.onUpdate,
attributeFormData = _ref.attributeFormData,
state = _ref.state;
var translator = _ref2.translator;
var name = attributeFormData.has('name') ? attributeFormData.get('name') : element.name;
var vertexOne = attributeFormData.has('vertexOne') ? attributeFormData.get('vertexOne') : null;
var vertexTwo = attributeFormData.has('vertexTwo') ? attributeFormData.get('vertexTwo') : null;
var lineLength = attributeFormData.has('lineLength') ? attributeFormData.get('lineLength') : null;
return _react2.default.createElement(
'div',
null,
_react2.default.createElement(
'table',
{ style: tableStyle },
_react2.default.createElement(
'tbody',
null,
_react2.default.createElement(
'tr',
null,
_react2.default.createElement(
'td',
{ style: firstTdStyle },
'Nome:'
),
_react2.default.createElement(
'td',
null,
_react2.default.createElement(_export.FormTextInput, { value: name, onChange: function onChange(event) {
return _onUpdate('name', event.target.value);
}, style: inputStyle })
)
),
_react2.default.createElement(
'tr',
null,
_react2.default.createElement(
'td',
{ style: firstTdStyle },
'X1:'
),
_react2.default.createElement(
'td',
null,
_react2.default.createElement(_export.FormNumberInput, { value: vertexOne.get('x'),
onChange: function onChange(event) {
return _onUpdate('vertexOne', { 'x': event.target.value });
}, style: inputStyle,
state: state })
)
),
_react2.default.createElement(
'tr',
null,
_react2.default.createElement(
'td',
{ style: firstTdStyle },
'Y1:'
),
_react2.default.createElement(
'td',
null,
_react2.default.createElement(_export.FormNumberInput, { value: vertexOne.get('y'),
onChange: function onChange(event) {
return _onUpdate('vertexOne', { 'y': event.target.value });
}, style: inputStyle,
state: state })
)
),
_react2.default.createElement(
'tr',
null,
_react2.default.createElement(
'td',
{ style: firstTdStyle },
'X2:'
),
_react2.default.createElement(
'td',
null,
_react2.default.createElement(_export.FormNumberInput, { value: vertexTwo.get('x'),
onChange: function onChange(event) {
return _onUpdate('vertexTwo', { 'x': event.target.value });
}, style: inputStyle,
state: state })
)
),
_react2.default.createElement(
'tr',
null,
_react2.default.createElement(
'td',
{ style: firstTdStyle },
'Y2:'
),
_react2.default.createElement(
'td',
null,
_react2.default.createElement(_export.FormNumberInput, { value: vertexTwo.get('y'),
onChange: function onChange(event) {
return _onUpdate('vertexTwo', { 'y': event.target.value });
}, style: inputStyle,
state: state })
)
)
)
),
_react2.default.createElement(_export2.PropertyLengthMeasure, {
value: lineLength,
onUpdate: function onUpdate(mapped) {
return _onUpdate('lineLength', mapped);
},
configs: { label: 'Length', min: 0, max: Infinity },
state: state
})
);
}
exports.default = LineAttributesEditor;
LineAttributesEditor.propTypes = {
element: _propTypes2.default.object.isRequired,
onUpdate: _propTypes2.default.func.isRequired,
attributeFormData: _propTypes2.default.object.isRequired,
state: _propTypes2.default.object.isRequired
};
LineAttributesEditor.contextTypes = {
translator: _propTypes2.default.object.isRequired
}; |
examples/tree-view/index.js | tappleby/redux | import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import Node from './containers/Node'
import configureStore from './store/configureStore'
import generateTree from './generateTree'
const tree = generateTree()
const store = configureStore(tree)
render(
<Provider store={store}>
<Node id={0} />
</Provider>,
document.getElementById('root')
)
|
src/containers/board/HandleDelete.js | jvallexm/message-board | import React from 'react';
export default class HandleDelete extends React.Component{
constructor(props)
{
super(props);
this.state = {
message: "",
input: ""
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e)
{
if(e.target.value.length > 20)
return false;
this.setState({input: e.target.value})
}
handleSubmit()
{
if(this.state.input == this.props.toDelete.delete_password || this.state.input == "👎👎👎👎👎")
{
console.log("pass");
this.props.deletePost();
}
else
{
console.log("fail");
this.setState({message: "Wrong password :("});
}
}
render()
{
return(
<div>
<div className="red error">
{this.state.message}
</div>
<div className="row">
<div className="col-md-8 col-left">
<input className="width-100 smol"
placeholder={"Delete Key"}
value={this.state.input}
onChange={this.handleChange}/>
</div>
<div className="col-md-2 col-left col-right post">
<button className="btn btn-smol smol width-100"
onClick={this.handleSubmit}>
Delete
</button>
</div>
<div className="col-md-2 col-right post ">
<button className="btn btn-smol smol width-100 cancel"
onClick={this.props.deleteToggle}>
Cancel
</button>
</div>
</div>
</div>
);
}
} |
src/ContentBlocks/BlockParagraphCTAs/BlockParagraphCTAsForm.js | grommet/grommet-cms-content-blocks | // @flow
import React, { Component } from 'react';
import Box from 'grommet/components/Box';
import Button from 'grommet/components/Button';
import Tabs from 'grommet/components/Tabs';
import Tab from 'grommet/components/Tab';
import Select from 'grommet/components/Select';
import FormField from 'grommet/components/FormField';
import FormFields from 'grommet/components/FormFields';
import AddIcon from 'grommet/components/icons/base/Add';
import TrashIcon from 'grommet/components/icons/base/Trash';
import { BlockButtonForm } from '../BlockButton';
import { ConfirmLayer } from '../Shared';
import { ResponsiveBox } from './styles';
type CtaSlide = any;
type OnChangeEvent = SyntheticInputEvent & {
option: string,
};
type Props = {
ctaArray: CtaSlide[],
content: string,
onSubmit: ?Function,
assetNode: ?React$Element<any>,
paragraphSize: 'small' | 'medium' | 'large',
}
type State = {
ctaArray: CtaSlide[],
confirmLayer: boolean,
activeSlideIndex: number,
content: string,
error: string,
paragraphSize: 'small' | 'medium' | 'large',
}
class BlockParagraphCTAsForm extends Component {
constructor(props: Props) {
super(props);
this.state = {
ctaArray: props.ctaArray || [],
paragraphSize: props.paragraphSize || 'medium',
confirmLayer: false,
activeSlideIndex: 0,
content: props.content || '',
error: '',
};
const This = (this: any);
This.deleteSlide = this.deleteSlide.bind(this);
This.onSubmit = this.onSubmit.bind(this);
This.handleAssetSelect = this.handleAssetSelect.bind(this);
This.handleChange = this.handleChange.bind(this);
This.addSlideClick = this.addSlideClick.bind(this);
This.onTabsClick = this.onTabsClick.bind(this);
This.toggleConfirm = this.toggleConfirm.bind(this);
This.onChangeContent = this.onChangeContent.bind(this);
}
state: State;
componentWillMount() {
if (!this.props.ctaArray) {
this.addSlideClick();
}
}
componentWillReceiveProps(nextProps: Props) {
if (nextProps.ctaArray) {
// Copy CTA state array.
this.setState({
ctaArray: nextProps.ctaArray.slice(),
});
}
}
onTabsClick(tabIndex: number) {
this.setState({ activeSlideIndex: tabIndex });
}
onChangeContent(event: OnChangeEvent) {
const { target, option } = event;
const { id, value } = (target: any);
const key = id;
const newState = {
[`${key}`]: option || value,
};
this.setState(newState);
}
onSubmit({ ctaArray, content, paragraphSize }: State) {
const dataToSubmit = {
ctaArray,
content,
paragraphSize,
};
if (this.props.onSubmit) {
this.props.onSubmit(dataToSubmit);
}
}
deleteSlideClick() {
this.toggleConfirm();
}
deleteSlide(activeIndex: number, event: Event) {
event.preventDefault();
const nextCtaArrayState = this.state.ctaArray.slice();
nextCtaArrayState.splice(activeIndex, 1);
this.setState({
activeSlideIndex: 0,
ctaArray: nextCtaArrayState,
confirmLayer: false,
});
}
handleAssetSelect(asset: {
_id: string,
title: ?string,
path: string
}) {
const { path, _id } = asset;
const { ctaArray, activeSlideIndex } = this.state;
const nextCtaArrayState = [
...ctaArray.slice(0, activeSlideIndex),
{
...ctaArray[activeSlideIndex],
_id,
path,
},
...ctaArray.slice(activeSlideIndex + 1),
];
this.setState({ ctaArray: nextCtaArrayState });
}
handleChange(event: OnChangeEvent) {
const { target, option } = event;
const { id, value } = target;
const { ctaArray, activeSlideIndex } = this.state;
const nextCtaArrayState = [
...ctaArray.slice(0, activeSlideIndex),
{
...ctaArray[activeSlideIndex],
[id]: option || value,
},
...ctaArray.slice(activeSlideIndex + 1),
];
this.setState({ ctaArray: nextCtaArrayState });
}
toggleConfirm() {
this.setState({ confirmLayer: !this.state.confirmLayer });
}
addSlideClick() {
const nextCtaArrayState = this.state.ctaArray.slice();
nextCtaArrayState.push({
label: '',
path: '',
assetType: 'path',
buttonType: 'Anchor',
primary: 'True',
});
this.setState({
activeSlideIndex: nextCtaArrayState.length - 1,
ctaArray: nextCtaArrayState,
});
}
props: Props;
render() {
const { assetNode } = this.props;
const { activeSlideIndex, content, paragraphSize } = this.state;
const buttonForm = (
<BlockButtonForm
pad={false}
data={this.state.ctaArray[activeSlideIndex]}
onChange={this.handleChange}
onSubmit={this.onSubmit.bind(this, this.state)}
>
{assetNode && React.cloneElement(
assetNode,
{
onAssetSelect: this.handleAssetSelect,
},
)}
</BlockButtonForm>
);
const tabs = this.state.ctaArray.map((slide, index) =>
<Tab
title={`CTA ${index + 1}`}
key={index}
onClick={this.onTabsClick.bind(this, index)}
/>,
);
const confirmLayer = (this.state.confirmLayer)
? (
<ConfirmLayer
name={`CTA ${activeSlideIndex + 1}`}
onClose={this.toggleConfirm}
onSubmit={this.deleteSlide.bind(this, activeSlideIndex)}
/>
)
: undefined;
return (
<Box direction="column" pad="medium" colorIndex="light-2">
{confirmLayer}
<Box direction="row">
<ResponsiveBox direction="row" align="center">
<Button icon={<AddIcon />} label="add slide" onClick={this.addSlideClick} />
<Box pad="small" />
<Button
icon={<TrashIcon />} label="delete slide"
onClick={this.deleteSlideClick.bind(this, activeSlideIndex)}
/>
</ResponsiveBox>
</Box>
<FormFields>
<FormField
label="Content"
htmlFor="content"
>
<textarea
autoFocus
id="content"
name="content"
type="text"
value={content}
onChange={this.onChangeContent}
rows="3"
/>
</FormField>
<FormField
label="Paragraph Size"
htmlFor="paragraphSize"
>
<Select
onChange={this.onChangeContent}
value={paragraphSize}
options={[
'small',
'medium',
'large',
]}
name="paragraphSize"
id="paragraphSize"
/>
</FormField>
</FormFields>
<Box>
<Box>
<Tabs
activeIndex={activeSlideIndex} justify="start"
style={{ marginBottom: '-1px' }}
>
{tabs}
</Tabs>
</Box>
</Box>
{buttonForm}
</Box>
);
}
}
export default BlockParagraphCTAsForm;
|
admin/lib/App.js | synthesis-js/react-synthesis | // App.js
import React from 'react';
import { browserHistory } from 'react-router';
// import components
import NavBar from './navbar/components/NavBar';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {}
this.getComponentsXHR = this.getComponentsXHR.bind(this);
this.checkUser = this.checkUser.bind(this);
this.sendComponentsToStore = this.sendComponentsToStore.bind(this);
this.getPostsXHR = this.getPostsXHR.bind(this);
this.sendPostsToStore = this.sendPostsToStore.bind(this);
}
componentDidMount() {
this.getComponentsXHR();
this.getPostsXHR();
let token = localStorage.getItem('token');
if(!token) {
this.checkUser();
}
}
checkUser() {
let that = this;
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if(xhr.status === 200 && xhr.readyState === 4) {
that.handleUserData(JSON.parse(xhr.responseText));
}
}
xhr.open('GET', '/api/users');
xhr.send();
}
handleUserData(userData) {
if(userData.length === 0) {
browserHistory.push('/signup')
}
}
getComponentsXHR() {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if(xhr.status === 200 && xhr.readyState === 4) {
this.sendComponentsToStore(JSON.parse(xhr.responseText));
}
}
xhr.open('GET', '/api/plugins');
xhr.send();
}
sendComponentsToStore(pluginData) {
let plugins = [];
pluginData.forEach(plugin => {
plugins.push(plugin);
})
this.props.getComponents(plugins);
}
getPostsXHR() {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if(xhr.status === 200 && xhr.readyState === 4) {
this.sendPostsToStore(JSON.parse(xhr.responseText));
}
}
xhr.open('GET', '/api/posts');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send();
}
sendPostsToStore(postData) {
let posts = {};
postData.forEach(post => {
posts[post._id] = post;
})
this.props.getPosts(posts);
}
logoutUser() {
localStorage.removeItem('token');
localStorage.removeItem('userId')
}
render() {
return (
<div>
<NavBar hasToken={this.props.user} logoutUser={this.logoutUser} />
<div className="container-fluid">
{React.cloneElement(this.props.children, this.props)}
</div>
</div>
)
}
}
|
ajax/libs/forerunnerdb/1.3.733/fdb-core+views.min.js | sashberd/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":8,"../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;d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}(),e=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0},b.exports=e},{}],6:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n;d=a("./Shared");var o=function(a,b){this.init.apply(this,arguments)};o.prototype.init=function(a,b){this.sharedPathSolver=n,this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Events"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.CRUD"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Triggers"),d.mixin(o.prototype,"Mixin.Sorting"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.Updating"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n=new h,d.synthesize(o.prototype,"deferredCalls"),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"metaData"),d.synthesize(o.prototype,"capped"),d.synthesize(o.prototype,"cappedSize"),o.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},o.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},o.prototype.data=function(){return this._data},o.prototype.drop=function(a){var b;if(this.isDropped())return a&&a.call(this,!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._data,delete this._metrics,delete this._listeners,a&&a.call(this,!1,!0),!0}return a&&a.call(this,!1,!0),!1},o.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",{keyName:a,oldData:b})}return this}return this._primaryKey},o.prototype._onInsert=function(a,b){this.emit("insert",a,b)},o.prototype._onUpdate=function(a){this.emit("update",a)},o.prototype._onRemove=function(a){this.emit("remove",a)},o.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=this.serialiser.convert(new Date))},d.synthesize(o.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"mongoEmulation"),o.prototype.setData=new l("Collection.prototype.setData",{"*":function(a){return this.$main.call(this,a,{})},"*, object":function(a,b){return this.$main.call(this,a,b)},"*, function":function(a,b){return this.$main.call(this,a,{},b)},"*, *, function":function(a,b,c){return this.$main.call(this,a,b,c)},"*, *, *":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this.deferredCalls(),e=[].concat(this._data);this.deferredCalls(!1),b=this.options(b),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),this.remove({}),this.insert(a),this.deferredCalls(d),this._onChange(),this.emit("setData",this._data,e)}return c&&c.call(this),this}}),o.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.hash(d),i.set(d[k],e),j.set(e,d)}},o.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},o.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},o.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b.call(this),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a,b);break;case"update":g.result=this.update(c,a,{},b)}return g}return b&&b.call(this),{}},o.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},o.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},o.prototype.update=function(a,b,c,d){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.mongoEmulation()?(this.convertToFdb(a),this.convertToFdb(b)):b=this.decouple(b),b=this.transformIn(b),this._handleUpdate(a,b,c,d)},o.prototype._handleUpdate=function(a,b,c,d){var e,f,g=this,h=this._metrics.create("update"),i=function(d){var e,f,i,j=g.decouple(d);return g.willTrigger(g.TYPE_UPDATE,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_UPDATE,g.PHASE_AFTER)?(e=g.decouple(d),f={type:"update",query:g.decouple(a),update:g.decouple(b),options:g.decouple(c),op:h},i=g.updateObject(e,f.update,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_BEFORE,d,e)!==!1?(i=g.updateObject(d,e,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_AFTER,j,e)):i=!1):i=g.updateObject(d,b,a,c,""),g._updateIndexes(j,d),i};return h.start(),h.time("Retrieve documents to update"),e=this.find(a,{$decouple:!1}),h.time("Retrieve documents to update"),e.length&&(h.time("Update documents"),f=e.filter(i),h.time("Update documents"),f.length&&(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),h.time("Resolve chains"),this.chainWillSend()&&this.chainSend("update",{query:a,update:b,dataSet:this.decouple(f)},c),h.time("Resolve chains"),this._onUpdate(f),this._onChange(),d&&d.call(this),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f}))),h.stop(),f||[]},o.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},o.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},o.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":(!(a[s]instanceof Object)||a[s]instanceof Array)&&(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},o.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},o.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c.call(this,!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.emit("immediateChange",{type:"remove",data:g}),this.deferEmit("change",{type:"remove",data:g}))}return c&&c.call(this,!1,g),g},o.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},o.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b.call(this,c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},o.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},o.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},o.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c.call(this,e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i}),this.deferEmit("change",{type:"insert",data:i}),e},o.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainWillSend()&&g.chainSend("insert",{dataSet:g.decouple([a])},{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},o.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},o.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},o.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},o.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.hash(a),f=this._primaryKey;c=this._primaryIndex.uniqueSet(a[f],a),this._primaryCrc.uniqueSet(a[f],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},o.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.hash(a),e=this._primaryKey;this._primaryIndex.unSet(a[e]),this._primaryCrc.unSet(a[e]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},o.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},o.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},o.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new o,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(o.prototype,"subsetOf"),o.prototype.isSubsetOf=function(a){return this._subsetOf===a},o.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},o.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},o.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new o,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},o.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},o.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},o.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c.call(this,"Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},o.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this._metrics.create("find"),y=this.primaryKey(),z=this,A=!0,B={},C=[],D=[],E=[],F={},G={};if(b instanceof Array||(b=this.options(b)),w=function(c){return z._match(c,a,b,"and",F)},x.start(),a){if(a instanceof Array){for(v=this,n=0;n<a.length;n++)v=v.subset(a[n],b&&b[n]?b[n]:{});return v.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(x.time("analyseQuery"),c=this._analyseQuery(z.decouple(a),b,x),x.time("analyseQuery"),x.data("analysis",c),c.hasJoin&&c.queriesJoin){for(x.time("joinReferences"),f=0;f<c.joinsOn.length;f++)m=c.joinsOn[f],j=m.key,k=m.type,l=m.id,i=new h(c.joinQueries[j]),g=i.value(a)[0],B[l]=this._db[k](j).subset(g),delete a[c.joinQueries[j]];x.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(x.data("index.potential",c.indexMatch),x.data("index.used",c.indexMatch[0].index),x.time("indexLookup"),e=c.indexMatch[0].lookup||[],x.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(A=!1)):x.flag("usedIndex",!1),A&&(e&&e.length?(d=e.length,x.time("tableScan: "+d),e=e.filter(w)):(d=this._data.length,x.time("tableScan: "+d),e=this._data.filter(w)),x.time("tableScan: "+d)),b.$orderBy&&(x.time("sort"),e=this.sort(b.$orderBy,e),x.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(G.page=b.$page,G.pages=Math.ceil(e.length/b.$limit),G.records=e.length,b.$page&&b.$limit>0&&(x.data("cursor",G),e.splice(0,b.$page*b.$limit))),b.$skip&&(G.skip=b.$skip,e.splice(0,b.$skip),x.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(G.limit=b.$limit,e.length=b.$limit,x.data("limit",b.$limit)),b.$decouple&&(x.time("decouple"),e=this.decouple(e),x.time("decouple"),x.data("flag.decouple",!0)),b.$join&&(C=C.concat(this.applyJoin(e,b.$join,B)),x.data("flag.join",!0)),C.length&&(x.time("removalQueue"),this.spliceArrayByIndexList(e,C),x.time("removalQueue")),b.$transform){for(x.time("transform"),n=0;n<e.length;n++)e.splice(n,1,b.$transform(e[n]));x.time("transform"),x.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(x.time("transformOut"),e=this.transformOut(e),x.time("transformOut")),x.data("results",e.length)}else e=[];if(!b.$aggregate){x.time("scanFields");for(n in b)b.hasOwnProperty(n)&&0!==n.indexOf("$")&&(1===b[n]?D.push(n):0===b[n]&&E.push(n));if(x.time("scanFields"),D.length||E.length){for(x.data("flag.limitFields",!0),x.data("limitFields.on",D),x.data("limitFields.off",E),x.time("limitFields"),n=0;n<e.length;n++){t=e[n];for(o in t)t.hasOwnProperty(o)&&(D.length&&o!==y&&-1===D.indexOf(o)&&delete t[o],E.length&&E.indexOf(o)>-1&&delete t[o])}x.time("limitFields")}if(b.$elemMatch){x.data("flag.elemMatch",!0),x.time("projection-elemMatch");for(n in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length)for(p=0;p<r.length;p++)if(z._match(r[p],b.$elemMatch[n],b,"",{})){q.set(e[o],n,[r[p]]);break}x.time("projection-elemMatch")}if(b.$elemsMatch){x.data("flag.elemsMatch",!0),x.time("projection-elemsMatch");for(n in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length){for(s=[],p=0;p<r.length;p++)z._match(r[p],b.$elemsMatch[n],b,"",{})&&s.push(r[p]);q.set(e[o],n,s)}x.time("projection-elemsMatch")}}return b.$aggregate&&(x.data("flag.aggregate",!0),x.time("aggregate"),u=new h(b.$aggregate),e=u.value(e),x.time("aggregate")),x.stop(),e.__fdbOp=x,e.$cursor=G,e},o.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},o.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},o.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]),c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},o.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},o.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},o.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),
b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},o.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},o.prototype.sort=function(a,b){var c=this,d=n.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(n.get(a,f.path),n.get(b,f.path)):-1===f.value&&(g=c.sortDesc(n.get(a,f.path),n.get(b,f.path))),0!==g)return g;return g}),b},o.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},o.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u={queriesOn:[{id:"$collection."+this._name,type:"colletion",key:this._name}],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},v=[],w=[];if(c.time("checkIndexes"),p=new h,q=p.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(r=typeof a[this._primaryKey],("string"===r||"number"===r||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),s=this._primaryIndex.lookup(a,b),u.indexMatch.push({lookup:s,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:q,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(t in this._indexById)if(this._indexById.hasOwnProperty(t)&&(m=this._indexById[t],n=m.name(),c.time("checkIndexMatch: "+n),l=m.match(a,b),l.score>0&&(o=m.lookup(a,b),u.indexMatch.push({lookup:o,keyData:l,index:m})),c.time("checkIndexMatch: "+n),l.score===q))break;c.time("checkIndexes"),u.indexMatch.length>1&&(c.time("findOptimalIndex"),u.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(u.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(i=b.$join[d][e],f=i.$sourceType||"collection",g="$"+f+"."+e,v.push({id:g,type:f,key:e}),void 0!==b.$join[d][e].$as?w.push(b.$join[d][e].$as):w.push(e));for(k=0;k<w.length;k++)j=this._queryReferencesSource(a,w[k],""),j&&(u.joinQueries[v[k].key]=j,u.queriesJoin=!0);u.joinsOn=v,u.queriesOn=u.queriesOn.concat(v)}return u},o.prototype._queryReferencesSource=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesSource(a[d],b,c)}return!1},o.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},o.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},o.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new o("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;j>e;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},o.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},o.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},o.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,e={start:(new Date).getTime()};if(b)if(b.type){if(!d.index[b.type])throw this.logIdentifier()+' Cannot create index of type "'+b.type+'", type not found in the index type register (Shared.index)';c=new d.index[b.type](a,b,this)}else 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,e.end=(new Date).getTime(),e.total=e.end-e.start,this._lastOp={type:"ensureIndex",stats:{time:e}},{index:c,id:c.id(),name:c.name(),state:c.state()})},o.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},o.prototype.lastOp=function(){return this._metrics.list()},o.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},o.prototype.collateAdd=new l("Collection.prototype.collateAdd",{"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data.dataSet),c.update({},e)):c.insert(d.data.dataSet);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data.dataSet)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),o.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l("Db.prototype.collection",{"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof o?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new o(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=o},{"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":29,"./Shared":31}],7:[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"),d.mixin(h.prototype,"Mixin.Events"),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.dataSet=this.decouple(a.data.dataSet),this._data.remove(a.data.oldData),this._data.insert(a.data.dataSet);break;case"insert":a.data.dataSet=this.decouple(a.data.dataSet),this._data.insert(a.data.dataSet);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){var b=this;return a?a instanceof h?a:this._collectionGroup&&this._collectionGroup[a]?this._collectionGroup[a]:(this._collectionGroup[a]=new h(a).db(this),b.emit("create",b._collectionGroup[a],"collectionGroup",a),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":6,"./Shared":31}],8:[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}],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("./Checksum.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.Checksum=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Checksum.js":5,"./Collection.js":6,"./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.index["2d"]=k,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.index.btree=g,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.index.hashed=f,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)}},chainWillSend:function(){return Boolean(this._chain)},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length,h=this.decouple(b,g);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,h[e],c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d},f=!1;this.debug&&this.debug()&&console.log(this.logIdentifier()+" Received data from parent reactor node"),this._chainHandler&&(f=this._chainHandler(e)),f||this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],18:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,make:function(a){return h.convert(a)},store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return JSON.parse(a,h.reviver())},jStringify:function(a){return JSON.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},hash:function(a){return JSON.stringify(a)},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return"ForerunnerDB "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state},debounce:function(a,b,c){var d,e=this;e._debounce=e._debounce||{},e._debounce[a]&&clearTimeout(e._debounce[a].timeout),d={callback:b,timeout:setTimeout(function(){delete e._debounce[a],b()},c)},e._debounce[a]=d}},b.exports=d},{"./Overload":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("object"===m&&null===a&&(m="null"),"object"===n&&null===b&&(n="null"),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&&"null"!==m||"string"!==n&&"number"!==n&&"null"!==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||"null"===m||"null"===n?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a,e.$rootQuery),!1);case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a,e.$rootQuery),!1);case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1},applyJoin:function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this,y=[];for(a instanceof Array||(a=[a]),e=0;e<b.length;e++)for(f in b[e])if(b[e].hasOwnProperty(f))for(g=b[e][f],h=g.$sourceType||"collection",i="$"+h+"."+f,j=f,c[i]?k=c[i]:this._db[h]&&"function"==typeof this._db[h]&&(k=this._db[h](f)),l=0;l<a.length;l++){m={},n=!1,o=!1,p="";for(q in g)if(g.hasOwnProperty(q))if(r=g[q],"$"===q.substr(0,1))switch(q){case"$where":if(!r.$query&&!r.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';r.$query&&(m=x.resolveDynamicQuery(r.$query,a[l])),r.$options&&(s=r.$options);break;case"$as":j=r;break;case"$multi":n=r;break;case"$require":o=r;break;case"$prefix":p=r}else m[q]=x.resolveDynamicQuery(r,a[l]);if(t=k.find(m,s),!o||o&&t[0])if("$root"===j){if(n!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';u=t[0],v=a[l];for(w in u)u.hasOwnProperty(w)&&void 0===v[p+w]&&(v[p+w]=u[w])}else a[l][j]=n===!1?t[0]:t;else y.push(l)}return y},resolveDynamicQuery:function(a,b){var c,d,e,f,g,h=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?this.sharedPathSolver.value(b,a.substr(3,a.length-3)):this.sharedPathSolver.value(b,a),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=this.sharedPathSolver.value(b,e.substr(3,e.length-3))[0]:c[g]=e;break;case"object":c[g]=h.resolveDynamicQuery(e,b);break;default:c[g]=e}return c},spliceArrayByIndexList:function(a,b){var c;for(c=b.length-1;c>=0;c--)a.splice(b[c],1)}};b.exports=d},{}],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.triggerStack={},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},ignoreTriggers:function(a){return void 0!==a?(this._ignoreTriggers=a,this):this._ignoreTriggers},addLinkIO:function(a,b){var c,d,e,f,g,h,i,j,k,l=this;if(l._linkIO=l._linkIO||{},l._linkIO[a]=b,d=b["export"],e=b["import"],d&&(h=l.db().collection(d.to)),e&&(i=l.db().collection(e.from)),j=[l.TYPE_INSERT,l.TYPE_UPDATE,l.TYPE_REMOVE],c=function(a,b){b(!1,!0)},d&&(d.match||(d.match=c),d.types||(d.types=j),f=function(a,b,c){d.match(c,function(b,e){e&&d.data(c,a.type,function(b,c,d){c&&(h.ignoreTriggers(!0),"remove"!==a.type?h.upsert(c,d):h.remove(c,d),h.ignoreTriggers(!1))})})}),e&&(e.match||(e.match=c),e.types||(e.types=j),g=function(a,b,c){e.match(c,function(b,d){d&&e.data(c,a.type,function(b,c,d){c&&(h.ignoreTriggers(!0),"remove"!==a.type?l.upsert(c,d):l.remove(c,d),h.ignoreTriggers(!1))})})}),d)for(k=0;k<d.types.length;k++)l.addTrigger(a+"export"+d.types[k],d.types[k],l.PHASE_AFTER,f);if(e)for(k=0;k<e.types.length;k++)i.addTrigger(a+"import"+e.types[k],e.types[k],l.PHASE_AFTER,g)},removeLinkIO:function(a){var b,c,d,e,f=this,g=f._linkIO[a];if(g){if(b=g["export"],c=g["import"],b)for(e=0;e<b.types.length;e++)f.removeTrigger(a+"export"+b.types[e],b.types[e],f.db.PHASE_AFTER);if(c)for(d=f.db().collection(c.from),e=0;e<c.types.length;e++)d.removeTrigger(a+"import"+c.types[e],c.types[e],f.db.PHASE_AFTER);return delete f._linkIO[a],!0}return!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._ignoreTriggers&&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,l,m=this;if(!m._ignoreTriggers&&m._trigger&&m._trigger[b]&&m._trigger[b][c]){for(f=m._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(m.debug()){switch(b){case this.TYPE_INSERT:k="insert";break;case this.TYPE_UPDATE:k="update";break;case this.TYPE_REMOVE:k="remove";break;default:k=""}switch(c){case this.PHASE_BEFORE:l="before";break;case this.PHASE_AFTER:l="after";break;default:l=""}console.log('Triggers: Processing trigger "'+i.id+'" for '+k+' in phase "'+l+'"')}if(m.triggerStack&&m.triggerStack[b]&&m.triggerStack[b][c]&&m.triggerStack[b][c][i.id]){m.debug()&&console.log('Triggers: Will not run trigger "'+i.id+'" for '+k+' in phase "'+l+'" as it is already in the stack!');continue}if(m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!0,j=i.method.call(m,a,d,e),m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!1,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+'" to val "'+c+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],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,b){if(b||(b=a,a=void 0),b){var c,d,e,f,g,h,i=this;if(!(b instanceof Array)){e={};for(c in b)if(b.hasOwnProperty(c))if(f=c.replace(/ /g,""),-1===f.indexOf("*"))e[f]=b[c];else for(h=this.generateSignaturePermutations(f),g=0;g<h.length;g++)e[h[g]]||(e[h[g]]=b[c]);b=e}return function(){var e,f,g,h=[];if(b instanceof Array){for(d=b.length,c=0;d>c;c++)if(b[c].length===arguments.length)return i.callExtend(this,"$main",b,b[c],arguments)}else{for(c=0;c<arguments.length&&(f=typeof arguments[c],"object"===f&&arguments[c]instanceof Array&&(f="array"),1!==arguments.length||"undefined"!==f);c++)h.push(f);if(e=h.join(","),b[e])return i.callExtend(this,"$main",b,b[e],arguments);for(c=h.length;c>=0;c--)if(e=h.slice(0,c).join(","),b[e+",..."])return i.callExtend(this,"$main",b,b[e+",..."],arguments)}throw g=void 0!==a?a:"function"==typeof this.name?this.name():"Unknown",console.log("Overload Definition:",b),'ForerunnerDB.Overload "'+g+'": Overloaded method does not have a matching signature "'+e+'" for the passed arguments: '+this.jStringify(h)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["array","string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],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(){var a=this;this._encoder=[],this._decoder=[],this.registerHandler("$date",function(a){return a instanceof Date?(a.toJSON=function(){return"$date:"+this.toISOString()},!0):!1},function(b){return"string"==typeof b&&0===b.indexOf("$date:")?a.convert(new Date(b.substr(6))):void 0}),this.registerHandler("$regexp",function(a){return a instanceof RegExp?(a.toJSON=function(){return"$regexp:"+this.source.length+":"+this.source+":"+(this.global?"g":"")+(this.ignoreCase?"i":"")},!0):!1},function(b){if("string"==typeof b&&0===b.indexOf("$regexp:")){var c=b.substr(8),d=c.indexOf(":"),e=Number(c.substr(0,d)),f=c.substr(d+1,e),g=c.substr(d+e+2);return a.convert(new RegExp(f,g))}})},d.prototype.registerHandler=function(a,b,c){void 0!==a&&(this._encoder.push(b),this._decoder.push(c))},d.prototype.convert=function(a){var b,c=this._encoder;for(b=0;b<c.length;b++)if(c[b](a))return a;return a},d.prototype.reviver=function(){var a=this._decoder;return function(b,c){var d,e;for(e=0;e<a.length;e++)if(d=a[e](c),void 0!==d)return d;return c}},b.exports=d},{}],31:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.733",modules:{},plugins:{},index:{},_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,m,n=a("./Overload");d=a("./Shared");var o=function(a,b,c){this.init.apply(this,arguments)};d.addModule("View",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Triggers"),d.mixin(o.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,l=d.modules.Path,m=new l,o.prototype.init=function(a,b,c){var d=this;this.sharedPathSolver=m,this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._data=new f(this.name()+"_internal")},o.prototype._handleChainIO=function(a,b){var c,d,e,f,g=a.type;return"setData"!==g&&"insert"!==g&&"update"!==g&&"remove"!==g?!1:(c=Boolean(b._querySettings.options&&b._querySettings.options.$join),d=Boolean(b._querySettings.query),e=void 0!==b._data._transformIn,c||d||e?(f={dataArr:[],removeArr:[]},"insert"===a.type?a.data.dataSet instanceof Array?f.dataArr=a.data.dataSet:f.dataArr=[a.data.dataSet]:"update"===a.type?f.dataArr=a.data.dataSet:"remove"===a.type&&(a.data.dataSet instanceof Array?f.removeArr=a.data.dataSet:f.removeArr=[a.data.dataSet]),f.dataArr instanceof Array||(console.warn("WARNING: dataArr being processed by chain reactor in View class is inconsistent!"),f.dataArr=[]),f.removeArr instanceof Array||(console.warn("WARNING: removeArr being processed by chain reactor in View class is inconsistent!"),f.removeArr=[]),c&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveJoin"),b._handleChainIO_ActiveJoin(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveJoin")),d&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveQuery"),b._handleChainIO_ActiveQuery(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveQuery")),e&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_TransformIn"),b._handleChainIO_TransformIn(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_TransformIn")),f.dataArr.length||f.removeArr.length?(f.pk=b._data.primaryKey(),f.removeArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_RemovePackets"),b._handleChainIO_RemovePackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_RemovePackets")),f.dataArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_UpsertPackets"),b._handleChainIO_UpsertPackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_UpsertPackets")),!0):!0):!1)},o.prototype._handleChainIO_ActiveJoin=function(a,b){var c,d=b.dataArr;c=this.applyJoin(d,this._querySettings.options.$join,{},{}),this.spliceArrayByIndexList(d,c),b.removeArr=b.removeArr.concat(c)},o.prototype._handleChainIO_ActiveQuery=function(a,b){var c,d=this,e=b.dataArr;for(c=e.length-1;c>=0;c--)d._match(e[c],d._querySettings.query,d._querySettings.options,"and",{})||(b.removeArr.push(e[c]),e.splice(c,1))},o.prototype._handleChainIO_TransformIn=function(a,b){var c,d=this,e=b.dataArr,f=b.removeArr,g=d._data._transformIn;for(c=0;c<e.length;c++)e[c]=g(e[c]);for(c=0;c<f.length;c++)f[c]=g(f[c])},o.prototype._handleChainIO_RemovePackets=function(a,b,c){var d,e,f=[],g=c.pk,h=c.removeArr,i={dataSet:h,query:{$or:f}};for(e=0;e<h.length;e++)d={},d[g]=h[e][g],f.push(d);a.chainSend("remove",i)},o.prototype._handleChainIO_UpsertPackets=function(a,b,c){var d,e,f,g=this._data,h=g._primaryIndex,i=g._primaryCrc,j=c.pk,k=c.dataArr,l=[],m=[];for(f=0;f<k.length;f++)d=k[f],h.get(d[j])?i.get(d[j])!==this.hash(d[j])&&m.push(d):l.push(d);if(l.length&&a.chainSend("insert",{dataSet:l}),m.length)for(f=0;f<m.length;f++)d=m[f],e={},e[j]=d[j],a.chainSend("update",{query:e,update:d,dataSet:[d]})},o.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},o.prototype.update=function(){this._from.update.apply(this._from,arguments)},o.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},o.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},o.prototype.find=function(a,b){return this._data.find(a,b)},o.prototype.findOne=function(a,b){return this._data.findOne(a,b)},o.prototype.findById=function(a,b){return this._data.findById(a,b)},o.prototype.findSub=function(a,b,c,d){return this._data.findSub(a,b,c,d)},o.prototype.findSubOne=function(a,b,c,d){return this._data.findSubOne(a,b,c,d)},o.prototype.data=function(){return this._data},o.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._data,this.debug()&&console.log(this.logIdentifier()+' Using internal data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(this._from,this,function(a){return c._handleChainIO.call(this,a,c)}),this._data.primaryKey(a.primaryKey());var d=a.find(this._querySettings.query,this._querySettings.options);return this._data.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},o.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),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._data.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._data.setData(j),this.rebuildActiveBucket(this._querySettings.options);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._data.name()+'"'),a.data.dataSet=this.decouple(a.data.dataSet),a.data.dataSet instanceof Array||(a.data.dataSet=[a.data.dataSet]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._data._insertHandle(b[d],e);else e=this._data._data.length,this._data._insertHandle(a.data.dataSet,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._data.name()+'"'),g=this._data.primaryKey(),f=this._data._handleUpdate(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._data._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._data._updateSpliceMove(this._data._data,i,e);break;case"remove":if(this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._data.name()+'"'),this._data.remove(a.data.query,a.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;c>d;d++)this._activeBucket.remove(b[d])}},o.prototype._collectionDropped=function(a){a&&delete this._from},o.prototype.ensureIndex=function(){return this._data.ensureIndex.apply(this._data,arguments)},o.prototype.on=function(){return this._data.on.apply(this._data,arguments)},o.prototype.off=function(){return this._data.off.apply(this._data,arguments)},o.prototype.emit=function(){return this._data.emit.apply(this._data,arguments)},o.prototype.deferEmit=function(){return this._data.deferEmit.apply(this._data,arguments)},o.prototype.distinct=function(a,b,c){return this._data.distinct(a,b,c)},o.prototype.primaryKey=function(){return this._data.primaryKey()},o.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._data&&this._data.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._data,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},o.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),(void 0!==a||void 0!==b)&&(void 0===c||c===!0)&&this.refresh(),void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this._querySettings},o.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(),void 0!==e&&this.emit("queryChange",e)},o.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(),void 0!==d&&this.emit("queryChange",d)}},o.prototype.query=new n({"":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._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),(void 0!==a||void 0!==b)&&(void 0===c||c===!0)&&this.refresh(),void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this._querySettings}}),o.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},o.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},o.prototype.pageFirst=function(){return this.page(0)},o.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},o.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)}},o.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),void 0!==a&&this.emit("queryOptionsChange",a),this):this._querySettings.options},o.prototype.rebuildActiveBucket=function(a){if(a){var b=this._data._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._data.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},o.prototype.refresh=function(){var a,b,c,d,e=this;if(this._from&&(this._data.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._data.insert(a),this._data._data.$cursor=a.$cursor,this._data._data.$cursor=a.$cursor),this._querySettings&&this._querySettings.options&&this._querySettings.options.$join&&this._querySettings.options.$join.length){if(e.__joinChange=e.__joinChange||function(){e._joinChange()},this._joinCollections&&this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).off("immediateChange",e.__joinChange);for(b=this._querySettings.options.$join,this._joinCollections=[],c=0;c<b.length;c++)for(d in b[c])b[c].hasOwnProperty(d)&&this._joinCollections.push(d);if(this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).on("immediateChange",e.__joinChange)}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},o.prototype._joinChange=function(a,b){this.emit("joinChange"),this.refresh()},o.prototype.count=function(){return this._data.count.apply(this._data,arguments)},o.prototype.subset=function(){return this._data.subset.apply(this._data,arguments)},o.prototype.transform=function(a){var b,c;return b=this._data.transform(),this._data.transform(a),c=this._data.transform(),c.enabled&&c.dataIn&&(b.enabled!==c.enabled||b.dataIn!==c.dataIn)&&this.refresh(),c},o.prototype.filter=function(a,b,c){return this._data.filter(a,b,c)},o.prototype.data=function(){return this._data},o.prototype.indexOf=function(){return this._data.indexOf.apply(this._data,arguments)},d.synthesize(o.prototype,"db",function(a){return a&&(this._data.db(a),this.debug(a.debug()),this._data.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),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 o(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 o?a:this._view[a]?this._view[a]:((this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=new o(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=o},{"./ActiveBucket":3,"./Collection":6,"./CollectionGroup":7,"./Overload":27,"./ReactorIO":29,"./Shared":31}]},{},[1]); |
node_modules/axios/lib/helpers/cookies.js | sanj44/icicibot | 'use strict';
var utils = require('./../utils');
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
|
reactjs/src/App.js | damien-otis/ui-exercise | import React, { Component } from 'react';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<p>Your code here</p>
</div>
);
}
}
export default App;
|
ajax/libs/antd-mobile/0.9.0-beta.0/antd-mobile.min.js | tholu/cdnjs | /*!
* antd-mobile v0.9.0-beta.0
*
* Copyright 2015-present, Alipay, Inc.
* All rights reserved.
*/
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports["antd-mobile"]=t(require("react"),require("react-dom")):e["antd-mobile"]=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}(function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))switch(typeof e[t]){case"function":break;case"object":e[t]=function(t){var n=t.slice(1),r=e[t[0]];return function(e,t,o){r.apply(this,[e,t,o].concat(n))}}(e[t]);break;default:e[t]=e[e[t]]}return e}([function(e,t,n){e.exports=n(127)},function(t,n){t.exports=e},function(e,t){"use strict";t.__esModule=!0,t["default"]=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(222),i=r(o),a=n(219),s=r(a),l=n(31),u=r(l);t["default"]=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+("undefined"==typeof t?"undefined":(0,u["default"])(t)));e.prototype=(0,s["default"])(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(i["default"]?(0,i["default"])(e,t):e.__proto__=t)}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(31),i=r(o);t["default"]=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==("undefined"==typeof t?"undefined":(0,i["default"])(t))&&"function"!=typeof t?e:t}},function(e,t,n){var r,o;/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
!function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var o=typeof r;if("string"===o||"number"===o)e.push(r);else if(Array.isArray(r))e.push(n.apply(null,r));else if("object"===o)for(var a in r)i.call(r,a)&&r[a]&&e.push(a)}}return e.join(" ")}var i={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=n:(r=[],o=function(){return n}.apply(t,r),!(void 0!==o&&(e.exports=o)))}()},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(220),i=r(o);t["default"]=function(e,t,n){return t in e?(0,i["default"])(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}},function(e,t,n){"use strict";n(324),n(313)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(218),i=r(o);t["default"]=i["default"]||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}},function(e,n){e.exports=t},function(e,t){"use strict";function n(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function r(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var o={};return"abcdefghijklmnopqrst".split("").forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(i){return!1}}var o=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;e.exports=r()?Object.assign:function(e,t){for(var r,a,s=n(e),l=1;l<arguments.length;l++){r=Object(arguments[l]);for(var u in r)o.call(r,u)&&(s[u]=r[u]);if(Object.getOwnPropertySymbols){a=Object.getOwnPropertySymbols(r);for(var c=0;c<a.length;c++)i.call(r,a[c])&&(s[a[c]]=r[a[c]])}}return s}},function(e,t){var n=e.exports={version:"2.4.0"};"number"==typeof __e&&(__e=n)},function(e,t,n){var r=n(60)("wks"),o=n(39),i=n(15).Symbol,a="function"==typeof i,s=e.exports=function(e){return r[e]||(r[e]=a&&i[e]||(a?i:o)("Symbol."+e))};s.store=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),i=r(o),a=n(1),s=r(a);t["default"]=function(e){var t=e.type,n=e.className,r=void 0===n?"":n;return s["default"].createElement("i",(0,i["default"])({},e,{className:(r+" anticon anticon-"+t).trim()}))},e.exports=t["default"]},function(e,t,n){var r=n(15),o=n(11),i=n(52),a=n(27),s="prototype",l=function(e,t,n){var u,c,d,f=e&l.F,p=e&l.G,h=e&l.S,m=e&l.P,v=e&l.B,y=e&l.W,g=p?o:o[t]||(o[t]={}),b=g[s],_=p?r:h?r[t]:(r[t]||{})[s];p&&(n=t);for(u in n)c=!f&&_&&void 0!==_[u],c&&u in g||(d=c?_[u]:n[u],g[u]=p&&"function"!=typeof _[u]?n[u]:v&&c?i(d,r):y&&_[u]==d?function(e){var t=function(t,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,r)}return e.apply(this,arguments)};return t[s]=e[s],t}(d):m&&"function"==typeof d?i(Function.call,d):d,m&&((g.virtual||(g.virtual={}))[u]=d,e&l.R&&b&&!b[u]&&a(b,u,d)))};l.F=1,l.G=2,l.S=4,l.P=8,l.B=16,l.W=32,l.U=64,l.R=128,e.exports=l},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){var r=n(18),o=n(94),i=n(62),a=Object.defineProperty;t.f=n(19)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),o)try{return a(e,t,n)}catch(s){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(217),i=r(o),a=n(216),s=r(a);t["default"]=function(){function e(e,t){var n=[],r=!0,o=!1,i=void 0;try{for(var a,l=(0,s["default"])(e);!(r=(a=l.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(u){o=!0,i=u}finally{try{!r&&l["return"]&&l["return"]()}finally{if(o)throw i}}return n}return function(t,n){if(Array.isArray(t))return t;if((0,i["default"])(Object(t)))return e(t,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}()},function(e,t,n){var r=n(32);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t,n){e.exports=!n(26)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){var r=n(95),o=n(53);e.exports=function(e){return r(o(e))}},function(e,t){"use strict";function n(e,t){var n={},r={};return Object.keys(e).forEach(function(o){t.indexOf(o)!==-1?n[o]=e[o]:r[o]=e[o]}),[n,r]}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";n(291)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(159),m=r(h),v=n(5),y=r(v),g=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.children,o=t.className,a=t.style,s=t.renderHeader,l=t.renderFooter,u=(0,y["default"])((e={},(0,i["default"])(e,n,!0),(0,i["default"])(e,o,o),e));return p["default"].createElement("div",{className:u,style:a},s?p["default"].createElement("div",{className:n+"-header"},s()):null,r?p["default"].createElement("div",{className:n+"-body"},r):null,l?p["default"].createElement("div",{className:n+"-footer"},l()):null)},t}(p["default"].Component);t["default"]=g,g.Item=m["default"],g.defaultProps={prefixCls:"am-list"},e.exports=t["default"]},[441,295],function(e,t){e.exports=function(e){try{return!!e()}catch(t){return!0}}},function(e,t,n){var r=n(16),o=n(33);e.exports=n(19)?function(e,t,n){return r.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t){e.exports={}},function(e,t,n){var r=n(99),o=n(54);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(148),i=r(o),a=n(149),s=r(a);i["default"].Item=s["default"],t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(224),i=r(o),a=n(223),s=r(a),l="function"==typeof s["default"]&&"symbol"==typeof i["default"]?function(e){return typeof e}:function(e){return e&&"function"==typeof s["default"]&&e.constructor===s["default"]?"symbol":typeof e};t["default"]="function"==typeof s["default"]&&"symbol"===l(i["default"])?function(e){return"undefined"==typeof e?"undefined":l(e)}:function(e){return e&&"function"==typeof s["default"]&&e.constructor===s["default"]?"symbol":"undefined"==typeof e?"undefined":l(e)}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){"use strict";function r(e,t){return e+t}function o(e,t,n){var r=n;{if("object"!==("undefined"==typeof t?"undefined":S(t)))return"undefined"!=typeof r?("number"==typeof r&&(r+="px"),void(e.style[t]=r)):M(e,t);for(var i in t)t.hasOwnProperty(i)&&o(e,i,t[i])}}function i(e){var t=void 0,n=void 0,r=void 0,o=e.ownerDocument,i=o.body,a=o&&o.documentElement;return t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=a.clientLeft||i.clientLeft||0,r-=a.clientTop||i.clientTop||0,{left:n,top:r}}function a(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function s(e){return a(e)}function l(e){return a(e,!0)}function u(e){var t=i(e),n=e.ownerDocument,r=n.defaultView||n.parentWindow;return t.left+=s(r),t.top+=l(r),t}function c(e,t,n){var r=n,o="",i=e.ownerDocument;return r=r||i.defaultView.getComputedStyle(e,null),r&&(o=r.getPropertyValue(t)||r[t]),o}function d(e,t){var n=e[N]&&e[N][t];if(k.test(n)&&!O.test(t)){var r=e.style,o=r[R],i=e[D][R];e[D][R]=e[N][R],r[R]="fontSize"===t?"1em":n||0,n=r.pixelLeft+A,r[R]=o,e[D][R]=i}return""===n?"auto":n}function f(e,t){return"left"===e?t.useCssRight?"right":e:t.useCssBottom?"bottom":e}function p(e){return"left"===e?"right":"right"===e?"left":"top"===e?"bottom":"bottom"===e?"top":void 0}function h(e,t,n){"static"===o(e,"position")&&(e.style.position="relative");var i=-999,a=-999,s=f("left",n),l=f("top",n),c=p(s),d=p(l);"left"!==s&&(i=999),"top"!==l&&(a=999);var h="",m=u(e);("left"in t||"top"in t)&&(h=(0,P.getTransitionProperty)(e)||"",(0,P.setTransitionProperty)(e,"none")),"left"in t&&(e.style[c]="",e.style[s]=i+"px"),"top"in t&&(e.style[d]="",e.style[l]=a+"px");var v=u(e),y={};for(var g in t)if(t.hasOwnProperty(g)){var b=f(g,n),_="left"===g?i:a,x=m[g]-v[g];b===g?y[b]=_+x:y[b]=_-x}o(e,y),r(e.offsetTop,e.offsetLeft),("left"in t||"top"in t)&&(0,P.setTransitionProperty)(e,h);var T={};for(var C in t)if(t.hasOwnProperty(C)){var w=f(C,n),S=t[C]-m[C];C===w?T[w]=y[w]+S:T[w]=y[w]-S}o(e,T)}function m(e,t){var n=u(e),r=(0,P.getTransformXY)(e),o={x:r.x,y:r.y};"left"in t&&(o.x=r.x+t.left-n.left),"top"in t&&(o.y=r.y+t.top-n.top),(0,P.setTransformXY)(e,o)}function v(e,t,n){n.useCssRight||n.useCssBottom?h(e,t,n):n.useCssTransform&&(0,P.getTransformName)()in document.body.style?m(e,t,n):h(e,t,n)}function y(e,t){for(var n=0;n<e.length;n++)t(e[n])}function g(e){return"border-box"===M(e,"boxSizing")}function b(e,t,n){var r={},o=e.style,i=void 0;for(i in t)t.hasOwnProperty(i)&&(r[i]=o[i],o[i]=t[i]);n.call(e);for(i in t)t.hasOwnProperty(i)&&(o[i]=r[i])}function _(e,t,n){var r=0,o=void 0,i=void 0,a=void 0;for(i=0;i<t.length;i++)if(o=t[i])for(a=0;a<n.length;a++){var s=void 0;s="border"===o?""+o+n[a]+"Width":o+n[a],r+=parseFloat(M(e,s))||0}return r}function x(e){return null!==e&&void 0!==e&&e==e.window}function T(e,t,n){var r=n;if(x(e))return"width"===t?Y.viewportWidth(e):Y.viewportHeight(e);if(9===e.nodeType)return"width"===t?Y.docWidth(e):Y.docHeight(e);var o="width"===t?["Left","Right"]:["Top","Bottom"],i="width"===t?e.offsetWidth:e.offsetHeight,a=M(e),s=g(e,a),l=0;(null===i||void 0===i||i<=0)&&(i=void 0,l=M(e,t),(null===l||void 0===l||Number(l)<0)&&(l=e.style[t]||0),l=parseFloat(l)||0),void 0===r&&(r=s?W:j);var u=void 0!==i||s,c=i||l;return r===j?u?c-_(e,["border","padding"],o,a):l:u?r===W?c:c+(r===L?-_(e,["border"],o,a):_(e,["margin"],o,a)):l+_(e,I.slice(r),o,a)}function C(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=void 0,o=t[0];return 0!==o.offsetWidth?r=T.apply(void 0,t):b(o,F,function(){r=T.apply(void 0,t)}),r}function w(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}Object.defineProperty(t,"__esModule",{value:!0});var S="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},P=n(278),E=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,M=void 0,k=new RegExp("^("+E+")(?!px)[a-z%]+$","i"),O=/^(top|right|bottom|left)$/,N="currentStyle",D="runtimeStyle",R="left",A="px";"undefined"!=typeof window&&(M=window.getComputedStyle?c:d);var I=["margin","border","padding"],j=-1,L=2,W=1,H=0,Y={};y(["Width","Height"],function(e){Y["doc"+e]=function(t){var n=t.document;return Math.max(n.documentElement["scroll"+e],n.body["scroll"+e],Y["viewport"+e](n))},Y["viewport"+e]=function(t){var n="client"+e,r=t.document,o=r.body,i=r.documentElement,a=i[n];return"CSS1Compat"===r.compatMode&&a||o&&o[n]||a}});var F={position:"absolute",visibility:"hidden",display:"block"};y(["width","height"],function(e){var t=e.charAt(0).toUpperCase()+e.slice(1);Y["outer"+t]=function(t,n){return t&&C(t,e,n?H:W)};var n="width"===e?["Left","Right"]:["Top","Bottom"];Y[e]=function(t,r){var i=r;{if(void 0===i)return t&&C(t,e,j);if(t){var a=M(t),s=g(t);return s&&(i+=_(t,["padding","border"],n,a)),o(t,e,i)}}}});var V={getWindow:function(e){if(e&&e.document&&e.setTimeout)return e;var t=e.ownerDocument||e;return t.defaultView||t.parentWindow},offset:function(e,t,n){return"undefined"==typeof t?u(e):void v(e,t,n||{})},isWindow:x,each:y,css:o,clone:function(e){var t=void 0,n={};for(t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);var r=e.overflow;if(r)for(t in e)e.hasOwnProperty(t)&&(n.overflow[t]=e.overflow[t]);return n},mix:w,getWindowScrollLeft:function(e){return s(e)},getWindowScrollTop:function(e){return l(e)},merge:function(){for(var e={},t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];for(var o=0;o<n.length;o++)V.mix(e,n[o]);return e},viewportWidth:0,viewportHeight:0};w(V,Y),t["default"]=V,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=arguments.length<=1||void 0===arguments[1]?"":arguments[1],n=l["default"].createClass({displayName:"TouchableFeedbackComponent",statics:{myName:t||"TouchableFeedbackComponent"},getInitialState:function(){return{touchFeedback:!1}},setTouchFeedbackState:function(e){this.setState({touchFeedback:e})},onTouchStart:function(e){this.props.onTouchStart&&this.props.onTouchStart(e),this.setTouchFeedbackState(!0)},onTouchEnd:function(e){this.props.onTouchEnd&&this.props.onTouchEnd(e),this.setTouchFeedbackState(!1)},onTouchCancel:function(e){this.props.onTouchCancel&&this.props.onTouchCancel(e),this.setTouchFeedbackState(!1)},onMouseDown:function(e){this.props.onTouchStart&&this.props.onTouchStart(e),this.setTouchFeedbackState(!0)},onMouseUp:function(e){this.props.onTouchEnd&&this.props.onTouchEnd(e),this.setTouchFeedbackState(!1)},render:function(){var t=u?{onTouchStart:this.onTouchStart,onTouchEnd:this.onTouchEnd,onTouchCancel:this.onTouchCancel}:{onMouseDown:this.onMouseDown,onMouseUp:this.onMouseUp};return l["default"].createElement(e,(0,a["default"])({},this.props,{touchFeedback:this.state.touchFeedback},t))}});return n}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=r(i);t["default"]=o;var s=n(1),l=r(s),u="undefined"!=typeof window&&"ontouchstart"in window;e.exports=t["default"]},[441,289],function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){var r=n(53);e.exports=function(e){return Object(r(e))}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t,n){"use strict";var r=n(256)(!0);n(96)(String,"String",function(e){this._t=String(e),this._i=0},function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){"use strict";var r=n(328),o=r;e.exports=o},function(e,t,n){"use strict";e.exports=n(351)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),i=r(o),a=n(1),s=r(a),l=n(360),u=r(l),c=n(115),d=r(c),f=s["default"].createClass({displayName:"DialogWrap",mixins:[(0,d["default"])({isVisible:function(e){return e.props.visible},autoDestroy:!1,getComponent:function(e,t){return s["default"].createElement(u["default"],(0,i["default"])({},e.props,t,{key:"dialog"}))}})],getDefaultProps:function(){return{visible:!1}},shouldComponentUpdate:function(e){var t=e.visible;return!(!this.props.visible&&!t)},componentWillUnmount:function(){this.props.visible?this.renderComponent({afterClose:this.removeContainer,onClose:function(){},visible:!1}):this.removeContainer()},getElement:function(e){return this._component.getElement(e)},render:function(){return null}});t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){var r=l["default"].unstable_batchedUpdates?function(e){l["default"].unstable_batchedUpdates(n,e)}:n;return(0,a["default"])(e,t,r)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var i=n(126),a=r(i),s=n(9),l=r(s);e.exports=t["default"]},function(e,t,n){"use strict";var r=n(342);e.exports=function(e,t,n,o){var i=n?n.call(o,e,t):void 0;if(void 0!==i)return!!i;if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var a=r(e),s=r(t),l=a.length;if(l!==s.length)return!1;o=o||null;for(var u=Object.prototype.hasOwnProperty.bind(t),c=0;c<l;c++){var d=a[c];if(!u(d))return!1;var f=e[d],p=t[d],h=n?n.call(o,f,p,d):void 0;if(h===!1||void 0===h&&f!==p)return!1}return!0}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){return"string"==typeof e}function i(e){return o(e.type)&&k(e.props.children)?b["default"].cloneElement(e,{},e.props.children.split("").join(" ")):o(e)?(k(e)&&(e=e.split("").join(" ")),b["default"].createElement("span",null,e)):e}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),s=r(a),l=n(6),u=r(l),c=n(17),d=r(c),f=n(2),p=r(f),h=n(4),m=r(h),v=n(3),y=r(v),g=n(1),b=r(g),_=n(5),x=r(_),T=n(13),C=r(T),w=n(22),S=r(w),P=n(35),E=r(P),M=/^[\u4e00-\u9fa5]{2}$/,k=M.test.bind(M),O=function(e){function t(){(0,p["default"])(this,t);for(var n=arguments.length,r=Array(n),o=0;o<n;o++)r[o]=arguments[o];var i=(0,m["default"])(this,e.call.apply(e,[this].concat(r)));return i.onClick=function(){i.props.onClick(i)},i}return(0,y["default"])(t,e),t.prototype.render=function(){var e,t=(0,S["default"])(this.props,["children","className","prefixCls","type","size","inline","disabled","htmlType","icon","loading","touchFeedback"]),n=(0,d["default"])(t,2),r=n[0],o=r.children,a=r.className,l=r.prefixCls,c=r.type,f=r.size,p=r.inline,h=r.disabled,m=r.htmlType,v=r.icon,y=r.loading,g=r.touchFeedback,_=n[1],T=(0,x["default"])((e={},(0,u["default"])(e,a,a),(0,u["default"])(e,l,!0),(0,u["default"])(e,l+"-primary","primary"===c),(0,u["default"])(e,l+"-ghost","ghost"===c),(0,u["default"])(e,l+"-warning","warning"===c),(0,u["default"])(e,l+"-small","small"===f),(0,u["default"])(e,l+"-loading",y),(0,u["default"])(e,l+"-inline",p),(0,u["default"])(e,l+"-disabled",h),(0,u["default"])(e,l+"-touchFeedback",g),e)),w=y?"loading":v,P=b["default"].Children.map(o,i);return b["default"].createElement("button",(0,s["default"])({},_,{type:m||"button",className:T,disabled:h,onClick:this.onClick}),w?b["default"].createElement(C["default"],{type:w}):null,P)},t}(b["default"].Component);O.defaultProps={prefixCls:"am-button",size:"large",inline:!1,disabled:!1,loading:!1,onClick:function(){}},t["default"]=(0,E["default"])(O),e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(2),i=r(o),a=n(4),s=r(a),l=n(3),u=r(l),c=n(1),d=r(c),f=n(108),p=r(f),h=function(e){function t(){return(0,i["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.style,r=e.name,o=e.defaultChecked,i=e.checked,a=e.disabled,s=e.className,l=e.onChange;return d["default"].createElement(p["default"],{prefixCls:t,className:s,style:n,checked:i,defaultChecked:o,name:r,onChange:l,disabled:a})},t}(d["default"].Component);t["default"]=h,h.defaultProps={prefixCls:"am-checkbox"},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(8),i=r(o),a=n(6),s=r(a),l=n(2),u=r(l),c=n(4),d=r(c),f=n(3),p=r(f),h=n(1),m=r(h),v=n(43),y=r(v),g=n(5),b=r(g),_=n(10),x=r(_),T=n(163),C=r(T),w=function(e){function t(){return(0,u["default"])(this,t),(0,d["default"])(this,e.apply(this,arguments))}return(0,p["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.className,o=t.transparent,a=t.animated,l=t.transitionName,u=t.maskTransitionName,c=t.style,d=t.footer,f=(0,b["default"])((e={},(0,s["default"])(e,r,!!r),(0,s["default"])(e,n+"-transparent",o),e)),p=l||(a?o?"am-fade":"am-slide-up":null),h=u||(a?o?"am-fade":"am-slide-up":null),v=n+"-button-group-"+(2===d.length?"h":"v"),g=d.length?[m["default"].createElement("div",{key:"footer",className:v},d.map(function(e,t){return m["default"].createElement(C["default"],{prefixCls:n,button:e,key:t})}))]:null,_=o?(0,x["default"])({width:"5.4rem",height:"auto"},c):(0,x["default"])({width:"100%",height:"100%"},c),T=(0,x["default"])({},this.props);return["prefixCls","className","transparent","animated","transitionName","maskTransitionName","style","footer","touchFeedback"].forEach(function(e){T.hasOwnProperty(e)&&delete T[e]}),m["default"].createElement(y["default"],(0,i["default"])({prefixCls:n,className:f,transitionName:p,maskTransitionName:h,style:_,footer:g},T))},t}(m["default"].Component);t["default"]=w,w.defaultProps={prefixCls:"am-modal",transparent:!1,animated:!0,style:{},onShow:function(){},footer:[]},e.exports=t["default"]},function(e,t){"use strict";t.__esModule=!0,t["default"]=function(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(215),i=r(o);t["default"]=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return(0,i["default"])(e)}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){var r=n(236);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t){e.exports=!0},function(e,t,n){var r=n(18),o=n(251),i=n(54),a=n(59)("IE_PROTO"),s=function(){},l="prototype",u=function(){var e,t=n(93)("iframe"),r=i.length,o="<",a=">";for(t.style.display="none",n(241).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write(o+"script"+a+"document.F=Object"+o+"/script"+a),e.close(),u=e.F;r--;)delete u[l][i[r]];return u()};e.exports=Object.create||function(e,t){var n;return null!==e?(s[l]=r(e),n=new s,s[l]=null,n[a]=e):n=u(),void 0===t?n:o(n,t)}},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){var r=n(16).f,o=n(20),i=n(12)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t})}},function(e,t,n){var r=n(60)("keys"),o=n(39);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t,n){var r=n(15),o="__core-js_shared__",i=r[o]||(r[o]={});e.exports=function(e){return i[e]||(i[e]={})}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){var r=n(32);e.exports=function(e,t){if(!r(e))return e;var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t,n){var r=n(15),o=n(11),i=n(55),a=n(64),s=n(16).f;e.exports=function(e){var t=o.Symbol||(o.Symbol=i?{}:r.Symbol||{});"_"==e.charAt(0)||e in t||s(t,e,{value:a.f(e)})}},function(e,t,n){t.f=n(12)},function(e,t,n){n(261);for(var r=n(15),o=n(27),i=n(28),a=n(12)("toStringTag"),s=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],l=0;l<5;l++){var u=s[l],c=r[u],d=c&&c.prototype;d&&!d[a]&&o(d,a,u),i[u]=i.Array}},function(e,t,n){"use strict";function r(e,t,n,r,o,i,a,s){if(!e){var l;if(void 0===t)l=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var u=[n,r,o,i,a,s],c=0;l=new Error(t.replace(/%s/g,function(){return u[c++]})),l.name="Invariant Violation"}throw l.framesToPop=1,l}}e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),i=r(o),a=n(6),s=r(a),l=n(1),u=r(l),c=n(5),d=r(c),f=n(68),p=u["default"].createClass({displayName:"TabContent",propTypes:{animated:l.PropTypes.bool,prefixCls:l.PropTypes.string,children:l.PropTypes.any,activeKey:l.PropTypes.string,style:l.PropTypes.any,tabBarPosition:l.PropTypes.string},getDefaultProps:function(){return{animated:!0}},getTabPanes:function(){var e=this.props,t=e.activeKey,n=e.children,r=[];return u["default"].Children.forEach(n,function(n){var o=n.key,i=t===o;r.push(u["default"].cloneElement(n,{active:i,destroyInactiveTabPane:e.destroyInactiveTabPane,rootPrefixCls:e.prefixCls}))}),r},render:function(){var e,t=this.props,n=t.prefixCls,r=t.children,o=t.activeKey,a=t.tabBarPosition,l=t.animated,c=t.style,p=(0,d["default"])((e={},(0,s["default"])(e,n+"-content",!0),(0,s["default"])(e,l?n+"-content-animated":n+"-content-no-animated",!0),e));if(l){var h=(0,f.getActiveIndex)(r,o);c=h!==-1?(0,i["default"])({},c,(0,f.getTransformPropValue)((0,f.getTransformByIndex)(h,a))):(0,i["default"])({},c,{display:"none"})}return u["default"].createElement("div",{className:p,style:c},this.getTabPanes())}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e))return e;var t=[];return h["default"].Children.forEach(e,function(e){return t.push(e)}),t}function i(e,t){for(var n=o(e),r=0;r<n.length;r++)if(n[r].key===t)return r;return-1}function a(e,t){var n=o(e);return n[t].key}function s(e,t){e.transform=t,e.webkitTransform=t,e.mozTransform=t}function l(e){return"transform"in e||"webkitTransform"in e||"MozTransform"in e}function u(e,t){e.transition=t,e.webkitTransition=t,e.MozTransition=t}function c(e){return{transform:e,WebkitTransform:e,MozTransform:e}}function d(e){return"left"===e||"right"===e}function f(e,t){var n=d(t)?"translateY":"translateX";return n+"("+100*-e+"%) translateZ(0)"}Object.defineProperty(t,"__esModule",{value:!0}),t.toArray=o,t.getActiveIndex=i,t.getActiveKey=a,t.setTransform=s,t.isTransformSupported=l,t.setTransition=u,t.getTransformPropValue=c,t.isVertical=d,t.getTransformByIndex=f;var p=n(1),h=r(p)},function(e,t,n){function r(e,t){t.hasOwnProperty("vertical")&&console.warn("vertical is deprecated, please use `direction` instead");var n=t.direction;(n||t.hasOwnProperty("vertical"))&&(direction=n?n:t.vertical?"DIRECTION_ALL":"DIRECTION_HORIZONTAL",e.get("pan").set({direction:a[direction]}),e.get("swipe").set({direction:a[direction]})),t.options&&Object.keys(t.options).forEach(function(n){if("recognizers"===n)Object.keys(t.options.recognizers).forEach(function(n){var r=e.get(n);r.set(t.options.recognizers[n])},this);else{var r=n,o={};o[r]=t.options[n],e.set(o)}},this),t.recognizeWith&&Object.keys(t.recognizeWith).forEach(function(n){var r=e.get(n);r.recognizeWith(t.recognizeWith[n])},this),Object.keys(t).forEach(function(n){var r=l[n];r&&(e.off(r),e.on(r,t[n]))})}var o=n(1),i=n(9),a="undefined"!=typeof window?n(336):void 0,s={children:!0,direction:!0,options:!0,recognizeWith:!0,vertical:!0},l={action:"tap press",onDoubleTap:"doubletap",onPan:"pan",onPanCancel:"pancancel",onPanEnd:"panend",onPanStart:"panstart",onPinch:"pinch",onPinchCancel:"pinchcancel",onPinchEnd:"pinchend",onPinchIn:"pinchin",onPinchOut:"pinchout",onPinchStart:"pinchstart",onPress:"press",onPressUp:"pressup",onRotate:"rotate",onRotateCancel:"rotatecancel",onRotateEnd:"rotateend",onRotateMove:"rotatemove",onRotateStart:"rotatestart",onSwipe:"swipe",onTap:"tap"};Object.keys(l).forEach(function(e){s[e]=!0});var u=o.createClass({displayName:"Hammer",propTypes:{className:o.PropTypes.string},componentDidMount:function(){this.hammer=new a(i.findDOMNode(this)),r(this.hammer,this.props)},componentDidUpdate:function(){this.hammer&&r(this.hammer,this.props)},componentWillUnmount:function(){this.hammer&&(this.hammer.stop(),this.hammer.destroy()),this.hammer=null},render:function(){var e={};return Object.keys(this.props).forEach(function(t){s[t]||(e[t]=this.props[t])},this),o.cloneElement(o.Children.only(this.props.children),e)}});e.exports=u},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(119),i=r(o),a=n(421),s=r(a);i["default"].IndexedList=s["default"],t["default"]=i["default"],e.exports=t["default"]},function(e,t){function n(e,t,n){n=n||{},n.childrenKeyName=n.childrenKeyName||"children";var r,o=e||[],i=[],a=0;do{var r=o.filter(function(e){return t(e,a)})[0];if(!r)break;i.push(r),o=r[n.childrenKeyName]||[],a+=1}while(o.length>0);return i}e.exports=n},function(e,t){"use strict";function n(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return 1===t.length?r.apply(void 0,t):o.apply(void 0,t)}function r(e){var t=void 0;return"undefined"!=typeof Reflect&&"function"==typeof Reflect.ownKeys?t=Reflect.ownKeys(e.prototype):(t=Object.getOwnPropertyNames(e.prototype),"function"==typeof Object.getOwnPropertySymbols&&(t=t.concat(Object.getOwnPropertySymbols(e.prototype)))),t.forEach(function(t){if("constructor"!==t){var n=Object.getOwnPropertyDescriptor(e.prototype,t);"function"==typeof n.value&&Object.defineProperty(e.prototype,t,o(e,t,n))}}),e}function o(e,t,n){var r=n.value;if("function"!=typeof r)throw new Error("@autobind decorator can only be applied to methods not: "+typeof r);return{configurable:!0,get:function(){if(this===e.prototype||this.hasOwnProperty(t))return r;var n=r.bind(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n}}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t,n=this.props,r=n.text,o=n.prefixCls,a=n.overflowCount,s=n.className,l=n.style,u=n.children,c=this.props.dot,d=this.props.size,f=this.props.corner;r=r>a?a+"+":r,c&&(r="");var h=!(r&&"0"!==r||c),v=(0,m["default"])((e={},(0,i["default"])(e,o+"-dot",c),(0,i["default"])(e,o+"-dot-large",c&&"large"===d),(0,i["default"])(e,o+"-text",!c&&!f),(0,i["default"])(e,o+"-corner",f),(0,i["default"])(e,o+"-corner-large",f&&"large"===d),e)),y=(0,m["default"])((t={},(0,i["default"])(t,s,!!s),(0,i["default"])(t,o,!0),(0,i["default"])(t,o+"-not-a-wrapper",!u),(0,i["default"])(t,o+"-corner-wrapper",f),(0,i["default"])(t,o+"-corner-wrapper-large",f&&"large"===d),t));return p["default"].createElement("span",{className:y,title:r},u,!h&&p["default"].createElement("sup",{className:v,style:l},r))},t}(p["default"].Component);t["default"]=v,v.defaultProps={prefixCls:"am-badge",text:null,dot:!1,corner:!1,overflowCount:99,size:null},e.exports=t["default"]},[442,283],[442,284],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(8),i=r(o),a=n(6),s=r(a),l=n(2),u=r(l),c=n(4),d=r(c),f=n(3),p=r(f),h=n(1),m=r(h),v=n(5),y=r(v),g=n(343),b=r(g),_=n(10),x=r(_),T=function(e){function t(n){(0,u["default"])(this,t);var r=(0,d["default"])(this,e.call(this,n));return r.state={selectedIndex:r.props.selectedIndex
},r.onChange=r.onChange.bind(r),r}return(0,p["default"])(t,e),t.prototype.onChange=function(e){this.setState({selectedIndex:e})},t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.children,r=this.state.selectedIndex,o=void 0;if(!n)return null;var a=(0,x["default"])({},this.props);a.infinite&&(a.wrapAround=!0),a.selectedIndex&&(a.slideIndex=a.selectedIndex),a.beforeChange&&(a.beforeSlide=a.beforeChange),a.afterChange&&(a.afterSlide=a.afterChange),a.vertical&&(o=a.prefixCls+" "+a.prefixCls+"-vertical");var l=[{component:m["default"].createClass({displayName:"component",render:function(){var e=this,n=this.getIndexes(e.props.slideCount,e.props.slidesToScroll);return m["default"].createElement("div",{className:t+"-wrap"},n.map(function(e){var n,o=(0,y["default"])((n={},(0,s["default"])(n,t+"-wrap-dot",!0),(0,s["default"])(n,t+"-wrap-dot-active",e===r),n));return m["default"].createElement("div",{className:o,key:e},m["default"].createElement("span",null))}))},getIndexes:function(e,t){for(var n=[],r=0;r<e;r+=t)n.push(r);return n}}),position:"BottomCenter"}];return m["default"].createElement("div",{className:o},m["default"].createElement(b["default"],(0,i["default"])({},a,{decorators:l,afterSlide:this.onChange})))},t}(m["default"].Component);t["default"]=T,T.defaultProps={prefixCls:"am-carousel",dots:!0,arrows:!1,autoplay:!1,infinite:!1,edgeEasing:"linear",cellAlign:"center",selectedIndex:0},e.exports=t["default"]},[441,286],[443,287],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n=(0,c["default"])(e,["renderHeader","renderFooter","renderSectionHeader","renderRow"]),r=(0,a["default"])(n,2),o=r[0],i=o.renderHeader,s=o.renderFooter,u=o.renderSectionHeader,d=o.renderRow,f=r[1],h=e.listPrefixCls,m={renderHeader:null,renderFooter:null,renderSectionHeader:null,renderBodyComponent:function(){return l["default"].createElement("div",{className:h+"-body"})},renderRow:d};return i&&(m.renderHeader=function(){return l["default"].createElement("div",{className:h+"-header"},i())}),s&&(m.renderFooter=function(){return l["default"].createElement("div",{className:h+"-footer"},s())}),u&&(m.renderSectionHeader=t?function(e,t){return l["default"].createElement("div",null,l["default"].createElement(p,null,u(e,t)))}:function(e,t){return l["default"].createElement(p,null,u(e,t))}),{restProps:f,extraProps:m}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(17),a=r(i);t["default"]=o;var s=n(1),l=r(s),u=n(22),c=r(u),d=n(24),f=r(d),p=f["default"].Item;e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(48),i=r(o),a=n(164),s=r(a),l=n(165),u=r(l);i["default"].alert=s["default"],i["default"].prompt=u["default"],t["default"]=i["default"],e.exports=t["default"]},[441,297],[441,301],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(8),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(108),m=r(h),v=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){return p["default"].createElement(m["default"],(0,i["default"])({},this.props,{type:"radio"}))},t}(p["default"].Component);t["default"]=v,v.defaultProps={prefixCls:"am-radio"},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(83),i=r(o),a=n(180),s=r(a);i["default"].RadioItem=s["default"],t["default"]=i["default"],e.exports=t["default"]},[443,305],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){return f=u["default"].newInstance({prefixCls:p,style:{top:0},transitionName:"am-fade"})}function i(e,t){var n=arguments.length<=2||void 0===arguments[2]?3:arguments[2],r=arguments[3],i={info:"",success:"check-circle-o",fail:"cross-circle-o",offline:"frown",loading:"loading"}[t];"function"==typeof n&&(r=n,n=3);var a=o();a.notice({duration:n,style:{},content:i?s["default"].createElement("div",{className:p+"-text "+p+"-text-icon"},s["default"].createElement(d["default"],{type:i}),s["default"].createElement("div",null,e)):s["default"].createElement("div",{className:p+"-text"},s["default"].createElement("div",null,e)),onClose:function(){r&&r(),a.destroy(),a=null,f=null}})}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),s=r(a),l=n(368),u=r(l),c=n(13),d=r(c),f=void 0,p="am-toast";t["default"]={SHORT:3,LONG:8,show:function(e,t){return i(e,"info",t,function(){})},info:function(e,t,n){return i(e,"info",t,n)},success:function(e,t,n){return i(e,"success",t,n)},fail:function(e,t,n){return i(e,"fail",t,n)},offline:function(e,t,n){return i(e,"offline",t,n)},loading:function(e,t,n){return i(e,"loading",t,n)},hide:function(){f&&(f.destroy(),f=null)}},e.exports=t["default"]},[442,321],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(2),i=r(o),a=n(4),s=r(a),l=n(3),u=r(l),c=n(1),d=r(c),f=n(10),p=r(f),h=function(e){function t(){return(0,i["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t.prototype.render=function(){var e=(0,p["default"])({},this.props);Array.isArray(e.style)&&!function(){var t={};e.style.forEach(function(e){(0,p["default"])(t,e)}),e.style=t}();var t=e.Component;return d["default"].createElement(t,e)},t}(d["default"].Component);t["default"]=h,h.defaultProps={Component:"div"},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.size,o=t.className,a=t.children,s=t.style,l=(0,m["default"])((e={},(0,i["default"])(e,""+n,!0),(0,i["default"])(e,n+"-"+r,!0),(0,i["default"])(e,o,!!o),e));return p["default"].createElement("div",{className:l,style:s},a)},t}(p["default"].Component);t["default"]=v,v.defaultProps={prefixCls:"am-wingblank",size:"lg"},e.exports=t["default"]},[441,323],function(e,t){e.exports=function(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0;n<e.length;++n)if(e[n]===t)return n;return-1}},function(e,t,n){var r=n(51),o=n(12)("toStringTag"),i="Arguments"==r(function(){return arguments}()),a=function(e,t){try{return e[t]}catch(n){}};e.exports=function(e){var t,n,s;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=a(t=Object(e),o))?n:i?r(t):"Object"==(s=r(t))&&"function"==typeof t.callee?"Arguments":s}},function(e,t,n){var r=n(32),o=n(15).document,i=r(o)&&r(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t,n){e.exports=!n(19)&&!n(26)(function(){return 7!=Object.defineProperty(n(93)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(51);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e)}},function(e,t,n){"use strict";var r=n(55),o=n(14),i=n(100),a=n(27),s=n(20),l=n(28),u=n(245),c=n(58),d=n(253),f=n(12)("iterator"),p=!([].keys&&"next"in[].keys()),h="@@iterator",m="keys",v="values",y=function(){return this};e.exports=function(e,t,n,g,b,_,x){u(n,t,g);var T,C,w,S=function(e){if(!p&&e in k)return k[e];switch(e){case m:return function(){return new n(this,e)};case v:return function(){return new n(this,e)}}return function(){return new n(this,e)}},P=t+" Iterator",E=b==v,M=!1,k=e.prototype,O=k[f]||k[h]||b&&k[b],N=O||S(b),D=b?E?S("entries"):N:void 0,R="Array"==t?k.entries||O:O;if(R&&(w=d(R.call(new e)),w!==Object.prototype&&(c(w,P,!0),r||s(w,f)||a(w,f,y))),E&&O&&O.name!==v&&(M=!0,N=function(){return O.call(this)}),r&&!x||!p&&!M&&k[f]||a(k,f,N),l[t]=N,l[P]=y,b)if(T={values:E?N:S(v),keys:_?N:S(m),entries:D},x)for(C in T)C in k||i(k,C,T[C]);else o(o.P+o.F*(p||M),t,T);return T}},function(e,t,n){var r=n(37),o=n(33),i=n(21),a=n(62),s=n(20),l=n(94),u=Object.getOwnPropertyDescriptor;t.f=n(19)?u:function(e,t){if(e=i(e),t=a(t,!0),l)try{return u(e,t)}catch(n){}if(s(e,t))return o(!r.f.call(e,t),e[t])}},function(e,t,n){var r=n(99),o=n(54).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return r(e,o)}},function(e,t,n){var r=n(20),o=n(21),i=n(238)(!1),a=n(59)("IE_PROTO");e.exports=function(e,t){var n,s=o(e),l=0,u=[];for(n in s)n!=a&&r(s,n)&&u.push(n);for(;t.length>l;)r(s,n=t[l++])&&(~i(u,n)||u.push(n));return u}},function(e,t,n){e.exports=n(27)},function(e,t,n){var r=n(61),o=Math.min;e.exports=function(e){return e>0?o(r(e),9007199254740991):0}},function(e,t,n){var r=n(92),o=n(12)("iterator"),i=n(28);e.exports=n(11).getIteratorMethod=function(e){if(void 0!=e)return e[o]||e["@@iterator"]||i[r(e)]}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=window.getComputedStyle(e),r="",o=0;o<h.length&&!(r=n.getPropertyValue(h[o]+t));o++);return r}function i(e){if(f){var t=parseFloat(o(e,"transition-delay"))||0,n=parseFloat(o(e,"transition-duration"))||0,r=parseFloat(o(e,"animation-delay"))||0,i=parseFloat(o(e,"animation-duration"))||0,a=Math.max(n+t,i+r);e.rcEndAnimTimeout=setTimeout(function(){e.rcEndAnimTimeout=null,e.rcEndListener&&e.rcEndListener()},1e3*a+200)}}function a(e){e.rcEndAnimTimeout&&(clearTimeout(e.rcEndAnimTimeout),e.rcEndAnimTimeout=null)}Object.defineProperty(t,"__esModule",{value:!0});var s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},l=n(271),u=r(l),c=n(225),d=r(c),f=0!==u["default"].endEvents.length,p=["Webkit","Moz","O","ms"],h=["-webkit-","-moz-","-o-","ms-",""],m=function(e,t,n){var r="object"===("undefined"==typeof t?"undefined":s(t)),o=r?t.name:t,l=r?t.active:t+"-active",c=n,f=void 0,p=void 0,h=(0,d["default"])(e);return n&&"[object Object]"===Object.prototype.toString.call(n)&&(c=n.end,f=n.start,p=n.active),e.rcEndListener&&e.rcEndListener(),e.rcEndListener=function(t){t&&t.target!==e||(e.rcAnimTimeout&&(clearTimeout(e.rcAnimTimeout),e.rcAnimTimeout=null),a(e),h.remove(o),h.remove(l),u["default"].removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,c&&c())},u["default"].addEndEventListener(e,e.rcEndListener),f&&f(),h.add(o),e.rcAnimTimeout=setTimeout(function(){e.rcAnimTimeout=null,h.add(l),p&&setTimeout(p,0),i(e)},30),{stop:function(){e.rcEndListener&&e.rcEndListener()}}};m.style=function(e,t,n){e.rcEndListener&&e.rcEndListener(),e.rcEndListener=function(t){t&&t.target!==e||(e.rcAnimTimeout&&(clearTimeout(e.rcAnimTimeout),e.rcAnimTimeout=null),a(e),u["default"].removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,n&&n())},u["default"].addEndEventListener(e,e.rcEndListener),e.rcAnimTimeout=setTimeout(function(){for(var n in t)t.hasOwnProperty(n)&&(e.style[n]=t[n]);e.rcAnimTimeout=null,i(e)},0)},m.setTransition=function(e,t,n){var r=t,o=n;void 0===n&&(o=r,r=""),r=r||"",p.forEach(function(t){e.style[t+"Transition"+r]=o})},m.isCssAnimationSupported=f,t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.ownerDocument,n=t.body,r=void 0,o=a["default"].css(e,"position"),i="fixed"===o||"absolute"===o;if(!i)return"html"===e.nodeName.toLowerCase()?null:e.parentNode;for(r=e.parentNode;r&&r!==n;r=r.parentNode)if(o=a["default"].css(r,"position"),"static"!==o)return r;return null}Object.defineProperty(t,"__esModule",{value:!0});var i=n(34),a=r(i);t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";e.exports=function(e,t){var n=!0;return function(r){n&&(n=!1,setTimeout(function(){n=!0},t),e(r))}}},function(e,t){!function(n,r){"object"==typeof t&&"undefined"!=typeof e?e.exports=r():"function"==typeof define&&define.amd?define(r):n.moment=r()}(this,function(){"use strict";function t(){return hr.apply(null,arguments)}function n(e){hr=e}function r(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function o(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function i(e){var t;for(t in e)return!1;return!0}function a(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function s(e,t){var n,r=[];for(n=0;n<e.length;++n)r.push(t(e[n],n));return r}function l(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function u(e,t){for(var n in t)l(t,n)&&(e[n]=t[n]);return l(t,"toString")&&(e.toString=t.toString),l(t,"valueOf")&&(e.valueOf=t.valueOf),e}function c(e,t,n,r){return yt(e,t,n,r,!0).utc()}function d(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],meridiem:null}}function f(e){return null==e._pf&&(e._pf=d()),e._pf}function p(e){if(null==e._isValid){var t=f(e),n=mr.call(t.parsedDateParts,function(e){return null!=e}),r=!isNaN(e._d.getTime())&&t.overflow<0&&!t.empty&&!t.invalidMonth&&!t.invalidWeekday&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&n);if(e._strict&&(r=r&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour),null!=Object.isFrozen&&Object.isFrozen(e))return r;e._isValid=r}return e._isValid}function h(e){var t=c(NaN);return null!=e?u(f(t),e):f(t).userInvalidated=!0,t}function m(e){return void 0===e}function v(e,t){var n,r,o;if(m(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),m(t._i)||(e._i=t._i),m(t._f)||(e._f=t._f),m(t._l)||(e._l=t._l),m(t._strict)||(e._strict=t._strict),m(t._tzm)||(e._tzm=t._tzm),m(t._isUTC)||(e._isUTC=t._isUTC),m(t._offset)||(e._offset=t._offset),m(t._pf)||(e._pf=f(t)),m(t._locale)||(e._locale=t._locale),vr.length>0)for(n in vr)r=vr[n],o=t[r],m(o)||(e[r]=o);return e}function y(e){v(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),yr===!1&&(yr=!0,t.updateOffset(this),yr=!1)}function g(e){return e instanceof y||null!=e&&null!=e._isAMomentObject}function b(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function _(e){var t=+e,n=0;return 0!==t&&isFinite(t)&&(n=b(t)),n}function x(e,t,n){var r,o=Math.min(e.length,t.length),i=Math.abs(e.length-t.length),a=0;for(r=0;r<o;r++)(n&&e[r]!==t[r]||!n&&_(e[r])!==_(t[r]))&&a++;return a+i}function T(e){t.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function C(e,n){var r=!0;return u(function(){if(null!=t.deprecationHandler&&t.deprecationHandler(null,e),r){for(var o,i=[],a=0;a<arguments.length;a++){if(o="","object"==typeof arguments[a]){o+="\n["+a+"] ";for(var s in arguments[0])o+=s+": "+arguments[0][s]+", ";o=o.slice(0,-2)}else o=arguments[a];i.push(o)}T(e+"\nArguments: "+Array.prototype.slice.call(i).join("")+"\n"+(new Error).stack),r=!1}return n.apply(this,arguments)},n)}function w(e,n){null!=t.deprecationHandler&&t.deprecationHandler(e,n),gr[e]||(T(n),gr[e]=!0)}function S(e){return e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function P(e){var t,n;for(n in e)t=e[n],S(t)?this[n]=t:this["_"+n]=t;this._config=e,this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)}function E(e,t){var n,r=u({},e);for(n in t)l(t,n)&&(o(e[n])&&o(t[n])?(r[n]={},u(r[n],e[n]),u(r[n],t[n])):null!=t[n]?r[n]=t[n]:delete r[n]);for(n in e)l(e,n)&&!l(t,n)&&o(e[n])&&(r[n]=u({},r[n]));return r}function M(e){null!=e&&this.set(e)}function k(e,t,n){var r=this._calendar[e]||this._calendar.sameElse;return S(r)?r.call(t,n):r}function O(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.replace(/MMMM|MM|DD|dddd/g,function(e){return e.slice(1)}),this._longDateFormat[e])}function N(){return this._invalidDate}function D(e){return this._ordinal.replace("%d",e)}function R(e,t,n,r){var o=this._relativeTime[n];return S(o)?o(e,t,n,r):o.replace(/%d/i,e)}function A(e,t){var n=this._relativeTime[e>0?"future":"past"];return S(n)?n(t):n.replace(/%s/i,t)}function I(e,t){var n=e.toLowerCase();Er[n]=Er[n+"s"]=Er[t]=e}function j(e){return"string"==typeof e?Er[e]||Er[e.toLowerCase()]:void 0}function L(e){var t,n,r={};for(n in e)l(e,n)&&(t=j(n),t&&(r[t]=e[n]));return r}function W(e,t){Mr[e]=t}function H(e){var t=[];for(var n in e)t.push({unit:n,priority:Mr[n]});return t.sort(function(e,t){return e.priority-t.priority}),t}function Y(e,n){return function(r){return null!=r?(V(this,e,r),t.updateOffset(this,n),this):F(this,e)}}function F(e,t){return e.isValid()?e._d["get"+(e._isUTC?"UTC":"")+t]():NaN}function V(e,t,n){e.isValid()&&e._d["set"+(e._isUTC?"UTC":"")+t](n)}function B(e){return e=j(e),S(this[e])?this[e]():this}function z(e,t){if("object"==typeof e){e=L(e);for(var n=H(e),r=0;r<n.length;r++)this[n[r].unit](e[n[r].unit])}else if(e=j(e),S(this[e]))return this[e](t);return this}function U(e,t,n){var r=""+Math.abs(e),o=t-r.length,i=e>=0;return(i?n?"+":"":"-")+Math.pow(10,Math.max(0,o)).toString().substr(1)+r}function X(e,t,n,r){var o=r;"string"==typeof r&&(o=function(){return this[r]()}),e&&(Dr[e]=o),t&&(Dr[t[0]]=function(){return U(o.apply(this,arguments),t[1],t[2])}),n&&(Dr[n]=function(){return this.localeData().ordinal(o.apply(this,arguments),e)})}function K(e){return e.match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"")}function G(e){var t,n,r=e.match(kr);for(t=0,n=r.length;t<n;t++)Dr[r[t]]?r[t]=Dr[r[t]]:r[t]=K(r[t]);return function(t){var o,i="";for(o=0;o<n;o++)i+=r[o]instanceof Function?r[o].call(t,e):r[o];return i}}function q(e,t){return e.isValid()?(t=Z(t,e.localeData()),Nr[t]=Nr[t]||G(t),Nr[t](e)):e.localeData().invalidDate()}function Z(e,t){function n(e){return t.longDateFormat(e)||e}var r=5;for(Or.lastIndex=0;r>=0&&Or.test(e);)e=e.replace(Or,n),Or.lastIndex=0,r-=1;return e}function Q(e,t,n){Zr[e]=S(t)?t:function(e,r){return e&&n?n:t}}function $(e,t){return l(Zr,e)?Zr[e](t._strict,t._locale):new RegExp(J(e))}function J(e){return ee(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,n,r,o){return t||n||r||o}))}function ee(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function te(e,t){var n,r=t;for("string"==typeof e&&(e=[e]),"number"==typeof t&&(r=function(e,n){n[t]=_(e)}),n=0;n<e.length;n++)Qr[e[n]]=r}function ne(e,t){te(e,function(e,n,r,o){r._w=r._w||{},t(e,r._w,r,o)})}function re(e,t,n){null!=t&&l(Qr,e)&&Qr[e](t,n._a,n,e)}function oe(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}function ie(e,t){return e?r(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||so).test(t)?"format":"standalone"][e.month()]:this._months}function ae(e,t){return e?r(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[so.test(t)?"format":"standalone"][e.month()]:this._monthsShort}function se(e,t,n){var r,o,i,a=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],r=0;r<12;++r)i=c([2e3,r]),this._shortMonthsParse[r]=this.monthsShort(i,"").toLocaleLowerCase(),this._longMonthsParse[r]=this.months(i,"").toLocaleLowerCase();return n?"MMM"===t?(o=_r.call(this._shortMonthsParse,a),o!==-1?o:null):(o=_r.call(this._longMonthsParse,a),o!==-1?o:null):"MMM"===t?(o=_r.call(this._shortMonthsParse,a),o!==-1?o:(o=_r.call(this._longMonthsParse,a),o!==-1?o:null)):(o=_r.call(this._longMonthsParse,a),o!==-1?o:(o=_r.call(this._shortMonthsParse,a),o!==-1?o:null))}function le(e,t,n){var r,o,i;if(this._monthsParseExact)return se.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),r=0;r<12;r++){if(o=c([2e3,r]),n&&!this._longMonthsParse[r]&&(this._longMonthsParse[r]=new RegExp("^"+this.months(o,"").replace(".","")+"$","i"),this._shortMonthsParse[r]=new RegExp("^"+this.monthsShort(o,"").replace(".","")+"$","i")),n||this._monthsParse[r]||(i="^"+this.months(o,"")+"|^"+this.monthsShort(o,""),this._monthsParse[r]=new RegExp(i.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[r].test(e))return r;if(n&&"MMM"===t&&this._shortMonthsParse[r].test(e))return r;if(!n&&this._monthsParse[r].test(e))return r}}function ue(e,t){var n;if(!e.isValid())return e;if("string"==typeof t)if(/^\d+$/.test(t))t=_(t);else if(t=e.localeData().monthsParse(t),"number"!=typeof t)return e;return n=Math.min(e.date(),oe(e.year(),t)),e._d["set"+(e._isUTC?"UTC":"")+"Month"](t,n),e}function ce(e){return null!=e?(ue(this,e),t.updateOffset(this,!0),this):F(this,"Month")}function de(){return oe(this.year(),this.month())}function fe(e){return this._monthsParseExact?(l(this,"_monthsRegex")||he.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(l(this,"_monthsShortRegex")||(this._monthsShortRegex=co),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)}function pe(e){return this._monthsParseExact?(l(this,"_monthsRegex")||he.call(this),e?this._monthsStrictRegex:this._monthsRegex):(l(this,"_monthsRegex")||(this._monthsRegex=fo),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)}function he(){function e(e,t){return t.length-e.length}var t,n,r=[],o=[],i=[];for(t=0;t<12;t++)n=c([2e3,t]),r.push(this.monthsShort(n,"")),o.push(this.months(n,"")),i.push(this.months(n,"")),i.push(this.monthsShort(n,""));for(r.sort(e),o.sort(e),i.sort(e),t=0;t<12;t++)r[t]=ee(r[t]),o[t]=ee(o[t]);for(t=0;t<24;t++)i[t]=ee(i[t]);this._monthsRegex=new RegExp("^("+i.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+o.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+r.join("|")+")","i")}function me(e){return ve(e)?366:365}function ve(e){return e%4===0&&e%100!==0||e%400===0}function ye(){return ve(this.year())}function ge(e,t,n,r,o,i,a){var s=new Date(e,t,n,r,o,i,a);return e<100&&e>=0&&isFinite(s.getFullYear())&&s.setFullYear(e),s}function be(e){var t=new Date(Date.UTC.apply(null,arguments));return e<100&&e>=0&&isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e),t}function _e(e,t,n){var r=7+t-n,o=(7+be(e,0,r).getUTCDay()-t)%7;return-o+r-1}function xe(e,t,n,r,o){var i,a,s=(7+n-r)%7,l=_e(e,r,o),u=1+7*(t-1)+s+l;return u<=0?(i=e-1,a=me(i)+u):u>me(e)?(i=e+1,a=u-me(e)):(i=e,a=u),{year:i,dayOfYear:a}}function Te(e,t,n){var r,o,i=_e(e.year(),t,n),a=Math.floor((e.dayOfYear()-i-1)/7)+1;return a<1?(o=e.year()-1,r=a+Ce(o,t,n)):a>Ce(e.year(),t,n)?(r=a-Ce(e.year(),t,n),o=e.year()+1):(o=e.year(),r=a),{week:r,year:o}}function Ce(e,t,n){var r=_e(e,t,n),o=_e(e+1,t,n);return(me(e)-r+o)/7}function we(e){return Te(e,this._week.dow,this._week.doy).week}function Se(){return this._week.dow}function Pe(){return this._week.doy}function Ee(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")}function Me(e){var t=Te(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")}function ke(e,t){return"string"!=typeof e?e:isNaN(e)?(e=t.weekdaysParse(e),"number"==typeof e?e:null):parseInt(e,10)}function Oe(e,t){return"string"==typeof e?t.weekdaysParse(e)%7||7:isNaN(e)?null:e}function Ne(e,t){return e?r(this._weekdays)?this._weekdays[e.day()]:this._weekdays[this._weekdays.isFormat.test(t)?"format":"standalone"][e.day()]:this._weekdays}function De(e){return e?this._weekdaysShort[e.day()]:this._weekdaysShort}function Re(e){return e?this._weekdaysMin[e.day()]:this._weekdaysMin}function Ae(e,t,n){var r,o,i,a=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],r=0;r<7;++r)i=c([2e3,1]).day(r),this._minWeekdaysParse[r]=this.weekdaysMin(i,"").toLocaleLowerCase(),this._shortWeekdaysParse[r]=this.weekdaysShort(i,"").toLocaleLowerCase(),this._weekdaysParse[r]=this.weekdays(i,"").toLocaleLowerCase();return n?"dddd"===t?(o=_r.call(this._weekdaysParse,a),o!==-1?o:null):"ddd"===t?(o=_r.call(this._shortWeekdaysParse,a),o!==-1?o:null):(o=_r.call(this._minWeekdaysParse,a),o!==-1?o:null):"dddd"===t?(o=_r.call(this._weekdaysParse,a),o!==-1?o:(o=_r.call(this._shortWeekdaysParse,a),o!==-1?o:(o=_r.call(this._minWeekdaysParse,a),o!==-1?o:null))):"ddd"===t?(o=_r.call(this._shortWeekdaysParse,a),o!==-1?o:(o=_r.call(this._weekdaysParse,a),o!==-1?o:(o=_r.call(this._minWeekdaysParse,a),o!==-1?o:null))):(o=_r.call(this._minWeekdaysParse,a),o!==-1?o:(o=_r.call(this._weekdaysParse,a),o!==-1?o:(o=_r.call(this._shortWeekdaysParse,a),o!==-1?o:null)))}function Ie(e,t,n){var r,o,i;if(this._weekdaysParseExact)return Ae.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),r=0;r<7;r++){if(o=c([2e3,1]).day(r),n&&!this._fullWeekdaysParse[r]&&(this._fullWeekdaysParse[r]=new RegExp("^"+this.weekdays(o,"").replace(".",".?")+"$","i"),this._shortWeekdaysParse[r]=new RegExp("^"+this.weekdaysShort(o,"").replace(".",".?")+"$","i"),this._minWeekdaysParse[r]=new RegExp("^"+this.weekdaysMin(o,"").replace(".",".?")+"$","i")),this._weekdaysParse[r]||(i="^"+this.weekdays(o,"")+"|^"+this.weekdaysShort(o,"")+"|^"+this.weekdaysMin(o,""),this._weekdaysParse[r]=new RegExp(i.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[r].test(e))return r;if(n&&"ddd"===t&&this._shortWeekdaysParse[r].test(e))return r;if(n&&"dd"===t&&this._minWeekdaysParse[r].test(e))return r;if(!n&&this._weekdaysParse[r].test(e))return r}}function je(e){if(!this.isValid())return null!=e?this:NaN;var t=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=e?(e=ke(e,this.localeData()),this.add(e-t,"d")):t}function Le(e){if(!this.isValid())return null!=e?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return null==e?t:this.add(e-t,"d")}function We(e){if(!this.isValid())return null!=e?this:NaN;if(null!=e){var t=Oe(e,this.localeData());return this.day(this.day()%7?t:t-7)}return this.day()||7}function He(e){return this._weekdaysParseExact?(l(this,"_weekdaysRegex")||Ve.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(l(this,"_weekdaysRegex")||(this._weekdaysRegex=go),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)}function Ye(e){return this._weekdaysParseExact?(l(this,"_weekdaysRegex")||Ve.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(l(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=bo),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)}function Fe(e){return this._weekdaysParseExact?(l(this,"_weekdaysRegex")||Ve.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(l(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=_o),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)}function Ve(){function e(e,t){return t.length-e.length}var t,n,r,o,i,a=[],s=[],l=[],u=[];for(t=0;t<7;t++)n=c([2e3,1]).day(t),r=this.weekdaysMin(n,""),o=this.weekdaysShort(n,""),i=this.weekdays(n,""),a.push(r),s.push(o),l.push(i),u.push(r),u.push(o),u.push(i);for(a.sort(e),s.sort(e),l.sort(e),u.sort(e),t=0;t<7;t++)s[t]=ee(s[t]),l[t]=ee(l[t]),u[t]=ee(u[t]);this._weekdaysRegex=new RegExp("^("+u.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+l.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+s.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+a.join("|")+")","i")}function Be(){return this.hours()%12||12}function ze(){return this.hours()||24}function Ue(e,t){X(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}function Xe(e,t){return t._meridiemParse}function Ke(e){return"p"===(e+"").toLowerCase().charAt(0)}function Ge(e,t,n){return e>11?n?"pm":"PM":n?"am":"AM"}function qe(e){return e?e.toLowerCase().replace("_","-"):e}function Ze(e){for(var t,n,r,o,i=0;i<e.length;){for(o=qe(e[i]).split("-"),t=o.length,n=qe(e[i+1]),n=n?n.split("-"):null;t>0;){if(r=Qe(o.slice(0,t).join("-")))return r;if(n&&n.length>=t&&x(o,n,!0)>=t-1)break;t--}i++}return null}function Qe(t){var n=null;if(!So[t]&&"undefined"!=typeof e&&e&&e.require)try{n=xo._abbr,e.require("./locale/"+t),$e(n)}catch(r){}return So[t]}function $e(e,t){var n;return e&&(n=m(t)?tt(e):Je(e,t),n&&(xo=n)),xo._abbr}function Je(e,t){if(null!==t){var n=wo;return t.abbr=e,null!=So[e]?(w("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),n=So[e]._config):null!=t.parentLocale&&(null!=So[t.parentLocale]?n=So[t.parentLocale]._config:w("parentLocaleUndefined","specified parentLocale is not defined yet. See http://momentjs.com/guides/#/warnings/parent-locale/")),So[e]=new M(E(n,t)),$e(e),So[e]}return delete So[e],null}function et(e,t){if(null!=t){var n,r=wo;null!=So[e]&&(r=So[e]._config),t=E(r,t),n=new M(t),n.parentLocale=So[e],So[e]=n,$e(e)}else null!=So[e]&&(null!=So[e].parentLocale?So[e]=So[e].parentLocale:null!=So[e]&&delete So[e]);return So[e]}function tt(e){var t;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return xo;if(!r(e)){if(t=Qe(e))return t;e=[e]}return Ze(e)}function nt(){return br(So)}function rt(e){var t,n=e._a;return n&&f(e).overflow===-2&&(t=n[Jr]<0||n[Jr]>11?Jr:n[eo]<1||n[eo]>oe(n[$r],n[Jr])?eo:n[to]<0||n[to]>24||24===n[to]&&(0!==n[no]||0!==n[ro]||0!==n[oo])?to:n[no]<0||n[no]>59?no:n[ro]<0||n[ro]>59?ro:n[oo]<0||n[oo]>999?oo:-1,f(e)._overflowDayOfYear&&(t<$r||t>eo)&&(t=eo),f(e)._overflowWeeks&&t===-1&&(t=io),f(e)._overflowWeekday&&t===-1&&(t=ao),f(e).overflow=t),e}function ot(e){var t,n,r,o,i,a,s=e._i,l=Po.exec(s)||Eo.exec(s);if(l){for(f(e).iso=!0,t=0,n=ko.length;t<n;t++)if(ko[t][1].exec(l[1])){o=ko[t][0],r=ko[t][2]!==!1;break}if(null==o)return void(e._isValid=!1);if(l[3]){for(t=0,n=Oo.length;t<n;t++)if(Oo[t][1].exec(l[3])){i=(l[2]||" ")+Oo[t][0];break}if(null==i)return void(e._isValid=!1)}if(!r&&null!=i)return void(e._isValid=!1);if(l[4]){if(!Mo.exec(l[4]))return void(e._isValid=!1);a="Z"}e._f=o+(i||"")+(a||""),ct(e)}else e._isValid=!1}function it(e){var n=No.exec(e._i);return null!==n?void(e._d=new Date((+n[1]))):(ot(e),void(e._isValid===!1&&(delete e._isValid,t.createFromInputFallback(e))))}function at(e,t,n){return null!=e?e:null!=t?t:n}function st(e){var n=new Date(t.now());return e._useUTC?[n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()]:[n.getFullYear(),n.getMonth(),n.getDate()]}function lt(e){var t,n,r,o,i=[];if(!e._d){for(r=st(e),e._w&&null==e._a[eo]&&null==e._a[Jr]&&ut(e),e._dayOfYear&&(o=at(e._a[$r],r[$r]),e._dayOfYear>me(o)&&(f(e)._overflowDayOfYear=!0),n=be(o,0,e._dayOfYear),e._a[Jr]=n.getUTCMonth(),e._a[eo]=n.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=i[t]=r[t];for(;t<7;t++)e._a[t]=i[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[to]&&0===e._a[no]&&0===e._a[ro]&&0===e._a[oo]&&(e._nextDay=!0,e._a[to]=0),e._d=(e._useUTC?be:ge).apply(null,i),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[to]=24)}}function ut(e){var t,n,r,o,i,a,s,l;t=e._w,null!=t.GG||null!=t.W||null!=t.E?(i=1,a=4,n=at(t.GG,e._a[$r],Te(gt(),1,4).year),r=at(t.W,1),o=at(t.E,1),(o<1||o>7)&&(l=!0)):(i=e._locale._week.dow,a=e._locale._week.doy,n=at(t.gg,e._a[$r],Te(gt(),i,a).year),r=at(t.w,1),null!=t.d?(o=t.d,(o<0||o>6)&&(l=!0)):null!=t.e?(o=t.e+i,(t.e<0||t.e>6)&&(l=!0)):o=i),r<1||r>Ce(n,i,a)?f(e)._overflowWeeks=!0:null!=l?f(e)._overflowWeekday=!0:(s=xe(n,r,o,i,a),e._a[$r]=s.year,e._dayOfYear=s.dayOfYear)}function ct(e){if(e._f===t.ISO_8601)return void ot(e);e._a=[],f(e).empty=!0;var n,r,o,i,a,s=""+e._i,l=s.length,u=0;for(o=Z(e._f,e._locale).match(kr)||[],n=0;n<o.length;n++)i=o[n],r=(s.match($(i,e))||[])[0],
r&&(a=s.substr(0,s.indexOf(r)),a.length>0&&f(e).unusedInput.push(a),s=s.slice(s.indexOf(r)+r.length),u+=r.length),Dr[i]?(r?f(e).empty=!1:f(e).unusedTokens.push(i),re(i,r,e)):e._strict&&!r&&f(e).unusedTokens.push(i);f(e).charsLeftOver=l-u,s.length>0&&f(e).unusedInput.push(s),e._a[to]<=12&&f(e).bigHour===!0&&e._a[to]>0&&(f(e).bigHour=void 0),f(e).parsedDateParts=e._a.slice(0),f(e).meridiem=e._meridiem,e._a[to]=dt(e._locale,e._a[to],e._meridiem),lt(e),rt(e)}function dt(e,t,n){var r;return null==n?t:null!=e.meridiemHour?e.meridiemHour(t,n):null!=e.isPM?(r=e.isPM(n),r&&t<12&&(t+=12),r||12!==t||(t=0),t):t}function ft(e){var t,n,r,o,i;if(0===e._f.length)return f(e).invalidFormat=!0,void(e._d=new Date(NaN));for(o=0;o<e._f.length;o++)i=0,t=v({},e),null!=e._useUTC&&(t._useUTC=e._useUTC),t._f=e._f[o],ct(t),p(t)&&(i+=f(t).charsLeftOver,i+=10*f(t).unusedTokens.length,f(t).score=i,(null==r||i<r)&&(r=i,n=t));u(e,n||t)}function pt(e){if(!e._d){var t=L(e._i);e._a=s([t.year,t.month,t.day||t.date,t.hour,t.minute,t.second,t.millisecond],function(e){return e&&parseInt(e,10)}),lt(e)}}function ht(e){var t=new y(rt(mt(e)));return t._nextDay&&(t.add(1,"d"),t._nextDay=void 0),t}function mt(e){var t=e._i,n=e._f;return e._locale=e._locale||tt(e._l),null===t||void 0===n&&""===t?h({nullInput:!0}):("string"==typeof t&&(e._i=t=e._locale.preparse(t)),g(t)?new y(rt(t)):(r(n)?ft(e):a(t)?e._d=t:n?ct(e):vt(e),p(e)||(e._d=null),e))}function vt(e){var n=e._i;void 0===n?e._d=new Date(t.now()):a(n)?e._d=new Date(n.valueOf()):"string"==typeof n?it(e):r(n)?(e._a=s(n.slice(0),function(e){return parseInt(e,10)}),lt(e)):"object"==typeof n?pt(e):"number"==typeof n?e._d=new Date(n):t.createFromInputFallback(e)}function yt(e,t,n,a,s){var l={};return"boolean"==typeof n&&(a=n,n=void 0),(o(e)&&i(e)||r(e)&&0===e.length)&&(e=void 0),l._isAMomentObject=!0,l._useUTC=l._isUTC=s,l._l=n,l._i=e,l._f=t,l._strict=a,ht(l)}function gt(e,t,n,r){return yt(e,t,n,r,!1)}function bt(e,t){var n,o;if(1===t.length&&r(t[0])&&(t=t[0]),!t.length)return gt();for(n=t[0],o=1;o<t.length;++o)t[o].isValid()&&!t[o][e](n)||(n=t[o]);return n}function _t(){var e=[].slice.call(arguments,0);return bt("isBefore",e)}function xt(){var e=[].slice.call(arguments,0);return bt("isAfter",e)}function Tt(e){var t=L(e),n=t.year||0,r=t.quarter||0,o=t.month||0,i=t.week||0,a=t.day||0,s=t.hour||0,l=t.minute||0,u=t.second||0,c=t.millisecond||0;this._milliseconds=+c+1e3*u+6e4*l+1e3*s*60*60,this._days=+a+7*i,this._months=+o+3*r+12*n,this._data={},this._locale=tt(),this._bubble()}function Ct(e){return e instanceof Tt}function wt(e){return e<0?Math.round(-1*e)*-1:Math.round(e)}function St(e,t){X(e,0,0,function(){var e=this.utcOffset(),n="+";return e<0&&(e=-e,n="-"),n+U(~~(e/60),2)+t+U(~~e%60,2)})}function Pt(e,t){var n=(t||"").match(e)||[],r=n[n.length-1]||[],o=(r+"").match(Io)||["-",0,0],i=+(60*o[1])+_(o[2]);return"+"===o[0]?i:-i}function Et(e,n){var r,o;return n._isUTC?(r=n.clone(),o=(g(e)||a(e)?e.valueOf():gt(e).valueOf())-r.valueOf(),r._d.setTime(r._d.valueOf()+o),t.updateOffset(r,!1),r):gt(e).local()}function Mt(e){return 15*-Math.round(e._d.getTimezoneOffset()/15)}function kt(e,n){var r,o=this._offset||0;return this.isValid()?null!=e?("string"==typeof e?e=Pt(Kr,e):Math.abs(e)<16&&(e=60*e),!this._isUTC&&n&&(r=Mt(this)),this._offset=e,this._isUTC=!0,null!=r&&this.add(r,"m"),o!==e&&(!n||this._changeInProgress?Ut(this,Yt(e-o,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,t.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?o:Mt(this):null!=e?this:NaN}function Ot(e,t){return null!=e?("string"!=typeof e&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()}function Nt(e){return this.utcOffset(0,e)}function Dt(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Mt(this),"m")),this}function Rt(){if(this._tzm)this.utcOffset(this._tzm);else if("string"==typeof this._i){var e=Pt(Xr,this._i);0===e?this.utcOffset(0,!0):this.utcOffset(Pt(Xr,this._i))}return this}function At(e){return!!this.isValid()&&(e=e?gt(e).utcOffset():0,(this.utcOffset()-e)%60===0)}function It(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function jt(){if(!m(this._isDSTShifted))return this._isDSTShifted;var e={};if(v(e,this),e=mt(e),e._a){var t=e._isUTC?c(e._a):gt(e._a);this._isDSTShifted=this.isValid()&&x(e._a,t.toArray())>0}else this._isDSTShifted=!1;return this._isDSTShifted}function Lt(){return!!this.isValid()&&!this._isUTC}function Wt(){return!!this.isValid()&&this._isUTC}function Ht(){return!!this.isValid()&&(this._isUTC&&0===this._offset)}function Yt(e,t){var n,r,o,i=e,a=null;return Ct(e)?i={ms:e._milliseconds,d:e._days,M:e._months}:"number"==typeof e?(i={},t?i[t]=e:i.milliseconds=e):(a=jo.exec(e))?(n="-"===a[1]?-1:1,i={y:0,d:_(a[eo])*n,h:_(a[to])*n,m:_(a[no])*n,s:_(a[ro])*n,ms:_(wt(1e3*a[oo]))*n}):(a=Lo.exec(e))?(n="-"===a[1]?-1:1,i={y:Ft(a[2],n),M:Ft(a[3],n),w:Ft(a[4],n),d:Ft(a[5],n),h:Ft(a[6],n),m:Ft(a[7],n),s:Ft(a[8],n)}):null==i?i={}:"object"==typeof i&&("from"in i||"to"in i)&&(o=Bt(gt(i.from),gt(i.to)),i={},i.ms=o.milliseconds,i.M=o.months),r=new Tt(i),Ct(e)&&l(e,"_locale")&&(r._locale=e._locale),r}function Ft(e,t){var n=e&&parseFloat(e.replace(",","."));return(isNaN(n)?0:n)*t}function Vt(e,t){var n={milliseconds:0,months:0};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=+t-+e.clone().add(n.months,"M"),n}function Bt(e,t){var n;return e.isValid()&&t.isValid()?(t=Et(t,e),e.isBefore(t)?n=Vt(e,t):(n=Vt(t,e),n.milliseconds=-n.milliseconds,n.months=-n.months),n):{milliseconds:0,months:0}}function zt(e,t){return function(n,r){var o,i;return null===r||isNaN(+r)||(w(t,"moment()."+t+"(period, number) is deprecated. Please use moment()."+t+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),i=n,n=r,r=i),n="string"==typeof n?+n:n,o=Yt(n,r),Ut(this,o,e),this}}function Ut(e,n,r,o){var i=n._milliseconds,a=wt(n._days),s=wt(n._months);e.isValid()&&(o=null==o||o,i&&e._d.setTime(e._d.valueOf()+i*r),a&&V(e,"Date",F(e,"Date")+a*r),s&&ue(e,F(e,"Month")+s*r),o&&t.updateOffset(e,a||s))}function Xt(e,t){var n=e.diff(t,"days",!0);return n<-6?"sameElse":n<-1?"lastWeek":n<0?"lastDay":n<1?"sameDay":n<2?"nextDay":n<7?"nextWeek":"sameElse"}function Kt(e,n){var r=e||gt(),o=Et(r,this).startOf("day"),i=t.calendarFormat(this,o)||"sameElse",a=n&&(S(n[i])?n[i].call(this,r):n[i]);return this.format(a||this.localeData().calendar(i,this,gt(r)))}function Gt(){return new y(this)}function qt(e,t){var n=g(e)?e:gt(e);return!(!this.isValid()||!n.isValid())&&(t=j(m(t)?"millisecond":t),"millisecond"===t?this.valueOf()>n.valueOf():n.valueOf()<this.clone().startOf(t).valueOf())}function Zt(e,t){var n=g(e)?e:gt(e);return!(!this.isValid()||!n.isValid())&&(t=j(m(t)?"millisecond":t),"millisecond"===t?this.valueOf()<n.valueOf():this.clone().endOf(t).valueOf()<n.valueOf())}function Qt(e,t,n,r){return r=r||"()",("("===r[0]?this.isAfter(e,n):!this.isBefore(e,n))&&(")"===r[1]?this.isBefore(t,n):!this.isAfter(t,n))}function $t(e,t){var n,r=g(e)?e:gt(e);return!(!this.isValid()||!r.isValid())&&(t=j(t||"millisecond"),"millisecond"===t?this.valueOf()===r.valueOf():(n=r.valueOf(),this.clone().startOf(t).valueOf()<=n&&n<=this.clone().endOf(t).valueOf()))}function Jt(e,t){return this.isSame(e,t)||this.isAfter(e,t)}function en(e,t){return this.isSame(e,t)||this.isBefore(e,t)}function tn(e,t,n){var r,o,i,a;return this.isValid()?(r=Et(e,this),r.isValid()?(o=6e4*(r.utcOffset()-this.utcOffset()),t=j(t),"year"===t||"month"===t||"quarter"===t?(a=nn(this,r),"quarter"===t?a/=3:"year"===t&&(a/=12)):(i=this-r,a="second"===t?i/1e3:"minute"===t?i/6e4:"hour"===t?i/36e5:"day"===t?(i-o)/864e5:"week"===t?(i-o)/6048e5:i),n?a:b(a)):NaN):NaN}function nn(e,t){var n,r,o=12*(t.year()-e.year())+(t.month()-e.month()),i=e.clone().add(o,"months");return t-i<0?(n=e.clone().add(o-1,"months"),r=(t-i)/(i-n)):(n=e.clone().add(o+1,"months"),r=(t-i)/(n-i)),-(o+r)||0}function rn(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function on(){var e=this.clone().utc();return 0<e.year()&&e.year()<=9999?S(Date.prototype.toISOString)?this.toDate().toISOString():q(e,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]"):q(e,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}function an(e){e||(e=this.isUtc()?t.defaultFormatUtc:t.defaultFormat);var n=q(this,e);return this.localeData().postformat(n)}function sn(e,t){return this.isValid()&&(g(e)&&e.isValid()||gt(e).isValid())?Yt({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()}function ln(e){return this.from(gt(),e)}function un(e,t){return this.isValid()&&(g(e)&&e.isValid()||gt(e).isValid())?Yt({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()}function cn(e){return this.to(gt(),e)}function dn(e){var t;return void 0===e?this._locale._abbr:(t=tt(e),null!=t&&(this._locale=t),this)}function fn(){return this._locale}function pn(e){switch(e=j(e)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":case"date":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===e&&this.weekday(0),"isoWeek"===e&&this.isoWeekday(1),"quarter"===e&&this.month(3*Math.floor(this.month()/3)),this}function hn(e){return e=j(e),void 0===e||"millisecond"===e?this:("date"===e&&(e="day"),this.startOf(e).add(1,"isoWeek"===e?"week":e).subtract(1,"ms"))}function mn(){return this._d.valueOf()-6e4*(this._offset||0)}function vn(){return Math.floor(this.valueOf()/1e3)}function yn(){return new Date(this.valueOf())}function gn(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]}function bn(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}}function _n(){return this.isValid()?this.toISOString():null}function xn(){return p(this)}function Tn(){return u({},f(this))}function Cn(){return f(this).overflow}function wn(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}function Sn(e,t){X(0,[e,e.length],0,t)}function Pn(e){return On.call(this,e,this.week(),this.weekday(),this.localeData()._week.dow,this.localeData()._week.doy)}function En(e){return On.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)}function Mn(){return Ce(this.year(),1,4)}function kn(){var e=this.localeData()._week;return Ce(this.year(),e.dow,e.doy)}function On(e,t,n,r,o){var i;return null==e?Te(this,r,o).year:(i=Ce(e,r,o),t>i&&(t=i),Nn.call(this,e,t,n,r,o))}function Nn(e,t,n,r,o){var i=xe(e,t,n,r,o),a=be(i.year,0,i.dayOfYear);return this.year(a.getUTCFullYear()),this.month(a.getUTCMonth()),this.date(a.getUTCDate()),this}function Dn(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)}function Rn(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")}function An(e,t){t[oo]=_(1e3*("0."+e))}function In(){return this._isUTC?"UTC":""}function jn(){return this._isUTC?"Coordinated Universal Time":""}function Ln(e){return gt(1e3*e)}function Wn(){return gt.apply(null,arguments).parseZone()}function Hn(e){return e}function Yn(e,t,n,r){var o=tt(),i=c().set(r,t);return o[n](i,e)}function Fn(e,t,n){if("number"==typeof e&&(t=e,e=void 0),e=e||"",null!=t)return Yn(e,t,n,"month");var r,o=[];for(r=0;r<12;r++)o[r]=Yn(e,r,n,"month");return o}function Vn(e,t,n,r){"boolean"==typeof e?("number"==typeof t&&(n=t,t=void 0),t=t||""):(t=e,n=t,e=!1,"number"==typeof t&&(n=t,t=void 0),t=t||"");var o=tt(),i=e?o._week.dow:0;if(null!=n)return Yn(t,(n+i)%7,r,"day");var a,s=[];for(a=0;a<7;a++)s[a]=Yn(t,(a+i)%7,r,"day");return s}function Bn(e,t){return Fn(e,t,"months")}function zn(e,t){return Fn(e,t,"monthsShort")}function Un(e,t,n){return Vn(e,t,n,"weekdays")}function Xn(e,t,n){return Vn(e,t,n,"weekdaysShort")}function Kn(e,t,n){return Vn(e,t,n,"weekdaysMin")}function Gn(){var e=this._data;return this._milliseconds=qo(this._milliseconds),this._days=qo(this._days),this._months=qo(this._months),e.milliseconds=qo(e.milliseconds),e.seconds=qo(e.seconds),e.minutes=qo(e.minutes),e.hours=qo(e.hours),e.months=qo(e.months),e.years=qo(e.years),this}function qn(e,t,n,r){var o=Yt(t,n);return e._milliseconds+=r*o._milliseconds,e._days+=r*o._days,e._months+=r*o._months,e._bubble()}function Zn(e,t){return qn(this,e,t,1)}function Qn(e,t){return qn(this,e,t,-1)}function $n(e){return e<0?Math.floor(e):Math.ceil(e)}function Jn(){var e,t,n,r,o,i=this._milliseconds,a=this._days,s=this._months,l=this._data;return i>=0&&a>=0&&s>=0||i<=0&&a<=0&&s<=0||(i+=864e5*$n(tr(s)+a),a=0,s=0),l.milliseconds=i%1e3,e=b(i/1e3),l.seconds=e%60,t=b(e/60),l.minutes=t%60,n=b(t/60),l.hours=n%24,a+=b(n/24),o=b(er(a)),s+=o,a-=$n(tr(o)),r=b(s/12),s%=12,l.days=a,l.months=s,l.years=r,this}function er(e){return 4800*e/146097}function tr(e){return 146097*e/4800}function nr(e){var t,n,r=this._milliseconds;if(e=j(e),"month"===e||"year"===e)return t=this._days+r/864e5,n=this._months+er(t),"month"===e?n:n/12;switch(t=this._days+Math.round(tr(this._months)),e){case"week":return t/7+r/6048e5;case"day":return t+r/864e5;case"hour":return 24*t+r/36e5;case"minute":return 1440*t+r/6e4;case"second":return 86400*t+r/1e3;case"millisecond":return Math.floor(864e5*t)+r;default:throw new Error("Unknown unit "+e)}}function rr(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*_(this._months/12)}function or(e){return function(){return this.as(e)}}function ir(e){return e=j(e),this[e+"s"]()}function ar(e){return function(){return this._data[e]}}function sr(){return b(this.days()/7)}function lr(e,t,n,r,o){return o.relativeTime(t||1,!!n,e,r)}function ur(e,t,n){var r=Yt(e).abs(),o=di(r.as("s")),i=di(r.as("m")),a=di(r.as("h")),s=di(r.as("d")),l=di(r.as("M")),u=di(r.as("y")),c=o<fi.s&&["s",o]||i<=1&&["m"]||i<fi.m&&["mm",i]||a<=1&&["h"]||a<fi.h&&["hh",a]||s<=1&&["d"]||s<fi.d&&["dd",s]||l<=1&&["M"]||l<fi.M&&["MM",l]||u<=1&&["y"]||["yy",u];return c[2]=t,c[3]=+e>0,c[4]=n,lr.apply(null,c)}function cr(e){return void 0===e?di:"function"==typeof e&&(di=e,!0)}function dr(e,t){return void 0!==fi[e]&&(void 0===t?fi[e]:(fi[e]=t,!0))}function fr(e){var t=this.localeData(),n=ur(this,!e,t);return e&&(n=t.pastFuture(+this,n)),t.postformat(n)}function pr(){var e,t,n,r=pi(this._milliseconds)/1e3,o=pi(this._days),i=pi(this._months);e=b(r/60),t=b(e/60),r%=60,e%=60,n=b(i/12),i%=12;var a=n,s=i,l=o,u=t,c=e,d=r,f=this.asSeconds();return f?(f<0?"-":"")+"P"+(a?a+"Y":"")+(s?s+"M":"")+(l?l+"D":"")+(u||c||d?"T":"")+(u?u+"H":"")+(c?c+"M":"")+(d?d+"S":""):"P0D"}var hr,mr;mr=Array.prototype.some?Array.prototype.some:function(e){for(var t=Object(this),n=t.length>>>0,r=0;r<n;r++)if(r in t&&e.call(this,t[r],r,t))return!0;return!1};var vr=t.momentProperties=[],yr=!1,gr={};t.suppressDeprecationWarnings=!1,t.deprecationHandler=null;var br;br=Object.keys?Object.keys:function(e){var t,n=[];for(t in e)l(e,t)&&n.push(t);return n};var _r,xr={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},Tr={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},Cr="Invalid date",wr="%d",Sr=/\d{1,2}/,Pr={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},Er={},Mr={},kr=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,Or=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Nr={},Dr={},Rr=/\d/,Ar=/\d\d/,Ir=/\d{3}/,jr=/\d{4}/,Lr=/[+-]?\d{6}/,Wr=/\d\d?/,Hr=/\d\d\d\d?/,Yr=/\d\d\d\d\d\d?/,Fr=/\d{1,3}/,Vr=/\d{1,4}/,Br=/[+-]?\d{1,6}/,zr=/\d+/,Ur=/[+-]?\d+/,Xr=/Z|[+-]\d\d:?\d\d/gi,Kr=/Z|[+-]\d\d(?::?\d\d)?/gi,Gr=/[+-]?\d+(\.\d{1,3})?/,qr=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,Zr={},Qr={},$r=0,Jr=1,eo=2,to=3,no=4,ro=5,oo=6,io=7,ao=8;_r=Array.prototype.indexOf?Array.prototype.indexOf:function(e){var t;for(t=0;t<this.length;++t)if(this[t]===e)return t;return-1},X("M",["MM",2],"Mo",function(){return this.month()+1}),X("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)}),X("MMMM",0,0,function(e){return this.localeData().months(this,e)}),I("month","M"),W("month",8),Q("M",Wr),Q("MM",Wr,Ar),Q("MMM",function(e,t){return t.monthsShortRegex(e)}),Q("MMMM",function(e,t){return t.monthsRegex(e)}),te(["M","MM"],function(e,t){t[Jr]=_(e)-1}),te(["MMM","MMMM"],function(e,t,n,r){var o=n._locale.monthsParse(e,r,n._strict);null!=o?t[Jr]=o:f(n).invalidMonth=e});var so=/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/,lo="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),uo="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),co=qr,fo=qr;X("Y",0,0,function(){var e=this.year();return e<=9999?""+e:"+"+e}),X(0,["YY",2],0,function(){return this.year()%100}),X(0,["YYYY",4],0,"year"),X(0,["YYYYY",5],0,"year"),X(0,["YYYYYY",6,!0],0,"year"),I("year","y"),W("year",1),Q("Y",Ur),Q("YY",Wr,Ar),Q("YYYY",Vr,jr),Q("YYYYY",Br,Lr),Q("YYYYYY",Br,Lr),te(["YYYYY","YYYYYY"],$r),te("YYYY",function(e,n){n[$r]=2===e.length?t.parseTwoDigitYear(e):_(e)}),te("YY",function(e,n){n[$r]=t.parseTwoDigitYear(e)}),te("Y",function(e,t){t[$r]=parseInt(e,10)}),t.parseTwoDigitYear=function(e){return _(e)+(_(e)>68?1900:2e3)};var po=Y("FullYear",!0);X("w",["ww",2],"wo","week"),X("W",["WW",2],"Wo","isoWeek"),I("week","w"),I("isoWeek","W"),W("week",5),W("isoWeek",5),Q("w",Wr),Q("ww",Wr,Ar),Q("W",Wr),Q("WW",Wr,Ar),ne(["w","ww","W","WW"],function(e,t,n,r){t[r.substr(0,1)]=_(e)});var ho={dow:0,doy:6};X("d",0,"do","day"),X("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),X("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),X("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),X("e",0,0,"weekday"),X("E",0,0,"isoWeekday"),I("day","d"),I("weekday","e"),I("isoWeekday","E"),W("day",11),W("weekday",11),W("isoWeekday",11),Q("d",Wr),Q("e",Wr),Q("E",Wr),Q("dd",function(e,t){return t.weekdaysMinRegex(e)}),Q("ddd",function(e,t){return t.weekdaysShortRegex(e)}),Q("dddd",function(e,t){return t.weekdaysRegex(e)}),ne(["dd","ddd","dddd"],function(e,t,n,r){var o=n._locale.weekdaysParse(e,r,n._strict);null!=o?t.d=o:f(n).invalidWeekday=e}),ne(["d","e","E"],function(e,t,n,r){t[r]=_(e)});var mo="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),vo="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),yo="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),go=qr,bo=qr,_o=qr;X("H",["HH",2],0,"hour"),X("h",["hh",2],0,Be),X("k",["kk",2],0,ze),X("hmm",0,0,function(){return""+Be.apply(this)+U(this.minutes(),2)}),X("hmmss",0,0,function(){return""+Be.apply(this)+U(this.minutes(),2)+U(this.seconds(),2)}),X("Hmm",0,0,function(){return""+this.hours()+U(this.minutes(),2)}),X("Hmmss",0,0,function(){return""+this.hours()+U(this.minutes(),2)+U(this.seconds(),2)}),Ue("a",!0),Ue("A",!1),I("hour","h"),W("hour",13),Q("a",Xe),Q("A",Xe),Q("H",Wr),Q("h",Wr),Q("HH",Wr,Ar),Q("hh",Wr,Ar),Q("hmm",Hr),Q("hmmss",Yr),Q("Hmm",Hr),Q("Hmmss",Yr),te(["H","HH"],to),te(["a","A"],function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e}),te(["h","hh"],function(e,t,n){t[to]=_(e),f(n).bigHour=!0}),te("hmm",function(e,t,n){var r=e.length-2;t[to]=_(e.substr(0,r)),t[no]=_(e.substr(r)),f(n).bigHour=!0}),te("hmmss",function(e,t,n){var r=e.length-4,o=e.length-2;t[to]=_(e.substr(0,r)),t[no]=_(e.substr(r,2)),t[ro]=_(e.substr(o)),f(n).bigHour=!0}),te("Hmm",function(e,t,n){var r=e.length-2;t[to]=_(e.substr(0,r)),t[no]=_(e.substr(r))}),te("Hmmss",function(e,t,n){var r=e.length-4,o=e.length-2;t[to]=_(e.substr(0,r)),t[no]=_(e.substr(r,2)),t[ro]=_(e.substr(o))});var xo,To=/[ap]\.?m?\.?/i,Co=Y("Hours",!0),wo={calendar:xr,longDateFormat:Tr,invalidDate:Cr,ordinal:wr,ordinalParse:Sr,relativeTime:Pr,months:lo,monthsShort:uo,week:ho,weekdays:mo,weekdaysMin:yo,weekdaysShort:vo,meridiemParse:To},So={},Po=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/,Eo=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?/,Mo=/Z|[+-]\d\d(?::?\d\d)?/,ko=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/]],Oo=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],No=/^\/?Date\((\-?\d+)/i;t.createFromInputFallback=C("value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))}),t.ISO_8601=function(){};var Do=C("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=gt.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:h()}),Ro=C("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=gt.apply(null,arguments);return this.isValid()&&e.isValid()?e>this?this:e:h()}),Ao=function(){return Date.now?Date.now():+new Date};St("Z",":"),St("ZZ",""),Q("Z",Kr),Q("ZZ",Kr),te(["Z","ZZ"],function(e,t,n){n._useUTC=!0,n._tzm=Pt(Kr,e)});var Io=/([\+\-]|\d\d)/gi;t.updateOffset=function(){};var jo=/^(\-)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/,Lo=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/;Yt.fn=Tt.prototype;var Wo=zt(1,"add"),Ho=zt(-1,"subtract");t.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",t.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";var Yo=C("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return void 0===e?this.localeData():this.locale(e)});X(0,["gg",2],0,function(){return this.weekYear()%100}),X(0,["GG",2],0,function(){return this.isoWeekYear()%100}),Sn("gggg","weekYear"),Sn("ggggg","weekYear"),Sn("GGGG","isoWeekYear"),Sn("GGGGG","isoWeekYear"),I("weekYear","gg"),I("isoWeekYear","GG"),W("weekYear",1),W("isoWeekYear",1),Q("G",Ur),Q("g",Ur),Q("GG",Wr,Ar),Q("gg",Wr,Ar),Q("GGGG",Vr,jr),Q("gggg",Vr,jr),Q("GGGGG",Br,Lr),Q("ggggg",Br,Lr),ne(["gggg","ggggg","GGGG","GGGGG"],function(e,t,n,r){t[r.substr(0,2)]=_(e)}),ne(["gg","GG"],function(e,n,r,o){n[o]=t.parseTwoDigitYear(e)}),X("Q",0,"Qo","quarter"),I("quarter","Q"),W("quarter",7),Q("Q",Rr),te("Q",function(e,t){t[Jr]=3*(_(e)-1)}),X("D",["DD",2],"Do","date"),I("date","D"),W("date",9),Q("D",Wr),Q("DD",Wr,Ar),Q("Do",function(e,t){return e?t._ordinalParse:t._ordinalParseLenient}),te(["D","DD"],eo),te("Do",function(e,t){t[eo]=_(e.match(Wr)[0],10)});var Fo=Y("Date",!0);X("DDD",["DDDD",3],"DDDo","dayOfYear"),I("dayOfYear","DDD"),W("dayOfYear",4),Q("DDD",Fr),Q("DDDD",Ir),te(["DDD","DDDD"],function(e,t,n){n._dayOfYear=_(e)}),X("m",["mm",2],0,"minute"),I("minute","m"),W("minute",14),Q("m",Wr),Q("mm",Wr,Ar),te(["m","mm"],no);var Vo=Y("Minutes",!1);X("s",["ss",2],0,"second"),I("second","s"),W("second",15),Q("s",Wr),Q("ss",Wr,Ar),te(["s","ss"],ro);var Bo=Y("Seconds",!1);X("S",0,0,function(){return~~(this.millisecond()/100)}),X(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),X(0,["SSS",3],0,"millisecond"),X(0,["SSSS",4],0,function(){return 10*this.millisecond()}),X(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),X(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),X(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),X(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),X(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),I("millisecond","ms"),W("millisecond",16),Q("S",Fr,Rr),Q("SS",Fr,Ar),Q("SSS",Fr,Ir);var zo;for(zo="SSSS";zo.length<=9;zo+="S")Q(zo,zr);for(zo="S";zo.length<=9;zo+="S")te(zo,An);var Uo=Y("Milliseconds",!1);X("z",0,0,"zoneAbbr"),X("zz",0,0,"zoneName");var Xo=y.prototype;Xo.add=Wo,Xo.calendar=Kt,Xo.clone=Gt,Xo.diff=tn,Xo.endOf=hn,Xo.format=an,Xo.from=sn,Xo.fromNow=ln,Xo.to=un,Xo.toNow=cn,Xo.get=B,Xo.invalidAt=Cn,Xo.isAfter=qt,Xo.isBefore=Zt,Xo.isBetween=Qt,Xo.isSame=$t,Xo.isSameOrAfter=Jt,Xo.isSameOrBefore=en,Xo.isValid=xn,Xo.lang=Yo,Xo.locale=dn,Xo.localeData=fn,Xo.max=Ro,Xo.min=Do,Xo.parsingFlags=Tn,Xo.set=z,Xo.startOf=pn,Xo.subtract=Ho,Xo.toArray=gn,Xo.toObject=bn,Xo.toDate=yn,Xo.toISOString=on,Xo.toJSON=_n,Xo.toString=rn,Xo.unix=vn,Xo.valueOf=mn,Xo.creationData=wn,Xo.year=po,Xo.isLeapYear=ye,Xo.weekYear=Pn,Xo.isoWeekYear=En,Xo.quarter=Xo.quarters=Dn,Xo.month=ce,Xo.daysInMonth=de,Xo.week=Xo.weeks=Ee,Xo.isoWeek=Xo.isoWeeks=Me,Xo.weeksInYear=kn,Xo.isoWeeksInYear=Mn,Xo.date=Fo,Xo.day=Xo.days=je,Xo.weekday=Le,Xo.isoWeekday=We,Xo.dayOfYear=Rn,Xo.hour=Xo.hours=Co,Xo.minute=Xo.minutes=Vo,Xo.second=Xo.seconds=Bo,Xo.millisecond=Xo.milliseconds=Uo,Xo.utcOffset=kt,Xo.utc=Nt,Xo.local=Dt,Xo.parseZone=Rt,Xo.hasAlignedHourOffset=At,Xo.isDST=It,Xo.isLocal=Lt,Xo.isUtcOffset=Wt,Xo.isUtc=Ht,Xo.isUTC=Ht,Xo.zoneAbbr=In,Xo.zoneName=jn,Xo.dates=C("dates accessor is deprecated. Use date instead.",Fo),Xo.months=C("months accessor is deprecated. Use month instead",ce),Xo.years=C("years accessor is deprecated. Use year instead",po),Xo.zone=C("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",Ot),Xo.isDSTShifted=C("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",jt);var Ko=Xo,Go=M.prototype;Go.calendar=k,Go.longDateFormat=O,Go.invalidDate=N,Go.ordinal=D,Go.preparse=Hn,Go.postformat=Hn,Go.relativeTime=R,Go.pastFuture=A,Go.set=P,Go.months=ie,Go.monthsShort=ae,Go.monthsParse=le,Go.monthsRegex=pe,Go.monthsShortRegex=fe,Go.week=we,Go.firstDayOfYear=Pe,Go.firstDayOfWeek=Se,Go.weekdays=Ne,Go.weekdaysMin=Re,Go.weekdaysShort=De,Go.weekdaysParse=Ie,Go.weekdaysRegex=He,Go.weekdaysShortRegex=Ye,Go.weekdaysMinRegex=Fe,Go.isPM=Ke,Go.meridiem=Ge,$e("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10,n=1===_(e%100/10)?"th":1===t?"st":2===t?"nd":3===t?"rd":"th";return e+n}}),t.lang=C("moment.lang is deprecated. Use moment.locale instead.",$e),t.langData=C("moment.langData is deprecated. Use moment.localeData instead.",tt);var qo=Math.abs,Zo=or("ms"),Qo=or("s"),$o=or("m"),Jo=or("h"),ei=or("d"),ti=or("w"),ni=or("M"),ri=or("y"),oi=ar("milliseconds"),ii=ar("seconds"),ai=ar("minutes"),si=ar("hours"),li=ar("days"),ui=ar("months"),ci=ar("years"),di=Math.round,fi={s:45,m:45,h:22,d:26,M:11},pi=Math.abs,hi=Tt.prototype;hi.abs=Gn,hi.add=Zn,hi.subtract=Qn,hi.as=nr,hi.asMilliseconds=Zo,hi.asSeconds=Qo,hi.asMinutes=$o,hi.asHours=Jo,hi.asDays=ei,hi.asWeeks=ti,hi.asMonths=ni,hi.asYears=ri,hi.valueOf=rr,hi._bubble=Jn,hi.get=ir,hi.milliseconds=oi,hi.seconds=ii,hi.minutes=ai,hi.hours=si,hi.days=li,hi.weeks=sr,hi.months=ui,hi.years=ci,hi.humanize=fr,hi.toISOString=pr,hi.toString=pr,hi.toJSON=pr,hi.locale=dn,hi.localeData=fn,hi.toIsoString=C("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",pr),hi.lang=Yo,X("X",0,0,"unix"),X("x",0,0,"valueOf"),Q("x",Ur),Q("X",Gr),te("X",function(e,t,n){n._d=new Date(1e3*parseFloat(e,10))}),te("x",function(e,t,n){n._d=new Date(_(e))}),t.version="2.15.0",n(gt),t.fn=Ko,t.min=_t,t.max=xt,t.now=Ao,t.utc=c,t.unix=Ln,t.months=Bn,t.isDate=a,t.locale=$e,t.invalid=h,t.duration=Yt,t.isMoment=g,t.weekdays=Un,t.parseZone=Wn,t.localeData=tt,t.isDuration=Ct,t.monthsShort=zn,t.weekdaysMin=Kn,t.defineLocale=Je,t.updateLocale=et,t.locales=nt,t.weekdaysShort=Xn,t.normalizeUnits=j,t.relativeTimeRounding=cr,t.relativeTimeThreshold=dr,t.calendarFormat=Xt,t.prototype=Ko;var mi=t;return mi})},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={isAppearSupported:function(e){return e.transitionName&&e.transitionAppear||e.animation.appear},isEnterSupported:function(e){return e.transitionName&&e.transitionEnter||e.animation.enter},isLeaveSupported:function(e){return e.transitionName&&e.transitionLeave||e.animation.leave},allowAppearCallback:function(e){return e.transitionAppear||e.animation.appear},allowEnterCallback:function(e){return e.transitionEnter||e.animation.enter},allowLeaveCallback:function(e){return e.transitionLeave||e.animation.leave}};t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(354)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(45),s=r(a),l=i["default"].createClass({displayName:"ExpandIcon",propTypes:{record:o.PropTypes.object,prefixCls:o.PropTypes.string,expandable:o.PropTypes.any,expanded:o.PropTypes.bool,needIndentSpaced:o.PropTypes.bool,onExpand:o.PropTypes.func},shouldComponentUpdate:function(e){return!(0,s["default"])(e,this.props)},render:function(){var e=this.props,t=e.expandable,n=e.prefixCls,r=e.onExpand,o=e.needIndentSpaced,a=e.expanded,s=e.record;if(t){var l=a?"expanded":"collapsed";return i["default"].createElement("span",{className:n+"-expand-icon "+n+"-"+l,onClick:function(e){return r(!a,s,e)}})}return o?i["default"].createElement("span",{className:n+"-expand-icon "+n+"-spaced"}):null}});t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),i=r(o),a=n(1),s=r(a),l={"float":"right"};t["default"]={getDefaultProps:function(){return{styles:{}}},onTabClick:function(e){this.props.onTabClick(e)},getTabs:function(){var e=this,t=this.props,n=t.panels,r=t.activeKey,o=[],a=t.prefixCls;return s["default"].Children.forEach(n,function(t){var n=t.key,l=r===n?a+"-tab-active":"";l+=" "+a+"-tab";var u={};t.props.disabled?l+=" "+a+"-tab-disabled":u={onClick:e.onTabClick.bind(e,n)};var c={};r===n&&(c.ref="activeTab"),o.push(s["default"].createElement("div",(0,i["default"])({role:"tab","aria-disabled":t.props.disabled?"true":"false","aria-selected":r===n?"true":"false"},u,{className:l,key:n},c),t.props.tab))}),o},getRootNode:function(e){var t=this.props,n=t.prefixCls,r=t.onKeyDown,o=t.extraContent,i=t.style;return s["default"].createElement("div",{role:"tablist",className:n+"-bar",tabIndex:"0",ref:"root",onKeyDown:r,style:i},o?s["default"].createElement("div",{style:l,key:"extra"},o):null,e)}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),i=r(o),a=n(1),s=r(a),l=n(5),u=r(l),c=s["default"].createClass({displayName:"TabPane",propTypes:{active:a.PropTypes.bool,destroyInactiveTabPane:a.PropTypes.bool,placeholder:a.PropTypes.node},getDefaultProps:function(){return{placeholder:null}},render:function(){var e,t=this.props,n=t.destroyInactiveTabPane,r=t.active;this._isActived=this._isActived||r;var o=t.rootPrefixCls+"-tabpane",a=(0,u["default"])((e={},(0,i["default"])(e,o+"-inactive",!r),(0,i["default"])(e,o+"-active",r),(0,i["default"])(e,o,1),e)),l=n?r:this._isActived;return s["default"].createElement("div",{
role:"tabpanel","aria-hidden":t.active?"false":"true",className:a},l?t.children:t.placeholder)}});t["default"]=c,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.TabPane=t["default"]=void 0;var o=n(391),i=r(o),a=n(111),s=r(a);t["default"]=i["default"],t.TabPane=s["default"]},function(e,t,n){"use strict";e.exports=n(392)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),a=r(i),s=a["default"].createClass({displayName:"LazyRenderBox",propTypes:{children:i.PropTypes.any,className:i.PropTypes.string,visible:i.PropTypes.bool,hiddenClassName:i.PropTypes.string},shouldComponentUpdate:function(e){return e.hiddenClassName||e.visible},render:function(){var e=this.props,t=e.hiddenClassName,n=e.visible,r=o(e,["hiddenClassName","visible"]);return t||a["default"].Children.count(r.children)>1?(!n&&t&&(r.className+=" "+t),a["default"].createElement("div",r)):a["default"].Children.only(r.children)}});t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=document.createElement("div");return document.body.appendChild(e),e}function i(e){function t(e,t,n){(!c||e._component||c(e))&&(e._container||(e._container=p(e)),l["default"].unstable_renderSubtreeIntoContainer(e,d(e,t),e._container,function(){e._component=this,n&&n.call(this)}))}function n(e){if(e._container){var t=e._container;l["default"].unmountComponentAtNode(t),t.parentNode.removeChild(t),e._container=null}}var r=e.autoMount,i=void 0===r||r,s=e.autoDestroy,u=void 0===s||s,c=e.isVisible,d=e.getComponent,f=e.getContainer,p=void 0===f?o:f,h=void 0;return i&&(h=a({},h,{componentDidMount:function(){t(this)},componentDidUpdate:function(){t(this)}})),i&&u||(h=a({},h,{renderComponent:function(e,n){t(this,e,n)}})),h=u?a({},h,{componentWillUnmount:function(){n(this)}}):a({},h,{removeContainer:function(){n(this)}})}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=i;var s=n(9),l=r(s);e.exports=t["default"]},function(e,t,n){function r(e){var t=e.getDefaultProps;t&&(e.defaultProps=t(),delete e.getDefaultProps)}function o(e){function t(e){var t=e.state||{};s(t,n.call(e)),e.state=t}var n=e.getInitialState,r=e.componentWillMount;n&&(r?e.componentWillMount=function(){t(this),r.call(this)}:e.componentWillMount=function(){t(this)},delete e.getInitialState)}function i(e,t){r(t),o(t);var n={},s={};Object.keys(t).forEach(function(e){"mixins"!==e&&"statics"!==e&&("function"==typeof t[e]?n[e]=t[e]:s[e]=t[e])}),l(e.prototype,n);var u=function(e,t,n){if(!e)return t;if(!t)return e;var r={};return Object.keys(e).forEach(function(n){t[n]||(r[n]=e[n])}),Object.keys(t).forEach(function(n){e[n]?r[n]=function(){return t[n].apply(this,arguments)&&e[n].apply(this,arguments)}:r[n]=t[n]}),r};return a({childContextTypes:u,contextTypes:u,propTypes:a.MANY_MERGED_LOOSE,defaultProps:a.MANY_MERGED_LOOSE})(e,s),t.statics&&Object.getOwnPropertyNames(t.statics).forEach(function(n){var r=e[n],o=t.statics[n];if(void 0!==r&&void 0!==o)throw new TypeError("Cannot mixin statics because statics."+n+" and Component."+n+" are defined.");e[n]=void 0!==r?r:o}),t.mixins&&t.mixins.reverse().forEach(i.bind(null,e)),e}var a=n(436),s=n(10),l=a({componentDidMount:a.MANY,componentWillMount:a.MANY,componentWillReceiveProps:a.MANY,shouldComponentUpdate:a.ONCE,componentWillUpdate:a.MANY,componentDidUpdate:a.MANY,componentWillUnmount:a.MANY,getChildContext:a.MANY_MERGED});e.exports=function(){var e=l;return e.onClass=function(e,t){return t=s({},t),i(e,t)},e.decorate=function(t){return function(n){return e.onClass(n,t)}},e}()},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var r=function o(e){n(this,o);var t=[];e=e||{},this.subscribe=function(e){t.push(e)},this.unsubscribe=function(e){var n=t.indexOf(e);n!==-1&&t.splice(n,1)},this.update=function(n){n&&n(e),t.forEach(function(t){return t(e)})}};t["default"]=r,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var r={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridRow:!0,gridColumn:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},o=["Webkit","ms","Moz","O"];Object.keys(r).forEach(function(e){o.forEach(function(t){r[n(t,e)]=r[e]})});var i={background:{backgroundAttachment:!0,backgroundColor:!0,backgroundImage:!0,backgroundPositionX:!0,backgroundPositionY:!0,backgroundRepeat:!0},backgroundPosition:{backgroundPositionX:!0,backgroundPositionY:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0},outline:{outlineWidth:!0,outlineStyle:!0,outlineColor:!0}},a={isUnitlessNumber:r,shorthandPropertyExpansions:i};e.exports=a},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),i=r(o),a=n(49),s=r(a),l=n(2),u=r(l),c=n(4),d=r(c),f=n(3),p=r(f),h=n(1),m=r(h),v=n(9),y=r(v),g=n(422),b=r(g),_=n(423),x=r(_),T=n(120),C=r(T),w=n(424),S=r(w),P=n(407),E=r(P),M=n(10),k=r(M),O=n(116),N=r(O),D=n(72),R=r(D),A=n(405),I=n(105),j=1,L=10,W=1e3,H=1e3,Y=50,F="listviewscroll",V=function(e){function t(){var n,r,o;(0,u["default"])(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=(0,d["default"])(this,e.call.apply(e,[this].concat(a))),r.state={curRenderedRowsCount:r.props.initialListSize,highlightedRow:{}},r.stickyRefs={},o=n,(0,d["default"])(r,o)}return(0,p["default"])(t,e),t.prototype.getMetrics=function(){return{contentLength:this.scrollProperties.contentLength,totalRows:this.props.dataSource.getRowCount(),renderedRows:this.state.curRenderedRowsCount,visibleRows:Object.keys(this._visibleRows).length}},t.prototype.getScrollResponder=function(){return this.refs[F]&&this.refs[F].getScrollResponder&&this.refs[F].getScrollResponder()},t.prototype.scrollTo=function(){var e;this.refs[F]&&this.refs[F].scrollTo&&(e=this.refs[F]).scrollTo.apply(e,arguments)},t.prototype.setNativeProps=function(e){this.refs[F]&&this.refs[F].setNativeProps(e)},t.prototype.getInnerViewNode=function(){return this.refs[F].getInnerViewNode()},t.prototype.componentWillMount=function(){this.scrollProperties={visibleLength:null,contentLength:null,offset:0},this._childFrames=[],this._visibleRows={},this._prevRenderedRowsCount=0,this._sentEndForContentLength=null},t.prototype.componentDidMount=function(){(this.props.stickyHeader||this.props.useBodyScroll)&&(this.__onScroll=I(this._onScroll,this.props.scrollEventThrottle),window.addEventListener("scroll",this.__onScroll)),this.componentDidUpdate()},t.prototype.componentWillReceiveProps=function(e){var t=this;this.props.dataSource===e.dataSource&&this.props.initialListSize===e.initialListSize||this.setState(function(e,n){return t._prevRenderedRowsCount=0,{curRenderedRowsCount:Math.min(Math.max(e.curRenderedRowsCount,n.initialListSize),n.dataSource.getRowCount())}},function(){return t._renderMoreRowsIfNeeded()})},t.prototype.componentDidUpdate=function(){var e=this;this.requestAnimationFrame(function(){e._measureAndUpdateScrollProps()})},t.prototype.componentWillUnmount=function(){(this.props.stickyHeader||this.props.useBodyScroll)&&window.removeEventListener("scroll",this.__onScroll)},t.prototype.onRowHighlighted=function(e,t){this.setState({highlightedRow:{sectionID:e,rowID:t}})},t.prototype.render=function(){var e=this,t=[],n=this.props.dataSource,r=n.rowIdentities,o=0,a=[],l=this.props.renderHeader&&this.props.renderHeader(),u=this.props.renderFooter&&this.props.renderFooter(),c=l?1:0,d=function(s){var l=n.sectionIdentities[s],u=r[s];if(0===u.length)return"continue";if(e.props.renderSectionHeader){var d=o>=e._prevRenderedRowsCount&&n.sectionHeaderShouldUpdate(s),f=m["default"].createElement(S["default"],{key:"s_"+l,shouldUpdate:!!d,render:e.props.renderSectionHeader.bind(null,n.getSectionHeaderData(s),l)});e.props.stickyHeader&&(f=m["default"].createElement(A.Sticky,(0,i["default"])({},e.props.stickyProps,{key:"s_"+l,ref:function(t){e.stickyRefs[l]=t}}),f)),t.push(f),a.push(c++)}for(var p=[],h=0;h<u.length;h++){var v=u[h],y=l+"_"+v,g=o>=e._prevRenderedRowsCount&&n.rowShouldUpdate(s,h),b=m["default"].createElement(S["default"],{key:"r_"+y,shouldUpdate:!!g,render:e.props.renderRow.bind(null,n.getRowData(s,h),l,v,e.onRowHighlighted)});if(p.push(b),c++,e.props.renderSeparator&&(h!==u.length-1||s===r.length-1)){var _=e.state.highlightedRow.sectionID===l&&(e.state.highlightedRow.rowID===v||e.state.highlightedRow.rowID===u[h+1]),x=e.props.renderSeparator(l,v,_);x&&(p.push(x),c++)}if(++o===e.state.curRenderedRowsCount)break}return t.push(m["default"].cloneElement(e.props.renderSectionBodyWrapper(l),{},p)),o>=e.state.curRenderedRowsCount?"break":void 0};e:for(var f=0;f<r.length;f++){var p=d(f);switch(p){case"continue":continue;case"break":break e}}var h=this.props,v=h.renderScrollComponent,y=(0,s["default"])(h,["renderScrollComponent"]);return t=m["default"].cloneElement(y.renderBodyComponent(),{},t),y.stickyHeader&&(t=m["default"].createElement(A.StickyContainer,y.stickyContainerProps,t)),void 0===y.removeClippedSubviews&&(y.removeClippedSubviews=!0),(0,k["default"])(y,{onScroll:this._onScroll,stickyHeaderIndices:this.props.stickyHeaderIndices.concat(a),onKeyboardWillShow:void 0,onKeyboardWillHide:void 0,onKeyboardDidShow:void 0,onKeyboardDidHide:void 0}),(y.stickyHeader||y.useBodyScroll)&&delete y.onScroll,this._sc=m["default"].cloneElement(v(y),{ref:F,onContentSizeChange:this._onContentSizeChange,onLayout:y.stickyHeader||y.useBodyScroll?function(t){e.props.onLayout&&e.props.onLayout(t)}:this._onLayout},l,t,u,y.children),this._sc},t.prototype._measureAndUpdateScrollProps=function(){var e=this.getScrollResponder();!e||!e.getInnerViewNode},t.prototype._onContentSizeChange=function(e,t){var n=this.props.horizontal?e:t;n!==this.scrollProperties.contentLength&&(this.scrollProperties.contentLength=n,this._updateVisibleRows(),this._renderMoreRowsIfNeeded()),this.props.onContentSizeChange&&this.props.onContentSizeChange(e,t)},t.prototype._onLayout=function(e){var t=e.nativeEvent.layout,n=t.width,r=t.height,o=this.props.horizontal?n:r;o!==this.scrollProperties.visibleLength&&(this.scrollProperties.visibleLength=o,this._updateVisibleRows(),this._renderMoreRowsIfNeeded()),this.props.onLayout&&this.props.onLayout(e)},t.prototype._maybeCallOnEndReached=function(e){return!!(this.props.onEndReached&&this._getDistanceFromEnd(this.scrollProperties)<this.props.onEndReachedThreshold&&this.state.curRenderedRowsCount===this.props.dataSource.getRowCount())&&(this._sentEndForContentLength=this.scrollProperties.contentLength,this.props.onEndReached(e),!0)},t.prototype._renderMoreRowsIfNeeded=function(){if(null===this.scrollProperties.contentLength||null===this.scrollProperties.visibleLength||this.state.curRenderedRowsCount===this.props.dataSource.getRowCount())return void this._maybeCallOnEndReached();var e=this._getDistanceFromEnd(this.scrollProperties);e<this.props.scrollRenderAheadDistance&&this._pageInNewRows()},t.prototype._pageInNewRows=function(){var e=this;this.setState(function(t,n){var r=Math.min(t.curRenderedRowsCount+n.pageSize,n.dataSource.getRowCount());return e._prevRenderedRowsCount=t.curRenderedRowsCount,{curRenderedRowsCount:r}},function(){e._measureAndUpdateScrollProps(),e._prevRenderedRowsCount=e.state.curRenderedRowsCount})},t.prototype._getDistanceFromEnd=function(e){return e.contentLength-e.visibleLength-e.offset},t.prototype._updateVisibleRows=function(e){},t.prototype._onScroll=function(e){var t=!this.props.horizontal,n=y["default"].findDOMNode(this.refs[F]);this.props.stickyHeader||this.props.useBodyScroll?(this.scrollProperties.visibleLength=window[t?"innerHeight":"innerWidth"],this.scrollProperties.contentLength=n[t?"scrollHeight":"scrollWidth"],this.scrollProperties.offset=window.document.body[t?"scrollTop":"scrollLeft"]):(this.scrollProperties.visibleLength=n[t?"offsetHeight":"offsetWidth"],this.scrollProperties.contentLength=n[t?"scrollHeight":"scrollWidth"],this.scrollProperties.offset=n[t?"scrollTop":"scrollLeft"]),this._maybeCallOnEndReached(e)||this._renderMoreRowsIfNeeded(),this.props.onEndReached&&this._getDistanceFromEnd(this.scrollProperties)>this.props.onEndReachedThreshold&&(this._sentEndForContentLength=null),this.props.onScroll&&this.props.onScroll(e)},t}(m["default"].Component);V.DataSource=b["default"],V.propTypes=(0,i["default"])({},x["default"].propTypes,{dataSource:h.PropTypes.instanceOf(b["default"]).isRequired,renderSeparator:h.PropTypes.func,renderRow:h.PropTypes.func.isRequired,initialListSize:h.PropTypes.number,onEndReached:h.PropTypes.func,onEndReachedThreshold:h.PropTypes.number,pageSize:h.PropTypes.number,renderFooter:h.PropTypes.func,renderHeader:h.PropTypes.func,renderBodyComponent:h.PropTypes.func,renderSectionHeader:h.PropTypes.func,renderSectionBodyWrapper:h.PropTypes.func,renderScrollComponent:m["default"].PropTypes.func.isRequired,scrollRenderAheadDistance:m["default"].PropTypes.number,scrollEventThrottle:m["default"].PropTypes.number,onChangeVisibleRows:m["default"].PropTypes.func,removeClippedSubviews:m["default"].PropTypes.bool,stickyHeaderIndices:h.PropTypes.arrayOf(h.PropTypes.number),useBodyScroll:h.PropTypes.bool,stickyHeader:h.PropTypes.bool,stickyProps:h.PropTypes.object,stickyContainerProps:h.PropTypes.object}),V.defaultProps={initialListSize:L,pageSize:j,renderScrollComponent:function(e){return m["default"].createElement(x["default"],e)},renderBodyComponent:function(){return m["default"].createElement("div",null)},renderSectionBodyWrapper:function(e){return m["default"].createElement("div",{key:e,className:"list-view-section-body"})},scrollRenderAheadDistance:W,onEndReachedThreshold:H,scrollEventThrottle:Y,stickyHeaderIndices:[],stickyProps:{},stickyContainerProps:{}},(0,N["default"])(V.prototype,C["default"].Mixin),(0,N["default"])(V.prototype,E["default"]),(0,R["default"])(V),V.isReactNativeComponent=!0,t["default"]=V,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=n(1),i=(r(o),n(9)),a=r(i),s=n(41),l=r(s),u=16,c={scrollResponderMixinGetInitialState:function(){return{isTouching:!1,lastMomentumScrollBeginTime:0,lastMomentumScrollEndTime:0,observedScrollSinceBecomingResponder:!1,becameResponderWhileAnimating:!1}},scrollResponderHandleScrollShouldSetResponder:function(){return this.state.isTouching},scrollResponderHandleStartShouldSetResponder:function(){return!1},scrollResponderHandleStartShouldSetResponderCapture:function(e){return this.scrollResponderIsAnimating()},scrollResponderHandleMoveShouldSetResponderCapture:function(e){return!0},scrollResponderHandleResponderReject:function(){(0,l["default"])(!1,"ScrollView doesn't take rejection well - scrolls anyway")},scrollResponderHandleTerminationRequest:function(){return!this.state.observedScrollSinceBecomingResponder},scrollResponderHandleTouchEnd:function(e){var t=e.nativeEvent;this.state.isTouching=0!==t.touches.length,this.props.onTouchEnd&&this.props.onTouchEnd(e)},scrollResponderHandleResponderRelease:function(e){this.props.onResponderRelease&&this.props.onResponderRelease(e),this.props.keyboardShouldPersistTaps||this.state.observedScrollSinceBecomingResponder||this.state.becameResponderWhileAnimating||this.props.onScrollResponderKeyboardDismissed&&this.props.onScrollResponderKeyboardDismissed(e)},scrollResponderHandleScroll:function(e){this.state.observedScrollSinceBecomingResponder=!0,this.props.onScroll&&this.props.onScroll(e)},scrollResponderHandleResponderGrant:function(e){this.state.observedScrollSinceBecomingResponder=!1,this.props.onResponderGrant&&this.props.onResponderGrant(e),this.state.becameResponderWhileAnimating=this.scrollResponderIsAnimating()},scrollResponderHandleScrollBeginDrag:function(e){this.props.onScrollBeginDrag&&this.props.onScrollBeginDrag(e)},scrollResponderHandleScrollEndDrag:function(e){this.props.onScrollEndDrag&&this.props.onScrollEndDrag(e)},scrollResponderHandleMomentumScrollBegin:function(e){this.state.lastMomentumScrollBeginTime=Date.now(),this.props.onMomentumScrollBegin&&this.props.onMomentumScrollBegin(e)},scrollResponderHandleMomentumScrollEnd:function(e){this.state.lastMomentumScrollEndTime=Date.now(),this.props.onMomentumScrollEnd&&this.props.onMomentumScrollEnd(e)},scrollResponderHandleTouchStart:function(e){this.state.isTouching=!0,this.props.onTouchStart&&this.props.onTouchStart(e)},scrollResponderHandleTouchMove:function(e){this.props.onTouchMove&&this.props.onTouchMove(e)},scrollResponderIsAnimating:function(){var e=Date.now(),t=e-this.state.lastMomentumScrollEndTime,n=t<u||this.state.lastMomentumScrollEndTime<this.state.lastMomentumScrollBeginTime;return n},scrollResponderScrollTo:function(e,t){this.scrollResponderScrollWithouthAnimationTo(e,t)},scrollResponderScrollWithouthAnimationTo:function(e,t){var n=a["default"].findDOMNode(this);n.offsetX=e,n.offsetY=t},scrollResponderZoomTo:function(e){},scrollResponderScrollNativeHandleToKeyboard:function(e,t,n){this.additionalScrollOffset=t||0,this.preventNegativeScrollOffset=!!n},scrollResponderInputMeasureAndScrollToKeyboard:function(e,t,n,r){if(this.keyboardWillOpenTo){var o=t-this.keyboardWillOpenTo.endCoordinates.screenY+r+this.additionalScrollOffset;this.preventNegativeScrollOffset&&(o=Math.max(0,o)),this.scrollResponderScrollTo(0,o)}this.additionalOffset=0,this.preventNegativeScrollOffset=!1},scrollResponderTextInputFocusError:function(e){console.error("Error measuring text field: ",e)},componentWillMount:function(){},scrollResponderKeyboardWillShow:function(e){this.keyboardWillOpenTo=e,this.props.onKeyboardWillShow&&this.props.onKeyboardWillShow(e)},scrollResponderKeyboardWillHide:function(e){this.keyboardWillOpenTo=null,this.props.onKeyboardWillHide&&this.props.onKeyboardWillHide(e)},scrollResponderKeyboardDidShow:function(e){e&&(this.keyboardWillOpenTo=e),this.props.onKeyboardDidShow&&this.props.onKeyboardDidShow(e)},scrollResponderKeyboardDidHide:function(){this.keyboardWillOpenTo=null,this.props.onKeyboardDidHide&&this.props.onKeyboardDidHide()}},d={Mixin:c};e.exports=d},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(6),a=o(i),s=n(1),l=r(s),u=n(5),c=o(u),d=n(435),f=o(d),p=n(438),h=o(p),m=l.createClass({displayName:"Picker",getDefaultProps:function(){return{prefixCls:"rmc-picker",pure:!0,onValueChange:function(){}}},getInitialState:function(){var e=void 0,t=this.props,n=t.selectedValue,r=t.defaultSelectedValue,o=t.children;return void 0!==n?e=n:void 0!==r?e=r:o.length&&(e=o[0].value),{selectedValue:e}},componentDidMount:function(){this.itemHeight=this.refs.indicator.offsetHeight,this.refs.content.style.padding=3*this.itemHeight+"px 0",this.zscroller=new h["default"](this.refs.content,{scrollingX:!1,snapping:!0,penetrationDeceleration:.1,minVelocityToKeepDecelerating:.5,scrollingComplete:this.scrollingComplete}),this.zscroller.setDisabled(this.props.disabled),this.zscroller.scroller.setSnapSize(0,this.itemHeight),this.select(this.state.selectedValue)},componentWillReceiveProps:function(e){"selectedValue"in e&&this.setState({selectedValue:e.selectedValue}),this.zscroller.setDisabled(e.disabled)},shouldComponentUpdate:function(e,t){return this.state.selectedValue!==t.selectedValue||!(0,f["default"])(this.props.children,e.children,this.props.pure)},componentDidUpdate:function(){this.select(this.state.selectedValue)},componentWillUnmount:function(){this.zscroller.destroy()},selectByIndex:function(e){e<0||e>=this.props.children.length||this.zscroller.scroller.scrollTo(0,e*this.itemHeight)},select:function(e){for(var t=this.props.children,n=0,r=t.length;n<r;n++)if(t[n].value===e)return void this.selectByIndex(n);this.selectByIndex(0)},fireValueChange:function(e){e!==this.state.selectedValue&&("selectedValue"in this.props||this.setState({selectedValue:e}),this.props.onValueChange(e))},scrollingComplete:function(){var e=this.zscroller.scroller.getValues(),t=e.top,n=Math.round((t-this.itemHeight/2)/this.itemHeight),r=this.props.children[n];r&&this.fireValueChange(r.value)},render:function(){var e,t=this.props,n=t.children,r=t.prefixCls,o=t.className,i=this.state.selectedValue,s=r+"-item",u=s+" "+r+"-item-selected",d=n.map(function(e){return l.createElement("div",{className:i===e.value?u:s,key:e.value},e.label)}),f=(e={},(0,a["default"])(e,o,!!o),(0,a["default"])(e,r,!0),e);return l.createElement("div",{className:(0,c["default"])(f)},l.createElement("div",{className:r+"-mask"}),l.createElement("div",{className:r+"-indicator",ref:"indicator"}),l.createElement("div",{className:r+"-content",ref:"content"},d))}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),a=o(i),s=n(43),l=r(s),u=n(433),c=r(u),d=a.createClass({displayName:"PopupPicker",mixins:[c["default"]],getDefaultProps:function(){return{prefixCls:"rmc-picker-popup",triggerType:"onClick",WrapComponent:"span"}},getModal:function(){var e=this.props;return this.state.visible?a.createElement(l["default"],{prefixCls:""+e.prefixCls,className:e.className||"",visible:!0,closable:!1,transitionName:e.transitionName||e.popupTransitionName,maskTransitionName:e.maskTransitionName,onClose:this.hide,style:e.style},a.createElement("div",null,a.createElement("div",{className:e.prefixCls+"-header"},a.createElement("div",{className:e.prefixCls+"-item "+e.prefixCls+"-header-left",onClick:this.onDismiss},e.dismissText),a.createElement("div",{className:e.prefixCls+"-item "+e.prefixCls+"-title"},e.title),a.createElement("div",{className:e.prefixCls+"-item "+e.prefixCls+"-header-right",onClick:this.onOk},e.okText)),this.props.content)):null},render:function(){return this.getRender()}});t["default"]=d,e.exports=t["default"]},function(e,t,n){function r(e){return n(o(e))}function o(e){return i[e]||function(){throw new Error("Cannot find module '"+e+"'.")}()}var i={"./accordion/index.web.tsx":128,"./accordion/style/index.web.tsx":129,"./action-sheet/index.web.tsx":130,"./action-sheet/style/index.web.tsx":131,"./activity-indicator/index.web.tsx":132,"./activity-indicator/style/index.web.tsx":133,"./badge/index.web.tsx":73,"./badge/style/index.web.tsx":74,"./button/index.web.tsx":46,"./button/style/index.web.tsx":75,"./card/index.web.tsx":137,"./card/style/index.web.tsx":138,"./carousel/index.web.tsx":76,"./carousel/style/index.web.tsx":77,"./checkbox/index.web.tsx":141,"./checkbox/style/index.web.tsx":78,"./date-picker/index.web.tsx":142,"./date-picker/style/index.web.tsx":144,"./drawer/index.web.tsx":146,"./drawer/style/index.web.tsx":147,"./flex/index.web.tsx":30,"./flex/style/index.web.tsx":36,"./grid/index.web.tsx":150,"./grid/style/index.web.tsx":151,"./icon/index.web.tsx":13,"./icon/style/index.web.tsx":23,"./image-picker/index.web.tsx":152,"./image-picker/style/index.web.tsx":153,"./input-item/index.web.tsx":154,"./input-item/style/index.web.tsx":155,"./list-view/index.web.tsx":157,"./list-view/style/index.web.tsx":158,"./list/index.web.tsx":24,"./list/style/index.web.tsx":25,"./menu/index.web.tsx":161,"./menu/style/index.web.tsx":162,"./modal/index.web.tsx":80,"./modal/style/index.web.tsx":81,"./nav-bar/index.web.tsx":166,"./nav-bar/style/index.web.tsx":167,"./notice-bar/index.web.tsx":168,"./notice-bar/style/index.web.tsx":169,"./pagination/index.web.tsx":170,"./pagination/style/index.web.tsx":171,"./picker/index.web.tsx":172,"./picker/style/index.web.tsx":82,"./popover/index.web.tsx":173,"./popover/style/index.web.tsx":175,"./popup/index.web.tsx":176,"./popup/style/index.web.tsx":177,"./progress/index.web.tsx":178,"./progress/style/index.web.tsx":179,"./radio/index.web.tsx":84,"./radio/style/index.web.tsx":85,"./refresh-control/index.web.tsx":181,"./refresh-control/style/index.web.tsx":182,"./result/index.web.tsx":183,"./result/style/index.web.tsx":184,"./search-bar/index.web.tsx":186,"./search-bar/style/index.web.tsx":187,"./segmented-control/index.web.tsx":189,"./segmented-control/style/index.web.tsx":190,"./slider/index.web.tsx":191,"./slider/style/index.web.tsx":192,"./stepper/index.web.tsx":193,"./stepper/style/index.web.tsx":194,"./steps/index.web.tsx":195,"./steps/style/index.web.tsx":196,"./style/index.web.tsx":7,"./swipe-action/index.web.tsx":197,"./swipe-action/style/index.web.tsx":198,"./switch/index.web.tsx":199,"./switch/style/index.web.tsx":200,"./tab-bar/index.web.tsx":202,"./tab-bar/style/index.web.tsx":203,"./table/index.web.tsx":204,"./table/style/index.web.tsx":205,"./tabs/index.web.tsx":206,"./tabs/style/index.web.tsx":207,"./tag/index.web.tsx":208,"./tag/style/index.web.tsx":209,"./text/index.web.tsx":210,"./textarea-item/index.web.tsx":211,"./textarea-item/style/index.web.tsx":212,"./toast/index.web.tsx":86,"./toast/style/index.web.tsx":87,"./view/index.web.tsx":88,"./white-space/index.web.tsx":213,"./white-space/style/index.web.tsx":214,"./wing-blank/index.web.tsx":89,"./wing-blank/style/index.web.tsx":90};r.keys=function(){return Object.keys(i)},r.resolve=o,e.exports=r,r.id=123},function(e,t){"use strict";function n(){return!1}function r(){return!0}function o(){this.timeStamp=Date.now(),this.target=void 0,this.currentTarget=void 0}Object.defineProperty(t,"__esModule",{value:!0}),o.prototype={isEventObject:1,constructor:o,isDefaultPrevented:n,isPropagationStopped:n,isImmediatePropagationStopped:n,preventDefault:function(){this.isDefaultPrevented=r},stopPropagation:function(){this.isPropagationStopped=r},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=r,this.stopPropagation()},halt:function(e){e?this.stopImmediatePropagation():this.stopPropagation(),this.preventDefault()}},t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){return null===e||void 0===e}function i(){return f}function a(){return p}function s(e){var t=e.type,n="function"==typeof e.stopPropagation||"boolean"==typeof e.cancelBubble;u["default"].call(this),this.nativeEvent=e;var r=a;"defaultPrevented"in e?r=e.defaultPrevented?i:a:"getPreventDefault"in e?r=e.getPreventDefault()?i:a:"returnValue"in e&&(r=e.returnValue===p?i:a),this.isDefaultPrevented=r;var o=[],s=void 0,l=void 0,c=void 0,d=h.concat();for(m.forEach(function(e){t.match(e.reg)&&(d=d.concat(e.props),e.fix&&o.push(e.fix))}),l=d.length;l;)c=d[--l],this[c]=e[c];for(!this.target&&n&&(this.target=e.srcElement||document),this.target&&3===this.target.nodeType&&(this.target=this.target.parentNode),l=o.length;l;)(s=o[--l])(this,e);this.timeStamp=e.timeStamp||Date.now()}Object.defineProperty(t,"__esModule",{value:!0});var l=n(124),u=r(l),c=n(10),d=r(c),f=!0,p=!1,h=["altKey","bubbles","cancelable","ctrlKey","currentTarget","eventPhase","metaKey","shiftKey","target","timeStamp","view","type"],m=[{reg:/^key/,props:["char","charCode","key","keyCode","which"],fix:function(e,t){o(e.which)&&(e.which=o(t.charCode)?t.keyCode:t.charCode),void 0===e.metaKey&&(e.metaKey=e.ctrlKey)}},{reg:/^touch/,props:["touches","changedTouches","targetTouches"]},{reg:/^hashchange$/,props:["newURL","oldURL"]},{reg:/^gesturechange$/i,props:["rotation","scale"]},{reg:/^(mousewheel|DOMMouseScroll)$/,props:[],fix:function(e,t){var n=void 0,r=void 0,o=void 0,i=t.wheelDelta,a=t.axis,s=t.wheelDeltaY,l=t.wheelDeltaX,u=t.detail;i&&(o=i/120),u&&(o=0-(u%3===0?u/3:u)),void 0!==a&&(a===e.HORIZONTAL_AXIS?(r=0,n=0-o):a===e.VERTICAL_AXIS&&(n=0,r=o)),void 0!==s&&(r=s/120),void 0!==l&&(n=-1*l/120),n||r||(r=o),void 0!==n&&(e.deltaX=n),void 0!==r&&(e.deltaY=r),void 0!==o&&(e.delta=o)}},{reg:/^mouse|contextmenu|click|mspointer|(^DOMMouseScroll$)/i,props:["buttons","clientX","clientY","button","offsetX","relatedTarget","which","fromElement","toElement","offsetY","pageX","pageY","screenX","screenY"],fix:function(e,t){var n=void 0,r=void 0,i=void 0,a=e.target,s=t.button;return a&&o(e.pageX)&&!o(t.clientX)&&(n=a.ownerDocument||document,r=n.documentElement,i=n.body,e.pageX=t.clientX+(r&&r.scrollLeft||i&&i.scrollLeft||0)-(r&&r.clientLeft||i&&i.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||i&&i.scrollTop||0)-(r&&r.clientTop||i&&i.clientTop||0)),e.which||void 0===s||(1&s?e.which=1:2&s?e.which=3:4&s?e.which=2:e.which=0),!e.relatedTarget&&e.fromElement&&(e.relatedTarget=e.fromElement===a?e.toElement:e.fromElement),e}}],v=u["default"].prototype;(0,d["default"])(s.prototype,v,{constructor:s,preventDefault:function(){var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=p,v.preventDefault.call(this)},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=f,v.stopPropagation.call(this)}}),t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){function r(t){var r=new a["default"](t);n.call(e,r)}return e.addEventListener?(e.addEventListener(t,r,!1),{remove:function(){e.removeEventListener(t,r,!1)}}):e.attachEvent?(e.attachEvent("on"+t,r),{remove:function(){e.detachEvent("on"+t,r)}}):void 0}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var i=n(125),a=r(i);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-(\w)/g,function(e,t){return t.toUpperCase()})}var o=n(123);o.keys().forEach(function(e){var n=o(e);n&&n["default"]&&(n=n["default"]);var i=e.match(/^\.\/([^_][\w-]+)\/index\.web\.tsx?$/);i&&i[1]&&(t[r(i[1])]=n)}),"undefined"!=typeof console&&console.warn&&console.warn("you are using prebuild antd-mobile,\nplease use https://github.com/ant-design/babel-plugin-antd to reduce app bundle size.")},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(2),i=r(o),a=n(4),s=r(a),l=n(3),u=r(l),c=n(1),d=r(c),f=n(358),p=r(f),h=function(e){function t(){return(0,i["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t.prototype.render=function(){return d["default"].createElement(p["default"],this.props)},t}(d["default"].Component);t["default"]=h,h.Panel=f.Panel,h.defaultProps={prefixCls:"am-accordion"},e.exports=t["default"]},[441,280],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e){var t={};return Object.keys(e).forEach(function(n){
0===n.indexOf("data-")&&(t[n]=e[n])}),t}function a(e,t,n){function r(){if(x){h["default"].unmountComponentAtNode(x),x.parentNode.removeChild(x),x=null;var e=S.indexOf(r);e!==-1&&S.splice(e,1)}}function o(e){var t=arguments.length<=1||void 0===arguments[1]?0:arguments[1],o=n(e,t);o&&o.then?o.then(function(){r()}):r()}var a,s=(0,T["default"])({},{prefixCls:"am-action-sheet",cancelButtonText:"\u53d6\u6d88"},t),u=s.prefixCls,d=s.className,p=s.transitionName,m=s.maskTransitionName,y=s.maskClosable,b=void 0===y||y,x=document.createElement("div");document.body.appendChild(x),S.push(r);var P=s.title,E=s.message,M=s.options,k=s.destructiveButtonIndex,O=s.cancelButtonIndex,N=s.cancelButtonText,D=[P?f["default"].createElement("h3",{key:"0",className:u+"-title"},P):null,E?f["default"].createElement("div",{key:"1",className:u+"-message"},E):null],R=null,A="normal";!function(){switch(e){case C:A="normal",R=f["default"].createElement("div",i(s),D,f["default"].createElement("ul",{className:u+"-button-list"},M.map(function(e,t){var n,r={onClick:function(){return o(t)}},i=f["default"].createElement("li",(0,l["default"])({className:[u+"-button-list-item"],key:t},r),e),a=(n={},(0,c["default"])(n,u+"-destructive-button",k===t),(0,c["default"])(n,u+"-cancel-button",O===t),n);return O!==t&&k!==t||(i=f["default"].createElement("li",(0,l["default"])({key:t,className:(0,g["default"])(a)},r),e,O===t?f["default"].createElement("span",{className:u+"-cancel-button-mask"}):null)),i})));break;case w:A="share";var t=M.length&&Array.isArray(M[0])||!1,n=function(e,t){var n=arguments.length<=2||void 0===arguments[2]?0:arguments[2];return f["default"].createElement("div",{className:u+"-share-list-item",key:t,onClick:function(){return o(t,n)}},f["default"].createElement("div",{className:u+"-share-list-item-icon"},e.iconName?f["default"].createElement(_["default"],{type:e.iconName}):e.icon),f["default"].createElement("div",{className:u+"-share-list-item-title"},e.title))};R=f["default"].createElement("div",i(s),D,f["default"].createElement("div",{className:u+"-share"},t?M.map(function(e,t){return f["default"].createElement("div",{key:t,className:u+"-share-list"},e.map(function(e,r){return n(e,r,t)}))}):f["default"].createElement("div",{className:u+"-share-list"},M.map(function(e,t){return n(e,t)})),f["default"].createElement("div",{className:u+"-share-cancel-button",onClick:function(){return o(-1)}},N)))}}();var I=(0,g["default"])((a={},(0,c["default"])(a,d,!!d),(0,c["default"])(a,u+"-"+A,!0),a));return h["default"].render(f["default"].createElement(v["default"],{visible:!0,title:"",footer:"",prefixCls:u,className:I,transitionName:p||"am-slide-up",maskTransitionName:m||"am-fade",onClose:r,maskClosable:b},R),x),{close:r}}Object.defineProperty(t,"__esModule",{value:!0});var s=n(8),l=r(s),u=n(6),c=r(u),d=n(1),f=r(d),p=n(9),h=r(p),m=n(43),v=r(m),y=n(5),g=r(y),b=n(13),_=r(b),x=n(10),T=r(x),C="NORMAL",w="SHARE",S=[];t["default"]={showActionSheetWithOptions:function(e){var t=arguments.length<=1||void 0===arguments[1]?o:arguments[1];a(C,e,t)},showShareActionSheetWithOptions:function(e){var t=arguments.length<=1||void 0===arguments[1]?o:arguments[1];a(w,e,t)},close:function(){S.forEach(function(e){return e()})}},e.exports=t["default"]},[441,281],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t,n=this.props,r=n.prefixCls,o=n.className,a=n.animating,s=n.toast,l=n.size,u=n.color,c=n.text,d=(0,m["default"])((e={},(0,i["default"])(e,""+r,!0),(0,i["default"])(e,r+"-lg","large"===l),(0,i["default"])(e,r+"-sm","small"===l),(0,i["default"])(e,o,!!o),(0,i["default"])(e,r+"-toast",!!s),e)),f=(0,m["default"])((t={},(0,i["default"])(t,r+"-spinner",!0),(0,i["default"])(t,r+"-spinner-lg",!!s||"large"===l),(0,i["default"])(t,r+"-spinner-white",!!s||"white"===u),t));return a?s?p["default"].createElement("div",{className:d},p["default"].createElement("div",{className:r+"-content"},p["default"].createElement("span",{className:f}),c&&p["default"].createElement("span",{className:r+"-toast"},c))):p["default"].createElement("div",{className:d},p["default"].createElement("span",{className:f}),c&&p["default"].createElement("span",{className:r+"-tip"},c)):null},t}(p["default"].Component);t["default"]=v,v.defaultProps={prefixCls:"am-activity-indicator",animating:!0,size:"small",color:"gray",panelColor:"rgba(34,34,34,0.6)",toast:!1},e.exports=t["default"]},[441,282],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.children,o=t.className,a=(0,m["default"])((e={},(0,i["default"])(e,n+"-body",!0),(0,i["default"])(e,o,o),e));return p["default"].createElement("div",{className:a},r)},t}(p["default"].Component);t["default"]=v,v.defaultProps={prefixCls:"am-card"},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.content,o=t.className,a=t.extra,s=(0,m["default"])((e={},(0,i["default"])(e,n+"-footer",!0),(0,i["default"])(e,o,o),e));return p["default"].createElement("div",{className:s},p["default"].createElement("div",{className:n+"-footer-content"},r),a?p["default"].createElement("div",{className:n+"-footer-extra"},a):null)},t}(p["default"].Component);t["default"]=v,v.defaultProps={prefixCls:"am-card"},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.className,o=t.title,a=t.thumb,s=t.thumbStyle,l=t.extra,u=(0,m["default"])((e={},(0,i["default"])(e,n+"-header",!0),(0,i["default"])(e,r,r),e));return p["default"].createElement("div",{className:u},p["default"].createElement("div",{className:n+"-header-content"},a?p["default"].createElement("img",{style:s,src:a}):null,o),l?p["default"].createElement("div",{className:n+"-header-extra"},l):null)},t}(p["default"].Component);t["default"]=v,v.defaultProps={prefixCls:"am-card",thumbStyle:{}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=n(136),y=r(v),g=n(134),b=r(g),_=n(135),x=r(_),T=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.full,o=t.children,a=t.className,s=(0,m["default"])((e={},(0,i["default"])(e,n,!0),(0,i["default"])(e,n+"-full",r),(0,i["default"])(e,a,a),e));return p["default"].createElement("div",{className:s},o)},t}(p["default"].Component);t["default"]=T,T.defaultProps={prefixCls:"am-card",full:!1},T.Header=y["default"],T.Body=b["default"],T.Footer=x["default"],e.exports=t["default"]},[441,285],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=n(47),y=r(v),g=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.style,o=t.name,a=t.defaultChecked,s=t.checked,l=t.disabled,u=t.children,c=t.onChange,d=t.className,f=(0,m["default"])((e={},(0,i["default"])(e,n+"-agree",!0),(0,i["default"])(e,d,d),e));return p["default"].createElement("div",{className:f,style:r},p["default"].createElement("label",{className:n+"-agree-label",htmlFor:o},p["default"].createElement(y["default"],{prefixCls:n,defaultChecked:a,checked:s,name:o,onChange:c,disabled:l}),u))},t}(p["default"].Component);t["default"]=g,g.defaultProps={prefixCls:"am-checkbox"},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(8),i=r(o),a=n(6),s=r(a),l=n(2),u=r(l),c=n(4),d=r(c),f=n(3),p=r(f),h=n(1),m=r(h),v=n(5),y=r(v),g=n(47),b=r(g),_=n(24),x=r(_),T=x["default"].Item,C=function(e){function t(){return(0,u["default"])(this,t),(0,d["default"])(this,e.apply(this,arguments))}return(0,p["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.listPrefixCls,o=t.style,a=t.className,l=t.name,u=t.defaultChecked,c=t.checked,d=t.disabled,f=t.children,p=t.extra,h=t.onChange,v=(0,y["default"])((e={},(0,s["default"])(e,n+"-item",!0),(0,s["default"])(e,n+"-item-disabled",d===!0),(0,s["default"])(e,a,a),e)),g=d?{}:{onClick:function(){}};return m["default"].createElement(T,(0,i["default"])({prefixCls:r,style:o,className:v,extra:p},g,{thumb:m["default"].createElement(b["default"],{prefixCls:n,defaultChecked:u,checked:c,name:l,onChange:h,disabled:d})}),f)},t}(m["default"].Component);t["default"]=C,C.defaultProps={prefixCls:"am-checkbox",listPrefixCls:"am-list"},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(47),i=r(o),a=n(140),s=r(a),l=n(139),u=r(l);i["default"].CheckboxItem=s["default"],i["default"].AgreeItem=u["default"],t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){return(0,x["default"])({prefixCls:"am-picker",pickerPrefixCls:"am-picker-col",popupPrefixCls:"am-picker-popup"},(0,b.getProps)())}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var i=n(8),a=r(i),s=n(2),l=r(s),u=n(4),c=r(u),d=n(3),f=r(d),p=n(1),h=r(p),m=n(418),v=r(m),y=n(416),g=r(y),b=n(145),_=n(10),x=r(_),T=function(e){function t(){return(0,l["default"])(this,t),(0,c["default"])(this,e.apply(this,arguments))}return(0,f["default"])(t,e),t.prototype.render=function(){var e=this.props,t=e.children,n=e.value,r=e.defaultDate,o=e.extra,i=e.okText,s=e.dismissText,l=e.popupPrefixCls,u={extra:n?(0,b.formatFn)(this,n):o},c=h["default"].createElement(g["default"],{locale:e.locale,minDate:e.minDate,maxDate:e.maxDate,mode:e.mode,pickerPrefixCls:e.pickerPrefixCls,prefixCls:e.prefixCls,defaultDate:n||r});return h["default"].createElement(v["default"],(0,a["default"])({datePicker:c,WrapComponent:"div",transitionName:"am-slide-up",maskTransitionName:"am-fade"},e,{prefixCls:l,date:n||r,dismissText:h["default"].createElement("span",{className:l+"-header-cancel-button"},s),okText:h["default"].createElement("span",{className:l+"-header-ok-button"},i)}),h["default"].cloneElement(t,t.type&&"ListItem"===t.type.myName?u:{}))},t}(h["default"].Component);t["default"]=T,T.defaultProps=o(),e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(420);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r(o)["default"]}}),e.exports=t["default"]},function(e,t,n){"use strict";n(82)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=void 0;return t="time"===e?"HH:mm":"datetime"===e?"YYYY-MM-DD HH:mm":"YYYY-MM-DD"}function i(e,t){var n=e.props.format,r="undefined"==typeof n?"undefined":(0,l["default"])(n);return"string"===r?t.format(r):"function"===r?n(t):t.format(o(e.props.mode))}function a(){return{mode:"datetime",locale:c["default"],extra:"\u8bf7\u9009\u62e9",defaultDate:(0,f["default"])(),onChange:function(){},okText:"\u786e\u5b9a",dismissText:"\u53d6\u6d88",title:""}}Object.defineProperty(t,"__esModule",{value:!0});var s=n(31),l=r(s);t.formatFn=i,t.getProps=a;var u=n(143),c=r(u),d=n(106),f=r(d)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(8),i=r(o),a=n(17),s=r(a),l=n(2),u=r(l),c=n(4),d=r(c),f=n(3),p=r(f),h=n(1),m=r(h),v=n(363),y=r(v),g=n(22),b=r(g),_=function(e){function t(){return(0,u["default"])(this,t),(0,d["default"])(this,e.apply(this,arguments))}return(0,p["default"])(t,e),t.prototype.render=function(){var e=(0,b["default"])(this.props,["prefixCls","children"]),t=(0,s["default"])(e,2),n=t[0],r=n.prefixCls,o=n.children,a=t[1];return m["default"].createElement(y["default"],(0,i["default"])({prefixCls:r},a),o)},t}(m["default"].Component);t["default"]=_,_.defaultProps={prefixCls:"am-drawer",enableDragHandle:!1},e.exports=t["default"]},[441,288],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.direction,r=t.wrap,o=t.justify,a=t.align,s=t.alignContent,l=t.className,u=t.children,c=t.prefixCls,d=t.style,f=t.onClick,h=(0,m["default"])((e={},(0,i["default"])(e,c,!0),(0,i["default"])(e,c+"-dir-row","row"===n),(0,i["default"])(e,c+"-dir-row-reverse","row-reverse"===n),(0,i["default"])(e,c+"-dir-column","column"===n),(0,i["default"])(e,c+"-dir-column-reverse","column-reverse"===n),(0,i["default"])(e,c+"-nowrap","nowrap"===r),(0,i["default"])(e,c+"-wrap","wrap"===r),(0,i["default"])(e,c+"-wrap-reverse","wrap-reverse"===r),(0,i["default"])(e,c+"-justify-start","start"===o),(0,i["default"])(e,c+"-justify-end","end"===o),(0,i["default"])(e,c+"-justify-center","center"===o),(0,i["default"])(e,c+"-justify-between","between"===o),(0,i["default"])(e,c+"-justify-around","around"===o),(0,i["default"])(e,c+"-align-top","top"===a||"start"===a),(0,i["default"])(e,c+"-align-middle","middle"===a||"center"===a),(0,i["default"])(e,c+"-align-bottom","bottom"===a||"end"===a),(0,i["default"])(e,c+"-align-baseline","baseline"===a),(0,i["default"])(e,c+"-align-stretch","stretch"===a),(0,i["default"])(e,c+"-align-content-start","start"===s),(0,i["default"])(e,c+"-align-content-end","end"===s),(0,i["default"])(e,c+"-align-content-center","center"===s),(0,i["default"])(e,c+"-align-content-between","between"===s),(0,i["default"])(e,c+"-align-content-around","around"===s),(0,i["default"])(e,c+"-align-content-stretch","stretch"===s),(0,i["default"])(e,l,l),e));return p["default"].createElement("div",{className:h,style:d,onClick:f},u)},t}(p["default"].Component);t["default"]=v,v.defaultProps={prefixCls:"am-flexbox",align:"center",onClick:function(){}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.children,r=t.className,o=t.prefixCls,a=t.style,s=t.onClick,l=(0,m["default"])((e={},(0,i["default"])(e,o+"-item",!0),(0,i["default"])(e,r,r),e));return p["default"].createElement("div",{className:l,style:a,onClick:s},n)},t}(p["default"].Component);t["default"]=v,v.defaultProps={prefixCls:"am-flexbox"},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=n(30),y=r(v),g=n(76),b=r(g),_=function(e){function t(){(0,s["default"])(this,t);for(var n=arguments.length,r=Array(n),o=0;o<n;o++)r[o]=arguments[o];var i=(0,u["default"])(this,e.call.apply(e,[this].concat(r)));return i.clientWidth=document.documentElement.clientWidth,i}return(0,d["default"])(t,e),t.prototype.render=function(){for(var e,t=this,n=this.props,r=n.className,o=n.data,a=n.prefixCls,s=n.hasLine,l=n.isCarousel,u=n.columnNum,c=n.carouselMaxRow,d=(0,m["default"])((e={},(0,i["default"])(e,a,!0),(0,i["default"])(e,a+"-line",s),(0,i["default"])(e,r,r),e)),f=(0,m["default"])((0,i["default"])({},a+"-item",!0)),h=o.length,v=Math.ceil(h/u),g=this.clientWidth/u,_=this.props.renderItem||function(e,t){return p["default"].createElement("div",{className:a+"-item-contain column-num-"+u,style:{height:g+"px"}},p["default"].createElement("img",{className:a+"-icon",src:e.icon}),p["default"].createElement("div",{className:a+"-text"},e.text))},x=[],T=[],C=0;C<v;C++){for(var w=[],S=function(e){var n=C*u+e;n<h?w.push(p["default"].createElement(y["default"].Item,{className:f,onClick:function(){t.props.onClick(o[n],n)},key:"griditem-"+n},_(o[n],n))):w.push(p["default"].createElement(y["default"].Item,{key:"griditem-"+n}))},P=0;P<u;P++)S(P);x.push(p["default"].createElement(y["default"],{justify:"center",align:"stretch",key:"gridline-"+C},w))}var E=Math.ceil(v/c);if(l&&E>1)for(var M=0;M<E;M++){for(var k=[],O=0;O<c;O++){var N=M*c+O;N<v?k.push(x[N]):k.push(p["default"].createElement("div",{key:"gridline-"+N}))}T.push(p["default"].createElement("div",{className:a+"-carousel-page",key:"pageitem-"+M},k))}return p["default"].createElement("div",{className:d},l&&E>1?p["default"].createElement(b["default"],null,T):x)},t}(p["default"].Component);t["default"]=_,_.defaultProps={prefixCls:"am-grid",data:[],onClick:function(){},columnNum:4,hasLine:!0,isCarousel:!1,carouselMaxRow:2},e.exports=t["default"]},function(e,t,n){"use strict";n(7),n(36),n(77),n(290)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var i=n(6),a=r(i),s=n(2),l=r(s),u=n(4),c=r(u),d=n(3),f=r(d),p=n(1),h=r(p),m=n(5),v=r(m),y=n(89),g=r(y),b=n(30),_=r(b),x=n(86),T=r(x),C=function(e){function t(){(0,l["default"])(this,t);for(var n=arguments.length,r=Array(n),o=0;o<n;o++)r[o]=arguments[o];var i=(0,c["default"])(this,e.call.apply(e,[this].concat(r)));return i.getOrientation=function(e,t){if(/iphone|ipad/i.test(navigator.userAgent)){var n=new FileReader;n.onload=function(e){var n=new DataView(e.target.result);if(65496!==n.getUint16(0,!1))return t(-2);for(var r=n.byteLength,o=2;o<r;){var i=n.getUint16(o,!1);if(o+=2,65505===i){var a=n.getUint32(o+=2,!1);if(1165519206!==a)return t(-1);var s=18761===n.getUint16(o+=6,!1);o+=n.getUint32(o+4,s);var l=n.getUint16(o,s);o+=2;for(var u=0;u<l;u++)if(274===n.getUint16(o+12*u,s))return t(n.getUint16(o+12*u+8,s))}else{if(65280!==(65280&i))break;o+=n.getUint16(o,!1)}}return t(-1)},n.readAsArrayBuffer(e.slice(0,65536))}else t("-1")},i.removeImage=function(e){var t=[];i.props.files.forEach(function(n,r){e!==r&&t.push(n)}),i.props.onChange(t,"remove",e)},i.addImage=function(e){var t=i.props.files.concat(e);i.props.onChange(t,"add")},i.onFileChange=function(){var e=i.refs.fileSelectorInput;e.files&&e.files.length&&!function(){var t=e.files[0],n=new FileReader;n.onload=function(n){var r=n.target.result;if(!r)return void T["default"].fail("\u56fe\u7247\u83b7\u53d6\u5931\u8d25");var o=1;i.getOrientation(t,function(t){t>0&&(o=t),i.addImage({url:r,orientation:o}),e.value=""})},n.readAsDataURL(t)}()},i}return(0,f["default"])(t,e),t.prototype.render=function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.style,i=n.className,s=n.files,l=window.devicePixelRatio||1,u=[],c=(document.documentElement.clientWidth-18*l-6*l*3)/4,d=(0,v["default"])((e={},(0,a["default"])(e,""+r,!0),(0,a["default"])(e,i,i),e)),f={width:c+"px",height:c+"px"};return s.forEach(function(e,n){u.push(h["default"].createElement("div",{key:n,className:r+"-item",style:f},h["default"].createElement("div",{className:r+"-item-remove",onClick:t.removeImage.bind(t,n)}),h["default"].createElement("div",{className:r+"-item-content",style:{backgroundImage:"url("+e.url+")"}})))}),h["default"].createElement("div",{className:d,style:o},h["default"].createElement("div",{className:r+"-list"},h["default"].createElement(g["default"],{size:"md"},h["default"].createElement(_["default"],{wrap:"wrap"},u,h["default"].createElement("div",{className:r+"-item "+r+"-upload-btn",style:f},h["default"].createElement("input",{style:f,ref:"fileSelectorInput",type:"file",accept:"image/jpg,image/jpeg,image/png,image/gif",onChange:this.onFileChange}))))))},t}(h["default"].Component);t["default"]=C,C.defaultProps={prefixCls:"am-image-picker",files:[],onChange:o},e.exports=t["default"]},function(e,t,n){"use strict";n(7),n(90),n(36),n(87),n(292)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e){return"undefined"==typeof e||null===e?"":e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var a=n(8),s=r(a),l=n(6),u=r(l),c=n(2),d=r(c),f=n(4),p=r(f),h=n(3),m=r(h),v=n(1),y=r(v),g=n(5),b=r(g),_=function(e){function t(n){(0,d["default"])(this,t);var r=(0,p["default"])(this,e.call(this,n));return r.onInputChange=function(e){var t=e.target.value,n=r.props,o=n.onChange,i=n.type;switch(i){case"text":break;case"bankCard":t=t.replace(/\D/g,""),t=t.replace(/\D/g,"").replace(/(....)(?=.)/g,"$1 ");break;case"phone":t=t.replace(/\D/g,"").substring(0,11);var a=t.length;a>3&&a<8?t=t.substr(0,3)+" "+t.substr(3):a>=8&&(t=t.substr(0,3)+" "+t.substr(3,4)+" "+t.substr(7));break;case"number":t=t.replace(/\D/g,"");break;case"password":}o(t)},r.onInputBlur=function(e){r.debounceTimeout=setTimeout(function(){r.setState({focus:!1})},300);var t=e.target.value;r.props.onBlur(t)},r.onInputFocus=function(e){r.setState({focus:!0});var t=e.target.value;r.props.onFocus(t)},r.onExtraClick=function(e){r.props.onExtraClick(e)},r.onErrorClick=function(e){r.props.onErrorClick(e)},r.clearInput=function(){"password"!==r.props.type&&r.setState({placeholder:r.props.value}),r.props.onChange("")},r.state={focus:!1,placeholder:r.props.placeholder},r}return(0,m["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){"placeholder"in e&&this.state.placeholder!==e.placeholder&&this.setState({placeholder:e.placeholder})},t.prototype.componentWillUnmount=function(){this.debounceTimeout&&clearTimeout(this.debounceTimeout)},t.prototype.render=function(){var e,t,n=this.props,r=n.prefixCls,o=n.prefixListCls,a=n.type,l=n.value,c=n.defaultValue,d=n.name,f=n.editable,p=n.disabled,h=n.style,m=n.clear,v=n.children,g=n.error,_=n.className,x=n.extra,T=n.labelNumber,C=n.maxLength,w=void 0;w=void 0!==l?{value:i(l)}:{defaultValue:c};var S=this.state,P=S.focus,E=S.placeholder,M=(0,b["default"])((e={},(0,u["default"])(e,o+"-item",!0),(0,u["default"])(e,r+"-item",!0),(0,u["default"])(e,r+"-disabled",p),(0,u["default"])(e,r+"-error",g),(0,u["default"])(e,r+"-focus",P),(0,u["default"])(e,_,_),e)),k=(0,b["default"])((t={},(0,u["default"])(t,r+"-label",!0),(0,u["default"])(t,r+"-label-2",2===T),(0,u["default"])(t,r+"-label-3",3===T),(0,u["default"])(t,r+"-label-4",4===T),(0,u["default"])(t,r+"-label-5",5===T),(0,u["default"])(t,r+"-label-6",6===T),(0,u["default"])(t,r+"-label-7",7===T),t)),O="text";return"bankCard"===a||"phone"===a?O="tel":"password"===a&&(O="password"),y["default"].createElement("div",{className:M,style:h},v?y["default"].createElement("div",{className:k},v):null,y["default"].createElement("div",{className:r+"-control"},y["default"].createElement("input",(0,s["default"])({},w,{type:O,maxLength:C,name:d,placeholder:E,onChange:this.onInputChange,onBlur:this.onInputBlur,onFocus:this.onInputFocus,readOnly:!f,disabled:p,pattern:"number"===a?"[0-9]*":""}))),m&&f&&!p&&l&&l.length>0?y["default"].createElement("div",{className:r+"-clear",onClick:this.clearInput}):null,g?y["default"].createElement("div",{className:r+"-error-extra",onClick:this.onErrorClick}):null,""!==x?y["default"].createElement("div",{className:r+"-extra",onClick:this.onExtraClick},x):null)},t}(y["default"].Component);t["default"]=_,_.defaultProps={prefixCls:"am-input",prefixListCls:"am-list",type:"text",name:"",defaultValue:"",editable:!0,disabled:!1,placeholder:"",clear:!1,onChange:o,onBlur:o,onFocus:o,extra:"",onExtraClick:o,error:!1,onErrorClick:o,size:"large",labelNumber:4,labelPosition:"left",textAlign:"left"},e.exports=t["default"]},[443,293],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(8),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(70),m=r(h),v=n(79),y=r(v),g=m["default"].IndexedList,b=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e=(0,y["default"])(this.props,!0),t=e.restProps,n=e.extraProps;return p["default"].createElement(g,(0,i["default"])({sectionHeaderClassName:"am-indexed-list-section-header am-list-body",sectionBodyClassName:"am-indexed-list-section-body am-list-body"},t,n),this.props.children)},t}(p["default"].Component);t["default"]=b,b.defaultProps={prefixCls:"am-indexed-list",listPrefixCls:"am-list",listViewPrefixCls:"am-list-view"},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(8),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(70),m=r(h),v=n(79),y=r(v),g=n(156),b=r(g),_=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e=(0,y["default"])(this.props,!1),t=e.restProps,n=e.extraProps,r=this.props,o=r.useZscroller,a=r.refreshControl;return a&&(o=!0),p["default"].createElement(m["default"],(0,i["default"])({},t,n,{useZscroller:o}))},t}(p["default"].Component);t["default"]=_,_.defaultProps={prefixCls:"am-list-view",listPrefixCls:"am-list"},_.DataSource=m["default"].DataSource,_.IndexedList=b["default"],e.exports=t["default"]},[441,294],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=t.Brief=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=t.Brief=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){return p["default"].createElement("div",{className:"am-list-brief",style:this.props.style},this.props.children)},t}(p["default"].Component),y=function(e){function t(n){(0,s["default"])(this,t);var r=(0,u["default"])(this,e.call(this,n));return r.onClick=function(e){r.props.onClick&&r.props.onClick(e)},r.onTouchStart=function(){r.props.onClick&&r.setState({hover:!0})},r.onTouchEnd=function(){r.props.onClick&&r.setState({hover:!1})},r.state={hover:!1},r}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t,n,r=this.props,o=r.prefixCls,a=r.thumb,s=r.arrow,l=r.error,u=r.children,c=r.extra,d=r.className,f=r.align,h=r.multipleLine,v=r.wrap,y=r.style,g=this.state.hover,b=void 0,_=void 0,x=(0,m["default"])((e={},(0,i["default"])(e,o+"-item",!0),(0,i["default"])(e,o+"-item-error",l),(0,i["default"])(e,o+"-item-top","top"===f),(0,i["default"])(e,o+"-item-middle","middle"===f),(0,i["default"])(e,o+"-item-bottom","bottom"===f),(0,i["default"])(e,o+"-item-hover",g),(0,i["default"])(e,d,d),e)),T=(0,m["default"])((t={},(0,i["default"])(t,o+"-line",!0),(0,i["default"])(t,o+"-line-multiple",h),(0,i["default"])(t,o+"-line-wrap",v),t)),C=(0,m["default"])((n={},(0,i["default"])(n,o+"-arrow",!0),(0,i["default"])(n,o+"-arrow-horizontal","horizontal"===s),(0,i["default"])(n,o+"-arrow-vertical","down"===s||"up"===s),(0,i["default"])(n,o+"-arrow-vertical-up","up"===s),n));return a&&(b="string"==typeof a?p["default"].createElement("div",{className:o+"-thumb"},p["default"].createElement("img",{src:a})):p["default"].createElement("div",{className:o+"-thumb"},a)),_=""!==s?p["default"].createElement("div",{className:C}):null,p["default"].createElement("div",{className:x,onClick:this.onClick,onTouchStart:this.onTouchStart,onTouchEnd:this.onTouchEnd,onTouchCancel:this.onTouchEnd,style:y},b,p["default"].createElement("div",{className:T},""!==u?p["default"].createElement("div",{className:o+"-content"},u):null,""!==c?p["default"].createElement("div",{className:o+"-extra"},c):null,_))},t}(p["default"].Component);t["default"]=y,y.Brief=v,y.defaultProps={prefixCls:"am-list",thumb:"",arrow:"",children:"",extra:"",error:!1,multipleLine:!1,align:"middle",wrap:!1},y.myName="ListItem"},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=n(24),y=r(v),g=n(84),b=r(g),_=function(e){function t(n){(0,s["default"])(this,t);var r=(0,u["default"])(this,e.call(this,n));return r.onClick=function(e){r.setState({value:[e]}),r.props.onChange(e)},r.state={value:r.props.value,data:r.props.data},r}return(0,d["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){"data"in e&&this.setState({data:e.data})},t.prototype.render=function(){var e,t=this,n=this.state,r=n.value,o=n.data,a=this.props,s=a.className,l=a.prefixCls,u=a.radioPrefixCls,c=(0,m["default"])((e={},(0,i["default"])(e,""+l,!0),(0,i["default"])(e,s,s),e)),d=[];return o.forEach(function(e,n){var o,a=(0,m["default"])((o={},(0,i["default"])(o,u+"-item",!0),(0,i["default"])(o,l+"-item-selected",r.length>0&&r[0].value===e.value),(0,i["default"])(o,l+"-item-disabled",e.disabled),o));d.push(p["default"].createElement(y["default"].Item,{className:a,key:n,extra:p["default"].createElement(b["default"],{checked:r.length>0&&r[0].value===e.value,disabled:e.disabled,onChange:t.onClick.bind(t,e)})},e.label))}),p["default"].createElement(y["default"],{style:{paddingTop:0},className:c},d)},t}(p["default"].Component);t["default"]=_,_.defaultProps={prefixCls:"am-sub-menu",radioPrefixCls:"am-radio",value:[],data:[],onChange:function(){}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=n(10),y=r(v),g=n(160),b=r(g),_=n(24),x=r(_),T=n(30),C=r(T),w=function(e){function t(n){(0,s["default"])(this,t);var r=(0,u["default"])(this,e.call(this,n));r.onClickListItem=function(e){e.isLeaf===!0&&r.setState({firstValue:e.value,SubMenuData:[]},function(){r.props.onChange([e.value])}),r.setState({firstValue:e.value,SubMenuData:e.children||[]})},r.onClickSubMenuItem=function(e){var t=r.props,n=t.level,o=t.onChange;
setTimeout(function(){o(2===n?[r.state.firstValue,e.value]:[e.value])},300)};var o=n.data,i=n.value,a=n.level;if(2!==a)return r.state={SubMenuData:o},(0,u["default"])(r);if(i.length>0){var l=o.filter(function(e){return e.value===(i.length>0&&i[0]||null)})[0].children||[];return r.state={SubMenuData:l,firstValue:i[0]||""},(0,u["default"])(r)}var c=o[0].children||[];return o[0].isLeaf?r.state={SubMenuData:[],firstValue:""}:r.state={SubMenuData:c,firstValue:o[0].value},r}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this,n=this.props,r=n.className,o=n.data,a=n.prefixCls,s=n.value,l=n.level,u=n.style,c=this.props.height;c||(c=document.documentElement.clientHeight/2);var d={height:Math.round(c)+"px",overflowY:"scroll"},f=this.state,h=f.SubMenuData,v=f.firstValue,g=(0,m["default"])((e={},(0,i["default"])(e,a,!0),(0,i["default"])(e,r,!!r),e)),_=o.map(function(e,n){return p["default"].createElement(x["default"].Item,{className:e.value===v?a+"-selected":"",onClick:t.onClickListItem.bind(t,e),key:"listitem-1-"+n},e.label)});return p["default"].createElement("div",{className:g,style:(0,y["default"])({},u,d)},p["default"].createElement(C["default"],{align:"top"},2===l?p["default"].createElement(C["default"].Item,{style:d},p["default"].createElement(x["default"],null,_)):null,p["default"].createElement(C["default"].Item,{style:d},p["default"].createElement(b["default"],{value:h.filter(function(e){return e.value===(s.length&&s[s.length-1])}),data:h,onChange:this.onClickSubMenuItem}))))},t}(p["default"].Component);t["default"]=w,w.defaultProps={prefixCls:"am-menu",value:[],data:[],level:2,onChange:function(){}},e.exports=t["default"]},function(e,t,n){"use strict";n(7),n(78),n(36),n(25),n(85),n(296)},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=o(i),s=n(6),l=o(s),u=n(2),c=o(u),d=n(4),f=o(d),p=n(3),h=o(p),m=n(1),v=r(m),y=n(5),g=o(y),b=n(10),_=o(b),x=n(35),T=o(x),C=function(e){function t(){return(0,c["default"])(this,t),(0,f["default"])(this,e.apply(this,arguments))}return(0,h["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.button,r=t.prefixCls,o=t.touchFeedback,i=(0,_["default"])({},this.props);["button","prefixCls","touchFeedback"].forEach(function(e){i.hasOwnProperty(e)&&delete i[e]});var s=(0,g["default"])((e={},(0,l["default"])(e,r+"-button",!0),(0,l["default"])(e,r+"-button-touchFeedback",o),e));return v.createElement("a",(0,a["default"])({className:s,href:"#",onClick:function(e){e.preventDefault(),n.onPress&&n.onPress()}},i),n.text||"Button")},t}(v.Component);t["default"]=(0,T["default"])(C),e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=function(){function e(){s["default"].unmountComponentAtNode(a),a.parentNode.removeChild(a)}var t=arguments.length<=0?void 0:arguments[0],n=arguments.length<=1?void 0:arguments[1],r=(arguments.length<=2?void 0:arguments[2])||[{text:"\u786e\u5b9a"}];if(t||n){var o="am-modal",a=document.createElement("div");document.body.appendChild(a);var l=r.map(function(t){var n=t.onPress||function(){};return t.onPress=function(){n(),e()},t});s["default"].render(i["default"].createElement(u["default"],{visible:!0,transparent:!0,prefixCls:o,title:t,transitionName:"am-zoom",closable:!1,maskClosable:!1,footer:l,maskTransitionName:"am-fade"},i["default"].createElement("div",{style:{zoom:1,overflow:"hidden"}},n)),a)}};var o=n(1),i=r(o),a=n(9),s=r(a),l=n(48),u=r(l);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=function(){function e(e){var t=e.target,n=t.getAttribute("type");p[n]=t.value}function t(){s["default"].unmountComponentAtNode(m),m.parentNode.removeChild(m)}function n(e){var t=p.text||"",n=p.password||"";return"login-password"===f?e(t,n):e("secure-text"===f?n:t)}for(var r=arguments.length,o=Array(r),a=0;a<r;a++)o[a]=arguments[a];if(o&&o[2]){var l="am-modal",c=o[0],d=void 0,f=o[3]||"default",p={};switch(f){case"login-password":d=i["default"].createElement("div",null,i["default"].createElement("div",{className:l+"-input"},i["default"].createElement("input",{type:"text",defaultValue:"",onChange:e})),i["default"].createElement("div",{className:l+"-input"},i["default"].createElement("input",{type:"password",defaultValue:"",onChange:e})));break;case"secure-text":d=i["default"].createElement("div",null,i["default"].createElement("div",{className:l+"-input"},i["default"].createElement("input",{type:"password",defaultValue:"",onChange:e})));break;case"plain-text":case"default":default:d=i["default"].createElement("div",null,i["default"].createElement("div",{className:l+"-input"},i["default"].createElement("input",{type:"text",defaultValue:"",onChange:e})))}var h=i["default"].createElement("div",null,o[1],d),m=document.createElement("div");document.body.appendChild(m);var v=void 0;v="function"==typeof o[2]?[{text:"\u53d6\u6d88"},{text:"\u786e\u5b9a",onPress:function(){n(o[2])}}]:o[2].map(function(e){return{text:e.text,onPress:function(){e.onPress&&n(e.onPress)}}});var y=v.map(function(e){var n=e.onPress||function(){};return e.onPress=function(){n(),t()},e});s["default"].render(i["default"].createElement(u["default"],{visible:!0,transparent:!0,prefixCls:l,title:c,closable:!1,maskClosable:!1,transitionName:"am-zoom",footer:y,maskTransitionName:"am-fade"},i["default"].createElement("div",{style:{zoom:1,overflow:"hidden"}},h)),m)}};var o=n(1),i=r(o),a=n(9),s=r(a),l=n(48),u=r(l);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(8),i=r(o),a=n(6),s=r(a),l=n(17),u=r(l),c=n(2),d=r(c),f=n(4),p=r(f),h=n(3),m=r(h),v=n(1),y=r(v),g=n(5),b=r(g),_=n(13),x=r(_),T=n(22),C=r(T),w=function(e){function t(){return(0,d["default"])(this,t),(0,p["default"])(this,e.apply(this,arguments))}return(0,m["default"])(t,e),t.prototype.render=function(){var e,t=(0,C["default"])(this.props,["prefixCls","children","mode","className","iconName","leftContent","rightContent","onLeftClick"]),n=(0,u["default"])(t,2),r=n[0],o=r.prefixCls,a=r.children,l=r.mode,c=r.className,d=r.iconName,f=r.leftContent,p=r.rightContent,h=r.onLeftClick,m=n[1],v=(0,b["default"])((e={},(0,s["default"])(e,c,c),(0,s["default"])(e,o,!0),(0,s["default"])(e,o+"-"+l,!0),e));return y["default"].createElement("div",(0,i["default"])({},m,{className:v}),y["default"].createElement("div",{className:o+"-left",onClick:h},d?y["default"].createElement("span",{className:o+"-left-icon"},y["default"].createElement(x["default"],{type:d})):null,y["default"].createElement("span",{className:o+"-left-content"},f)),y["default"].createElement("div",{className:o+"-title"},a),y["default"].createElement("div",{className:o+"-right"},p))},t}(y["default"].Component);t["default"]=w,w.defaultProps={prefixCls:"am-navbar",mode:"dark",iconName:"left",onLeftClick:function(){}},e.exports=t["default"]},[442,298],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=n(13),y=r(v),g=function(e){function t(n){(0,s["default"])(this,t);var r=(0,u["default"])(this,e.call(this,n));return r.state={show:!0},r}return(0,d["default"])(t,e),t.prototype.onClick=function n(){var e=this.props,t=e.mode,n=e.onClick;n(),"closable"===t&&this.setState({show:!1})},t.prototype.render=function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.children,a=n.mode,s=n.type,l=n.onClick,u=n.className,c=(0,m["default"])((e={},(0,i["default"])(e,r,!0),(0,i["default"])(e,u,!!u),e)),d=void 0;switch(a){case"closable":d=p["default"].createElement("div",{className:r+"-operation",onClick:function(){return t.onClick()}},p["default"].createElement(y["default"],{type:"cross"}));break;case"link":d=p["default"].createElement("div",{className:r+"-operation",onClick:l},p["default"].createElement(y["default"],{type:"right"}));break;default:d=null}var f="";switch(s){case"success":f="check-circle";break;case"error":f="cross-circle";break;case"warn":f="exclamation-circle";break;case"question":f="question-circle";break;case"info":default:f="info-circle"}var h=s?p["default"].createElement("div",{className:r+"-icon"},p["default"].createElement(y["default"],{type:f})):null;return this.state.show?p["default"].createElement("div",{className:c},h,p["default"].createElement("div",{className:r+"-content"},o),d):null},t}(p["default"].Component);t["default"]=g,g.defaultProps={prefixCls:"am-notice-bar",mode:"",onClick:function(){}},e.exports=t["default"]},[442,299],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var i=n(6),a=r(i),s=n(2),l=r(s),u=n(4),c=r(u),d=n(3),f=r(d),p=n(1),h=r(p),m=n(5),v=r(m),y=n(46),g=r(y),b=n(30),_=r(b),x=function(e){function t(n){(0,l["default"])(this,t);var r=(0,c["default"])(this,e.call(this,n));return r.state={current:n.current},r.onPrev=r.onPrev.bind(r),r.onNext=r.onNext.bind(r),r}return(0,f["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){this.setState({current:e.current})},t.prototype._hasPrev=function(){return this.state.current>0},t.prototype._hasNext=function(){return this.state.current<this.props.total},t.prototype._handleChange=function(e){return this.setState({current:e}),this.props.onChange(e),e},t.prototype.onPrev=function(){this._handleChange(this.state.current-1)},t.prototype.onNext=function(){this._handleChange(this.state.current+1)},t.prototype.getIndexes=function(e){for(var t=[],n=0;n<e;n++)t.push(n);return t},t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.className,r=e.mode,o=e.total,i=e.simple,s=e.prevText,l=e.nextText,u=this.state.current,c=(0,v["default"])((0,a["default"])({className:n},t+"-wrap",!0)),d=void 0;switch(r){case"button":d=h["default"].createElement(_["default"],null,h["default"].createElement(_["default"].Item,{className:t+"-wrap-btn"},h["default"].createElement(g["default"],{inline:!0,disabled:u<=0,onClick:this.onPrev},s)),this.props.children?h["default"].createElement(_["default"].Item,null,this.props.children):!i&&h["default"].createElement(_["default"].Item,{className:c},h["default"].createElement("span",{className:"active"},u+1),"/",h["default"].createElement("span",null,o)),h["default"].createElement(_["default"].Item,{className:t+"-wrap-btn"},h["default"].createElement(g["default"],{disabled:u>=o-1,inline:!0,onClick:this.onNext},l)));break;case"number":d=h["default"].createElement("div",{className:c},h["default"].createElement("span",{className:"active"},u+1),"/",h["default"].createElement("span",null,o));break;case"pointer":var f=this.getIndexes(o);d=h["default"].createElement("div",{className:c},f.map(function(e){var n,r=(0,v["default"])((n={},(0,a["default"])(n,t+"-wrap-dot",!0),(0,a["default"])(n,t+"-wrap-dot-active",e===u),n));return h["default"].createElement("div",{className:r,key:"dot-"+e},h["default"].createElement("span",null))}));break;default:d=!1}return h["default"].createElement("div",{className:t},d)},t}(h["default"].Component);t["default"]=x,x.defaultProps={prefixCls:"am-pagination",mode:"button",current:0,simple:!1,prevText:"Prev",nextText:"Next",onChange:o},e.exports=t["default"]},[441,300],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=function(e){return e.join(",")};return{prefixCls:"am-picker",pickerPrefixCls:"am-picker-col",popupPrefixCls:"am-picker-popup",format:e,style:{left:0,bottom:0},cols:3,value:[],extra:"\u8bf7\u9009\u62e9",okText:"\u786e\u5b9a",dismissText:"\u53d6\u6d88",title:""}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var i=n(8),a=r(i),s=n(2),l=r(s),u=n(4),c=r(u),d=n(3),f=r(d),p=n(1),h=r(p),m=n(415),v=r(m),y=n(413),g=r(y),b=n(71),_=r(b),x=function(e){function t(){(0,l["default"])(this,t);for(var n=arguments.length,r=Array(n),o=0;o<n;o++)r[o]=arguments[o];var i=(0,c["default"])(this,e.call.apply(e,[this].concat(r)));return i.getSel=function(){var e=i.props.value||[],t=(0,_["default"])(i.props.data,function(t,n){return t.value===e[n]});return i.props.format(t.map(function(e){return e.label}))},i}return(0,f["default"])(t,e),t.prototype.render=function(){var e=this.props,t=e.children,n=e.value,r=e.extra,o=e.okText,i=e.dismissText,s=e.popupPrefixCls,l={extra:this.getSel()||r},u=h["default"].cloneElement(t,t.type&&"ListItem"===t.type.myName?l:{}),c=h["default"].createElement(g["default"],{prefixCls:e.prefixCls,pickerPrefixCls:e.pickerPrefixCls,data:e.data,cols:e.cols});return h["default"].createElement(v["default"],(0,a["default"])({cascader:c,WrapComponent:"div",transitionName:"am-slide-up",maskTransitionName:"am-fade"},e,{prefixCls:s,value:n,dismissText:h["default"].createElement("span",{className:s+"-header-cancel-button"},i),okText:h["default"].createElement("span",{className:s+"-header-ok-button"},o)}),u)},t}(h["default"].Component);t["default"]=x,x.defaultProps=o(),e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=arguments.length<=1||void 0===arguments[1]?function(e,t){return e}:arguments[1];return v["default"].Children.map(e,function(e,n){var r=t(e,n);return r&&r.props&&r.props.children?v["default"].cloneElement(r,{},o(r.props.children,t)):r})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var i=n(8),a=r(i),s=n(17),l=r(s),u=n(2),c=r(u),d=n(4),f=r(d),p=n(3),h=r(p),m=n(1),v=r(m),y=n(113),g=r(y),b=n(174),_=r(b),x=n(22),T=r(x),C=function(e){function t(){return(0,c["default"])(this,t),(0,f["default"])(this,e.apply(this,arguments))}return(0,h["default"])(t,e),t.prototype.render=function(){var e=(0,T["default"])(this.props,["children","prefixCls","placement","trigger","overlay","onSelect","popupAlign"]),t=(0,l["default"])(e,2),n=t[0],r=n.children,i=n.prefixCls,s=n.placement,u=n.trigger,c=n.overlay,d=n.onSelect,f=n.popupAlign,p=t[1],h=o(c,function(e,t){var n={firstItem:null,onClick:function(){}};return e&&e.type&&"PopoverItem"===e.type.myName&&!e.props.disabled?(n.onClick=function(){d(e)},n.firstItem=0===t,v["default"].cloneElement(e,n)):e});return v["default"].createElement(g["default"],(0,a["default"])({prefixCls:i,placement:s,trigger:u,overlay:h,popupAlign:f},p),r)},t}(v["default"].Component);t["default"]=C,C.defaultProps={prefixCls:"am-popover",placement:"bottomRight",popupAlign:{overflow:{adjustY:0,adjustX:0}},trigger:["click"],onSelect:function(){}},C.Item=_["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),i=r(o),a=n(6),s=r(a),l=n(17),u=r(l),c=n(2),d=r(c),f=n(4),p=r(f),h=n(3),m=r(h),v=n(1),y=r(v),g=n(5),b=r(g),_=n(13),x=r(_),T=n(22),C=r(T),w=n(35),S=r(w),P=function(e){function t(){return(0,d["default"])(this,t),(0,p["default"])(this,e.apply(this,arguments))}return(0,m["default"])(t,e),t.prototype.render=function(){var e,t=(0,C["default"])(this.props,["children","className","prefixCls","iconName","disabled","touchFeedback","firstItem"]),n=(0,u["default"])(t,2),r=n[0],o=r.children,a=r.className,l=r.prefixCls,c=r.iconName,d=r.disabled,f=r.touchFeedback,p=r.firstItem,h=n[1],m=(e={},(0,s["default"])(e,a,!!a),(0,s["default"])(e,l+"-item",!0),(0,s["default"])(e,l+"-item-disabled",d),(0,s["default"])(e,l+"-item-touchFeedback",f),(0,s["default"])(e,l+"-item-fix-active-arrow",p&&f),e);return y["default"].createElement("div",(0,i["default"])({className:(0,b["default"])(m)},h),c?y["default"].createElement("span",{className:l+"-item-icon"},y["default"].createElement(x["default"],{type:c})):null,y["default"].createElement("span",{className:l+"-item-content"},o))},t}(y["default"].Component);P.defaultProps={prefixCls:"am-popover",disabled:!1},t["default"]=(0,S["default"])(P,"PopoverItem"),e.exports=t["default"]},[441,302],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){function r(){v&&(c["default"].unmountComponentAtNode(v),v.parentNode.removeChild(v),v=null),o(e)}var o=arguments.length<=3||void 0===arguments[3]?function(e){}:arguments[3],i=(0,h["default"])({},{prefixCls:"am-popup",animationType:"slide-down"},t),a=i.prefixCls,s=i.transitionName,u=i.maskTransitionName,d=i.maskClosable,p=void 0===d||d,m=i.animationType,v=document.createElement("div");document.body.appendChild(v);var y="am-slide-down";return"slide-up"===m&&(y="am-slide-up"),c["default"].render(l["default"].createElement(f["default"],{prefixCls:a,visible:!0,title:"",footer:"",className:a+"-"+m,transitionName:s||y,maskTransitionName:u||"am-fade",onClose:r,maskClosable:p},n),v),{instanceId:e,close:r}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var i=n(2),a=r(i),s=n(1),l=r(s),u=n(9),c=r(u),d=n(43),f=r(d),p=n(10),h=r(p),m={defaultInstance:null,instances:[]},v=1,y=function g(){(0,a["default"])(this,g)};t["default"]=y,y.newInstance=function(){var e=void 0;return{show:function(t,n){e=o(v++,n,t,function(e){for(var t=0;t<m.instances.length;t++)if(m.instances[t].instanceId===e)return void m.instances.splice(t,1)}),m.instances.push(e)},hide:function(){e.close()}}},y.show=function(e,t){m.defaultInstance=o("0",t,e,function(e){"0"===e&&(m.defaultInstance=null)})},y.hide=function(){m.defaultInstance.close()},e.exports=t["default"]},[441,303],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=function(e){function t(n){(0,s["default"])(this,t);var r=(0,u["default"])(this,e.call(this,n));return r.state={},r}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.percent,o=t.position,a=t.unfilled,s={width:r+"%",height:0},l=(0,m["default"])((e={},(0,i["default"])(e,n+"-outer",!0),(0,i["default"])(e,n+"-fixed-outer","fixed"===o),(0,i["default"])(e,n+"-hide-outer","hide"===a),e));return p["default"].createElement("div",{className:l},p["default"].createElement("div",{className:n+"-bar",style:s}))},t}(p["default"].Component);t["default"]=v,v.defaultProps={prefixCls:"am-progress",percent:0,position:"fixed",unfilled:"show"},e.exports=t["default"]},[441,304],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(8),i=r(o),a=n(6),s=r(a),l=n(2),u=r(l),c=n(4),d=r(c),f=n(3),p=r(f),h=n(1),m=r(h),v=n(5),y=r(v),g=n(83),b=r(g),_=n(24),x=r(_),T=x["default"].Item,C=function(e){function t(){return(0,u["default"])(this,t),(0,d["default"])(this,e.apply(this,arguments))}return(0,p["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.listPrefixCls,o=t.style,a=t.name,l=t.defaultChecked,u=t.checked,c=t.disabled,d=t.children,f=t.className,p=t.onChange,h=(0,y["default"])((e={},(0,s["default"])(e,n+"-item",!0),(0,s["default"])(e,n+"-item-disabled",c===!0),(0,s["default"])(e,f,f),e)),v=c?{}:{onClick:function(){}};return m["default"].createElement(T,(0,i["default"])({prefixCls:r,style:o,className:h},v,{extra:m["default"].createElement(b["default"],{defaultChecked:l,checked:u,name:a,onChange:p,disabled:c})}),d)},t}(m["default"].Component);t["default"]=C,C.defaultProps={prefixCls:"am-radio",listPrefixCls:"am-list"},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(70),s=r(a),l=n(13),u=r(l),c=n(10),d=r(c);s["default"].RefreshControl.defaultProps=(0,d["default"])({},s["default"].RefreshControl.defaultProps,{prefixCls:"am-refresh-control",icon:i["default"].createElement("div",{style:{lineHeight:"50px"}},i["default"].createElement("div",{className:"am-refresh-control-pull"},i["default"].createElement(u["default"],{type:"arrow-down"})," \u4e0b\u62c9"),i["default"].createElement("div",{className:"am-refresh-control-release"},i["default"].createElement(u["default"],{type:"arrow-up"})," \u91ca\u653e")),loading:i["default"].createElement("div",{style:{lineHeight:"50px"}},i["default"].createElement(u["default"],{type:"loading"})),refreshing:!1}),t["default"]=s["default"].RefreshControl,e.exports=t["default"]},[441,306],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var i=n(6),a=r(i),s=n(2),l=r(s),u=n(4),c=r(u),d=n(3),f=r(d),p=n(1),h=r(p),m=n(46),v=r(m),y=n(5),g=r(y),b=function(e){function t(){return(0,l["default"])(this,t),(0,c["default"])(this,e.apply(this,arguments))}return(0,f["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.imgUrl,o=t.title,i=t.message,s=t.buttonText,l=t.buttonClick,u=t.buttonType,c=t.className,d=(0,g["default"])((e={},(0,a["default"])(e,""+n,!0),(0,a["default"])(e,c,c),e));return h["default"].createElement("div",{className:d},h["default"].createElement("div",{className:n+"-pic",style:{backgroundImage:"url("+r+")"}}),""!==o?h["default"].createElement("div",{className:n+"-title"},o):null,""!==i?h["default"].createElement("div",{className:n+"-message"},i):null,""!==s?h["default"].createElement("div",{className:n+"-button"},h["default"].createElement(v["default"],{type:u,onClick:l},s)):null)},t}(h["default"].Component);t["default"]=b,b.defaultProps={prefixCls:"am-result",imgUrl:"",title:"",message:"",buttonText:"",buttonType:"",buttonClick:o},e.exports=t["default"]},function(e,t,n){"use strict";n(7),n(75),n(307)},function(e,t){"use strict";function n(){}Object.defineProperty(t,"__esModule",{value:!0});t.defaultProps={prefixCls:"am-search",placeholder:"",onSubmit:n,onChange:n,onFocus:n,onBlur:n,onClear:n,showCancelButton:!1,cancelText:"\u53d6\u6d88",disabled:!1}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=n(185),y=function(e){function t(n){(0,s["default"])(this,t);var r=(0,u["default"])(this,e.call(this,n));r.onSubmit=function(e){e.preventDefault(),r.props.onSubmit(r.state.value)},r.onChange=function(e){var t=e.target.value;"value"in r.props||r.setState({value:t}),r.props.onChange(t)},r.onFocus=function(e){r.setState({focus:!0}),r.props.onFocus(e)},r.onBlur=function(e){r.setState({focus:!1}),r.props.onBlur(e)},r.onClear=function(){"value"in r.props||r.setState({value:""}),r.refs.searchInput.focus(),r.props.onClear(""),r.props.onChange("")},r.onCancel=function(){r.props.onCancel?r.props.onCancel(r.state.value):r.onClear(),r.refs.searchInput.blur()};var o=void 0;return o="value"in n?n.value:"defaultValue"in n?n.defaultValue:"",r.state={value:o,focus:!1},r}return(0,d["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:e.value})},t.prototype.componentDidMount=function(){/U3/i.test(navigator.userAgent)&&(this.initialInputContainerWidth=this.refs.searchInputContainer.offsetWidth,this.props.showCancelButton&&(this.refs.searchInputContainer.style.width=this.refs.searchInputContainer.offsetWidth-41*(window.devicePixelRatio||1)+"px"))},t.prototype.render=function(){var e,t,n,r=this.props,o=r.prefixCls,a=r.showCancelButton,s=r.disabled,l=r.placeholder,u=r.cancelText,c=r.className,d=this.state,f=d.value,h=d.focus,v=(0,m["default"])((e={},(0,i["default"])(e,""+o,!0),(0,i["default"])(e,o+"-start",a||h),(0,i["default"])(e,c,c),e)),y={};/U3/i.test(navigator.userAgent)&&this.initialInputContainerWidth&&(y=a||h?{width:this.initialInputContainerWidth-41*(window.devicePixelRatio||1)+"px"}:{width:this.initialInputContainerWidth+"px"});var g=(0,m["default"])((t={},(0,i["default"])(t,o+"-clear",!0),(0,i["default"])(t,o+"-clear-show",h&&f.length>0),t)),b=(0,m["default"])((n={},(0,i["default"])(n,o+"-cancel",!0),(0,i["default"])(n,o+"-all-cancel",a),n));return p["default"].createElement("form",{onSubmit:this.onSubmit,className:v},p["default"].createElement("div",{ref:"searchInputContainer",className:o+"-input",style:y},p["default"].createElement("input",{type:"search",className:o+"-value",value:f,disabled:s,placeholder:l,onChange:this.onChange,onFocus:this.onFocus,onBlur:this.onBlur,ref:"searchInput"}),p["default"].createElement("a",{onClick:this.onClear,className:g})),p["default"].createElement("div",{className:b,onClick:this.onCancel},u))},t}(p["default"].Component);t["default"]=y,y.defaultProps=v.defaultProps,e.exports=t["default"]},[441,308],function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=o(i),s=n(6),l=o(s),u=n(2),c=o(u),d=n(4),f=o(d),p=n(3),h=o(p),m=n(1),v=r(m),y=n(5),g=o(y),b=n(10),_=o(b),x=n(35),T=o(x),C=function(e){function t(){return(0,c["default"])(this,t),(0,f["default"])(this,e.apply(this,arguments))}return(0,h["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.label,r=t.prefixCls,o=t.selected,i=t.tintColor,s=t.enabled,u=t.touchFeedback,c=(0,g["default"])((e={},(0,l["default"])(e,r+"-item",!0),(0,l["default"])(e,r+"-item-selected",o),e)),d=(0,_["default"])({},this.props);return["prefixCls","label","selected","tintColor","enabled","touchFeedback"].forEach(function(e){d.hasOwnProperty(e)&&delete d[e]}),v.createElement("div",(0,a["default"])({className:c,style:{color:o?"#fff":i,backgroundColor:o?i:"#fff",borderColor:i}},d),v.createElement("div",{className:r+"-item-feedback",style:{backgroundColor:s&&u&&!o?i:"#fff"}}),n)},t}(v.Component);C.defaultProps={onClick:function(){},selected:!1},t["default"]=(0,T["default"])(C),e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=n(10),y=r(v),g=n(188),b=r(g),_=function(e){function t(n){(0,s["default"])(this,t);var r=(0,u["default"])(this,e.call(this,n));return r.state={selectedIndex:n.selectedIndex},r}return(0,d["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){e.selectedIndex!==this.state.selectedIndex&&this.setState({selectedIndex:e.selectedIndex})},t.prototype.onClick=function(e,t,n){var r=this.props,o=r.enabled,i=r.onChange,a=r.onValueChange;o&&this.state.selectedIndex!==t&&(e.nativeEvent.selectedSegmentIndex=t,e.nativeEvent.value=n,i(e),a(n),this.setState({selectedIndex:t}))},t.prototype.render=function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.style,a=n.enabled,s=n.values,l=n.className,u=n.tintColor,c=(0,m["default"])((e={},(0,i["default"])(e,l,!!l),(0,i["default"])(e,""+r,!0),e)),d=this.state.selectedIndex,f=s.map(function(e,n){return p["default"].createElement(b["default"],{key:n,prefixCls:r,label:e,enabled:a,tintColor:u,selected:n===d,onClick:function(r){return t.onClick(r,n,e)}})}),h=a?1:.5,v=(0,y["default"])({},o,{opacity:h,borderColor:u});return p["default"].createElement("div",{className:c,style:v},f)},t}(p["default"].Component);t["default"]=_,_.defaultProps={prefixCls:"am-segment",selectedIndex:0,enabled:!0,values:[],onChange:function(){},onValueChange:function(){},tintColor:"#108ee9",style:{}},e.exports=t["default"]},[441,309],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(2),i=r(o),a=n(4),s=r(a),l=n(3),u=r(l),c=n(1),d=r(c),f=n(374),p=r(f),h=function(e){function t(){return(0,i["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t.prototype.render=function(){return d["default"].createElement("div",{className:this.props.prefixCls+"-wrapper"},d["default"].createElement(p["default"],this.props))},t}(d["default"].Component);t["default"]=h,h.defaultProps={prefixCls:"am-slider",tipTransitionName:"zoom-down"},e.exports=t["default"]},[441,310],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(8),i=r(o),a=n(6),s=r(a),l=n(2),u=r(l),c=n(4),d=r(c),f=n(3),p=r(f),h=n(1),m=r(h),v=n(5),y=r(v),g=n(10),b=r(g),_=n(364),x=r(_),T=function(e){function t(){return(0,u["default"])(this,t),(0,d["default"])(this,e.apply(this,arguments))}return(0,p["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.className,o=t.showNumber,a=(0,y["default"])((e={},(0,s["default"])(e,r,!!r),(0,s["default"])(e,"showNumber",!!o),e)),l=(0,b["default"])({},this.props);return["className","prefixCls","showNumber"].forEach(function(e){l.hasOwnProperty(e)&&delete l[e]}),m["default"].createElement(x["default"],(0,i["default"])({ref:"inputNumber",prefixCls:n,className:a},l))},t}(m["default"].Component);t["default"]=T,T.defaultProps={prefixCls:"am-stepper",step:1,readOnly:!1,showNumber:!1},e.exports=t["default"]},[441,311],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(8),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(377),m=r(h),v=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e=this,t=this.props,n=t.current,r=t.direction;return p["default"].createElement(m["default"],(0,i["default"])({},this.props,{direction:r}),this.props.children.map(function(t,r){var o=-1;if(r<e.props.children.length-1){var i=e.props.children[r+1].props.status;"error"===i&&(o=r)}var a=o>-1?"error-tail":"",s=void 0,l=void 0;return t.props.icon?(s=t.props.icon,l="",r>0&&r<=n?s="check-circle":"error"===t.props.status?s="cross-circle":"process"===t.props.status&&(s="check-circle")):(l=r<=n?null:"ellipsis-item",s=r<=n?"check-circle-o":"error"===t.props.status?"cross-circle-o":"ellipsis"),l=a+" "+l,p["default"].cloneElement(t,{key:r,icon:s,className:l})}))},t}(p["default"].Component);t["default"]=v,v.Step=m["default"].Step,v.defaultProps={prefixCls:"am-steps",iconPrefix:"ant",labelPlacement:"vertical",current:0,direction:"vertical"},e.exports=t["default"]},[441,312],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),i=r(o),a=n(50),s=r(a),l=n(2),u=r(l),c=n(4),d=r(c),f=n(3),p=r(f),h=n(1),m=r(h),v=n(379),y=r(v),g=n(69),b=r(g),_=n(5),x=r(_),T=n(80),C=r(T),w=function(e){function t(n){(0,u["default"])(this,t);var r=(0,d["default"])(this,e.call(this,n));return r.onLongTap=function(){var e=r.props,t=e.disabled,n=e.onOpen;t||(n(),r.setState({showModal:!0}))},r.state={showModal:!1},r}return(0,p["default"])(t,e),t.prototype.onClose=function(){this.props.onClose(),this.setState({showModal:!1})},t.prototype.renderAndroid=function(){var e=this,t=this.props,n=t.children,r=t.title,o=t.autoClose,i=t.left,a=t.right,l={recognizers:{press:{time:500,threshold:50}}},u=[].concat((0,s["default"])(i),(0,s["default"])(a)).map(function(t){var n=t.onPress||function(){};return{text:t.text,style:t.style,onPress:function(){n(),o&&e.onClose()}}});return m["default"].createElement("div",null,m["default"].createElement(b["default"],{onPress:this.onLongTap,options:l
},n),this.state.showModal?m["default"].createElement(C["default"],{animated:!1,title:r,transparent:!0,closable:!1,maskClosable:!0,footer:u,visible:!0}):null)},t.prototype.render=function(){var e,t=this.props,n=t.className,r=t.prefixCls,o=t.left,a=t.right,s=t.autoClose,l=t.disabled,u=t.onOpen,c=t.onClose,d=t.children,f=!!navigator.userAgent.match(/Android/i),p=(0,x["default"])((e={},(0,i["default"])(e,""+r,1),(0,i["default"])(e,n,!!n),e));return o.length||a.length?m["default"].createElement("div",{className:p},f?this.renderAndroid():m["default"].createElement(y["default"],{prefixCls:r,left:o,right:a,autoClose:s,disabled:l,onOpen:u,onClose:c},d)):m["default"].createElement("div",{className:p},d)},t}(m["default"].Component);w.defaultProps={prefixCls:"am-swipe",title:"\u8bf7\u786e\u8ba4\u64cd\u4f5c",autoClose:!1,disabled:!1,left:[],right:[],onOpen:function(){},onClose:function(){}},t["default"]=w,e.exports=t["default"]},function(e,t,n){"use strict";n(7),n(81),n(314)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(8),i=r(o),a=n(6),s=r(a),l=n(2),u=r(l),c=n(4),d=r(c),f=n(3),p=r(f),h=n(1),m=r(h),v=n(5),y=r(v),g=function(e){function t(){(0,u["default"])(this,t);for(var n=arguments.length,r=Array(n),o=0;o<n;o++)r[o]=arguments[o];var i=(0,d["default"])(this,e.call.apply(e,[this].concat(r)));return i.onChange=function(e){var t=e.target.checked;i.props.onChange(t)},i}return(0,p["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.style,o=t.name,a=t.checked,l=t.disabled,u=t.className,c=(0,y["default"])((e={},(0,s["default"])(e,""+n,!0),(0,s["default"])(e,u,u),e));return m["default"].createElement("label",{className:c,style:r},m["default"].createElement("input",(0,i["default"])({type:"checkbox",name:o,className:n+"-checkbox"},l?{disabled:"disabled"}:"",{checked:a,onChange:this.onChange})),m["default"].createElement("div",{className:"checkbox"}))},t}(m["default"].Component);t["default"]=g,g.defaultProps={prefixCls:"am-switch",name:"",checked:!1,disabled:!1,onChange:function(){}},e.exports=t["default"]},[441,315],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),i=r(o),a=n(4),s=r(a),l=n(3),u=r(l),c=n(1),d=r(c),f=n(73),p=r(f),h=function(e){function t(){return(0,i["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t.prototype.render=function(){var e=this.props,t=e.title,n=e.icon,r=e.selectedIcon,o=e.prefixCls,i=e.badge,a=e.selected,s=e.unselectedTintColor,l=e.tintColor;return d["default"].createElement("div",null,d["default"].createElement("div",{className:o+"-icon"},i?d["default"].createElement(p["default"],{text:i,className:o+"-badge"},d["default"].createElement("img",{className:o+"-image",src:a?r.uri:n.uri,alt:t})):d["default"].createElement("img",{className:o+"-image",src:a?r.uri:n.uri,alt:t})),d["default"].createElement("p",{className:o+"-title",style:{color:a?l:s}},t))},t}(d["default"].Component);t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(112),s=r(a),l=n(201),u=r(l),c=n(67),d=r(c),f=n(390),p=r(f),h=i["default"].createClass({displayName:"AntTabBar",statics:{Item:function(){}},getDefaultProps:function(){return{prefixCls:"am-tab-bar",barTintColor:"white",tintColor:"#108ee9",unselectedTintColor:"#888"}},onChange:function(e){i["default"].Children.forEach(this.props.children,function(t){t.key===e&&t.props.onPress&&t.props.onPress()})},renderTabBar:function(){var e=this.props,t=e.onTabClick,n=e.barTintColor,r=e.hidden,o=e.prefixCls,a=r?o+"-bar-hidden":"";return i["default"].createElement(p["default"],{className:a,onTabClick:t,style:{backgroundColor:n}})},renderTabContent:function(){return i["default"].createElement(d["default"],{animated:!1})},render:function(){var e=this,t=void 0,n=[];i["default"].Children.forEach(this.props.children,function(e){e.props.selected&&(t=e.key),n.push(e)});var r=this.props,o=r.tintColor,l=r.unselectedTintColor,c=n.map(function(t){var n=t.props,r=i["default"].createElement(u["default"],{prefixCls:e.props.prefixCls+"-tab",badge:n.badge,selected:n.selected,icon:n.icon,selectedIcon:n.selectedIcon,title:n.title,tintColor:o,unselectedTintColor:l});return i["default"].createElement(a.TabPane,{placeholder:"\u6b63\u5728\u52a0\u8f7d",tab:r,key:t.key},n.children)});return i["default"].createElement(s["default"],{renderTabBar:this.renderTabBar,renderTabContent:this.renderTabContent,tabBarPosition:"bottom",prefixCls:this.props.prefixCls,activeKey:t,onChange:this.onChange},c)}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";n(7),n(316),n(74)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(8),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(10),m=r(h),v=n(384),y=r(v),g=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e=this.props,t=e.columns,n=e.dataSource,r=e.direction,o=e.scrollX,a=e.titleFixed,s=this.props,l=s.style,u=s.className,c=(0,m["default"])({},this.props);["style","className"].forEach(function(e){c.hasOwnProperty(e)&&delete c[e]});var d=void 0;return r&&"vertical"!==r?"horizon"===r?(t[0].className="am-table-horizonTitle",d=p["default"].createElement(y["default"],(0,i["default"])({},c,{columns:t,data:n,className:"am-table",showHeader:!1,scroll:{x:o}}))):"mix"===r&&(t[0].className="am-table-horizonTitle",d=p["default"].createElement(y["default"],(0,i["default"])({},c,{columns:t,data:n,className:"am-table",scroll:{x:o}}))):d=a?p["default"].createElement(y["default"],(0,i["default"])({},c,{columns:t,data:n,className:"am-table",scroll:{x:!0},showHeader:!1})):p["default"].createElement(y["default"],(0,i["default"])({},c,{columns:t,data:n,className:"am-table",scroll:{x:o}})),p["default"].createElement("div",{className:u,style:l},d)},t}(p["default"].Component);t["default"]=g,g.defaultProps={dataSource:[],prefixCls:"am-table"},e.exports=t["default"]},[441,317],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),i=r(o),a=n(1),s=r(a),l=n(112),u=r(l),c=n(389),d=r(c),f=n(67),p=r(f),h=n(386),m=r(h),v=s["default"].createClass({displayName:"Tabs",statics:{TabPane:l.TabPane},getDefaultProps:function(){return{prefixCls:"am-tabs",animated:!0,swipeable:!0,onChange:function(){},tabBarPosition:"top",onTabClick:function(){}}},renderTabBar:function(){var e=this.props;return s["default"].createElement(m["default"],{onTabClick:e.onTabClick,inkBarAnimated:e.animated})},renderTabContent:function(){var e=this.props,t=e.animated,n=e.swipeable;return n?s["default"].createElement(d["default"],{animated:t}):s["default"].createElement(p["default"],{animated:t})},render:function(){return s["default"].createElement(u["default"],(0,i["default"])({renderTabBar:this.renderTabBar,renderTabContent:this.renderTabContent},this.props))}});t["default"]=v,e.exports=t["default"]},[441,318],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=function(e){function t(n){(0,s["default"])(this,t);var r=(0,u["default"])(this,e.call(this,n));return r.onClick=function(){var e=r.props,t=e.disabled,n=e.onChange;if(!t){var o=r.state.selected;r.setState({selected:!o},function(){n(!o)})}},r.state={selected:n.selected,closed:!1},r}return(0,d["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){this.props.selected!==e.selected&&this.setState({selected:e.selected})},t.prototype.render=function(){var e,t=this.props,n=t.children,r=t.className,o=t.prefixCls,a=t.disabled,s=t.small,l=t.style,u=(0,m["default"])((e={},(0,i["default"])(e,r,!!r),(0,i["default"])(e,""+o,!0),(0,i["default"])(e,o+"-small",s),(0,i["default"])(e,o+"-normal",!this.state.selected&&!a),(0,i["default"])(e,o+"-active",this.state.selected&&!a),(0,i["default"])(e,o+"-disabled",a),e));return p["default"].createElement("div",{className:u,onClick:this.onClick,style:l},p["default"].createElement("div",{className:o+"-text"},n))},t}(p["default"].Component);t["default"]=v,v.defaultProps={prefixCls:"am-tag",disabled:!1,selected:!1,small:!1,onChange:function(){}},e.exports=t["default"]},[441,319],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(2),i=r(o),a=n(4),s=r(a),l=n(3),u=r(l),c=n(1),d=r(c),f=n(88),p=r(f),h=function(e){function t(){return(0,i["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t.prototype.render=function(){return d["default"].createElement(p["default"],this.props)},t}(d["default"].Component);t["default"]=h,h.defaultProps={Component:"span"},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e){return"undefined"==typeof e||null===e?"":e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var a=n(8),s=r(a),l=n(6),u=r(l),c=n(2),d=r(c),f=n(4),p=r(f),h=n(3),m=r(h),v=n(1),y=r(v),g=n(5),b=r(g),_=function(e){function t(n){(0,d["default"])(this,t);var r=(0,p["default"])(this,e.call(this,n));return r.onChange=function(e){var t=e.target.value,n=r.props.onChange;n(t)},r.onBlur=function(e){r.debounceTimeout=setTimeout(function(){r.setState({focus:!1})},500);var t=e.target.value;r.props.onBlur(t)},r.onFocus=function(e){r.setState({focus:!0});var t=e.target.value;r.props.onFocus(t)},r.onErrorClick=function(){r.props.onErrorClick()},r.clearInput=function(){r.props.onChange("")},r.state={focus:!1},r}return(0,m["default"])(t,e),t.prototype.componentDidMount=function(){this.props.autoHeight&&(this.initialTextHeight=this.refs.textarea.offsetHeight,this.componentDidUpdate())},t.prototype.componentDidUpdate=function(){if(this.props.autoHeight){var e=this.refs.textarea;e.style.height="",e.style.height=Math.max(this.initialTextHeight,e.scrollHeight)+"px"}},t.prototype.shouldComponentUpdate=function(e,t){return e.value!==this.props.value||e.defaultValue!==this.props.defaultValue||e.error!==this.props.error||e.disabled!==this.props.disabled||e.editable!==this.props.editable||t.focus!==this.state.focus},t.prototype.componentWillUnmount=function(){this.debounceTimeout&&clearTimeout(this.debounceTimeout)},t.prototype.render=function(){var e,t,n=this.props,r=n.prefixCls,o=n.prefixListCls,a=n.style,l=n.title,c=n.name,d=n.value,f=n.defaultValue,p=n.placeholder,h=n.clear,m=n.rows,v=n.count,g=n.editable,_=n.disabled,x=n.error,T=n.className,C=n.labelNumber,w=n.autoHeight,S=void 0;S=void 0!==d?{value:i(d)}:{defaultValue:f};var P=this.state.focus,E=(0,b["default"])((e={},(0,u["default"])(e,o+"-item",!0),(0,u["default"])(e,r+"-item",!0),(0,u["default"])(e,r+"-disabled",_),(0,u["default"])(e,r+"-item-single-line",1===m&&!w),(0,u["default"])(e,r+"-error",x),(0,u["default"])(e,r+"-focus",P),(0,u["default"])(e,T,T),e)),M=(0,b["default"])((t={},(0,u["default"])(t,r+"-label",!0),(0,u["default"])(t,r+"-label-2",2===C),(0,u["default"])(t,r+"-label-3",3===C),(0,u["default"])(t,r+"-label-4",4===C),(0,u["default"])(t,r+"-label-5",5===C),(0,u["default"])(t,r+"-label-6",6===C),(0,u["default"])(t,r+"-label-7",7===C),t));return y["default"].createElement("div",{className:E,style:a},l?y["default"].createElement("div",{className:M},l):null,y["default"].createElement("div",{className:r+"-control"},y["default"].createElement("textarea",(0,s["default"])({},S,{ref:"textarea",name:c,rows:m,placeholder:p,maxLength:v,onChange:this.onChange,onBlur:this.onBlur,onFocus:this.onFocus,readOnly:!g,disabled:_}))),h&&g&&d&&d.length>0?y["default"].createElement("div",{className:r+"-clear",onClick:this.clearInput,onTouchStart:this.clearInput}):null,x?y["default"].createElement("div",{className:r+"-error-extra",onClick:this.onErrorClick}):null,v>0&&m>1?y["default"].createElement("span",{className:r+"-count"},y["default"].createElement("span",null,d.length),"/",v):null)},t}(y["default"].Component);t["default"]=_,_.defaultProps={prefixCls:"am-textarea",prefixListCls:"am-list",title:"",autoHeight:!1,editable:!0,disabled:!1,name:"",defaultValue:"",placeholder:"",clear:!1,rows:1,onChange:o,onBlur:o,onFocus:o,onErrorClick:o,error:!1,labelNumber:4},e.exports=t["default"]},[443,320],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var o=n(6),i=r(o),a=n(2),s=r(a),l=n(4),u=r(l),c=n(3),d=r(c),f=n(1),p=r(f),h=n(5),m=r(h),v=function(e){function t(){return(0,s["default"])(this,t),(0,u["default"])(this,e.apply(this,arguments))}return(0,d["default"])(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.size,o=t.className,a=t.style,s=t.onClick,l=(0,m["default"])((e={},(0,i["default"])(e,""+n,!0),(0,i["default"])(e,n+"-"+r,!0),(0,i["default"])(e,o,!!o),e));return p["default"].createElement("div",{className:l,style:a,onClick:s})},t}(p["default"].Component);t["default"]=v,v.defaultProps={prefixCls:"am-whitespace",size:"md"},e.exports=t["default"]},[441,322],function(e,t,n){e.exports={"default":n(226),__esModule:!0}},function(e,t,n){e.exports={"default":n(227),__esModule:!0}},function(e,t,n){e.exports={"default":n(228),__esModule:!0}},function(e,t,n){e.exports={"default":n(229),__esModule:!0}},function(e,t,n){e.exports={"default":n(230),__esModule:!0}},function(e,t,n){e.exports={"default":n(231),__esModule:!0}},function(e,t,n){e.exports={"default":n(232),__esModule:!0}},function(e,t,n){e.exports={"default":n(233),__esModule:!0}},function(e,t,n){e.exports={"default":n(234),__esModule:!0}},function(e,t,n){e.exports={"default":n(235),__esModule:!0}},function(e,t,n){function r(e){if(!e||!e.nodeType)throw new Error("A DOM element reference is required");this.el=e,this.list=e.classList}try{var o=n(91)}catch(i){var o=n(91)}var a=/\s+/,s=Object.prototype.toString;e.exports=function(e){return new r(e)},r.prototype.add=function(e){if(this.list)return this.list.add(e),this;var t=this.array(),n=o(t,e);return~n||t.push(e),this.el.className=t.join(" "),this},r.prototype.remove=function(e){if("[object RegExp]"==s.call(e))return this.removeMatching(e);if(this.list)return this.list.remove(e),this;var t=this.array(),n=o(t,e);return~n&&t.splice(n,1),this.el.className=t.join(" "),this},r.prototype.removeMatching=function(e){for(var t=this.array(),n=0;n<t.length;n++)e.test(t[n])&&this.remove(t[n]);return this},r.prototype.toggle=function(e,t){return this.list?("undefined"!=typeof t?t!==this.list.toggle(e,t)&&this.list.toggle(e):this.list.toggle(e),this):("undefined"!=typeof t?t?this.add(e):this.remove(e):this.has(e)?this.remove(e):this.add(e),this)},r.prototype.array=function(){var e=this.el.getAttribute("class")||"",t=e.replace(/^\s+|\s+$/g,""),n=t.split(a);return""===n[0]&&n.shift(),n},r.prototype.has=r.prototype.contains=function(e){return this.list?this.list.contains(e):!!~o(this.array(),e)}},function(e,t,n){n(40),n(260),e.exports=n(11).Array.from},function(e,t,n){n(65),n(40),e.exports=n(258)},function(e,t,n){n(65),n(40),e.exports=n(259)},function(e,t,n){n(262),e.exports=n(11).Object.assign},function(e,t,n){n(263);var r=n(11).Object;e.exports=function(e,t){return r.create(e,t)}},function(e,t,n){n(264);var r=n(11).Object;e.exports=function(e,t,n){return r.defineProperty(e,t,n)}},function(e,t,n){n(265),e.exports=n(11).Object.keys},function(e,t,n){n(266),e.exports=n(11).Object.setPrototypeOf},function(e,t,n){n(268),n(267),n(269),n(270),e.exports=n(11).Symbol},function(e,t,n){n(40),n(65),e.exports=n(64).f("iterator")},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t){e.exports=function(){}},function(e,t,n){var r=n(21),o=n(101),i=n(257);e.exports=function(e){return function(t,n,a){var s,l=r(t),u=o(l.length),c=i(a,u);if(e&&n!=n){for(;u>c;)if(s=l[c++],s!=s)return!0}else for(;u>c;c++)if((e||c in l)&&l[c]===n)return e||c||0;return!e&&-1}}},function(e,t,n){"use strict";var r=n(16),o=n(33);e.exports=function(e,t,n){t in e?r.f(e,t,o(0,n)):e[t]=n}},function(e,t,n){var r=n(29),o=n(57),i=n(37);e.exports=function(e){var t=r(e),n=o.f;if(n)for(var a,s=n(e),l=i.f,u=0;s.length>u;)l.call(e,a=s[u++])&&t.push(a);return t}},function(e,t,n){e.exports=n(15).document&&document.documentElement},function(e,t,n){var r=n(28),o=n(12)("iterator"),i=Array.prototype;e.exports=function(e){return void 0!==e&&(r.Array===e||i[o]===e)}},function(e,t,n){var r=n(51);e.exports=Array.isArray||function(e){return"Array"==r(e)}},function(e,t,n){var r=n(18);e.exports=function(e,t,n,o){try{return o?t(r(n)[0],n[1]):t(n)}catch(i){var a=e["return"];throw void 0!==a&&r(a.call(e)),i}}},function(e,t,n){"use strict";var r=n(56),o=n(33),i=n(58),a={};n(27)(a,n(12)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=r(a,{next:o(1,n)}),i(e,t+" Iterator")}},function(e,t,n){var r=n(12)("iterator"),o=!1;try{var i=[7][r]();i["return"]=function(){o=!0},Array.from(i,function(){throw 2})}catch(a){}e.exports=function(e,t){if(!t&&!o)return!1;var n=!1;try{var i=[7],a=i[r]();a.next=function(){return{done:n=!0}},i[r]=function(){return a},e(i)}catch(s){}return n}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){var r=n(29),o=n(21);e.exports=function(e,t){for(var n,i=o(e),a=r(i),s=a.length,l=0;s>l;)if(i[n=a[l++]]===t)return n}},function(e,t,n){var r=n(39)("meta"),o=n(32),i=n(20),a=n(16).f,s=0,l=Object.isExtensible||function(){return!0},u=!n(26)(function(){return l(Object.preventExtensions({}))}),c=function(e){a(e,r,{value:{i:"O"+ ++s,w:{}}})},d=function(e,t){if(!o(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!i(e,r)){if(!l(e))return"F";if(!t)return"E";c(e)}return e[r].i},f=function(e,t){if(!i(e,r)){if(!l(e))return!0;if(!t)return!1;c(e)}return e[r].w},p=function(e){return u&&h.NEED&&l(e)&&!i(e,r)&&c(e),e},h=e.exports={KEY:r,NEED:!1,fastKey:d,getWeak:f,onFreeze:p}},function(e,t,n){"use strict";var r=n(29),o=n(57),i=n(37),a=n(38),s=n(95),l=Object.assign;e.exports=!l||n(26)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=l({},e)[n]||Object.keys(l({},t)).join("")!=r})?function(e,t){for(var n=a(e),l=arguments.length,u=1,c=o.f,d=i.f;l>u;)for(var f,p=s(arguments[u++]),h=c?r(p).concat(c(p)):r(p),m=h.length,v=0;m>v;)d.call(p,f=h[v++])&&(n[f]=p[f]);return n}:l},function(e,t,n){var r=n(16),o=n(18),i=n(29);e.exports=n(19)?Object.defineProperties:function(e,t){o(e);for(var n,a=i(t),s=a.length,l=0;s>l;)r.f(e,n=a[l++],t[n]);return e}},function(e,t,n){var r=n(21),o=n(98).f,i={}.toString,a="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],s=function(e){try{return o(e)}catch(t){return a.slice()}};e.exports.f=function(e){return a&&"[object Window]"==i.call(e)?s(e):o(r(e))}},function(e,t,n){var r=n(20),o=n(38),i=n(59)("IE_PROTO"),a=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=o(e),r(e,i)?e[i]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?a:null}},function(e,t,n){var r=n(14),o=n(11),i=n(26);e.exports=function(e,t){var n=(o.Object||{})[e]||Object[e],a={};a[e]=t(n),r(r.S+r.F*i(function(){n(1)}),"Object",a)}},function(e,t,n){var r=n(32),o=n(18),i=function(e,t){if(o(e),!r(t)&&null!==t)throw TypeError(t+": can't set as prototype!")};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{r=n(52)(Function.call,n(97).f(Object.prototype,"__proto__").set,2),r(e,[]),t=!(e instanceof Array)}catch(o){t=!0}return function(e,n){return i(e,n),t?e.__proto__=n:r(e,n),e}}({},!1):void 0),check:i}},function(e,t,n){var r=n(61),o=n(53);e.exports=function(e){return function(t,n){var i,a,s=String(o(t)),l=r(n),u=s.length;return l<0||l>=u?e?"":void 0:(i=s.charCodeAt(l),i<55296||i>56319||l+1===u||(a=s.charCodeAt(l+1))<56320||a>57343?e?s.charAt(l):i:e?s.slice(l,l+2):(i-55296<<10)+(a-56320)+65536)}}},function(e,t,n){var r=n(61),o=Math.max,i=Math.min;e.exports=function(e,t){return e=r(e),e<0?o(e+t,0):i(e,t)}},function(e,t,n){var r=n(18),o=n(102);e.exports=n(11).getIterator=function(e){var t=o(e);if("function"!=typeof t)throw TypeError(e+" is not iterable!");return r(t.call(e))}},function(e,t,n){var r=n(92),o=n(12)("iterator"),i=n(28);e.exports=n(11).isIterable=function(e){var t=Object(e);return void 0!==t[o]||"@@iterator"in t||i.hasOwnProperty(r(t))}},function(e,t,n){"use strict";var r=n(52),o=n(14),i=n(38),a=n(244),s=n(242),l=n(101),u=n(239),c=n(102);o(o.S+o.F*!n(246)(function(e){Array.from(e)}),"Array",{from:function(e){var t,n,o,d,f=i(e),p="function"==typeof this?this:Array,h=arguments.length,m=h>1?arguments[1]:void 0,v=void 0!==m,y=0,g=c(f);if(v&&(m=r(m,h>2?arguments[2]:void 0,2)),void 0==g||p==Array&&s(g))for(t=l(f.length),n=new p(t);t>y;y++)u(n,y,v?m(f[y],y):f[y]);else for(d=g.call(f),n=new p;!(o=d.next()).done;y++)u(n,y,v?a(d,m,[o.value,y],!0):o.value);return n.length=y,n}})},function(e,t,n){"use strict";var r=n(237),o=n(247),i=n(28),a=n(21);e.exports=n(96)(Array,"Array",function(e,t){this._t=a(e),this._i=0,this._k=t},function(){var e=this._t,t=this._k,n=this._i++;return!e||n>=e.length?(this._t=void 0,o(1)):"keys"==t?o(0,n):"values"==t?o(0,e[n]):o(0,[n,e[n]])},"values"),i.Arguments=i.Array,r("keys"),r("values"),r("entries")},function(e,t,n){var r=n(14);r(r.S+r.F,"Object",{assign:n(250)})},function(e,t,n){var r=n(14);r(r.S,"Object",{create:n(56)})},function(e,t,n){var r=n(14);r(r.S+r.F*!n(19),"Object",{defineProperty:n(16).f})},function(e,t,n){var r=n(38),o=n(29);n(254)("keys",function(){return function(e){return o(r(e))}})},function(e,t,n){var r=n(14);r(r.S,"Object",{setPrototypeOf:n(255).set})},function(e,t){},function(e,t,n){"use strict";var r=n(15),o=n(20),i=n(19),a=n(14),s=n(100),l=n(249).KEY,u=n(26),c=n(60),d=n(58),f=n(39),p=n(12),h=n(64),m=n(63),v=n(248),y=n(240),g=n(243),b=n(18),_=n(21),x=n(62),T=n(33),C=n(56),w=n(252),S=n(97),P=n(16),E=n(29),M=S.f,k=P.f,O=w.f,N=r.Symbol,D=r.JSON,R=D&&D.stringify,A="prototype",I=p("_hidden"),j=p("toPrimitive"),L={}.propertyIsEnumerable,W=c("symbol-registry"),H=c("symbols"),Y=c("op-symbols"),F=Object[A],V="function"==typeof N,B=r.QObject,z=!B||!B[A]||!B[A].findChild,U=i&&u(function(){return 7!=C(k({},"a",{get:function(){return k(this,"a",{value:7}).a}})).a})?function(e,t,n){var r=M(F,t);r&&delete F[t],k(e,t,n),r&&e!==F&&k(F,t,r)}:k,X=function(e){var t=H[e]=C(N[A]);return t._k=e,t},K=V&&"symbol"==typeof N.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof N},G=function(e,t,n){return e===F&&G(Y,t,n),b(e),t=x(t,!0),b(n),o(H,t)?(n.enumerable?(o(e,I)&&e[I][t]&&(e[I][t]=!1),n=C(n,{enumerable:T(0,!1)})):(o(e,I)||k(e,I,T(1,{})),e[I][t]=!0),U(e,t,n)):k(e,t,n)},q=function(e,t){b(e);for(var n,r=y(t=_(t)),o=0,i=r.length;i>o;)G(e,n=r[o++],t[n]);return e},Z=function(e,t){return void 0===t?C(e):q(C(e),t)},Q=function(e){var t=L.call(this,e=x(e,!0));return!(this===F&&o(H,e)&&!o(Y,e))&&(!(t||!o(this,e)||!o(H,e)||o(this,I)&&this[I][e])||t)},$=function(e,t){if(e=_(e),t=x(t,!0),e!==F||!o(H,t)||o(Y,t)){var n=M(e,t);return!n||!o(H,t)||o(e,I)&&e[I][t]||(n.enumerable=!0),n}},J=function(e){for(var t,n=O(_(e)),r=[],i=0;n.length>i;)o(H,t=n[i++])||t==I||t==l||r.push(t);return r},ee=function(e){for(var t,n=e===F,r=O(n?Y:_(e)),i=[],a=0;r.length>a;)!o(H,t=r[a++])||n&&!o(F,t)||i.push(H[t]);return i};V||(N=function(){if(this instanceof N)throw TypeError("Symbol is not a constructor!");var e=f(arguments.length>0?arguments[0]:void 0),t=function(n){this===F&&t.call(Y,n),o(this,I)&&o(this[I],e)&&(this[I][e]=!1),U(this,e,T(1,n))};return i&&z&&U(F,e,{configurable:!0,set:t}),X(e)},s(N[A],"toString",function(){return this._k}),S.f=$,P.f=G,n(98).f=w.f=J,n(37).f=Q,n(57).f=ee,i&&!n(55)&&s(F,"propertyIsEnumerable",Q,!0),h.f=function(e){return X(p(e))}),a(a.G+a.W+a.F*!V,{Symbol:N});for(var te="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),ne=0;te.length>ne;)p(te[ne++]);for(var te=E(p.store),ne=0;te.length>ne;)m(te[ne++]);a(a.S+a.F*!V,"Symbol",{"for":function(e){return o(W,e+="")?W[e]:W[e]=N(e)},keyFor:function(e){if(K(e))return v(W,e);throw TypeError(e+" is not a symbol!")},useSetter:function(){z=!0},useSimple:function(){z=!1}}),a(a.S+a.F*!V,"Object",{create:Z,defineProperty:G,defineProperties:q,getOwnPropertyDescriptor:$,getOwnPropertyNames:J,getOwnPropertySymbols:ee}),D&&a(a.S+a.F*(!V||u(function(){var e=N();return"[null]"!=R([e])||"{}"!=R({a:e})||"{}"!=R(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!K(e)){for(var t,n,r=[e],o=1;arguments.length>o;)r.push(arguments[o++]);return t=r[1],"function"==typeof t&&(n=t),!n&&g(t)||(t=function(e,t){if(n&&(t=n.call(this,e,t)),!K(t))return t}),r[1]=t,R.apply(D,r)}}}),N[A][j]||n(27)(N[A],j,N[A].valueOf),d(N,"Symbol"),d(Math,"Math",!0),d(r.JSON,"JSON",!0)},function(e,t,n){n(63)("asyncIterator")},function(e,t,n){n(63)("observable")},function(e,t){"use strict";function n(){var e=document.createElement("div"),t=e.style;"AnimationEvent"in window||delete i.animationend.animation,"TransitionEvent"in window||delete i.transitionend.transition;for(var n in i)if(i.hasOwnProperty(n)){var r=i[n];for(var o in r)if(o in t){a.push(r[o]);break}}}function r(e,t,n){e.addEventListener(t,n,!1)}function o(e,t,n){e.removeEventListener(t,n,!1)}Object.defineProperty(t,"__esModule",{value:!0});var i={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},a=[];"undefined"!=typeof window&&"undefined"!=typeof document&&n();var s={addEndEventListener:function(e,t){return 0===a.length?void window.setTimeout(t,0):void a.forEach(function(n){r(e,n,t)})},endEvents:a,removeEndEventListener:function(e,t){0!==a.length&&a.forEach(function(n){o(e,n,t)})}};t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r){var o=a["default"].clone(e),i={width:t.width,height:t.height};return r.adjustX&&o.left<n.left&&(o.left=n.left),r.resizeWidth&&o.left>=n.left&&o.left+i.width>n.right&&(i.width-=o.left+i.width-n.right),r.adjustX&&o.left+i.width>n.right&&(o.left=Math.max(n.right-i.width,n.left)),r.adjustY&&o.top<n.top&&(o.top=n.top),r.resizeHeight&&o.top>=n.top&&o.top+i.height>n.bottom&&(i.height-=o.top+i.height-n.bottom),r.adjustY&&o.top+i.height>n.bottom&&(o.top=Math.max(n.bottom-i.height,n.top)),a["default"].mix(o,i)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(34),a=r(i);t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){var n=t.charAt(0),r=t.charAt(1),o=e.width,i=e.height,a=void 0,s=void 0;return a=e.left,s=e.top,"c"===n?s+=i/2:"b"===n&&(s+=i),"c"===r?a+=o/2:"r"===r&&(a+=o),{left:a,top:s}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var i=void 0,s=void 0,l=void 0,u=void 0;return i={left:e.left,top:e.top},l=(0,a["default"])(t,n[1]),u=(0,a["default"])(e,n[0]),s=[u.left-l.left,u.top-l.top],{left:i.left-s[0]+r[0]-o[0],top:i.top-s[1]+r[1]-o[1]}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(273),a=r(i);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=void 0,n=void 0,r=void 0;if(a["default"].isWindow(e)||9===e.nodeType){var o=a["default"].getWindow(e);t={left:a["default"].getWindowScrollLeft(o),top:a["default"].getWindowScrollTop(o)},n=a["default"].viewportWidth(o),r=a["default"].viewportHeight(o)}else t=a["default"].offset(e),n=a["default"].outerWidth(e),r=a["default"].outerHeight(e);return t.width=n,t.height=r,t}Object.defineProperty(t,"__esModule",{value:!0});var i=n(34),a=r(i);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){for(var t={left:0,right:1/0,top:0,bottom:1/0},n=(0,l["default"])(e),r=void 0,o=void 0,i=void 0,s=e.ownerDocument,u=s.defaultView||s.parentWindow,c=s.body,d=s.documentElement;n;){if(navigator.userAgent.indexOf("MSIE")!==-1&&0===n.clientWidth||n===c||n===d||"visible"===a["default"].css(n,"overflow")){if(n===c||n===d)break}else{var f=a["default"].offset(n);f.left+=n.clientLeft,f.top+=n.clientTop,t.top=Math.max(t.top,f.top),t.right=Math.min(t.right,f.left+n.clientWidth),t.bottom=Math.min(t.bottom,f.top+n.clientHeight),t.left=Math.max(t.left,f.left)}n=(0,l["default"])(n)}return r=a["default"].getWindowScrollLeft(u),o=a["default"].getWindowScrollTop(u),t.left=Math.max(t.left,r),t.top=Math.max(t.top,o),i={width:a["default"].viewportWidth(u),height:a["default"].viewportHeight(u)},t.right=Math.min(t.right,r+i.width),t.bottom=Math.min(t.bottom,o+i.height),t.top>=0&&t.left>=0&&t.bottom>t.top&&t.right>t.left?t:null}Object.defineProperty(t,"__esModule",{value:!0});var i=n(34),a=r(i),s=n(104),l=r(s);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return e.left<n.left||e.left+t.width>n.right}function i(e,t,n){return e.top<n.top||e.top+t.height>n.bottom}function a(e,t,n){return e.left>n.right||e.left+t.width<n.left}function s(e,t,n){return e.top>n.bottom||e.top+t.height<n.top}function l(e,t,n){var r=[];return h["default"].each(e,function(e){r.push(e.replace(t,function(e){return n[e]}))}),r}function u(e,t){return e[t]=-e[t],e}function c(e,t){var n=void 0;return n=/%$/.test(e)?parseInt(e.substring(0,e.length-1),10)/100*t:parseInt(e,10),n||0}function d(e,t){e[0]=c(e[0],t.width),e[1]=c(e[1],t.height)}function f(e,t,n){var r=n.points,c=n.offset||[0,0],f=n.targetOffset||[0,0],p=n.overflow,m=n.target||t,v=n.source||e;c=[].concat(c),f=[].concat(f),p=p||{};var y={},b=0,x=(0,g["default"])(v),C=(0,T["default"])(v),S=(0,T["default"])(m);d(c,C),d(f,S);var P=(0,w["default"])(C,S,r,c,f),E=h["default"].merge(C,P);if(x&&(p.adjustX||p.adjustY)){if(p.adjustX&&o(P,C,x)){var M=l(r,/[lr]/gi,{l:"r",r:"l"}),k=u(c,0),O=u(f,0),N=(0,w["default"])(C,S,M,k,O);a(N,C,x)||(b=1,r=M,c=k,f=O)}if(p.adjustY&&i(P,C,x)){var D=l(r,/[tb]/gi,{t:"b",b:"t"}),R=u(c,1),A=u(f,1),I=(0,w["default"])(C,S,D,R,A);s(I,C,x)||(b=1,r=D,c=R,f=A)}b&&(P=(0,w["default"])(C,S,r,c,f),h["default"].mix(E,P)),y.adjustX=p.adjustX&&o(P,C,x),y.adjustY=p.adjustY&&i(P,C,x),(y.adjustX||y.adjustY)&&(E=(0,_["default"])(P,C,x,y))}return E.width!==C.width&&h["default"].css(v,"width",h["default"].width(v)+E.width-C.width),E.height!==C.height&&h["default"].css(v,"height",h["default"].height(v)+E.height-C.height),h["default"].offset(v,{left:E.left,top:E.top},{useCssRight:n.useCssRight,useCssBottom:n.useCssBottom,useCssTransform:n.useCssTransform}),{points:r,offset:c,targetOffset:f,overflow:y}}Object.defineProperty(t,"__esModule",{value:!0});var p=n(34),h=r(p),m=n(104),v=r(m),y=n(276),g=r(y),b=n(272),_=r(b),x=n(275),T=r(x),C=n(274),w=r(C);f.__getOffsetParent=v["default"],f.__getVisibleRectForElement=g["default"],t["default"]=f,e.exports=t["default"]},function(e,t){"use strict";function n(){if(void 0!==c)return c;c="";var e=document.createElement("p").style,t="Transform";for(var n in d)n+t in e&&(c=n);return c}function r(){return n()?n()+"TransitionProperty":"transitionProperty";
}function o(){return n()?n()+"Transform":"transform"}function i(e,t){var n=r();n&&(e.style[n]=t,"transitionProperty"!==n&&(e.style.transitionProperty=t))}function a(e,t){var n=o();n&&(e.style[n]=t,"transform"!==n&&(e.style.transform=t))}function s(e){return e.style.transitionProperty||e.style[r()]}function l(e){var t=window.getComputedStyle(e,null),n=t.getPropertyValue("transform")||t.getPropertyValue(o());if(n&&"none"!==n){var r=n.replace(/[^0-9\-.,]/g,"").split(",");return{x:parseFloat(r[12]||r[4],0),y:parseFloat(r[13]||r[5],0)}}return{x:0,y:0}}function u(e,t){var n=window.getComputedStyle(e,null),r=n.getPropertyValue("transform")||n.getPropertyValue(o());if(r&&"none"!==r){var i=void 0,s=r.match(f);if(s)s=s[1],i=s.split(",").map(function(e){return parseFloat(e,10)}),i[4]=t.x,i[5]=t.y,a(e,"matrix("+i.join(",")+")");else{var l=r.match(p)[1];i=l.split(",").map(function(e){return parseFloat(e,10)}),i[12]=t.x,i[13]=t.y,a(e,"matrix3d("+i.join(",")+")")}}else a(e,"translateX("+t.x+"px) translateY("+t.y+"px) translateZ(0)")}Object.defineProperty(t,"__esModule",{value:!0}),t.getTransformName=o,t.setTransitionProperty=i,t.getTransitionProperty=s,t.getTransformXY=l,t.setTransformXY=u;var c=void 0,d={Webkit:"-webkit-",Moz:"-moz-",ms:"-ms-",O:"-o-"},f=/matrix\((.*)\)/,p=/matrix3d\((.*)\)/},function(e,t,n){var r;/*!
Copyright (c) 2015 Jed Watson.
Based on code that is Copyright 2013-2015, Facebook, Inc.
All rights reserved.
*/
!function(){"use strict";var o=!("undefined"==typeof window||!window.document||!window.document.createElement),i={canUseDOM:o,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:o&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:o&&!!window.screen};r=function(){return i}.call(t,n,t,e),!(void 0!==r&&(e.exports=r))}()},function(e,t){},280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,function(e,t){"use strict";var n=!("undefined"==typeof window||!window.document||!window.document.createElement),r={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:n&&!!window.screen,isInWorker:!n};e.exports=r},function(e,t){"use strict";function n(e){return e.replace(r,function(e,t){return t.toUpperCase()})}var r=/-(.)/g;e.exports=n},function(e,t,n){"use strict";function r(e){return o(e.replace(i,"ms-"))}var o=n(326),i=/^-ms-/;e.exports=r},function(e,t){"use strict";function n(e){return function(){return e}}var r=function(){};r.thatReturns=n,r.thatReturnsFalse=n(!1),r.thatReturnsTrue=n(!0),r.thatReturnsNull=n(null),r.thatReturnsThis=function(){return this},r.thatReturnsArgument=function(e){return e},e.exports=r},function(e,t){"use strict";function n(e){return e.replace(r,"-$1").toLowerCase()}var r=/([A-Z])/g;e.exports=n},function(e,t,n){"use strict";function r(e){return o(e).replace(i,"-ms-")}var o=n(329),i=/^ms-/;e.exports=r},function(e,t,n){"use strict";function r(e){if(Array.isArray(e))return 0===e.length;if("object"==typeof e){if(e){o(e)&&void 0!==e.size?i(!1):void 0;for(var t in e)return!1}return!0}return!e}function o(e){return"undefined"!=typeof Symbol&&e[Symbol.iterator]}var i=n(66);e.exports=r},function(e,t){"use strict";function n(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}e.exports=n},function(e,t){"use strict";function n(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function r(e,t){if(n(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(var a=0;a<r.length;a++)if(!o.call(t,r[a])||!n(e[r[a]],t[r[a]]))return!1;return!0}var o=Object.prototype.hasOwnProperty;e.exports=r},function(e,t){/*!
* for-in <https://github.com/jonschlinkert/for-in>
*
* Copyright (c) 2014-2016, Jon Schlinkert.
* Licensed under the MIT License.
*/
"use strict";e.exports=function(e,t,n){for(var r in e)if(t.call(n,e[r],r,e)===!1)break}},function(e,t,n){/*!
* for-own <https://github.com/jonschlinkert/for-own>
*
* Copyright (c) 2014-2016, Jon Schlinkert.
* Licensed under the MIT License.
*/
"use strict";var r=n(334),o=Object.prototype.hasOwnProperty;e.exports=function(e,t,n){r(e,function(r,i){if(o.call(e,i))return t.call(n,e[i],i,e)})}},function(e,t,n){var r;/*! Hammer.JS - v2.0.7 - 2016-04-22
* http://hammerjs.github.io/
*
* Copyright (c) 2016 Jorik Tangelder;
* Licensed under the MIT license */
!function(o,i,a,s){"use strict";function l(e,t,n){return setTimeout(p(e,n),t)}function u(e,t,n){return!!Array.isArray(e)&&(c(e,n[t],n),!0)}function c(e,t,n){var r;if(e)if(e.forEach)e.forEach(t,n);else if(e.length!==s)for(r=0;r<e.length;)t.call(n,e[r],r,e),r++;else for(r in e)e.hasOwnProperty(r)&&t.call(n,e[r],r,e)}function d(e,t,n){var r="DEPRECATED METHOD: "+t+"\n"+n+" AT \n";return function(){var t=new Error("get-stack-trace"),n=t&&t.stack?t.stack.replace(/^[^\(]+?[\n$]/gm,"").replace(/^\s+at\s+/gm,"").replace(/^Object.<anonymous>\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",i=o.console&&(o.console.warn||o.console.log);return i&&i.call(o.console,r,n),e.apply(this,arguments)}}function f(e,t,n){var r,o=t.prototype;r=e.prototype=Object.create(o),r.constructor=e,r._super=o,n&&me(r,n)}function p(e,t){return function(){return e.apply(t,arguments)}}function h(e,t){return typeof e==ge?e.apply(t?t[0]||s:s,t):e}function m(e,t){return e===s?t:e}function v(e,t,n){c(_(t),function(t){e.addEventListener(t,n,!1)})}function y(e,t,n){c(_(t),function(t){e.removeEventListener(t,n,!1)})}function g(e,t){for(;e;){if(e==t)return!0;e=e.parentNode}return!1}function b(e,t){return e.indexOf(t)>-1}function _(e){return e.trim().split(/\s+/g)}function x(e,t,n){if(e.indexOf&&!n)return e.indexOf(t);for(var r=0;r<e.length;){if(n&&e[r][n]==t||!n&&e[r]===t)return r;r++}return-1}function T(e){return Array.prototype.slice.call(e,0)}function C(e,t,n){for(var r=[],o=[],i=0;i<e.length;){var a=t?e[i][t]:e[i];x(o,a)<0&&r.push(e[i]),o[i]=a,i++}return n&&(r=t?r.sort(function(e,n){return e[t]>n[t]}):r.sort()),r}function w(e,t){for(var n,r,o=t[0].toUpperCase()+t.slice(1),i=0;i<ve.length;){if(n=ve[i],r=n?n+o:t,r in e)return r;i++}return s}function S(){return we++}function P(e){var t=e.ownerDocument||e;return t.defaultView||t.parentWindow||o}function E(e,t){var n=this;this.manager=e,this.callback=t,this.element=e.element,this.target=e.options.inputTarget,this.domHandler=function(t){h(e.options.enable,[e])&&n.handler(t)},this.init()}function M(e){var t,n=e.options.inputClass;return new(t=n?n:Ee?V:Me?U:Pe?K:F)(e,k)}function k(e,t,n){var r=n.pointers.length,o=n.changedPointers.length,i=t&Ae&&r-o===0,a=t&(je|Le)&&r-o===0;n.isFirst=!!i,n.isFinal=!!a,i&&(e.session={}),n.eventType=t,O(e,n),e.emit("hammer.input",n),e.recognize(n),e.session.prevInput=n}function O(e,t){var n=e.session,r=t.pointers,o=r.length;n.firstInput||(n.firstInput=R(t)),o>1&&!n.firstMultiple?n.firstMultiple=R(t):1===o&&(n.firstMultiple=!1);var i=n.firstInput,a=n.firstMultiple,s=a?a.center:i.center,l=t.center=A(r);t.timeStamp=xe(),t.deltaTime=t.timeStamp-i.timeStamp,t.angle=W(s,l),t.distance=L(s,l),N(n,t),t.offsetDirection=j(t.deltaX,t.deltaY);var u=I(t.deltaTime,t.deltaX,t.deltaY);t.overallVelocityX=u.x,t.overallVelocityY=u.y,t.overallVelocity=_e(u.x)>_e(u.y)?u.x:u.y,t.scale=a?Y(a.pointers,r):1,t.rotation=a?H(a.pointers,r):0,t.maxPointers=n.prevInput?t.pointers.length>n.prevInput.maxPointers?t.pointers.length:n.prevInput.maxPointers:t.pointers.length,D(n,t);var c=e.element;g(t.srcEvent.target,c)&&(c=t.srcEvent.target),t.target=c}function N(e,t){var n=t.center,r=e.offsetDelta||{},o=e.prevDelta||{},i=e.prevInput||{};t.eventType!==Ae&&i.eventType!==je||(o=e.prevDelta={x:i.deltaX||0,y:i.deltaY||0},r=e.offsetDelta={x:n.x,y:n.y}),t.deltaX=o.x+(n.x-r.x),t.deltaY=o.y+(n.y-r.y)}function D(e,t){var n,r,o,i,a=e.lastInterval||t,l=t.timeStamp-a.timeStamp;if(t.eventType!=Le&&(l>Re||a.velocity===s)){var u=t.deltaX-a.deltaX,c=t.deltaY-a.deltaY,d=I(l,u,c);r=d.x,o=d.y,n=_e(d.x)>_e(d.y)?d.x:d.y,i=j(u,c),e.lastInterval=t}else n=a.velocity,r=a.velocityX,o=a.velocityY,i=a.direction;t.velocity=n,t.velocityX=r,t.velocityY=o,t.direction=i}function R(e){for(var t=[],n=0;n<e.pointers.length;)t[n]={clientX:be(e.pointers[n].clientX),clientY:be(e.pointers[n].clientY)},n++;return{timeStamp:xe(),pointers:t,center:A(t),deltaX:e.deltaX,deltaY:e.deltaY}}function A(e){var t=e.length;if(1===t)return{x:be(e[0].clientX),y:be(e[0].clientY)};for(var n=0,r=0,o=0;o<t;)n+=e[o].clientX,r+=e[o].clientY,o++;return{x:be(n/t),y:be(r/t)}}function I(e,t,n){return{x:t/e||0,y:n/e||0}}function j(e,t){return e===t?We:_e(e)>=_e(t)?e<0?He:Ye:t<0?Fe:Ve}function L(e,t,n){n||(n=Xe);var r=t[n[0]]-e[n[0]],o=t[n[1]]-e[n[1]];return Math.sqrt(r*r+o*o)}function W(e,t,n){n||(n=Xe);var r=t[n[0]]-e[n[0]],o=t[n[1]]-e[n[1]];return 180*Math.atan2(o,r)/Math.PI}function H(e,t){return W(t[1],t[0],Ke)+W(e[1],e[0],Ke)}function Y(e,t){return L(t[0],t[1],Ke)/L(e[0],e[1],Ke)}function F(){this.evEl=qe,this.evWin=Ze,this.pressed=!1,E.apply(this,arguments)}function V(){this.evEl=Je,this.evWin=et,E.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}function B(){this.evTarget=nt,this.evWin=rt,this.started=!1,E.apply(this,arguments)}function z(e,t){var n=T(e.touches),r=T(e.changedTouches);return t&(je|Le)&&(n=C(n.concat(r),"identifier",!0)),[n,r]}function U(){this.evTarget=it,this.targetIds={},E.apply(this,arguments)}function X(e,t){var n=T(e.touches),r=this.targetIds;if(t&(Ae|Ie)&&1===n.length)return r[n[0].identifier]=!0,[n,n];var o,i,a=T(e.changedTouches),s=[],l=this.target;if(i=n.filter(function(e){return g(e.target,l)}),t===Ae)for(o=0;o<i.length;)r[i[o].identifier]=!0,o++;for(o=0;o<a.length;)r[a[o].identifier]&&s.push(a[o]),t&(je|Le)&&delete r[a[o].identifier],o++;return s.length?[C(i.concat(s),"identifier",!0),s]:void 0}function K(){E.apply(this,arguments);var e=p(this.handler,this);this.touch=new U(this.manager,e),this.mouse=new F(this.manager,e),this.primaryTouch=null,this.lastTouches=[]}function G(e,t){e&Ae?(this.primaryTouch=t.changedPointers[0].identifier,q.call(this,t)):e&(je|Le)&&q.call(this,t)}function q(e){var t=e.changedPointers[0];if(t.identifier===this.primaryTouch){var n={x:t.clientX,y:t.clientY};this.lastTouches.push(n);var r=this.lastTouches,o=function(){var e=r.indexOf(n);e>-1&&r.splice(e,1)};setTimeout(o,at)}}function Z(e){for(var t=e.srcEvent.clientX,n=e.srcEvent.clientY,r=0;r<this.lastTouches.length;r++){var o=this.lastTouches[r],i=Math.abs(t-o.x),a=Math.abs(n-o.y);if(i<=st&&a<=st)return!0}return!1}function Q(e,t){this.manager=e,this.set(t)}function $(e){if(b(e,pt))return pt;var t=b(e,ht),n=b(e,mt);return t&&n?pt:t||n?t?ht:mt:b(e,ft)?ft:dt}function J(){if(!ut)return!1;var e={},t=o.CSS&&o.CSS.supports;return["auto","manipulation","pan-y","pan-x","pan-x pan-y","none"].forEach(function(n){e[n]=!t||o.CSS.supports("touch-action",n)}),e}function ee(e){this.options=me({},this.defaults,e||{}),this.id=S(),this.manager=null,this.options.enable=m(this.options.enable,!0),this.state=yt,this.simultaneous={},this.requireFail=[]}function te(e){return e&Tt?"cancel":e&_t?"end":e&bt?"move":e>?"start":""}function ne(e){return e==Ve?"down":e==Fe?"up":e==He?"left":e==Ye?"right":""}function re(e,t){var n=t.manager;return n?n.get(e):e}function oe(){ee.apply(this,arguments)}function ie(){oe.apply(this,arguments),this.pX=null,this.pY=null}function ae(){oe.apply(this,arguments)}function se(){ee.apply(this,arguments),this._timer=null,this._input=null}function le(){oe.apply(this,arguments)}function ue(){oe.apply(this,arguments)}function ce(){ee.apply(this,arguments),this.pTime=!1,this.pCenter=!1,this._timer=null,this._input=null,this.count=0}function de(e,t){return t=t||{},t.recognizers=m(t.recognizers,de.defaults.preset),new fe(e,t)}function fe(e,t){this.options=me({},de.defaults,t||{}),this.options.inputTarget=this.options.inputTarget||e,this.handlers={},this.session={},this.recognizers=[],this.oldCssProps={},this.element=e,this.input=M(this),this.touchAction=new Q(this,this.options.touchAction),pe(this,!0),c(this.options.recognizers,function(e){var t=this.add(new e[0](e[1]));e[2]&&t.recognizeWith(e[2]),e[3]&&t.requireFailure(e[3])},this)}function pe(e,t){var n=e.element;if(n.style){var r;c(e.options.cssProps,function(o,i){r=w(n.style,i),t?(e.oldCssProps[r]=n.style[r],n.style[r]=o):n.style[r]=e.oldCssProps[r]||""}),t||(e.oldCssProps={})}}function he(e,t){var n=i.createEvent("Event");n.initEvent(e,!0,!0),n.gesture=t,t.target.dispatchEvent(n)}var me,ve=["","webkit","Moz","MS","ms","o"],ye=i.createElement("div"),ge="function",be=Math.round,_e=Math.abs,xe=Date.now;me="function"!=typeof Object.assign?function(e){if(e===s||null===e)throw new TypeError("Cannot convert undefined or null to object");for(var t=Object(e),n=1;n<arguments.length;n++){var r=arguments[n];if(r!==s&&null!==r)for(var o in r)r.hasOwnProperty(o)&&(t[o]=r[o])}return t}:Object.assign;var Te=d(function(e,t,n){for(var r=Object.keys(t),o=0;o<r.length;)(!n||n&&e[r[o]]===s)&&(e[r[o]]=t[r[o]]),o++;return e},"extend","Use `assign`."),Ce=d(function(e,t){return Te(e,t,!0)},"merge","Use `assign`."),we=1,Se=/mobile|tablet|ip(ad|hone|od)|android/i,Pe="ontouchstart"in o,Ee=w(o,"PointerEvent")!==s,Me=Pe&&Se.test(navigator.userAgent),ke="touch",Oe="pen",Ne="mouse",De="kinect",Re=25,Ae=1,Ie=2,je=4,Le=8,We=1,He=2,Ye=4,Fe=8,Ve=16,Be=He|Ye,ze=Fe|Ve,Ue=Be|ze,Xe=["x","y"],Ke=["clientX","clientY"];E.prototype={handler:function(){},init:function(){this.evEl&&v(this.element,this.evEl,this.domHandler),this.evTarget&&v(this.target,this.evTarget,this.domHandler),this.evWin&&v(P(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&y(this.element,this.evEl,this.domHandler),this.evTarget&&y(this.target,this.evTarget,this.domHandler),this.evWin&&y(P(this.element),this.evWin,this.domHandler)}};var Ge={mousedown:Ae,mousemove:Ie,mouseup:je},qe="mousedown",Ze="mousemove mouseup";f(F,E,{handler:function(e){var t=Ge[e.type];t&Ae&&0===e.button&&(this.pressed=!0),t&Ie&&1!==e.which&&(t=je),this.pressed&&(t&je&&(this.pressed=!1),this.callback(this.manager,t,{pointers:[e],changedPointers:[e],pointerType:Ne,srcEvent:e}))}});var Qe={pointerdown:Ae,pointermove:Ie,pointerup:je,pointercancel:Le,pointerout:Le},$e={2:ke,3:Oe,4:Ne,5:De},Je="pointerdown",et="pointermove pointerup pointercancel";o.MSPointerEvent&&!o.PointerEvent&&(Je="MSPointerDown",et="MSPointerMove MSPointerUp MSPointerCancel"),f(V,E,{handler:function(e){var t=this.store,n=!1,r=e.type.toLowerCase().replace("ms",""),o=Qe[r],i=$e[e.pointerType]||e.pointerType,a=i==ke,s=x(t,e.pointerId,"pointerId");o&Ae&&(0===e.button||a)?s<0&&(t.push(e),s=t.length-1):o&(je|Le)&&(n=!0),s<0||(t[s]=e,this.callback(this.manager,o,{pointers:t,changedPointers:[e],pointerType:i,srcEvent:e}),n&&t.splice(s,1))}});var tt={touchstart:Ae,touchmove:Ie,touchend:je,touchcancel:Le},nt="touchstart",rt="touchstart touchmove touchend touchcancel";f(B,E,{handler:function(e){var t=tt[e.type];if(t===Ae&&(this.started=!0),this.started){var n=z.call(this,e,t);t&(je|Le)&&n[0].length-n[1].length===0&&(this.started=!1),this.callback(this.manager,t,{pointers:n[0],changedPointers:n[1],pointerType:ke,srcEvent:e})}}});var ot={touchstart:Ae,touchmove:Ie,touchend:je,touchcancel:Le},it="touchstart touchmove touchend touchcancel";f(U,E,{handler:function(e){var t=ot[e.type],n=X.call(this,e,t);n&&this.callback(this.manager,t,{pointers:n[0],changedPointers:n[1],pointerType:ke,srcEvent:e})}});var at=2500,st=25;f(K,E,{handler:function(e,t,n){var r=n.pointerType==ke,o=n.pointerType==Ne;if(!(o&&n.sourceCapabilities&&n.sourceCapabilities.firesTouchEvents)){if(r)G.call(this,t,n);else if(o&&Z.call(this,n))return;this.callback(e,t,n)}},destroy:function(){this.touch.destroy(),this.mouse.destroy()}});var lt=w(ye.style,"touchAction"),ut=lt!==s,ct="compute",dt="auto",ft="manipulation",pt="none",ht="pan-x",mt="pan-y",vt=J();Q.prototype={set:function(e){e==ct&&(e=this.compute()),ut&&this.manager.element.style&&vt[e]&&(this.manager.element.style[lt]=e),this.actions=e.toLowerCase().trim()},update:function(){this.set(this.manager.options.touchAction)},compute:function(){var e=[];return c(this.manager.recognizers,function(t){h(t.options.enable,[t])&&(e=e.concat(t.getTouchAction()))}),$(e.join(" "))},preventDefaults:function(e){var t=e.srcEvent,n=e.offsetDirection;if(this.manager.session.prevented)return void t.preventDefault();var r=this.actions,o=b(r,pt)&&!vt[pt],i=b(r,mt)&&!vt[mt],a=b(r,ht)&&!vt[ht];if(o){var s=1===e.pointers.length,l=e.distance<2,u=e.deltaTime<250;if(s&&l&&u)return}return a&&i?void 0:o||i&&n&Be||a&&n&ze?this.preventSrc(t):void 0},preventSrc:function(e){this.manager.session.prevented=!0,e.preventDefault()}};var yt=1,gt=2,bt=4,_t=8,xt=_t,Tt=16,Ct=32;ee.prototype={defaults:{},set:function(e){return me(this.options,e),this.manager&&this.manager.touchAction.update(),this},recognizeWith:function(e){if(u(e,"recognizeWith",this))return this;var t=this.simultaneous;return e=re(e,this),t[e.id]||(t[e.id]=e,e.recognizeWith(this)),this},dropRecognizeWith:function(e){return u(e,"dropRecognizeWith",this)?this:(e=re(e,this),delete this.simultaneous[e.id],this)},requireFailure:function(e){if(u(e,"requireFailure",this))return this;var t=this.requireFail;return e=re(e,this),x(t,e)===-1&&(t.push(e),e.requireFailure(this)),this},dropRequireFailure:function(e){if(u(e,"dropRequireFailure",this))return this;e=re(e,this);var t=x(this.requireFail,e);return t>-1&&this.requireFail.splice(t,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(e){return!!this.simultaneous[e.id]},emit:function(e){function t(t){n.manager.emit(t,e)}var n=this,r=this.state;r<_t&&t(n.options.event+te(r)),t(n.options.event),e.additionalEvent&&t(e.additionalEvent),r>=_t&&t(n.options.event+te(r))},tryEmit:function(e){return this.canEmit()?this.emit(e):void(this.state=Ct)},canEmit:function(){for(var e=0;e<this.requireFail.length;){if(!(this.requireFail[e].state&(Ct|yt)))return!1;e++}return!0},recognize:function(e){var t=me({},e);return h(this.options.enable,[this,t])?(this.state&(xt|Tt|Ct)&&(this.state=yt),this.state=this.process(t),void(this.state&(gt|bt|_t|Tt)&&this.tryEmit(t))):(this.reset(),void(this.state=Ct))},process:function(e){},getTouchAction:function(){},reset:function(){}},f(oe,ee,{defaults:{pointers:1},attrTest:function(e){var t=this.options.pointers;return 0===t||e.pointers.length===t},process:function(e){var t=this.state,n=e.eventType,r=t&(gt|bt),o=this.attrTest(e);return r&&(n&Le||!o)?t|Tt:r||o?n&je?t|_t:t>?t|bt:gt:Ct}}),f(ie,oe,{defaults:{event:"pan",threshold:10,pointers:1,direction:Ue},getTouchAction:function(){var e=this.options.direction,t=[];return e&Be&&t.push(mt),e&ze&&t.push(ht),t},directionTest:function(e){var t=this.options,n=!0,r=e.distance,o=e.direction,i=e.deltaX,a=e.deltaY;return o&t.direction||(t.direction&Be?(o=0===i?We:i<0?He:Ye,n=i!=this.pX,r=Math.abs(e.deltaX)):(o=0===a?We:a<0?Fe:Ve,n=a!=this.pY,r=Math.abs(e.deltaY))),e.direction=o,n&&r>t.threshold&&o&t.direction},attrTest:function(e){return oe.prototype.attrTest.call(this,e)&&(this.state>||!(this.state>)&&this.directionTest(e))},emit:function(e){this.pX=e.deltaX,this.pY=e.deltaY;var t=ne(e.direction);t&&(e.additionalEvent=this.options.event+t),this._super.emit.call(this,e)}}),f(ae,oe,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[pt]},attrTest:function(e){return this._super.attrTest.call(this,e)&&(Math.abs(e.scale-1)>this.options.threshold||this.state>)},emit:function(e){if(1!==e.scale){var t=e.scale<1?"in":"out";e.additionalEvent=this.options.event+t}this._super.emit.call(this,e)}}),f(se,ee,{defaults:{event:"press",pointers:1,time:251,threshold:9},getTouchAction:function(){return[dt]},process:function(e){var t=this.options,n=e.pointers.length===t.pointers,r=e.distance<t.threshold,o=e.deltaTime>t.time;if(this._input=e,!r||!n||e.eventType&(je|Le)&&!o)this.reset();else if(e.eventType&Ae)this.reset(),this._timer=l(function(){this.state=xt,this.tryEmit()},t.time,this);else if(e.eventType&je)return xt;return Ct},reset:function(){clearTimeout(this._timer)},emit:function(e){this.state===xt&&(e&&e.eventType&je?this.manager.emit(this.options.event+"up",e):(this._input.timeStamp=xe(),this.manager.emit(this.options.event,this._input)))}}),f(le,oe,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[pt]},attrTest:function(e){return this._super.attrTest.call(this,e)&&(Math.abs(e.rotation)>this.options.threshold||this.state>)}}),f(ue,oe,{defaults:{event:"swipe",threshold:10,velocity:.3,direction:Be|ze,pointers:1},getTouchAction:function(){return ie.prototype.getTouchAction.call(this)},attrTest:function(e){var t,n=this.options.direction;return n&(Be|ze)?t=e.overallVelocity:n&Be?t=e.overallVelocityX:n&ze&&(t=e.overallVelocityY),this._super.attrTest.call(this,e)&&n&e.offsetDirection&&e.distance>this.options.threshold&&e.maxPointers==this.options.pointers&&_e(t)>this.options.velocity&&e.eventType&je},emit:function(e){var t=ne(e.offsetDirection);t&&this.manager.emit(this.options.event+t,e),this.manager.emit(this.options.event,e)}}),f(ce,ee,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:9,posThreshold:10},getTouchAction:function(){return[ft]},process:function(e){var t=this.options,n=e.pointers.length===t.pointers,r=e.distance<t.threshold,o=e.deltaTime<t.time;if(this.reset(),e.eventType&Ae&&0===this.count)return this.failTimeout();if(r&&o&&n){if(e.eventType!=je)return this.failTimeout();var i=!this.pTime||e.timeStamp-this.pTime<t.interval,a=!this.pCenter||L(this.pCenter,e.center)<t.posThreshold;this.pTime=e.timeStamp,this.pCenter=e.center,a&&i?this.count+=1:this.count=1,this._input=e;var s=this.count%t.taps;if(0===s)return this.hasRequireFailures()?(this._timer=l(function(){this.state=xt,this.tryEmit()},t.interval,this),gt):xt}return Ct},failTimeout:function(){return this._timer=l(function(){this.state=Ct},this.options.interval,this),Ct},reset:function(){clearTimeout(this._timer)},emit:function(){this.state==xt&&(this._input.tapCount=this.count,this.manager.emit(this.options.event,this._input))}}),de.VERSION="2.0.7",de.defaults={domEvents:!1,touchAction:ct,enable:!0,inputTarget:null,inputClass:null,preset:[[le,{enable:!1}],[ae,{enable:!1},["rotate"]],[ue,{direction:Be}],[ie,{direction:Be},["swipe"]],[ce],[ce,{event:"doubletap",taps:2},["tap"]],[se]],cssProps:{userSelect:"none",touchSelect:"none",touchCallout:"none",contentZooming:"none",userDrag:"none",tapHighlightColor:"rgba(0,0,0,0)"}};var wt=1,St=2;fe.prototype={set:function(e){return me(this.options,e),e.touchAction&&this.touchAction.update(),e.inputTarget&&(this.input.destroy(),this.input.target=e.inputTarget,this.input.init()),this},stop:function(e){this.session.stopped=e?St:wt},recognize:function(e){var t=this.session;if(!t.stopped){this.touchAction.preventDefaults(e);var n,r=this.recognizers,o=t.curRecognizer;(!o||o&&o.state&xt)&&(o=t.curRecognizer=null);for(var i=0;i<r.length;)n=r[i],t.stopped===St||o&&n!=o&&!n.canRecognizeWith(o)?n.reset():n.recognize(e),!o&&n.state&(gt|bt|_t)&&(o=t.curRecognizer=n),i++}},get:function(e){if(e instanceof ee)return e;for(var t=this.recognizers,n=0;n<t.length;n++)if(t[n].options.event==e)return t[n];return null},add:function(e){if(u(e,"add",this))return this;var t=this.get(e.options.event);return t&&this.remove(t),this.recognizers.push(e),e.manager=this,this.touchAction.update(),e},remove:function(e){if(u(e,"remove",this))return this;if(e=this.get(e)){var t=this.recognizers,n=x(t,e);n!==-1&&(t.splice(n,1),this.touchAction.update())}return this},on:function(e,t){if(e!==s&&t!==s){var n=this.handlers;return c(_(e),function(e){n[e]=n[e]||[],n[e].push(t)}),this}},off:function(e,t){if(e!==s){var n=this.handlers;return c(_(e),function(e){t?n[e]&&n[e].splice(x(n[e],t),1):delete n[e]}),this}},emit:function(e,t){this.options.domEvents&&he(e,t);var n=this.handlers[e]&&this.handlers[e].slice();if(n&&n.length){t.type=e,t.preventDefault=function(){t.srcEvent.preventDefault()};for(var r=0;r<n.length;)n[r](t),r++}},destroy:function(){this.element&&pe(this,!1),this.handlers={},this.session={},this.input.destroy(),this.element=null}},me(de,{INPUT_START:Ae,INPUT_MOVE:Ie,INPUT_END:je,INPUT_CANCEL:Le,STATE_POSSIBLE:yt,STATE_BEGAN:gt,STATE_CHANGED:bt,STATE_ENDED:_t,STATE_RECOGNIZED:xt,STATE_CANCELLED:Tt,STATE_FAILED:Ct,DIRECTION_NONE:We,DIRECTION_LEFT:He,DIRECTION_RIGHT:Ye,DIRECTION_UP:Fe,DIRECTION_DOWN:Ve,DIRECTION_HORIZONTAL:Be,DIRECTION_VERTICAL:ze,DIRECTION_ALL:Ue,Manager:fe,Input:E,TouchAction:Q,TouchInput:U,MouseInput:F,PointerEventInput:V,TouchMouseInput:K,SingleTouchInput:B,Recognizer:ee,AttrRecognizer:oe,Tap:ce,Pan:ie,Swipe:ue,Pinch:ae,Rotate:le,Press:se,on:v,off:y,each:c,merge:Ce,extend:Te,assign:me,inherit:f,bindFn:p,prefixed:w});var Pt="undefined"!=typeof o?o:"undefined"!=typeof self?self:{};Pt.Hammer=de,r=function(){return de}.call(t,n,t,e),!(r!==s&&(e.exports=r))}(window,document,"Hammer")},function(e,t){/*!
* is-extendable <https://github.com/jonschlinkert/is-extendable>
*
* Copyright (c) 2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
"use strict";e.exports=function(e){return"undefined"!=typeof e&&null!==e&&("object"==typeof e||"function"==typeof e)}},function(e,t,n){!function(t,n){e.exports=n()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}({0:/*!*****************!*\
!*** multi lib ***!
\*****************/
function(e,t,n){e.exports=n(/*! ./index.js */169)},5:/*!******************************!*\
!*** ./~/process/browser.js ***!
\******************************/
function(e,t){function n(){u=!1,a.length?l=a.concat(l):c=-1,l.length&&r()}function r(){if(!u){var e=setTimeout(n);u=!0;for(var t=l.length;t;){for(a=l,l=[];++c<t;)a&&a[c].run();c=-1,t=l.length}a=null,u=!1,clearTimeout(e)}}function o(e,t){this.fun=e,this.array=t}function i(){}var a,s=e.exports={},l=[],u=!1,c=-1;s.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];l.push(new o(e,t)),1!==l.length||u||setTimeout(r,0)},o.prototype.run=function(){this.fun.apply(null,this.array)},s.title="browser",s.browser=!0,s.env={},s.argv=[],s.version="",s.versions={},s.on=i,s.addListener=i,s.once=i,s.off=i,s.removeListener=i,s.removeAllListeners=i,s.emit=i,s.binding=function(e){throw new Error("process.binding is not supported")},s.cwd=function(){return"/"},s.chdir=function(e){throw new Error("process.chdir is not supported")},s.umask=function(){return 0}},169:/*!******************!*\
!*** ./index.js ***!
\******************/
function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(/*! tween-functions */170),i=r(o),a=n(/*! raf */171),s=r(a),l="ADDITIVE",u=o.easeInOutQuad,c=300,d=0,f={ADDITIVE:"ADDITIVE",DESTRUCTIVE:"DESTRUCTIVE"},p={_rafID:null,getInitialState:function(){return{tweenQueue:[]}},componentWillUnmount:function(){s["default"].cancel(this._rafID),this._rafID=-1},tweenState:function(e,t){var n=this,r=t.easing,o=t.duration,i=t.delay,a=t.beginValue,p=t.endValue,h=t.onEnd,m=t.stackBehavior;this.setState(function(t){var v=t,y=void 0,g=void 0;if("string"==typeof e)y=e,g=e;else{for(var b=0;b<e.length-1;b++)v=v[e[b]];y=e[e.length-1],g=e.join("|")}var _={easing:r||u,duration:null==o?c:o,delay:null==i?d:i,beginValue:null==a?v[y]:a,endValue:p,onEnd:h,stackBehavior:m||l},x=t.tweenQueue;return _.stackBehavior===f.DESTRUCTIVE&&(x=t.tweenQueue.filter(function(e){return e.pathHash!==g})),x.push({pathHash:g,config:_,initTime:Date.now()+_.delay}),v[y]=_.endValue,1===x.length&&(n._rafID=(0,s["default"])(n._rafCb)),{tweenQueue:x}})},getTweeningValue:function(e){var t=this.state,n=void 0,r=void 0;if("string"==typeof e)n=t[e],r=e;else{n=t;for(var o=0;o<e.length;o++)n=n[e[o]];r=e.join("|")}for(var i=Date.now(),o=0;o<t.tweenQueue.length;o++){var a=t.tweenQueue[o],s=a.pathHash,l=a.initTime,u=a.config;if(s===r){var c=i-l>u.duration?u.duration:Math.max(0,i-l),d=0===u.duration?u.endValue:u.easing(c,u.beginValue,u.endValue,u.duration),f=d-u.endValue;n+=f}}return n},_rafCb:function(){var e=this.state;if(0!==e.tweenQueue.length){for(var t=Date.now(),n=[],r=0;r<e.tweenQueue.length;r++){var o=e.tweenQueue[r],i=o.initTime,a=o.config;t-i<a.duration?n.push(o):a.onEnd&&a.onEnd()}this._rafID!==-1&&(this.setState({tweenQueue:n}),this._rafID=(0,s["default"])(this._rafCb))}}};t["default"]={Mixin:p,easingTypes:i["default"],stackBehavior:f},e.exports=t["default"]},170:/*!************************************!*\
!*** ./~/tween-functions/index.js ***!
\************************************/
function(e,t){"use strict";var n={linear:function(e,t,n,r){var o=n-t;return o*e/r+t},easeInQuad:function(e,t,n,r){var o=n-t;return o*(e/=r)*e+t},easeOutQuad:function(e,t,n,r){var o=n-t;return-o*(e/=r)*(e-2)+t},easeInOutQuad:function(e,t,n,r){var o=n-t;return(e/=r/2)<1?o/2*e*e+t:-o/2*(--e*(e-2)-1)+t},easeInCubic:function(e,t,n,r){var o=n-t;return o*(e/=r)*e*e+t},easeOutCubic:function(e,t,n,r){var o=n-t;return o*((e=e/r-1)*e*e+1)+t},easeInOutCubic:function(e,t,n,r){var o=n-t;return(e/=r/2)<1?o/2*e*e*e+t:o/2*((e-=2)*e*e+2)+t},easeInQuart:function(e,t,n,r){var o=n-t;return o*(e/=r)*e*e*e+t},easeOutQuart:function(e,t,n,r){var o=n-t;return-o*((e=e/r-1)*e*e*e-1)+t},easeInOutQuart:function(e,t,n,r){var o=n-t;return(e/=r/2)<1?o/2*e*e*e*e+t:-o/2*((e-=2)*e*e*e-2)+t},easeInQuint:function(e,t,n,r){var o=n-t;return o*(e/=r)*e*e*e*e+t},easeOutQuint:function(e,t,n,r){var o=n-t;return o*((e=e/r-1)*e*e*e*e+1)+t},easeInOutQuint:function(e,t,n,r){var o=n-t;return(e/=r/2)<1?o/2*e*e*e*e*e+t:o/2*((e-=2)*e*e*e*e+2)+t},easeInSine:function(e,t,n,r){var o=n-t;return-o*Math.cos(e/r*(Math.PI/2))+o+t},easeOutSine:function(e,t,n,r){var o=n-t;return o*Math.sin(e/r*(Math.PI/2))+t},easeInOutSine:function(e,t,n,r){var o=n-t;return-o/2*(Math.cos(Math.PI*e/r)-1)+t},easeInExpo:function(e,t,n,r){var o=n-t;return 0==e?t:o*Math.pow(2,10*(e/r-1))+t},easeOutExpo:function(e,t,n,r){var o=n-t;return e==r?t+o:o*(-Math.pow(2,-10*e/r)+1)+t},easeInOutExpo:function(e,t,n,r){var o=n-t;return 0===e?t:e===r?t+o:(e/=r/2)<1?o/2*Math.pow(2,10*(e-1))+t:o/2*(-Math.pow(2,-10*--e)+2)+t},easeInCirc:function(e,t,n,r){var o=n-t;return-o*(Math.sqrt(1-(e/=r)*e)-1)+t},easeOutCirc:function(e,t,n,r){var o=n-t;return o*Math.sqrt(1-(e=e/r-1)*e)+t},easeInOutCirc:function(e,t,n,r){var o=n-t;return(e/=r/2)<1?-o/2*(Math.sqrt(1-e*e)-1)+t:o/2*(Math.sqrt(1-(e-=2)*e)+1)+t},easeInElastic:function(e,t,n,r){var o,i,a,s=n-t;return a=1.70158,i=0,o=s,0===e?t:1===(e/=r)?t+s:(i||(i=.3*r),o<Math.abs(s)?(o=s,a=i/4):a=i/(2*Math.PI)*Math.asin(s/o),-(o*Math.pow(2,10*(e-=1))*Math.sin((e*r-a)*(2*Math.PI)/i))+t)},easeOutElastic:function(e,t,n,r){var o,i,a,s=n-t;return a=1.70158,i=0,o=s,0===e?t:1===(e/=r)?t+s:(i||(i=.3*r),o<Math.abs(s)?(o=s,a=i/4):a=i/(2*Math.PI)*Math.asin(s/o),o*Math.pow(2,-10*e)*Math.sin((e*r-a)*(2*Math.PI)/i)+s+t)},easeInOutElastic:function(e,t,n,r){var o,i,a,s=n-t;return a=1.70158,i=0,o=s,0===e?t:2===(e/=r/2)?t+s:(i||(i=r*(.3*1.5)),o<Math.abs(s)?(o=s,a=i/4):a=i/(2*Math.PI)*Math.asin(s/o),e<1?-.5*(o*Math.pow(2,10*(e-=1))*Math.sin((e*r-a)*(2*Math.PI)/i))+t:o*Math.pow(2,-10*(e-=1))*Math.sin((e*r-a)*(2*Math.PI)/i)*.5+s+t)},easeInBack:function(e,t,n,r,o){var i=n-t;return void 0===o&&(o=1.70158),i*(e/=r)*e*((o+1)*e-o)+t},easeOutBack:function(e,t,n,r,o){var i=n-t;return void 0===o&&(o=1.70158),i*((e=e/r-1)*e*((o+1)*e+o)+1)+t},easeInOutBack:function(e,t,n,r,o){var i=n-t;return void 0===o&&(o=1.70158),(e/=r/2)<1?i/2*(e*e*(((o*=1.525)+1)*e-o))+t:i/2*((e-=2)*e*(((o*=1.525)+1)*e+o)+2)+t},easeInBounce:function(e,t,r,o){var i,a=r-t;return i=n.easeOutBounce(o-e,0,a,o),a-i+t},easeOutBounce:function(e,t,n,r){var o=n-t;return(e/=r)<1/2.75?o*(7.5625*e*e)+t:e<2/2.75?o*(7.5625*(e-=1.5/2.75)*e+.75)+t:e<2.5/2.75?o*(7.5625*(e-=2.25/2.75)*e+.9375)+t:o*(7.5625*(e-=2.625/2.75)*e+.984375)+t},easeInOutBounce:function(e,t,r,o){var i,a=r-t;return e<o/2?(i=n.easeInBounce(2*e,0,a,o),.5*i+t):(i=n.easeOutBounce(2*e-o,0,a,o),.5*i+.5*a+t)}};e.exports=n},171:/*!************************!*\
!*** ./~/raf/index.js ***!
\************************/
function(e,t,n){(function(t){for(var r=n(/*! performance-now */172),o="undefined"==typeof window?t:window,i=["moz","webkit"],a="AnimationFrame",s=o["request"+a],l=o["cancel"+a]||o["cancelRequest"+a],u=0;!s&&u<i.length;u++)s=o[i[u]+"Request"+a],l=o[i[u]+"Cancel"+a]||o[i[u]+"CancelRequest"+a];if(!s||!l){var c=0,d=0,f=[],p=1e3/60;s=function(e){if(0===f.length){var t=r(),n=Math.max(0,p-(t-c));c=n+t,setTimeout(function(){var e=f.slice(0);f.length=0;for(var t=0;t<e.length;t++)if(!e[t].cancelled)try{e[t].callback(c)}catch(n){setTimeout(function(){throw n},0)}},Math.round(n))}return f.push({handle:++d,callback:e,cancelled:!1}),d},l=function(e){for(var t=0;t<f.length;t++)f[t].handle===e&&(f[t].cancelled=!0)}}e.exports=function(e){return s.call(o,e)},e.exports.cancel=function(){l.apply(o,arguments)},e.exports.polyfill=function(){o.requestAnimationFrame=s,o.cancelAnimationFrame=l}}).call(t,function(){return this}())},172:/*!**************************************************!*\
!*** ./~/performance-now/lib/performance-now.js ***!
\**************************************************/
function(e,t,n){(function(t){(function(){var n,r,o;"undefined"!=typeof performance&&null!==performance&&performance.now?e.exports=function(){return performance.now()}:"undefined"!=typeof t&&null!==t&&t.hrtime?(e.exports=function(){return(n()-o)/1e6},r=t.hrtime,n=function(){var e;return e=r(),1e9*e[0]+e[1]},o=n()):Date.now?(e.exports=function(){return Date.now()-o},o=Date.now()):(e.exports=function(){return(new Date).getTime()-o},o=(new Date).getTime())}).call(this)}).call(t,n(/*! ./~/process/browser.js */5))}})})},function(e,t){function n(e){return!!e&&"object"==typeof e}function r(e,t){var n=null==e?void 0:e[t];return a(n)?n:void 0}function o(e){return i(e)&&f.call(e)==s}function i(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function a(e){return null!=e&&(o(e)?p.test(c.call(e)):n(e)&&l.test(e))}var s="[object Function]",l=/^\[object .+?Constructor\]$/,u=Object.prototype,c=Function.prototype.toString,d=u.hasOwnProperty,f=u.toString,p=RegExp("^"+c.call(d).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=r},function(e,t){function n(e){return o(e)&&h.call(e,"callee")&&(!v.call(e,"callee")||m.call(e)==c)}function r(e){return null!=e&&a(e.length)&&!i(e)}function o(e){return l(e)&&r(e)}function i(e){var t=s(e)?m.call(e):"";return t==d||t==f}function a(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=u}function s(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function l(e){return!!e&&"object"==typeof e}var u=9007199254740991,c="[object Arguments]",d="[object Function]",f="[object GeneratorFunction]",p=Object.prototype,h=p.hasOwnProperty,m=p.toString,v=p.propertyIsEnumerable;e.exports=n},function(e,t){function n(e){return!!e&&"object"==typeof e}function r(e,t){var n=null==e?void 0:e[t];return s(n)?n:void 0}function o(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=y}function i(e){return a(e)&&h.call(e)==u}function a(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function s(e){return null!=e&&(i(e)?m.test(f.call(e)):n(e)&&c.test(e))}var l="[object Array]",u="[object Function]",c=/^\[object .+?Constructor\]$/,d=Object.prototype,f=Function.prototype.toString,p=d.hasOwnProperty,h=d.toString,m=RegExp("^"+f.call(p).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),v=r(Array,"isArray"),y=9007199254740991,g=v||function(e){return n(e)&&o(e.length)&&h.call(e)==l};e.exports=g},function(e,t,n){function r(e){return function(t){return null==t?void 0:t[e]}}function o(e){return null!=e&&a(g(e))}function i(e,t){return e="number"==typeof e||p.test(e)?+e:-1,t=null==t?y:t,e>-1&&e%1==0&&e<t}function a(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=y}function s(e){for(var t=u(e),n=t.length,r=n&&e.length,o=!!r&&a(r)&&(f(e)||d(e)),s=-1,l=[];++s<n;){var c=t[s];(o&&i(c,r)||m.call(e,c))&&l.push(c)}return l}function l(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function u(e){if(null==e)return[];l(e)||(e=Object(e));var t=e.length;t=t&&a(t)&&(f(e)||d(e))&&t||0;for(var n=e.constructor,r=-1,o="function"==typeof n&&n.prototype===e,s=Array(t),u=t>0;++r<t;)s[r]=r+"";for(var c in e)u&&i(c,t)||"constructor"==c&&(o||!m.call(e,c))||s.push(c);return s}var c=n(339),d=n(340),f=n(341),p=/^\d+$/,h=Object.prototype,m=h.hasOwnProperty,v=c(Object,"keys"),y=9007199254740991,g=r("length"),b=v?function(e){var t=null==e?void 0:e.constructor;return"function"==typeof t&&t.prototype===e||"function"!=typeof e&&o(e)?s(e):l(e)?v(e):[]}:s;e.exports=b},function(e,t,n){"use strict";var r=n(344);e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),a=r(i),s=n(9),l=(r(s),n(338)),u=r(l),c=n(345),d=r(c),f=n(10),p=r(f),h=n(279),m=r(h),v=function(e,t,n){null!==e&&"undefined"!=typeof e&&(e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent?e.attachEvent("on"+t,n):e["on"+t]=n)},y=function(e,t,n){null!==e&&"undefined"!=typeof e&&(e.removeEventListener?e.removeEventListener(t,n,!1):e.detachEvent?e.detachEvent("on"+t,n):e["on"+t]=null)},g=a["default"].createClass({displayName:"Carousel",mixins:[u["default"].Mixin],propTypes:{afterSlide:a["default"].PropTypes.func,autoplay:a["default"].PropTypes.bool,autoplayInterval:a["default"].PropTypes.number,beforeSlide:a["default"].PropTypes.func,cellAlign:a["default"].PropTypes.oneOf(["left","center","right"]),cellSpacing:a["default"].PropTypes.number,data:a["default"].PropTypes.func,decorators:a["default"].PropTypes.arrayOf(a["default"].PropTypes.shape({component:a["default"].PropTypes.func,position:a["default"].PropTypes.oneOf(["TopLeft","TopCenter","TopRight","CenterLeft","CenterCenter","CenterRight","BottomLeft","BottomCenter","BottomRight"]),style:a["default"].PropTypes.object})),dragging:a["default"].PropTypes.bool,easing:a["default"].PropTypes.string,edgeEasing:a["default"].PropTypes.string,framePadding:a["default"].PropTypes.string,frameOverflow:a["default"].PropTypes.string,initialSlideHeight:a["default"].PropTypes.number,initialSlideWidth:a["default"].PropTypes.number,slideIndex:a["default"].PropTypes.number,slidesToShow:a["default"].PropTypes.number,slidesToScroll:a["default"].PropTypes.oneOfType([a["default"].PropTypes.number,a["default"].PropTypes.oneOf(["auto"])]),slideWidth:a["default"].PropTypes.oneOfType([a["default"].PropTypes.string,a["default"].PropTypes.number]),speed:a["default"].PropTypes.number,vertical:a["default"].PropTypes.bool,width:a["default"].PropTypes.string,wrapAround:a["default"].PropTypes.bool},getDefaultProps:function(){return{afterSlide:function(){},autoplay:!1,autoplayInterval:3e3,beforeSlide:function(){},cellAlign:"left",cellSpacing:0,data:function(){},decorators:d["default"],dragging:!0,easing:"easeOutCirc",edgeEasing:"easeOutElastic",framePadding:"0px",frameOverflow:"hidden",slideIndex:0,slidesToScroll:1,slidesToShow:1,slideWidth:1,speed:500,vertical:!1,width:"100%",wrapAround:!1}},getInitialState:function(){return{currentSlide:this.props.slideIndex,dragging:!1,frameWidth:0,left:0,slideCount:0,slidesToScroll:this.props.slidesToScroll,slideWidth:0,top:0}},componentWillMount:function(){this.setInitialDimensions()},componentDidMount:function(){this.setDimensions(),this.bindEvents(),this.setExternalData(),this.props.autoplay&&this.startAutoplay()},componentWillReceiveProps:function(e){this.setState({slideCount:e.children.length}),this.setDimensions(e),this.props.slideIndex!==e.slideIndex&&e.slideIndex!==this.state.currentSlide&&this.goToSlide(e.slideIndex),this.props.autoplay!==e.autoplay&&(e.autoplay?this.startAutoplay():this.stopAutoplay())},componentWillUnmount:function(){this.unbindEvents(),this.stopAutoplay()},render:function(){var e=this,t=a["default"].Children.count(this.props.children)>1?this.formatChildren(this.props.children):this.props.children;return a["default"].createElement("div",{className:["slider",this.props.className||""].join(" "),ref:"slider",style:(0,p["default"])(this.getSliderStyles(),this.props.style||{})},a["default"].createElement("div",o({className:"slider-frame",ref:"frame",style:this.getFrameStyles()},this.getTouchEvents(),this.getMouseEvents(),{onClick:this.handleClick}),a["default"].createElement("ul",{className:"slider-list",ref:"list",style:this.getListStyles()},t)),this.props.decorators?this.props.decorators.map(function(t,n){return a["default"].createElement("div",{style:(0,p["default"])(e.getDecoratorStyles(t.position),t.style||{}),className:"slider-decorator-"+n,key:n},a["default"].createElement(t.component,{currentSlide:e.state.currentSlide,slideCount:e.state.slideCount,frameWidth:e.state.frameWidth,slideWidth:e.state.slideWidth,slidesToScroll:e.state.slidesToScroll,cellSpacing:e.props.cellSpacing,slidesToShow:e.props.slidesToShow,wrapAround:e.props.wrapAround,nextSlide:e.nextSlide,previousSlide:e.previousSlide,goToSlide:e.goToSlide}))}):null,a["default"].createElement("style",{type:"text/css",dangerouslySetInnerHTML:{__html:e.getStyleTagStyles()}}))},touchObject:{},getTouchEvents:function(){var e=this;return{onTouchStart:function(t){e.touchObject={startX:t.touches[0].pageX,startY:t.touches[0].pageY},e.handleMouseOver()},onTouchMove:function(t){var n=e.swipeDirection(e.touchObject.startX,t.touches[0].pageX,e.touchObject.startY,t.touches[0].pageY);0!==n&&t.preventDefault();var r=e.props.vertical?Math.round(Math.sqrt(Math.pow(t.touches[0].pageY-e.touchObject.startY,2))):Math.round(Math.sqrt(Math.pow(t.touches[0].pageX-e.touchObject.startX,2)));e.touchObject={startX:e.touchObject.startX,startY:e.touchObject.startY,endX:t.touches[0].pageX,endY:t.touches[0].pageY,length:r,direction:n},e.setState({left:e.props.vertical?0:e.getTargetLeft(e.touchObject.length*e.touchObject.direction),top:e.props.vertical?e.getTargetLeft(e.touchObject.length*e.touchObject.direction):0})},onTouchEnd:function(t){e.handleSwipe(t),e.handleMouseOut()},onTouchCancel:function(t){e.handleSwipe(t)}}},clickSafe:!0,getMouseEvents:function(){var e=this;return this.props.dragging===!1?null:{onMouseOver:function(){e.handleMouseOver()},onMouseOut:function(){e.handleMouseOut()},onMouseDown:function(t){e.touchObject={startX:t.clientX,startY:t.clientY},e.setState({dragging:!0})},onMouseMove:function(t){if(e.state.dragging){var n=e.swipeDirection(e.touchObject.startX,t.clientX,e.touchObject.startY,t.clientY);0!==n&&t.preventDefault();var r=e.props.vertical?Math.round(Math.sqrt(Math.pow(t.clientY-e.touchObject.startY,2))):Math.round(Math.sqrt(Math.pow(t.clientX-e.touchObject.startX,2)));e.touchObject={startX:e.touchObject.startX,startY:e.touchObject.startY,endX:t.clientX,endY:t.clientY,length:r,direction:n},e.setState({left:e.props.vertical?0:e.getTargetLeft(e.touchObject.length*e.touchObject.direction),top:e.props.vertical?e.getTargetLeft(e.touchObject.length*e.touchObject.direction):0})}},onMouseUp:function(t){e.state.dragging&&e.handleSwipe(t)},onMouseLeave:function(t){e.state.dragging&&e.handleSwipe(t)}}},handleMouseOver:function(){this.props.autoplay&&(this.autoplayPaused=!0,this.stopAutoplay())},handleMouseOut:function(){this.props.autoplay&&this.autoplayPaused&&(this.startAutoplay(),this.autoplayPaused=null)},handleClick:function(e){this.clickSafe===!0&&(e.preventDefault(),e.stopPropagation(),e.nativeEvent&&e.nativeEvent.stopPropagation())},handleSwipe:function(e){"undefined"!=typeof this.touchObject.length&&this.touchObject.length>44?this.clickSafe=!0:this.clickSafe=!1;var t=this.props.slidesToShow;"auto"===this.props.slidesToScroll&&(t=this.state.slidesToScroll),this.touchObject.length>this.state.slideWidth/t/5?1===this.touchObject.direction?this.state.currentSlide>=a["default"].Children.count(this.props.children)-t&&!this.props.wrapAround?this.animateSlide(u["default"].easingTypes[this.props.edgeEasing]):this.nextSlide():this.touchObject.direction===-1&&(this.state.currentSlide<=0&&!this.props.wrapAround?this.animateSlide(u["default"].easingTypes[this.props.edgeEasing]):this.previousSlide()):this.goToSlide(this.state.currentSlide),this.touchObject={},this.setState({dragging:!1})},swipeDirection:function(e,t,n,r){var o,i,a,s;return o=e-t,i=n-r,a=Math.atan2(i,o),s=Math.round(180*a/Math.PI),s<0&&(s=360-Math.abs(s)),s<=45&&s>=0?1:s<=360&&s>=315?1:s>=135&&s<=225?-1:this.props.vertical===!0?s>=35&&s<=135?1:-1:0},autoplayIterator:function(){return this.props.wrapAround?this.nextSlide():void(this.state.currentSlide!==this.state.slideCount-this.state.slidesToShow?this.nextSlide():this.stopAutoplay())},startAutoplay:function(){this.autoplayID=setInterval(this.autoplayIterator,this.props.autoplayInterval)},resetAutoplay:function(){this.props.autoplay&&!this.autoplayPaused&&(this.stopAutoplay(),this.startAutoplay())},stopAutoplay:function(){this.autoplayID&&clearInterval(this.autoplayID)},goToSlide:function(e){var t=this;if(e>=a["default"].Children.count(this.props.children)||e<0){if(!this.props.wrapAround)return;if(e>=a["default"].Children.count(this.props.children))return this.props.beforeSlide(this.state.currentSlide,0),this.setState({currentSlide:0},function(){t.animateSlide(null,null,t.getTargetLeft(null,e),function(){t.animateSlide(null,.01),t.props.afterSlide(0),t.resetAutoplay(),t.setExternalData()})});var n=a["default"].Children.count(this.props.children)-this.state.slidesToScroll;return this.props.beforeSlide(this.state.currentSlide,n),this.setState({currentSlide:n},function(){t.animateSlide(null,null,t.getTargetLeft(null,e),function(){t.animateSlide(null,.01),t.props.afterSlide(n),t.resetAutoplay(),t.setExternalData()})})}this.props.beforeSlide(this.state.currentSlide,e),this.setState({currentSlide:e},function(){t.animateSlide(),this.props.afterSlide(e),t.resetAutoplay(),t.setExternalData()})},nextSlide:function(){var e=a["default"].Children.count(this.props.children),t=this.props.slidesToShow;if("auto"===this.props.slidesToScroll&&(t=this.state.slidesToScroll),!(this.state.currentSlide>=e-t)||this.props.wrapAround)if(this.props.wrapAround)this.goToSlide(this.state.currentSlide+this.state.slidesToScroll);else{if(1!==this.props.slideWidth)return this.goToSlide(this.state.currentSlide+this.state.slidesToScroll);this.goToSlide(Math.min(this.state.currentSlide+this.state.slidesToScroll,e-t))}},previousSlide:function(){this.state.currentSlide<=0&&!this.props.wrapAround||(this.props.wrapAround?this.goToSlide(this.state.currentSlide-this.state.slidesToScroll):this.goToSlide(Math.max(0,this.state.currentSlide-this.state.slidesToScroll)))},animateSlide:function(e,t,n,r){this.tweenState(this.props.vertical?"top":"left",{easing:e||u["default"].easingTypes[this.props.easing],duration:t||this.props.speed,endValue:n||this.getTargetLeft(),onEnd:r||null})},getTargetLeft:function(e,t){var n,r=t||this.state.currentSlide;switch(this.props.cellAlign){case"left":n=0,n-=this.props.cellSpacing*r;break;case"center":n=(this.state.frameWidth-this.state.slideWidth)/2,n-=this.props.cellSpacing*r;break;case"right":n=this.state.frameWidth-this.state.slideWidth,n-=this.props.cellSpacing*r}var o=this.state.slideWidth*r,i=this.state.currentSlide>0&&r+this.state.slidesToScroll>=this.state.slideCount;return i&&1!==this.props.slideWidth&&!this.props.wrapAround&&"auto"===this.props.slidesToScroll&&(o=this.state.slideWidth*this.state.slideCount-this.state.frameWidth,n=0,n-=this.props.cellSpacing*(this.state.slideCount-1)),n-=e||0,(o-n)*-1},bindEvents:function(){var e=this;m["default"].canUseDOM&&(v(window,"resize",e.onResize),v(document,"readystatechange",e.onReadyStateChange))},onResize:function(){this.setDimensions()},onReadyStateChange:function(){this.setDimensions()},unbindEvents:function(){var e=this;m["default"].canUseDOM&&(y(window,"resize",e.onResize),y(document,"readystatechange",e.onReadyStateChange))},formatChildren:function(e){var t=this,n=this.props.vertical?this.getTweeningValue("top"):this.getTweeningValue("left");return a["default"].Children.map(e,function(e,r){return a["default"].createElement("li",{className:"slider-slide",style:t.getSlideStyles(r,n),key:r},e)})},setInitialDimensions:function(){var e,t,n,r=this;e=this.props.vertical?this.props.initialSlideHeight||0:this.props.initialSlideWidth||0,n=this.props.initialSlideHeight?this.props.initialSlideHeight*this.props.slidesToShow:0,t=n+this.props.cellSpacing*(this.props.slidesToShow-1),this.setState({slideHeight:n,frameWidth:this.props.vertical?t:"100%",slideCount:a["default"].Children.count(this.props.children),slideWidth:e},function(){r.setLeft(),r.setExternalData()})},setDimensions:function(e){e=e||this.props;var t,n,r,o,i,a,s,l=this;n=e.slidesToScroll,o=this.refs.frame,r=o.childNodes[0].childNodes[0],r?(r.style.height="auto",s=this.props.vertical?r.offsetHeight*e.slidesToShow:r.offsetHeight):s=100,t="number"!=typeof e.slideWidth?parseInt(e.slideWidth):e.vertical?s/e.slidesToShow*e.slideWidth:o.offsetWidth/e.slidesToShow*e.slideWidth,e.vertical||(t-=e.cellSpacing*((100-100/e.slidesToShow)/100)),a=s+e.cellSpacing*(e.slidesToShow-1),i=e.vertical?a:o.offsetWidth,"auto"===e.slidesToScroll&&(n=Math.floor(i/(t+e.cellSpacing))),this.setState({slideHeight:s,frameWidth:i,slideWidth:t,slidesToScroll:n,left:e.vertical?0:this.getTargetLeft(),top:e.vertical?this.getTargetLeft():0},function(){l.setLeft()})},setLeft:function(){this.setState({left:this.props.vertical?0:this.getTargetLeft(),top:this.props.vertical?this.getTargetLeft():0})},setExternalData:function(){this.props.data&&this.props.data()},getListStyles:function(){var e=this.state.slideWidth*a["default"].Children.count(this.props.children),t=this.props.cellSpacing*a["default"].Children.count(this.props.children),n="translate3d("+this.getTweeningValue("left")+"px, "+this.getTweeningValue("top")+"px, 0)";return{transform:n,WebkitTransform:n,msTransform:"translate("+this.getTweeningValue("left")+"px, "+this.getTweeningValue("top")+"px)",position:"relative",display:"block",margin:this.props.vertical?this.props.cellSpacing/2*-1+"px 0px":"0px "+this.props.cellSpacing/2*-1+"px",padding:0,height:this.props.vertical?e+t:this.state.slideHeight,width:this.props.vertical?"auto":e+t,cursor:this.state.dragging===!0?"pointer":"inherit",boxSizing:"border-box",MozBoxSizing:"border-box"}},getFrameStyles:function(){return{position:"relative",display:"block",overflow:this.props.frameOverflow,height:this.props.vertical?this.state.frameWidth||"initial":"auto",margin:this.props.framePadding,padding:0,transform:"translate3d(0, 0, 0)",WebkitTransform:"translate3d(0, 0, 0)",msTransform:"translate(0, 0)",boxSizing:"border-box",MozBoxSizing:"border-box"}},getSlideStyles:function(e,t){var n=this.getSlideTargetPosition(e,t);return{position:"absolute",left:this.props.vertical?0:n,top:this.props.vertical?n:0,display:this.props.vertical?"block":"inline-block",listStyleType:"none",verticalAlign:"top",width:this.props.vertical?"100%":this.state.slideWidth,height:"auto",boxSizing:"border-box",MozBoxSizing:"border-box",marginLeft:this.props.vertical?"auto":this.props.cellSpacing/2,marginRight:this.props.vertical?"auto":this.props.cellSpacing/2,marginTop:this.props.vertical?this.props.cellSpacing/2:"auto",marginBottom:this.props.vertical?this.props.cellSpacing/2:"auto"}},getSlideTargetPosition:function(e,t){var n=this.state.frameWidth/this.state.slideWidth,r=(this.state.slideWidth+this.props.cellSpacing)*e,o=(this.state.slideWidth+this.props.cellSpacing)*n*-1;if(this.props.wrapAround){var i=Math.ceil(t/this.state.slideWidth);if(this.state.slideCount-i<=e)return(this.state.slideWidth+this.props.cellSpacing)*(this.state.slideCount-e)*-1;var a=Math.ceil((Math.abs(t)-Math.abs(o))/this.state.slideWidth);if(1!==this.state.slideWidth&&(a=Math.ceil((Math.abs(t)-this.state.slideWidth)/this.state.slideWidth)),e<=a-1)return(this.state.slideWidth+this.props.cellSpacing)*(this.state.slideCount+e)}return r},getSliderStyles:function(){return{position:"relative",display:"block",width:this.props.width,height:"auto",boxSizing:"border-box",MozBoxSizing:"border-box",visibility:this.state.slideWidth?"visible":"hidden"}},getStyleTagStyles:function(){return".slider-slide > img {width: 100%; display: block;}"},getDecoratorStyles:function(e){switch(e){case"TopLeft":return{position:"absolute",top:0,left:0};case"TopCenter":return{position:"absolute",top:0,left:"50%",transform:"translateX(-50%)",WebkitTransform:"translateX(-50%)",msTransform:"translateX(-50%)"};case"TopRight":return{position:"absolute",top:0,right:0};case"CenterLeft":return{position:"absolute",top:"50%",left:0,transform:"translateY(-50%)",WebkitTransform:"translateY(-50%)",msTransform:"translateY(-50%)"};case"CenterCenter":return{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",WebkitTransform:"translate(-50%, -50%)",msTransform:"translate(-50%, -50%)"};case"CenterRight":return{position:"absolute",top:"50%",right:0,transform:"translateY(-50%)",WebkitTransform:"translateY(-50%)",msTransform:"translateY(-50%)"};case"BottomLeft":return{position:"absolute",bottom:0,left:0};case"BottomCenter":return{position:"absolute",bottom:0,left:"50%",transform:"translateX(-50%)",WebkitTransform:"translateX(-50%)",msTransform:"translateX(-50%)"};case"BottomRight":return{position:"absolute",bottom:0,right:0};default:return{position:"absolute",top:0,left:0}}}});g.ControllerMixin={getInitialState:function(){return{carousels:{}}},setCarouselData:function(e){var t=this.state.carousels;t[e]=this.refs[e],this.setState({carousels:t})}},t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=[{component:i["default"].createClass({displayName:"component",render:function(){return i["default"].createElement("button",{style:this.getButtonStyles(0===this.props.currentSlide&&!this.props.wrapAround),onClick:this.handleClick},"PREV")},handleClick:function(e){e.preventDefault(),this.props.previousSlide()},getButtonStyles:function(e){return{border:0,background:"rgba(0,0,0,0.4)",color:"white",padding:10,outline:0,opacity:e?.3:1,cursor:"pointer"}}}),position:"CenterLeft"},{component:i["default"].createClass({displayName:"component",render:function(){return i["default"].createElement("button",{style:this.getButtonStyles(this.props.currentSlide+this.props.slidesToScroll>=this.props.slideCount&&!this.props.wrapAround),onClick:this.handleClick},"NEXT")},handleClick:function(e){e.preventDefault(),this.props.nextSlide()},getButtonStyles:function(e){return{border:0,background:"rgba(0,0,0,0.4)",color:"white",padding:10,outline:0,opacity:e?.3:1,cursor:"pointer"}}}),position:"CenterRight"},{component:i["default"].createClass({displayName:"component",render:function(){var e=this,t=this.getIndexes(e.props.slideCount,e.props.slidesToScroll);return i["default"].createElement("ul",{style:e.getListStyles()},t.map(function(t){return i["default"].createElement("li",{style:e.getListItemStyles(),key:t},i["default"].createElement("button",{style:e.getButtonStyles(e.props.currentSlide===t),onClick:e.props.goToSlide.bind(null,t)},"\u2022"))}))},getIndexes:function(e,t){for(var n=[],r=0;r<e;r+=t)n.push(r);return n},getListStyles:function(){return{position:"relative",margin:0,top:-10,padding:0}},getListItemStyles:function(){return{listStyleType:"none",display:"inline-block"}},getButtonStyles:function(e){return{border:0,background:"transparent",color:"black",cursor:"pointer",padding:10,outline:0,fontSize:24,opacity:e?1:.5}}}),position:"BottomCenter"}];t["default"]=a,e.exports=t["default"]},function(e,t,n){var r,o,i;!function(n,a){"use strict";"object"==typeof e&&"object"==typeof e.exports?e.exports=a():(o=[],r=a,i="function"==typeof r?r.apply(t,o):r,!(void 0!==i&&(e.exports=i)))}(this,function(){"use strict";function e(e,t){return null!=e&&Object.prototype.hasOwnProperty.call(e,t)}function t(t){if(!t)return!0;if(l(t)&&0===t.length)return!0;if("string"!=typeof t){for(var n in t)if(e(t,n))return!1;return!0}return!1}function n(e){return s.call(e)}function r(e){return"object"==typeof e&&"[object Object]"===n(e)}function o(e){return"boolean"==typeof e||"[object Boolean]"===n(e)}function i(e){var t=parseInt(e);return t.toString()===e?t:e}function a(n){function a(t,r){if(n.includeInheritedProps||"number"==typeof r&&Array.isArray(t)||e(t,r))return t[r]}function s(e,t,n,r){if("number"==typeof t&&(t=[t]),!t||0===t.length)return e;if("string"==typeof t)return s(e,t.split(".").map(i),n,r);var o=t[0],l=a(e,o);return 1===t.length?(void 0!==l&&r||(e[o]=n),l):(void 0===l&&("number"==typeof t[1]?e[o]=[]:e[o]={}),s(e[o],t.slice(1),n,r))}n=n||{};var u=function(e){return Object.keys(u).reduce(function(t,n){return"create"===n?t:("function"==typeof u[n]&&(t[n]=u[n].bind(u,e)),t)},{})};return u.has=function(t,r){if("number"==typeof r?r=[r]:"string"==typeof r&&(r=r.split(".")),!r||0===r.length)return!!t;for(var o=0;o<r.length;o++){var a=i(r[o]);if(!("number"==typeof a&&l(t)&&a<t.length||(n.includeInheritedProps?a in Object(t):e(t,a))))return!1;t=t[a]}return!0},u.ensureExists=function(e,t,n){return s(e,t,n,!0)},u.set=function(e,t,n,r){return s(e,t,n,r)},u.insert=function(e,t,n,r){var o=u.get(e,t);r=~~r,l(o)||(o=[],u.set(e,t,o)),o.splice(r,0,n)},u.empty=function(n,i){if(!t(i)&&null!=n){var a,s;if(a=u.get(n,i)){if("string"==typeof a)return u.set(n,i,"");if(o(a))return u.set(n,i,!1);if("number"==typeof a)return u.set(n,i,0);if(l(a))a.length=0;else{if(!r(a))return u.set(n,i,null);for(s in a)e(a,s)&&delete a[s]}}}},u.push=function(e,t){var n=u.get(e,t);l(n)||(n=[],u.set(e,t,n)),n.push.apply(n,Array.prototype.slice.call(arguments,2))},u.coalesce=function(e,t,n){for(var r,o=0,i=t.length;o<i;o++)if(void 0!==(r=u.get(e,t[o])))return r;return n},u.get=function(e,t,n){if("number"==typeof t&&(t=[t]),!t||0===t.length)return e;if(null==e)return n;if("string"==typeof t)return u.get(e,t.split("."),n);var r=i(t[0]),o=a(e,r);return void 0===o?n:1===t.length?o:u.get(e[r],t.slice(1),n)},u.del=function(e,n){if("number"==typeof n&&(n=[n]),null==e)return e;if(t(n))return e;if("string"==typeof n)return u.del(e,n.split("."));var r=i(n[0]),o=a(e,r);if(null==o)return o;if(1===n.length)l(e)?e.splice(r,1):delete e[r];else if(void 0!==e[r])return u.del(e[r],n.slice(1));return e},u}var s=Object.prototype.toString,l=Array.isArray||function(e){return"[object Array]"===s.call(e)},u=a();return u.create=a,u.withInheritedProps=a({includeInheritedProps:!0}),u})},function(e,t,n){/*!
* object.omit <https://github.com/jonschlinkert/object.omit>
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
"use strict";var r=n(337),o=n(335);e.exports=function(e,t){if(!r(e))return{};var n,t=[].concat.apply([],[].slice.call(arguments,1)),i=t[t.length-1],a={};"function"==typeof i&&(n=t.pop());var s="function"==typeof n;return t.length||s?(o(e,function(r,o){t.indexOf(o)===-1&&(s?n(r,o,e)&&(a[o]=r):a[o]=r)}),a):e}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){function n(){o&&(clearTimeout(o),o=null)}function r(){n(),o=setTimeout(e,t)}var o=void 0;return r.clear=n,r}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),a=r(i),s=n(9),l=r(s),u=n(277),c=r(u),d=n(44),f=r(d),p=n(350),h=r(p),m=a["default"].createClass({displayName:"Align",propTypes:{childrenProps:i.PropTypes.object,align:i.PropTypes.object.isRequired,target:i.PropTypes.func,onAlign:i.PropTypes.func,monitorBufferTime:i.PropTypes.number,monitorWindowResize:i.PropTypes.bool,disabled:i.PropTypes.bool,children:i.PropTypes.any},getDefaultProps:function(){return{target:function(){return window},onAlign:function(){},monitorBufferTime:50,monitorWindowResize:!1,disabled:!1}},componentDidMount:function(){var e=this.props;this.forceAlign(),!e.disabled&&e.monitorWindowResize&&this.startMonitorWindowResize()},componentDidUpdate:function(e){var t=!1,n=this.props;if(!n.disabled)if(e.disabled||e.align!==n.align)t=!0;else{var r=e.target(),o=n.target();(0,h["default"])(r)&&(0,h["default"])(o)?t=!1:r!==o&&(t=!0)}t&&this.forceAlign(),n.monitorWindowResize&&!n.disabled?this.startMonitorWindowResize():this.stopMonitorWindowResize()},componentWillUnmount:function(){this.stopMonitorWindowResize()},startMonitorWindowResize:function(){this.resizeHandler||(this.bufferMonitor=o(this.forceAlign,this.props.monitorBufferTime),this.resizeHandler=(0,f["default"])(window,"resize",this.bufferMonitor))},stopMonitorWindowResize:function(){this.resizeHandler&&(this.bufferMonitor.clear(),this.resizeHandler.remove(),this.resizeHandler=null)},forceAlign:function(){var e=this.props;if(!e.disabled){var t=l["default"].findDOMNode(this);e.onAlign(t,(0,c["default"])(t,e.target(),e.align))}},render:function(){var e=this.props,t=e.childrenProps,n=e.children,r=a["default"].Children.only(n);if(t){var o={};for(var i in t)t.hasOwnProperty(i)&&(o[i]=this.props[t[i]]);return a["default"].cloneElement(r,o)}return r}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(348),i=r(o);t["default"]=i["default"],e.exports=t["default"]},function(e,t){"use strict";function n(e){return null!=e&&e==e.window}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=e.children;return l["default"].isValidElement(t)&&!t.key?l["default"].cloneElement(t,{key:h}):t}function a(){}Object.defineProperty(t,"__esModule",{value:!0});var s=n(1),l=r(s),u=n(353),c=n(352),d=r(c),f=n(107),p=r(f),h="rc_animate_"+Date.now(),m=l["default"].createClass({displayName:"Animate",propTypes:{component:l["default"].PropTypes.any,animation:l["default"].PropTypes.object,transitionName:l["default"].PropTypes.oneOfType([l["default"].PropTypes.string,l["default"].PropTypes.object]),transitionEnter:l["default"].PropTypes.bool,transitionAppear:l["default"].PropTypes.bool,exclusive:l["default"].PropTypes.bool,transitionLeave:l["default"].PropTypes.bool,onEnd:l["default"].PropTypes.func,onEnter:l["default"].PropTypes.func,onLeave:l["default"].PropTypes.func,onAppear:l["default"].PropTypes.func,showProp:l["default"].PropTypes.string},getDefaultProps:function(){return{animation:{},component:"span",transitionEnter:!0,transitionLeave:!0,transitionAppear:!1,onEnd:a,onEnter:a,onLeave:a,onAppear:a}},getInitialState:function(){return this.currentlyAnimatingKeys={},this.keysToEnter=[],this.keysToLeave=[],{children:(0,u.toArrayChildren)(i(this.props))}},componentDidMount:function(){var e=this,t=this.props.showProp,n=this.state.children;t&&(n=n.filter(function(e){return!!e.props[t]})),n.forEach(function(t){t&&e.performAppear(t.key)})},componentWillReceiveProps:function(e){var t=this;this.nextProps=e;var n=(0,u.toArrayChildren)(i(e)),r=this.props;r.exclusive&&Object.keys(this.currentlyAnimatingKeys).forEach(function(e){t.stop(e)});var a=r.showProp,s=this.currentlyAnimatingKeys,c=r.exclusive?(0,u.toArrayChildren)(i(r)):this.state.children,d=[];a?(c.forEach(function(e){var t=e&&(0,u.findChildInChildrenByKey)(n,e.key),r=void 0;r=t&&t.props[a]||!e.props[a]?t:l["default"].cloneElement(t||e,o({},a,!0)),r&&d.push(r)}),n.forEach(function(e){e&&(0,u.findChildInChildrenByKey)(c,e.key)||d.push(e)})):d=(0,u.mergeChildren)(c,n),this.setState({children:d}),n.forEach(function(e){var n=e&&e.key;if(!e||!s[n]){var r=e&&(0,u.findChildInChildrenByKey)(c,n);if(a){var o=e.props[a];if(r){var i=(0,u.findShownChildInChildrenByKey)(c,n,a);!i&&o&&t.keysToEnter.push(n)}else o&&t.keysToEnter.push(n)}else r||t.keysToEnter.push(n)}}),c.forEach(function(e){var r=e&&e.key;if(!e||!s[r]){var o=e&&(0,u.findChildInChildrenByKey)(n,r);if(a){var i=e.props[a];if(o){var l=(0,u.findShownChildInChildrenByKey)(n,r,a);!l&&i&&t.keysToLeave.push(r)}else i&&t.keysToLeave.push(r)}else o||t.keysToLeave.push(r)}})},componentDidUpdate:function(){var e=this.keysToEnter;this.keysToEnter=[],e.forEach(this.performEnter);var t=this.keysToLeave;this.keysToLeave=[],t.forEach(this.performLeave)},performEnter:function(e){this.refs[e]&&(this.currentlyAnimatingKeys[e]=!0,this.refs[e].componentWillEnter(this.handleDoneAdding.bind(this,e,"enter")))},performAppear:function(e){this.refs[e]&&(this.currentlyAnimatingKeys[e]=!0,this.refs[e].componentWillAppear(this.handleDoneAdding.bind(this,e,"appear")))},handleDoneAdding:function(e,t){var n=this.props;if(delete this.currentlyAnimatingKeys[e],!n.exclusive||n===this.nextProps){var r=(0,u.toArrayChildren)(i(n));this.isValidChildByKey(r,e)?"appear"===t?p["default"].allowAppearCallback(n)&&(n.onAppear(e),n.onEnd(e,!0)):p["default"].allowEnterCallback(n)&&(n.onEnter(e),n.onEnd(e,!0)):this.performLeave(e)}},performLeave:function(e){this.refs[e]&&(this.currentlyAnimatingKeys[e]=!0,this.refs[e].componentWillLeave(this.handleDoneLeaving.bind(this,e)))},handleDoneLeaving:function(e){var t=this.props;if(delete this.currentlyAnimatingKeys[e],!t.exclusive||t===this.nextProps){var n=(0,u.toArrayChildren)(i(t));if(this.isValidChildByKey(n,e))this.performEnter(e);else{var r=function(){p["default"].allowLeaveCallback(t)&&(t.onLeave(e),t.onEnd(e,!1))};this.isMounted()&&!(0,u.isSameChildren)(this.state.children,n,t.showProp)?this.setState({children:n},r):r()}}},isValidChildByKey:function(e,t){var n=this.props.showProp;return n?(0,u.findShownChildInChildrenByKey)(e,t,n):(0,u.findChildInChildrenByKey)(e,t)},stop:function(e){delete this.currentlyAnimatingKeys[e];var t=this.refs[e];t&&t.stop()},render:function(){var e=this.props;this.nextProps=e;var t=this.state.children,n=null;t&&(n=t.map(function(t){if(null===t||void 0===t)return t;if(!t.key)throw new Error("must set key for <rc-animate> children");return l["default"].createElement(d["default"],{key:t.key,ref:t.key,animation:e.animation,transitionName:e.transitionName,transitionEnter:e.transitionEnter,transitionAppear:e.transitionAppear,transitionLeave:e.transitionLeave},t)}));var r=e.component;if(r){var o=e;return"string"==typeof r&&(o={className:e.className,style:e.style}),l["default"].createElement(r,o,n)}return n[0]||null}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},i=n(1),a=r(i),s=n(9),l=r(s),u=n(103),c=r(u),d=n(107),f=r(d),p={enter:"transitionEnter",appear:"transitionAppear",leave:"transitionLeave"},h=a["default"].createClass({displayName:"AnimateChild",propTypes:{children:a["default"].PropTypes.any},componentWillUnmount:function(){this.stop()},componentWillEnter:function(e){f["default"].isEnterSupported(this.props)?this.transition("enter",e):e()},componentWillAppear:function(e){f["default"].isAppearSupported(this.props)?this.transition("appear",e):e()},componentWillLeave:function(e){f["default"].isLeaveSupported(this.props)?this.transition("leave",e):e()},transition:function(e,t){var n=this,r=l["default"].findDOMNode(this),i=this.props,a=i.transitionName,s="object"===("undefined"==typeof a?"undefined":o(a));this.stop();var d=function(){n.stopper=null,t()};if((u.isCssAnimationSupported||!i.animation[e])&&a&&i[p[e]]){var f=s?a[e]:a+"-"+e,h=f+"-active";s&&a[e+"Active"]&&(h=a[e+"Active"]),this.stopper=(0,c["default"])(r,{name:f,active:h},d)}else this.stopper=i.animation[e](r,d)},stop:function(){var e=this.stopper;e&&(this.stopper=null,e.stop())},render:function(){return this.props.children}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=[];return d["default"].Children.forEach(e,function(e){t.push(e)}),t}function i(e,t){var n=null;return e&&e.forEach(function(e){n||e&&e.key===t&&(n=e)}),n}function a(e,t,n){var r=null;return e&&e.forEach(function(e){if(e&&e.key===t&&e.props[n]){if(r)throw new Error("two child with same key for <rc-animate> children");r=e}}),r}function s(e,t,n){var r=0;return e&&e.forEach(function(e){r||(r=e&&e.key===t&&!e.props[n])}),r}function l(e,t,n){var r=e.length===t.length;return r&&e.forEach(function(e,o){var i=t[o];e&&i&&(e&&!i||!e&&i?r=!1:e.key!==i.key?r=!1:n&&e.props[n]!==i.props[n]&&(r=!1))}),r}function u(e,t){var n=[],r={},o=[];return e.forEach(function(e){e&&i(t,e.key)?o.length&&(r[e.key]=o,o=[]):o.push(e)}),t.forEach(function(e){e&&r.hasOwnProperty(e.key)&&(n=n.concat(r[e.key])),n.push(e)}),n=n.concat(o)}Object.defineProperty(t,"__esModule",{value:!0}),t.toArrayChildren=o,t.findChildInChildrenByKey=i,t.findShownChildInChildrenByKey=a,t.findHiddenChildInChildrenByKey=s,t.isSameChildren=l,t.mergeChildren=u;var c=n(1),d=r(c)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c=n(1),d=r(c),f=n(403),p=r(f),h=n(5),m=r(h),v=function(e){function t(n){a(this,t);var r=s(this,e.call(this,n));r.handleFocus=function(e){r.setState({focus:!0}),r.props.onFocus(e)},r.handleBlur=function(e){r.setState({focus:!1}),r.props.onBlur(e)},r.handleChange=function(e){"checked"in r.props||r.setState({checked:e.target.checked}),r.props.onChange({target:u({},r.props,{checked:e.target.checked}),stopPropagation:function(){e.stopPropagation()},preventDefault:function(){e.preventDefault()}})};var o=!1;return o="checked"in n?n.checked:n.defaultChecked,r.state={checked:o,focus:!1},r}return l(t,e),t.prototype.componentWillReceiveProps=function(e){"checked"in e&&this.setState({checked:e.checked})},t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return p["default"].shouldComponentUpdate.apply(this,t)},t.prototype.render=function(){var e,t=u({},this.props);delete t.defaultChecked;var n=this.state,r=t.prefixCls,o=n.checked;"boolean"==typeof o&&(o=o?1:0);var a=(0,m["default"])((e={},i(e,t.className,!!t.className),i(e,r,1),i(e,r+"-checked",o),i(e,r+"-checked-"+o,!!o),i(e,r+"-focused",n.focus),i(e,r+"-disabled",t.disabled),e));return d["default"].createElement("span",{className:a,style:t.style},d["default"].createElement("span",{className:r+"-inner"}),d["default"].createElement("input",{name:t.name,type:t.type,readOnly:t.readOnly,disabled:t.disabled,tabIndex:t.tabIndex,className:r+"-input",checked:!!o,onClick:this.props.onClick,onFocus:this.handleFocus,onBlur:this.handleBlur,onChange:this.handleChange}))},t}(d["default"].Component);v.propTypes={name:d["default"].PropTypes.string,prefixCls:d["default"].PropTypes.string,style:d["default"].PropTypes.object,type:d["default"].PropTypes.string,className:d["default"].PropTypes.string,defaultChecked:d["default"].PropTypes.oneOfType([d["default"].PropTypes.number,d["default"].PropTypes.bool]),checked:d["default"].PropTypes.oneOfType([d["default"].PropTypes.number,d["default"].PropTypes.bool]),onFocus:d["default"].PropTypes.func,onBlur:d["default"].PropTypes.func,onChange:d["default"].PropTypes.func,onClick:d["default"].PropTypes.func},v.defaultProps={prefixCls:"rc-checkbox",style:{},type:"checkbox",className:"",defaultChecked:!1,onFocus:function(){},onBlur:function(){},onChange:function(){}},t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function i(e){var t=e;return Array.isArray(t)||(t=t?[t]:[]),t}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),s=r(a),l=n(356),u=r(l),c=n(359),d=r(c),f=s["default"].createClass({displayName:"Collapse",propTypes:{children:a.PropTypes.any,prefixCls:a.PropTypes.string,activeKey:a.PropTypes.oneOfType([a.PropTypes.string,a.PropTypes.arrayOf(a.PropTypes.string)]),defaultActiveKey:a.PropTypes.oneOfType([a.PropTypes.string,a.PropTypes.arrayOf(a.PropTypes.string)]),openAnimation:a.PropTypes.object,onChange:a.PropTypes.func,accordion:a.PropTypes.bool},statics:{Panel:u["default"]},getDefaultProps:function(){return{prefixCls:"rc-collapse",onChange:function(){},accordion:!1}},getInitialState:function(){var e=this.props,t=e.activeKey,n=e.defaultActiveKey,r=n;return"activeKey"in this.props&&(r=t),{openAnimation:this.props.openAnimation||(0,d["default"])(this.props.prefixCls),activeKey:i(r)}},componentWillReceiveProps:function(e){"activeKey"in e&&this.setState({activeKey:i(e.activeKey)}),"openAnimation"in e&&this.setState({openAnimation:e.openAnimation})},onClickItem:function(e){var t=this;return function(){var n=t.state.activeKey;if(t.props.accordion)n=n[0]===e?[]:[e];else{n=[].concat(o(n));var r=n.indexOf(e),i=r>-1;i?n.splice(r,1):n.push(e)}t.setActiveKey(n)}},getItems:function(){var e=this,t=this.state.activeKey,n=this.props,r=n.prefixCls,o=n.accordion;return a.Children.map(this.props.children,function(n,i){var a=n.key||String(i),l=n.props.header,u=!1;u=o?t[0]===a:t.indexOf(a)>-1;var c={key:a,header:l,isActive:u,prefixCls:r,openAnimation:e.state.openAnimation,children:n.props.children,onItemClick:e.onClickItem(a).bind(e)};return s["default"].cloneElement(n,c)})},setActiveKey:function(e){"activeKey"in this.props||this.setState({activeKey:e}),this.props.onChange(this.props.accordion?e[0]:e)},render:function(){var e=this.props.prefixCls;return s["default"].createElement("div",{className:e},this.getItems())}});t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),a=r(i),s=n(5),l=r(s),u=n(357),c=r(u),d=n(42),f=r(d),p=a["default"].createClass({displayName:"CollapsePanel",propTypes:{className:i.PropTypes.oneOfType([i.PropTypes.string,i.PropTypes.object]),children:i.PropTypes.any,openAnimation:i.PropTypes.object,prefixCls:i.PropTypes.string,header:i.PropTypes.oneOfType([i.PropTypes.string,i.PropTypes.number,i.PropTypes.node]),isActive:i.PropTypes.bool,onItemClick:i.PropTypes.func},getDefaultProps:function(){return{isActive:!1,onItemClick:function(){}}},handleItemClick:function(){this.props.onItemClick()},render:function(){var e,t=this.props,n=t.className,r=t.prefixCls,i=t.header,s=t.children,u=t.isActive,d=r+"-header",p=(0,l["default"])((e={},o(e,r+"-item",!0),o(e,r+"-item-active",u),o(e,n,n),e));return a["default"].createElement("div",{className:p},a["default"].createElement("div",{className:d,onClick:this.handleItemClick,role:"tab","aria-expanded":u},a["default"].createElement("i",{className:"arrow"}),i),a["default"].createElement(f["default"],{showProp:"isActive",exclusive:!0,component:"",animation:this.props.openAnimation},a["default"].createElement(c["default"],{prefixCls:r,isActive:u},s)))}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),a=r(i),s=n(5),l=r(s),u=a["default"].createClass({displayName:"PanelContent",propTypes:{prefixCls:i.PropTypes.string,isActive:i.PropTypes.bool,children:i.PropTypes.any},shouldComponentUpdate:function(e){return this.props.isActive||e.isActive},render:function(){var e;if(this._isActived=this._isActived||this.props.isActive,!this._isActived)return null;var t=this.props,n=t.prefixCls,r=t.isActive,i=t.children,s=(0,l["default"])((e={},o(e,n+"-content",!0),o(e,n+"-content-active",r),o(e,n+"-content-inactive",!r),e));return a["default"].createElement("div",{className:s,role:"tabpanel"},a["default"].createElement("div",{className:n+"-content-box"},i))}});t["default"]=u,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(355),i=r(o);t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r){var o=void 0;return(0,s["default"])(e,n,{start:function(){t?(o=e.offsetHeight,e.style.height=0):e.style.height=e.offsetHeight+"px"},active:function(){e.style.height=(t?o:0)+"px"},end:function(){e.style.height="",r()}})}function i(e){return{enter:function(t,n){return o(t,!0,e+"-anim",n)},leave:function(t,n){return o(t,!1,e+"-anim",n)}}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(103),s=r(a);t["default"]=i,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function a(e,t){var n=e.style;["Webkit","Moz","Ms","ms"].forEach(function(e){n[e+"TransformOrigin"]=t}),n.transformOrigin=t}function s(e){var t=e.getBoundingClientRect(),n={left:t.left,top:t.top},r=e.ownerDocument,o=r.defaultView||r.parentWindow;return n.left+=i(o),n.top+=i(o,!0),n}Object.defineProperty(t,"__esModule",{value:!0});var l=n(1),u=r(l),c=n(9),d=r(c),f=n(400),p=r(f),h=n(42),m=r(h),v=n(361),y=r(v),g=n(402),b=r(g),_=n(10),x=r(_),T=0,C=0,w=u["default"].createClass({displayName:"Dialog",getDefaultProps:function(){return{afterClose:o,className:"",mask:!0,visible:!1,keyboard:!0,closable:!0,maskClosable:!0,prefixCls:"rc-dialog",onClose:o}},componentWillMount:function(){this.titleId="rcDialogTitle"+T++},componentDidMount:function(){this.componentDidUpdate({})},componentDidUpdate:function(e){var t=this.props,n=this.props.mousePosition;if(t.visible){if(!e.visible){this.lastOutSideFocusNode=document.activeElement,this.addScrollingEffect(),this.refs.wrap.focus();var r=d["default"].findDOMNode(this.refs.dialog);if(n){var o=s(r);a(r,n.x-o.left+"px "+(n.y-o.top)+"px")}else a(r,"")}}else if(e.visible&&t.mask&&this.lastOutSideFocusNode){try{this.lastOutSideFocusNode.focus()}catch(i){this.lastOutSideFocusNode=null}this.lastOutSideFocusNode=null}},onAnimateLeave:function(){this.refs.wrap&&(this.refs.wrap.style.display="none"),this.removeScrollingEffect(),this.props.afterClose()},onMaskClick:function(e){e.target===e.currentTarget&&this.props.maskClosable&&this.close(e)},onKeyDown:function(e){var t=this.props;if(t.keyboard&&e.keyCode===p["default"].ESC&&this.close(e),t.visible&&e.keyCode===p["default"].TAB){var n=document.activeElement,r=this.refs.wrap,o=this.refs.sentinel;e.shiftKey?n===r&&o.focus():n===this.refs.sentinel&&r.focus()}},getDialogElement:function(){var e=this.props,t=e.closable,n=e.prefixCls,r={};void 0!==e.width&&(r.width=e.width),void 0!==e.height&&(r.height=e.height);var o=void 0;e.footer&&(o=u["default"].createElement("div",{className:n+"-footer",ref:"footer"},e.footer));var i=void 0;e.title&&(i=u["default"].createElement("div",{className:n+"-header",ref:"header"},u["default"].createElement("div",{className:n+"-title",id:this.titleId},e.title)));var a=void 0;t&&(a=u["default"].createElement("button",{onClick:this.close,"aria-label":"Close",className:n+"-close"},u["default"].createElement("span",{className:n+"-close-x"})));var s=(0,x["default"])({},e.style,r),l=this.getTransitionName(),c=u["default"].createElement(y["default"],{role:"document",ref:"dialog",style:s,className:n+" "+(e.className||""),visible:e.visible},u["default"].createElement("div",{className:n+"-content"},a,i,u["default"].createElement("div",{className:n+"-body",style:e.bodyStyle,ref:"body"},e.children),o),u["default"].createElement("div",{tabIndex:"0",ref:"sentinel",style:{width:0,height:0,overflow:"hidden"}},"sentinel"));return u["default"].createElement(m["default"],{key:"dialog",showProp:"visible",onLeave:this.onAnimateLeave,transitionName:l,component:"",transitionAppear:!0},c)},getZIndexStyle:function(){var e={},t=this.props;return void 0!==t.zIndex&&(e.zIndex=t.zIndex),e},getWrapStyle:function(){return(0,x["default"])({},this.getZIndexStyle(),this.props.wrapStyle)},getMaskStyle:function(){return(0,x["default"])({},this.getZIndexStyle(),this.props.maskStyle)},getMaskElement:function(){var e=this.props,t=void 0;if(e.mask){var n=this.getMaskTransitionName();t=u["default"].createElement(y["default"],{style:this.getMaskStyle(),key:"mask",className:e.prefixCls+"-mask",hiddenClassName:e.prefixCls+"-mask-hidden",visible:e.visible}),n&&(t=u["default"].createElement(m["default"],{key:"mask",showProp:"visible",transitionAppear:!0,component:"",transitionName:n},t))}return t},getMaskTransitionName:function(){var e=this.props,t=e.maskTransitionName,n=e.maskAnimation;return!t&&n&&(t=e.prefixCls+"-"+n),t},getTransitionName:function(){var e=this.props,t=e.transitionName,n=e.animation;return!t&&n&&(t=e.prefixCls+"-"+n),t},getElement:function(e){return this.refs[e]},setScrollbar:function(){this.bodyIsOverflowing&&void 0!==this.scrollbarWidth&&(document.body.style.paddingRight=this.scrollbarWidth+"px")},addScrollingEffect:function(){C++,1===C&&(this.checkScrollbar(),this.setScrollbar(),document.body.style.overflow="hidden")},removeScrollingEffect:function(){C--,0===C&&(document.body.style.overflow="",this.resetScrollbar())},close:function(e){this.props.onClose(e)},checkScrollbar:function(){var e=window.innerWidth;if(!e){var t=document.documentElement.getBoundingClientRect();e=t.right-Math.abs(t.left)}this.bodyIsOverflowing=document.body.clientWidth<e,this.bodyIsOverflowing&&(this.scrollbarWidth=(0,b["default"])())},resetScrollbar:function(){document.body.style.paddingRight=""},adjustDialog:function(){if(this.refs.wrap&&void 0!==this.scrollbarWidth){var e=this.refs.wrap.scrollHeight>document.documentElement.clientHeight;this.refs.wrap.style.paddingLeft=(!this.bodyIsOverflowing&&e?this.scrollbarWidth:"")+"px",this.refs.wrap.style.paddingRight=(this.bodyIsOverflowing&&!e?this.scrollbarWidth:"")+"px"}},resetAdjustments:function(){this.refs.wrap&&(this.refs.wrap.style.paddingLeft=this.refs.wrap.style.paddingLeft="")},render:function(){var e=this.props,t=e.prefixCls,n=this.getWrapStyle();return e.visible&&(n.display=null),u["default"].createElement("div",null,this.getMaskElement(),u["default"].createElement("div",{tabIndex:"-1",onKeyDown:this.onKeyDown,className:t+"-wrap "+(e.wrapClassName||""),ref:"wrap",onClick:this.onMaskClick,role:"dialog","aria-labelledby":e.title?this.titleId:null,style:n},this.getDialogElement()))}});t["default"]=w,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(10),s=r(a),l=i["default"].createClass({displayName:"LazyRenderBox",shouldComponentUpdate:function(e){return!!e.hiddenClassName||e.visible},render:function(){var e=this.props.className;this.props.hiddenClassName&&!this.props.visible&&(e+=" "+this.props.hiddenClassName);var t=(0,s["default"])({},this.props);return delete t.hiddenClassName,delete t.visible,t.className=e,i["default"].createElement("div",t)}});t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){for(var t=e,n=0,r=0;t&&!isNaN(t.offsetLeft)&&!isNaN(t.offsetTop);)n+=t.offsetLeft-t.scrollLeft,r+=t.offsetTop-t.scrollTop,t=t.offsetParent;return{top:r,left:n}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(6),a=r(i),s=n(8),l=r(s),u=n(31),c=r(u),d=n(2),f=r(d),p=n(4),h=r(p),m=n(3),v=r(m),y=n(1),g=r(y),b=n(9),_=r(b),x=n(5),T=r(x),C=20,w=function(e){function t(n){(0,f["default"])(this,t);var r=(0,h["default"])(this,e.call(this,n));return r.onOverlayClicked=function(){r.props.open&&r.props.onOpenChange(!1,{overlayClicked:!0})},r.onTouchStart=function(e){if(!r.isTouching()){var t=e.targetTouches[0];r.setState({touchIdentifier:r.notTouch?null:t.identifier,touchStartX:t.clientX,touchStartY:t.clientY,touchCurrentX:t.clientX,touchCurrentY:t.clientY})}},r.onTouchMove=function(e){if(r.isTouching())for(var t=0;t<e.targetTouches.length;t++)if(e.targetTouches[t].identifier===r.state.touchIdentifier){r.setState({touchCurrentX:e.targetTouches[t].clientX,touchCurrentY:e.targetTouches[t].clientY});break}},r.onTouchEnd=function(){if(r.notTouch=!1,r.isTouching()){var e=r.touchSidebarWidth();(r.props.open&&e<r.state.sidebarWidth-r.props.dragToggleDistance||!r.props.open&&e>r.props.dragToggleDistance)&&r.props.onOpenChange(!r.props.open);var t=r.touchSidebarHeight();(r.props.open&&t<r.state.sidebarHeight-r.props.dragToggleDistance||!r.props.open&&t>r.props.dragToggleDistance)&&r.props.onOpenChange(!r.props.open),r.setState({touchIdentifier:null,touchStartX:null,touchStartY:null,touchCurrentX:null,touchCurrentY:null})}},r.onScroll=function(){r.isTouching()&&r.inCancelDistanceOnScroll()&&r.setState({touchIdentifier:null,touchStartX:null,touchStartY:null,touchCurrentX:null,touchCurrentY:null})},r.inCancelDistanceOnScroll=function(){var e=void 0;switch(r.props.position){case"right":e=Math.abs(r.state.touchCurrentX-r.state.touchStartX)<C;break;case"bottom":e=Math.abs(r.state.touchCurrentY-r.state.touchStartY)<C;break;case"top":e=Math.abs(r.state.touchStartY-r.state.touchCurrentY)<C;break;case"left":default:e=Math.abs(r.state.touchStartX-r.state.touchCurrentX)<C}return e},r.isTouching=function(){return null!==r.state.touchIdentifier},r.saveSidebarSize=function(){var e=_["default"].findDOMNode(r.refs.sidebar),t=e.offsetWidth,n=e.offsetHeight,i=o(_["default"].findDOMNode(r.refs.sidebar)).top,a=o(_["default"].findDOMNode(r.refs.dragHandle)).top;t!==r.state.sidebarWidth&&r.setState({sidebarWidth:t}),n!==r.state.sidebarHeight&&r.setState({sidebarHeight:n}),i!==r.state.sidebarTop&&r.setState({sidebarTop:i}),a!==r.state.dragHandleTop&&r.setState({dragHandleTop:a})},r.touchSidebarWidth=function(){return"right"===r.props.position?r.props.open&&window.innerWidth-r.state.touchStartX<r.state.sidebarWidth?r.state.touchCurrentX>r.state.touchStartX?r.state.sidebarWidth+r.state.touchStartX-r.state.touchCurrentX:r.state.sidebarWidth:Math.min(window.innerWidth-r.state.touchCurrentX,r.state.sidebarWidth):"left"===r.props.position?r.props.open&&r.state.touchStartX<r.state.sidebarWidth?r.state.touchCurrentX>r.state.touchStartX?r.state.sidebarWidth:r.state.sidebarWidth-r.state.touchStartX+r.state.touchCurrentX:Math.min(r.state.touchCurrentX,r.state.sidebarWidth):void 0},r.touchSidebarHeight=function(){if("bottom"===r.props.position)return r.props.open&&window.innerHeight-r.state.touchStartY<r.state.sidebarHeight?r.state.touchCurrentY>r.state.touchStartY?r.state.sidebarHeight+r.state.touchStartY-r.state.touchCurrentY:r.state.sidebarHeight:Math.min(window.innerHeight-r.state.touchCurrentY,r.state.sidebarHeight);if("top"===r.props.position){var e=r.state.touchStartY-r.state.sidebarTop;return r.props.open&&e<r.state.sidebarHeight?r.state.touchCurrentY>r.state.touchStartY?r.state.sidebarHeight:r.state.sidebarHeight-r.state.touchStartY+r.state.touchCurrentY:Math.min(r.state.touchCurrentY-r.state.dragHandleTop,r.state.sidebarHeight)}},r.renderStyle=function(e){var t=e.sidebarStyle,n=e.isTouching,o=e.overlayStyle,i=e.contentStyle;if("right"===r.props.position||"left"===r.props.position){if(t.transform="translateX(0%)",t.WebkitTransform="translateX(0%)",n){var a=r.touchSidebarWidth()/r.state.sidebarWidth;"right"===r.props.position&&(t.transform="translateX("+100*(1-a)+"%)",t.WebkitTransform="translateX("+100*(1-a)+"%)"),"left"===r.props.position&&(t.transform="translateX(-"+100*(1-a)+"%)",t.WebkitTransform="translateX(-"+100*(1-a)+"%)"),o.opacity=a,o.visibility="visible"}i&&(i[r.props.position]=r.state.sidebarWidth+"px")}if("top"===r.props.position||"bottom"===r.props.position){if(t.transform="translateY(0%)",t.WebkitTransform="translateY(0%)",n){var s=r.touchSidebarHeight()/r.state.sidebarHeight;"bottom"===r.props.position&&(t.transform="translateY("+100*(1-s)+"%)",t.WebkitTransform="translateY("+100*(1-s)+"%)"),"top"===r.props.position&&(t.transform="translateY(-"+100*(1-s)+"%)",t.WebkitTransform="translateY(-"+100*(1-s)+"%)"),o.opacity=s,o.visibility="visible"}i&&(i[r.props.position]=r.state.sidebarHeight+"px")}},r.state={sidebarWidth:0,sidebarHeight:0,sidebarTop:0,dragHandleTop:0,touchIdentifier:null,touchStartX:null,touchStartY:null,touchCurrentX:null,touchCurrentY:null,touchSupported:"object"===("undefined"==typeof window?"undefined":(0,c["default"])(window))&&"ontouchstart"in window},r}return(0,v["default"])(t,e),t.prototype.componentDidMount=function(){this.saveSidebarSize()},t.prototype.componentDidUpdate=function(){this.isTouching()||this.saveSidebarSize()},t.prototype.render=function(){var e,t=this,n=this.props,r=n.className,o=n.style,i=n.prefixCls,s=n.position,u=n.transitions,c=n.touch,d=n.enableDragHandle,f=n.sidebar,p=n.children,h=n.docked,m=n.open,v=(0,l["default"])({},this.props.sidebarStyle),y=(0,l["default"])({},this.props.contentStyle),b=(0,l["default"])({},this.props.overlayStyle),_=(e={},(0,a["default"])(e,r,!!r),(0,a["default"])(e,i,!0),(0,a["default"])(e,i+"-"+s,!0),e),x={style:o},C=this.isTouching();C?this.renderStyle({sidebarStyle:v,isTouching:!0,overlayStyle:b}):h?0!==this.state.sidebarWidth&&(_[i+"-docked"]=!0,this.renderStyle({sidebarStyle:v,contentStyle:y})):m&&(_[i+"-open"]=!0,this.renderStyle({sidebarStyle:v}),b.opacity=1,b.visibility="visible"),!C&&u||(v.transition="none",v.WebkitTransition="none",
y.transition="none",b.transition="none");var w=null;return this.state.touchSupported&&c&&(m?(x.onTouchStart=function(e){t.notTouch=!0,t.onTouchStart(e)},x.onTouchMove=this.onTouchMove,x.onTouchEnd=this.onTouchEnd,x.onTouchCancel=this.onTouchEnd,x.onScroll=this.onScroll):d&&(w=g["default"].createElement("div",{className:i+"-draghandle",style:this.props.dragHandleStyle,onTouchStart:this.onTouchStart,onTouchMove:this.onTouchMove,onTouchEnd:this.onTouchEnd,onTouchCancel:this.onTouchEnd,ref:"dragHandle"}))),g["default"].createElement("div",(0,l["default"])({className:(0,T["default"])(_)},x),g["default"].createElement("div",{className:i+"-sidebar",style:v,ref:"sidebar"},f),g["default"].createElement("div",{className:i+"-overlay",style:b,role:"presentation",tabIndex:"0",ref:"overlay",onClick:this.onOverlayClicked}),g["default"].createElement("div",{className:i+"-content",style:y,ref:"content"},w,p))},t}(g["default"].Component);w.propTypes={prefixCls:g["default"].PropTypes.string,className:g["default"].PropTypes.string,children:g["default"].PropTypes.node.isRequired,style:g["default"].PropTypes.object,sidebarStyle:g["default"].PropTypes.object,contentStyle:g["default"].PropTypes.object,overlayStyle:g["default"].PropTypes.object,dragHandleStyle:g["default"].PropTypes.object,sidebar:g["default"].PropTypes.node.isRequired,docked:g["default"].PropTypes.bool,open:g["default"].PropTypes.bool,transitions:g["default"].PropTypes.bool,touch:g["default"].PropTypes.bool,enableDragHandle:g["default"].PropTypes.bool,position:g["default"].PropTypes.oneOf(["left","right","top","bottom"]),dragToggleDistance:g["default"].PropTypes.number,onOpenChange:g["default"].PropTypes.func},w.defaultProps={prefixCls:"rc-drawer",sidebarStyle:{},contentStyle:{},overlayStyle:{},dragHandleStyle:{},docked:!1,open:!1,transitions:!0,touch:!0,enableDragHandle:!0,position:"left",dragToggleDistance:30,onOpenChange:function(){}},t["default"]=w,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(362),i=r(o);t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e){e.preventDefault()}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),s=r(a),l=n(8),u=r(l),c=n(1),d=r(c),f=n(5),p=r(f),h=n(365),m=r(h),v=d["default"].createClass({displayName:"InputNumber",propTypes:{onChange:c.PropTypes.func,onKeyDown:c.PropTypes.func,onFocus:c.PropTypes.func,onBlur:c.PropTypes.func,readOnly:c.PropTypes.bool,max:c.PropTypes.number,min:c.PropTypes.number,step:c.PropTypes.oneOfType([c.PropTypes.number,c.PropTypes.string])},mixins:[m["default"]],getDefaultProps:function(){return{prefixCls:"rc-input-number"}},componentDidMount:function(){this.componentDidUpdate()},componentDidUpdate:function(){this.state.focused&&document.activeElement!==this.refs.input&&this.refs.input.focus()},onKeyDown:function(e){var t;38===e.keyCode?this.up(e):40===e.keyCode&&this.down(e);for(var n=arguments.length,r=Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];(t=this.props).onKeyDown.apply(t,[e].concat(r))},getValueFromEvent:function(e){return e.target.value},focus:function(){this.refs.input.focus()},render:function(){var e,t=(0,u["default"])({},this.props),n=t.prefixCls,r=(0,p["default"])((e={},(0,s["default"])(e,n,!0),(0,s["default"])(e,t.className,!!t.className),(0,s["default"])(e,n+"-disabled",t.disabled),(0,s["default"])(e,n+"-focused",this.state.focused),e)),a="",l="",c=this.state.value;if(isNaN(c))a=n+"-handler-up-disabled",l=n+"-handler-down-disabled";else{var f=Number(c);f>=t.max&&(a=n+"-handler-up-disabled"),f<=t.min&&(l=n+"-handler-down-disabled")}var h=!t.readOnly&&!t.disabled,m=void 0;return m=this.state.focused?this.state.inputValue:this.state.value,void 0===m&&(m=""),delete t.defaultValue,delete t.prefixCls,d["default"].createElement("div",{className:r,style:t.style},d["default"].createElement("div",{className:n+"-handler-wrap"},d["default"].createElement("a",{unselectable:"unselectable",ref:"up",onTouchStart:h&&!a?this.up:o,onTouchEnd:this.stop,onMouseDown:h&&!a?this.up:o,onMouseUp:this.stop,onMouseLeave:this.stop,className:n+"-handler "+n+"-handler-up "+a},d["default"].createElement("span",{unselectable:"unselectable",className:n+"-handler-up-inner",onClick:i})),d["default"].createElement("a",{unselectable:"unselectable",ref:"down",onTouchStart:h&&!l?this.down:o,onTouchEnd:this.stop,onMouseDown:h&&!l?this.down:o,onMouseUp:this.stop,onMouseLeave:this.stop,className:n+"-handler "+n+"-handler-down "+l},d["default"].createElement("span",{unselectable:"unselectable",className:n+"-handler-down-inner",onClick:i}))),d["default"].createElement("div",{className:n+"-input-wrap"},d["default"].createElement("input",(0,u["default"])({},t,{style:null,className:n+"-input",autoComplete:"off",onFocus:this.onFocus,onBlur:this.onBlur,onKeyDown:this.onKeyDown,autoFocus:t.autoFocus,readOnly:t.readOnly,disabled:t.disabled,max:t.max,min:t.min,name:t.name,onChange:this.onChange,ref:"input",value:m}))))}});t["default"]=v,e.exports=t["default"]},function(e,t){"use strict";function n(){}Object.defineProperty(t,"__esModule",{value:!0});var r=50,o=600;t["default"]={getDefaultProps:function(){return{max:1/0,min:-(1/0),step:1,style:{},defaultValue:null,onChange:n,onKeyDown:n,onFocus:n,onBlur:n}},getInitialState:function(){var e=void 0,t=this.props;return e="value"in t?t.value:t.defaultValue,e=this.toPrecisionAsStep(e),{inputValue:e,value:e,focused:t.autoFocus}},componentWillReceiveProps:function(e){if("value"in e){var t=this.toPrecisionAsStep(e.value);this.setState({inputValue:t,value:t})}},componentWillUnmount:function(){this.stop()},onChange:function(e){this.setInputValue(this.getValueFromEvent(e).trim())},onFocus:function(){var e;this.setState({focused:!0}),(e=this.props).onFocus.apply(e,arguments)},onBlur:function(e){var t;this.setState({focused:!1});var n=this.getCurrentValidValue(this.getValueFromEvent(e).trim());this.setValue(n);for(var r=arguments.length,o=Array(r>1?r-1:0),i=1;i<r;i++)o[i-1]=arguments[i];(t=this.props).onBlur.apply(t,[e].concat(o))},getCurrentValidValue:function(e){var t=e,n=this.props;return""===t?t="":isNaN(t)?t=this.state.value:(t=Number(t),t<n.min&&(t=n.min),t>n.max&&(t=n.max)),this.toPrecisionAsStep(t)},setValue:function(e){"value"in this.props||this.setState({value:e,inputValue:e});var t=isNaN(e)||""===e?void 0:e;t!==this.state.value?this.props.onChange(t):this.setState({inputValue:this.state.value})},setInputValue:function(e){this.setState({inputValue:e})},getPrecision:function(){var e=this.props,t=e.step.toString();if(t.indexOf("e-")>=0)return parseInt(t.slice(t.indexOf("e-")+1),10);var n=0;return t.indexOf(".")>=0&&(n=t.length-t.indexOf(".")-1),n},getPrecisionFactor:function(){var e=this.getPrecision();return Math.pow(10,e)},toPrecisionAsStep:function(e){if(isNaN(e)||""===e)return e;var t=this.getPrecision();return Number(Number(e).toFixed(Math.abs(t)))},upStep:function(e){var t=this.props,n=t.step,r=t.min,o=this.getPrecisionFactor(),i=void 0;return i="number"==typeof e?(o*e+o*n)/o:r===-(1/0)?n:r,this.toPrecisionAsStep(i)},downStep:function(e){var t=this.props,n=t.step,r=t.min,o=this.getPrecisionFactor(),i=void 0;return i="number"==typeof e?(o*e-o*n)/o:r===-(1/0)?-n:r,this.toPrecisionAsStep(i)},step:function(e,t){t&&t.preventDefault();var n=this.props;if(!n.disabled){var r=this.getCurrentValidValue(this.state.value);if(this.setState({value:r}),!isNaN(r)){var o=this[e+"Step"](r);o>n.max||o<n.min||(this.setValue(o),this.setState({focused:!0}))}}},stop:function(){this.autoStepTimer&&clearTimeout(this.autoStepTimer)},down:function(e,t){var n=this;e.persist&&e.persist(),this.stop(),this.step("down",e),this.autoStepTimer=setTimeout(function(){n.down(e,!0)},t?r:o)},up:function(e,t){var n=this;e.persist&&e.persist(),this.stop(),this.step("up",e),this.autoStepTimer=setTimeout(function(){n.up(e,!0)},t?r:o)}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),a=r(i),s=n(5),l=r(s),u=a["default"].createClass({displayName:"Notice",propTypes:{duration:i.PropTypes.number,onClose:i.PropTypes.func,children:i.PropTypes.any},getDefaultProps:function(){return{onEnd:function(){},onClose:function(){},duration:1.5,style:{right:"50%"}}},componentDidMount:function(){var e=this;this.props.duration&&(this.closeTimer=setTimeout(function(){e.close()},1e3*this.props.duration))},componentWillUnmount:function(){this.clearCloseTimer()},clearCloseTimer:function(){this.closeTimer&&(clearTimeout(this.closeTimer),this.closeTimer=null)},close:function(){this.clearCloseTimer(),this.props.onClose()},render:function(){var e,t=this.props,n=t.prefixCls+"-notice",r=(e={},o(e,""+n,1),o(e,n+"-closable",t.closable),o(e,t.className,!!t.className),e);return a["default"].createElement("div",{className:(0,l["default"])(r),style:t.style},a["default"].createElement("div",{className:n+"-content"},t.children),t.closable?a["default"].createElement("a",{tabIndex:"0",onClick:this.close,className:n+"-close"},a["default"].createElement("span",{className:n+"-close-x"})):null)}});t["default"]=u,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(){return"rcNotification_"+_+"_"+b++}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(1),l=r(s),u=n(9),c=r(u),d=n(42),f=r(d),p=n(401),h=r(p),m=n(5),v=r(m),y=n(366),g=r(y),b=0,_=Date.now(),x=l["default"].createClass({displayName:"Notification",propTypes:{prefixCls:s.PropTypes.string,transitionName:s.PropTypes.string,animation:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.object]),style:s.PropTypes.object},getDefaultProps:function(){return{prefixCls:"rc-notification",animation:"fade",style:{top:65,left:"50%"}}},getInitialState:function(){return{notices:[]}},getTransitionName:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=e.prefixCls+"-"+e.animation),t},add:function(e){var t=e.key=e.key||i();this.setState(function(n){var r=n.notices;if(!r.filter(function(e){return e.key===t}).length)return{notices:r.concat(e)}})},remove:function(e){this.setState(function(t){return{notices:t.notices.filter(function(t){return t.key!==e})}})},render:function(){var e,t=this,n=this.props,r=this.state.notices.map(function(e){var r=(0,h["default"])(t.remove.bind(t,e.key),e.onClose);return l["default"].createElement(g["default"],a({prefixCls:n.prefixCls},e,{onClose:r}),e.content)}),i=(e={},o(e,n.prefixCls,1),o(e,n.className,!!n.className),e);return l["default"].createElement("div",{className:(0,v["default"])(i),style:n.style},l["default"].createElement(f["default"],{transitionName:this.getTransitionName()},r))}});x.newInstance=function(e){var t=e||{},n=document.createElement("div");document.body.appendChild(n);var r=c["default"].render(l["default"].createElement(x,t),n);return{notice:function(e){r.add(e)},removeNotice:function(e){r.remove(e)},component:r,destroy:function(){c["default"].unmountComponentAtNode(n),document.body.removeChild(n)}}},t["default"]=x,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(367),i=r(o);t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),i=r(o),a=n(4),s=r(a),l=n(3),u=r(l),c=n(1),d=r(c),f=n(113),p=r(f),h=function(e){function t(n){(0,i["default"])(this,t);var r=(0,s["default"])(this,e.call(this,n));return r.state={isTooltipVisible:!1},r}return(0,u["default"])(t,e),t.prototype.showTooltip=function(){this.setState({isTooltipVisible:!0})},t.prototype.hideTooltip=function(){this.setState({isTooltipVisible:!1})},t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.className,r=e.tipTransitionName,o=e.tipFormatter,i=e.vertical,a=e.offset,s=e.value,l=e.dragging,u=e.noTip,c=i?{bottom:a+"%"}:{left:a+"%"},f=d["default"].createElement("div",{className:n,style:c,onMouseUp:this.showTooltip.bind(this),onMouseEnter:this.showTooltip.bind(this),onMouseLeave:this.hideTooltip.bind(this)});if(u)return f;var h=l||this.state.isTooltipVisible;return d["default"].createElement(p["default"],{prefixCls:t.replace("slider","tooltip"),placement:"top",visible:h,overlay:d["default"].createElement("span",null,o(s)),delay:0,transitionName:r},f)},t}(d["default"].Component);t["default"]=h,h.propTypes={prefixCls:d["default"].PropTypes.string,className:d["default"].PropTypes.string,vertical:d["default"].PropTypes.bool,offset:d["default"].PropTypes.number,tipTransitionName:d["default"].PropTypes.string,tipFormatter:d["default"].PropTypes.func,value:d["default"].PropTypes.number,dragging:d["default"].PropTypes.bool,noTip:d["default"].PropTypes.bool},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),i=r(o),a=n(31),s=r(a),l=n(6),u=r(l),c=n(1),d=r(c),f=n(5),p=r(f),h=function(e){var t=e.className,n=e.vertical,r=e.marks,o=e.included,a=e.upperBound,l=e.lowerBound,c=e.max,f=e.min,h=Object.keys(r),m=h.length,v=100/(m-1),y=.9*v,g=c-f,b=h.map(parseFloat).sort(function(e,t){return e-t}).map(function(e){var c,h=!o&&e===a||o&&e<=a&&e>=l,m=(0,p["default"])((c={},(0,u["default"])(c,t+"-text",!0),(0,u["default"])(c,t+"-text-active",h),c)),v={marginBottom:"-200%",bottom:(e-f)/g*100+"%"},b={width:y+"%",marginLeft:-y/2+"%",left:(e-f)/g*100+"%"},_=n?v:b,x=r[e],T="object"===("undefined"==typeof x?"undefined":(0,s["default"])(x))&&!d["default"].isValidElement(x),C=T?x.label:x,w=T?(0,i["default"])({},_,x.style):_;return d["default"].createElement("span",{className:m,style:w,key:e},C)});return d["default"].createElement("div",{className:t},b)};t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e){return e.touches.length>1||"touchend"===e.type.toLowerCase()&&e.touches.length>0}function a(e,t){return e?t.touches[0].clientY:t.touches[0].pageX}function s(e,t){return e?t.clientY:t.pageX}function l(e){e.stopPropagation(),e.preventDefault()}Object.defineProperty(t,"__esModule",{value:!0});var u=n(6),c=r(u),d=n(50),f=r(d),p=n(8),h=r(p),m=n(2),v=r(m),y=n(4),g=r(y),b=n(3),_=r(b),x=n(1),T=r(x),C=n(44),w=r(C),S=n(5),P=r(S),E=n(373),M=r(E),k=n(369),O=r(k),N=n(372),D=r(N),R=n(370),A=r(R),I=function(e){function t(n){(0,v["default"])(this,t);var r=(0,g["default"])(this,e.call(this,n)),o=n.range,i=n.min,a=n.max,s=o?Array.apply(null,Array(o+1)).map(function(){return i}):i,l="defaultValue"in n?n.defaultValue:s,u=void 0!==n.value?n.value:l,c=(o?u:[i,u]).map(function(e){return r.trimAlignValue(e)}),d=void 0;return d=o&&c[0]===c[c.length-1]&&c[0]===a?0:c.length-1,r.state={handle:null,recent:d,bounds:c},r}return(0,_["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){var t=this;if("value"in e||"min"in e||"max"in e){var n=this.state.bounds;if(e.range){var r=e.value||n,o=r.map(function(n){return t.trimAlignValue(n,e)});if(o.every(function(e,t){return e===n[t]}))return;this.setState({bounds:o}),n.some(function(n){return t.isValueOutOfBounds(n,e)})&&this.props.onChange(o)}else{var i=void 0!==e.value?e.value:n[1],a=this.trimAlignValue(i,e);if(a===n[1]&&n[0]===e.min)return;this.setState({bounds:[e.min,a]}),this.isValueOutOfBounds(n[1],e)&&this.props.onChange(a)}}},t.prototype.onChange=function(e){var t=this.props,n=!("value"in t);n?this.setState(e):e.handle&&this.setState({handle:e.handle});var r=(0,h["default"])({},this.state,e),o=t.range?r.bounds:r.bounds[1];t.onChange(o)},t.prototype.onMouseMove=function(e){var t=s(this.props.vertical,e);this.onMove(e,t)},t.prototype.onTouchMove=function(e){if(i(e))return void this.end("touch");var t=a(this.props.vertical,e);this.onMove(e,t)},t.prototype.onMove=function(e,t){l(e);var n=this.props,r=this.state,o=t-this.startPosition;o=this.props.vertical?-o:o;var i=o/this.getSliderLength()*(n.max-n.min),a=this.trimAlignValue(this.startValue+i),s=r[r.handle];if(a!==s){var u=[].concat((0,f["default"])(r.bounds));u[r.handle]=a;var c=r.handle;if(n.pushable!==!1){var d=r.bounds[c];this.pushSurroundingHandles(u,c,d)}else n.allowCross&&(u.sort(function(e,t){return e-t}),c=u.indexOf(a));this.onChange({handle:c,bounds:u})}},t.prototype.onTouchStart=function(e){if(!i(e)){var t=a(this.props.vertical,e);this.onStart(t),this.addDocumentEvents("touch"),l(e)}},t.prototype.onMouseDown=function(e){if(0===e.button){var t=s(this.props.vertical,e);this.onStart(t),this.addDocumentEvents("mouse"),l(e)}},t.prototype.onStart=function(e){var t=this.props;t.onBeforeChange(this.getValue());var n=this.calcValueByPos(e);this.startValue=n,this.startPosition=e;var r=this.state,o=r.bounds,i=1;if(this.props.range){for(var a=0,s=1;s<o.length-1;++s)n>o[s]&&(a=s);Math.abs(o[a+1]-n)<Math.abs(o[a]-n)&&(a+=1),i=a;var l=o[a+1]===o[a];l&&(i=r.recent),l&&n!==o[a+1]&&(i=n<o[a+1]?a:a+1)}this.setState({handle:i,recent:i});var u=r.bounds[i];if(n!==u){var c=[].concat((0,f["default"])(r.bounds));c[i]=n,this.onChange({bounds:c})}},t.prototype.getValue=function(){var e=this.state.bounds;return this.props.range?e:e[1]},t.prototype.getSliderLength=function(){var e=this.refs.slider;return e?this.props.vertical?e.clientHeight:e.clientWidth:0},t.prototype.getSliderStart=function(){var e=this.refs.slider,t=e.getBoundingClientRect();return this.props.vertical?t.top:t.left},t.prototype.getPrecision=function(e){var t=e.toString(),n=0;return t.indexOf(".")>=0&&(n=t.length-t.indexOf(".")-1),n},t.prototype.getPoints=function(){var e=this.props,t=e.marks,n=e.step,r=e.min,o=e.max,i=this._getPointsCache;if(!i||i.marks!==t||i.step!==n){var a=(0,h["default"])({},t);if(null!==n)for(var s=r;s<=o;s+=n)a[s]=s;var l=Object.keys(a).map(parseFloat);l.sort(function(e,t){return e-t}),this._getPointsCache={marks:t,step:n,points:l}}return this._getPointsCache.points},t.prototype.isValueOutOfBounds=function(e,t){return e<t.min||e>t.max},t.prototype.trimAlignValue=function(e,t){var n=this.state||{},r=n.handle,o=n.bounds,i=(0,h["default"])({},this.props,t||{}),a=i.marks,s=i.step,l=i.min,u=i.max,c=i.allowCross,d=e;d<=l&&(d=l),d>=u&&(d=u),!c&&null!=r&&r>0&&d<=o[r-1]&&(d=o[r-1]),!c&&null!=r&&r<o.length-1&&d>=o[r+1]&&(d=o[r+1]);var f=Object.keys(a).map(parseFloat);if(null!==s){var p=Math.round((d-l)/s)*s+l;f.push(p)}var m=f.map(function(e){return Math.abs(d-e)}),v=f[m.indexOf(Math.min.apply(Math,m))];return null!==s?parseFloat(v.toFixed(this.getPrecision(s))):v},t.prototype.pushHandleOnePoint=function(e,t,n){var r=this.getPoints(),o=r.indexOf(e[t]),i=o+n;if(i>=r.length||i<0)return!1;var a=t+n,s=r[i],l=this.props.pushable,u=n*(e[a]-s);return!!this.pushHandle(e,a,n,l-u)&&(e[t]=s,!0)},t.prototype.pushHandle=function(e,t,n,r){for(var o=e[t],i=e[t];n*(i-o)<r;){if(!this.pushHandleOnePoint(e,t,n))return e[t]=o,!1;i=e[t]}return!0},t.prototype.pushSurroundingHandles=function(e,t,n){var r=this.props.pushable,o=e[t],i=0;if(e[t+1]-o<r?i=1:o-e[t-1]<r&&(i=-1),0!==i){var a=t+i,s=i*(e[a]-o);this.pushHandle(e,a,i,r-s)||(e[t]=n)}},t.prototype.calcOffset=function(e){var t=this.props,n=t.min,r=t.max,o=(e-n)/(r-n);return 100*o},t.prototype.calcValue=function(e){var t=this.props,n=t.vertical,r=t.min,o=t.max,i=Math.abs(e/this.getSliderLength()),a=n?(1-i)*(o-r)+r:i*(o-r)+r;return a},t.prototype.calcValueByPos=function(e){var t=e-this.getSliderStart(),n=this.trimAlignValue(this.calcValue(t));return n},t.prototype.addDocumentEvents=function(e){"touch"===e?(this.onTouchMoveListener=(0,w["default"])(document,"touchmove",this.onTouchMove.bind(this)),this.onTouchUpListener=(0,w["default"])(document,"touchend",this.end.bind(this,"touch"))):"mouse"===e&&(this.onMouseMoveListener=(0,w["default"])(document,"mousemove",this.onMouseMove.bind(this)),this.onMouseUpListener=(0,w["default"])(document,"mouseup",this.end.bind(this,"mouse")))},t.prototype.removeEvents=function(e){"touch"===e?(this.onTouchMoveListener.remove(),this.onTouchUpListener.remove()):"mouse"===e&&(this.onMouseMoveListener.remove(),this.onMouseUpListener.remove())},t.prototype.end=function(e){this.removeEvents(e),this.props.onAfterChange(this.getValue()),this.setState({handle:null})},t.prototype.render=function(){var e,t=this,n=this.state,r=n.handle,i=n.bounds,a=this.props,s=a.className,l=a.prefixCls,u=a.disabled,d=a.vertical,f=a.dots,p=a.included,m=a.range,v=a.step,y=a.marks,g=a.max,b=a.min,_=a.tipTransitionName,C=a.tipFormatter,w=a.children,S=this.props.handle,E=i.map(function(e){return t.calcOffset(e)}),k=l+"-handle",O=i.map(function(e,t){var n;return(0,P["default"])((n={},(0,c["default"])(n,k,!0),(0,c["default"])(n,k+"-"+(t+1),!0),(0,c["default"])(n,k+"-lower",0===t),(0,c["default"])(n,k+"-upper",t===i.length-1),n))}),N=null===v||null===C,R={prefixCls:l,noTip:N,tipTransitionName:_,tipFormatter:C,vertical:d},I=i.map(function(e,t){return(0,x.cloneElement)(S,(0,h["default"])({},R,{className:O[t],value:e,offset:E[t],dragging:r===t,key:t}))});m||I.shift();for(var j=p||m,L=[],W=1;W<i.length;++W){var H,Y=(0,P["default"])((H={},(0,c["default"])(H,l+"-track",!0),(0,c["default"])(H,l+"-track-"+W,!0),H));L.push(T["default"].createElement(M["default"],{className:Y,vertical:d,included:j,offset:E[W-1],length:E[W]-E[W-1],key:W}))}var F=(0,P["default"])((e={},(0,c["default"])(e,l,!0),(0,c["default"])(e,l+"-disabled",u),(0,c["default"])(e,s,!!s),(0,c["default"])(e,l+"-vertical",this.props.vertical),e));return T["default"].createElement("div",{ref:"slider",className:F,onTouchStart:u?o:this.onTouchStart.bind(this),onMouseDown:u?o:this.onMouseDown.bind(this)},L,T["default"].createElement(D["default"],{prefixCls:l,vertical:d,marks:y,dots:f,step:v,included:j,lowerBound:i[0],upperBound:i[i.length-1],max:g,min:b}),I,T["default"].createElement(A["default"],{className:l+"-mark",vertical:d,marks:y,included:j,lowerBound:i[0],upperBound:i[i.length-1],max:g,min:b}),w)},t}(T["default"].Component);I.propTypes={min:T["default"].PropTypes.number,max:T["default"].PropTypes.number,step:T["default"].PropTypes.number,defaultValue:T["default"].PropTypes.oneOfType([T["default"].PropTypes.number,T["default"].PropTypes.arrayOf(T["default"].PropTypes.number)]),value:T["default"].PropTypes.oneOfType([T["default"].PropTypes.number,T["default"].PropTypes.arrayOf(T["default"].PropTypes.number)]),marks:T["default"].PropTypes.object,included:T["default"].PropTypes.bool,className:T["default"].PropTypes.string,prefixCls:T["default"].PropTypes.string,disabled:T["default"].PropTypes.bool,children:T["default"].PropTypes.any,onBeforeChange:T["default"].PropTypes.func,onChange:T["default"].PropTypes.func,onAfterChange:T["default"].PropTypes.func,handle:T["default"].PropTypes.element,tipTransitionName:T["default"].PropTypes.string,tipFormatter:T["default"].PropTypes.func,dots:T["default"].PropTypes.bool,range:T["default"].PropTypes.oneOfType([T["default"].PropTypes.bool,T["default"].PropTypes.number]),vertical:T["default"].PropTypes.bool,allowCross:T["default"].PropTypes.bool,pushable:T["default"].PropTypes.oneOfType([T["default"].PropTypes.bool,T["default"].PropTypes.number])},I.defaultProps={prefixCls:"rc-slider",className:"",tipTransitionName:"",min:0,max:100,step:1,marks:{},handle:T["default"].createElement(O["default"],null),onBeforeChange:o,onChange:o,onAfterChange:o,tipFormatter:function(e){return e},included:!0,disabled:!1,dots:!1,range:!1,vertical:!1,allowCross:!0,pushable:!1},t["default"]=I,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o,i){(0,f["default"])(!n||r>0,"`Slider[step]` should be a positive number in order to make Slider[dots] work.");var a=Object.keys(t).map(parseFloat);if(n)for(var s=o;s<=i;s+=r)a.indexOf(s)>=0||a.push(s);return a}Object.defineProperty(t,"__esModule",{value:!0});var i=n(6),a=r(i),s=n(1),l=r(s),u=n(5),c=r(u),d=n(437),f=r(d),p=function(e){var t=e.prefixCls,n=e.vertical,r=e.marks,i=e.dots,s=e.step,u=e.included,d=e.lowerBound,f=e.upperBound,p=e.max,h=e.min,m=p-h,v=o(n,r,i,s,h,p).map(function(e){var r,o=Math.abs(e-h)/m*100+"%",i=n?{bottom:o}:{left:o},s=!u&&e===f||u&&e<=f&&e>=d,p=(0,c["default"])((r={},(0,a["default"])(r,t+"-dot",!0),(0,a["default"])(r,t+"-dot-active",s),r));return l["default"].createElement("span",{className:p,style:i,key:e})});return l["default"].createElement("div",{className:t+"-step"},v)};t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=function(e){var t=e.className,n=e.included,r=e.vertical,o=e.offset,a=e.length,s={visibility:n?"visible":"hidden"};return r?(s.bottom=o+"%",s.height=a+"%"):(s.left=o+"%",s.width=a+"%"),i["default"].createElement("div",{className:t,style:s})};t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(371)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e){var t,n,r=e.className,a=e.prefixCls,l=e.style,c=e.tailWidth,f=e.status,p=void 0===f?"wait":f,h=e.iconPrefix,m=e.icon,v=e.wrapperStyle,y=e.adjustMarginRight,g=e.stepLast,b=e.stepNumber,_=e.description,x=e.title,T=i(e,["className","prefixCls","style","tailWidth","status","iconPrefix","icon","wrapperStyle","adjustMarginRight","stepLast","stepNumber","description","title"]),C=(0,d["default"])((t={},o(t,a+"-icon",!0),o(t,h+"icon",!0),o(t,h+"icon-"+m,m),o(t,h+"icon-check",!m&&"finish"===p),o(t,h+"icon-cross",!m&&"error"===p),t)),w=m||"finish"===p||"error"===p?u["default"].createElement("span",{className:C}):u["default"].createElement("span",{className:a+"-icon"},b),S=(0,d["default"])((n={},o(n,a+"-item",!0),o(n,a+"-item-last",g),o(n,a+"-status-"+p,!0),o(n,a+"-custom",m),o(n,r,!!r),n));return u["default"].createElement("div",s({},T,{className:S,style:s({width:c,marginRight:y},l)}),g?"":u["default"].createElement("div",{className:a+"-tail"},u["default"].createElement("i",null)),u["default"].createElement("div",{className:a+"-step"},u["default"].createElement("div",{className:a+"-head",style:{background:v.background||v.backgroundColor}},u["default"].createElement("div",{className:a+"-head-inner"},w)),u["default"].createElement("div",{className:a+"-main"},u["default"].createElement("div",{className:a+"-title",style:{background:v.background||v.backgroundColor}},x),_?u["default"].createElement("div",{className:a+"-description"},_):"")))}var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(1),u=r(l),c=n(5),d=r(c);a.propTypes={className:l.PropTypes.string,prefixCls:l.PropTypes.string,style:l.PropTypes.object,wrapperStyle:l.PropTypes.object,tailWidth:l.PropTypes.oneOfType([l.PropTypes.number,l.PropTypes.string]),status:l.PropTypes.string,iconPrefix:l.PropTypes.string,icon:l.PropTypes.string,adjustMarginRight:l.PropTypes.oneOfType([l.PropTypes.number,l.PropTypes.string]),stepLast:l.PropTypes.bool,stepNumber:l.PropTypes.string,description:l.PropTypes.any,title:l.PropTypes.any},e.exports=a},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],i=Object.getOwnPropertyDescriptor(t,o);i&&i.configurable&&void 0===e[o]&&Object.defineProperty(e,o,i)}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),f=r(d),p=n(9),h=r(p),m=n(5),v=r(m),y=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n));return r.culcLastStepOffsetWidth=function(){var e=h["default"].findDOMNode(r);e.children.length>0&&(r.culcTimeout=setTimeout(function(){var t=e.lastChild.offsetWidth+1;r.state.lastStepOffsetWidth!==t&&r.setState({lastStepOffsetWidth:t})}))},r.state={lastStepOffsetWidth:0},r}return u(t,e),t.prototype.componentDidMount=function(){this.culcLastStepOffsetWidth()},t.prototype.componentDidUpdate=function(){this.culcLastStepOffsetWidth()},t.prototype.componentWillUnmount=function(){this.culcTimeout&&clearTimeout(this.culcTimeout)},t.prototype.render=function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.style,s=void 0===o?{}:o,l=n.className,u=n.children,d=n.direction,p=n.labelPlacement,h=n.iconPrefix,m=n.status,y=n.size,g=n.current,b=a(n,["prefixCls","style","className","children","direction","labelPlacement","iconPrefix","status","size","current"]),_=u.length-1,x=this.state.lastStepOffsetWidth>0,T=(0,v["default"])((e={},i(e,r,!0),i(e,r+"-"+y,y),i(e,r+"-"+d,!0),i(e,r+"-label-"+p,"horizontal"===d),i(e,r+"-hidden",!x),i(e,l,l),e));return f["default"].createElement("div",c({className:T,style:s},b),f["default"].Children.map(u,function(e,o){var i="vertical"!==d&&o!==_&&x?100/_+"%":null,a="vertical"===d||o===_?null:-(t.state.lastStepOffsetWidth/_+1),l={stepNumber:(o+1).toString(),stepLast:o===_,tailWidth:i,adjustMarginRight:a,prefixCls:r,iconPrefix:h,wrapperStyle:s};return"error"===m&&o===g-1&&(l.className=n.prefixCls+"-next-error"),e.props.status||(o===g?l.status=m:o<g?l.status="finish":l.status="wait"),f["default"].cloneElement(e,l)},this))},t}(f["default"].Component);t["default"]=y,y.propTypes={prefixCls:d.PropTypes.string,iconPrefix:d.PropTypes.string,direction:d.PropTypes.string,labelPlacement:d.PropTypes.string,children:d.PropTypes.any,status:d.PropTypes.string,size:d.PropTypes.string},y.defaultProps={prefixCls:"rc-steps",iconPrefix:"rc",direction:"horizontal",labelPlacement:"horizontal",current:0,status:"process",size:""},e.exports=t["default"]},function(e,t,n){"use strict";var r=n(376);r.Step=n(375),e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),i=r(o),a=n(17),s=r(a),l=n(2),u=r(l),c=n(4),d=r(c),f=n(3),p=r(f),h=n(1),m=r(h),v=n(69),y=r(v),g=n(347),b=r(g),_=n(380),x=r(_),T=function(e){function t(n){(0,u["default"])(this,t);var r=(0,d["default"])(this,e.call(this,n));return r.onPanStart=r.onPanStart.bind(r),r.onPan=r.onPan.bind(r),r.onPanEnd=r.onPanEnd.bind(r),r.onTap=r.onTap.bind(r),r.openedLeft=!1,r.openedRight=!1,r}return(0,p["default"])(t,e),t.prototype.componentDidMount=function(){var e=this.props,t=e.left,n=e.right,r=this.refs.content.offsetWidth;
this.contentWidth=r,this.btnsLeftWidth=t?r/5*t.length:0,this.btnsRightWidth=n?r/5*n.length:0},t.prototype.onPanStart=function(e){this.props.disabled||(this.panStartX=e.deltaX)},t.prototype.onPan=function(e){if(!this.props.disabled){var t=e.deltaX-this.panStartX;this.openedRight?t-=this.btnsRightWidth:this.openedLeft&&(t+=this.btnsLeftWidth),t<0&&this.props.right?this._setStyle(Math.min(t,0)):t>0&&this.props.left&&this._setStyle(Math.max(t,0))}},t.prototype.onPanEnd=function(e){if(!this.props.disabled){var t=e.deltaX-this.panStartX,n=this.contentWidth,r=this.btnsLeftWidth,o=this.btnsRightWidth,i=.33*n,a=t>i||t>r/2,s=t<-i||t<-o/2;this.openedRight&&(s=t-i<-i),this.openedLeft&&(a=t+i>i),s&&t<0?this.open(-o,!1,!0):a&&t>0?this.open(r,!0,!1):this.close()}},t.prototype.onTap=function(e){(this.openedLeft||this.openedRight)&&(e.preventDefault(),this.close())},t.prototype.onBtnClick=function(e){var t=e.onPress;t&&t(),this.props.autoClose&&this.close()},t.prototype._getContentEasing=function(e,t){return e<0&&e<t?t-Math.pow(t-e,.85):e>0&&e>t?t+Math.pow(e-t,.85):e},t.prototype._setStyle=function(e){var t=this.props,n=t.left,r=t.right,o=e>0?this.btnsLeftWidth:-this.btnsRightWidth,i=this._getContentEasing(e,o);if(this.refs.content.style.left=i+"px",n.length){var a=Math.max(Math.min(e,Math.abs(o)),0);this.refs.left.style.width=a+"px"}if(r.length){var s=Math.max(Math.min(-e,Math.abs(o)),0);this.refs.right.style.width=s+"px"}},t.prototype.open=function(e,t,n){this.openedLeft||this.openedRight||this.props.onOpen(),this.openedLeft=t,this.openedRight=n,this._setStyle(e)},t.prototype.close=function(){(this.openedLeft||this.openedRight)&&this.props.onClose(),this.openedLeft=!1,this.openedRight=!1,this._setStyle(0)},t.prototype.renderButtons=function(e,t){var n=this,r=this.props.prefixCls;return e&&e.length?m["default"].createElement("div",{className:r+"-actions "+r+"-actions-"+t,ref:t},e.map(function(e,t){return m["default"].createElement("div",{key:t,className:r+"-btn",style:e.style,onClick:function(){return n.onBtnClick(e)}},m["default"].createElement("div",{className:r+"-text"},e.text||"Click"))})):null},t.prototype.render=function(){var e=(0,x["default"])(this.props,["prefixCls","left","right","children"]),t=(0,s["default"])(e,2),n=t[0],r=n.prefixCls,o=n.left,a=n.right,l=n.children,u=t[1],c=(0,b["default"])(u,["disabled","autoClose","onOpen","onClose"]),d="DIRECTION_HORIZONTAL";return o.length&&0===a.length&&(d="DIRECTION_RIGHT"),a.length&&0===o.length&&(d="DIRECTION_LEFT"),o.length||a.length?m["default"].createElement("div",(0,i["default"])({className:""+r},c),m["default"].createElement(y["default"],{direction:d,onPanStart:this.onPanStart,onPan:this.onPan,onPanEnd:this.onPanEnd,onTap:this.onTap},m["default"].createElement("div",{className:r+"-content",ref:"content"},l)),this.renderButtons(o,"left"),this.renderButtons(a,"right")):m["default"].createElement("div",(0,i["default"])({ref:"content"},c),l)},t}(m["default"].Component);T.propTypes={prefixCls:h.PropTypes.string,autoClose:h.PropTypes.bool,disabled:h.PropTypes.bool,left:h.PropTypes.arrayOf(h.PropTypes.object),right:h.PropTypes.arrayOf(h.PropTypes.object),onOpen:h.PropTypes.func,onClose:h.PropTypes.func,children:h.PropTypes.any},T.defaultProps={prefixCls:"rc-swipeout",autoClose:!1,disabled:!1,left:[],right:[],onOpen:function(){},onClose:function(){}},t["default"]=T,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(378);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r(o)["default"]}}),e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={},r={};return(0,a["default"])(e).forEach(function(o){t.indexOf(o)!==-1?n[o]=e[o]:r[o]=e[o]}),[n,r]}Object.defineProperty(t,"__esModule",{value:!0});var i=n(221),a=r(i);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),s=r(a),l=n(383),u=r(l),c=n(385),d=n(45),f=r(d),p=n(44),h=r(p),m=s["default"].createClass({displayName:"Table",propTypes:{data:a.PropTypes.array,expandIconAsCell:a.PropTypes.bool,defaultExpandAllRows:a.PropTypes.bool,expandedRowKeys:a.PropTypes.array,defaultExpandedRowKeys:a.PropTypes.array,useFixedHeader:a.PropTypes.bool,columns:a.PropTypes.array,prefixCls:a.PropTypes.string,bodyStyle:a.PropTypes.object,style:a.PropTypes.object,rowKey:a.PropTypes.oneOfType([a.PropTypes.string,a.PropTypes.func]),rowClassName:a.PropTypes.func,expandedRowClassName:a.PropTypes.func,childrenColumnName:a.PropTypes.string,onExpand:a.PropTypes.func,onExpandedRowsChange:a.PropTypes.func,indentSize:a.PropTypes.number,onRowClick:a.PropTypes.func,columnsPageRange:a.PropTypes.array,columnsPageSize:a.PropTypes.number,expandIconColumnIndex:a.PropTypes.number,showHeader:a.PropTypes.bool,title:a.PropTypes.func,footer:a.PropTypes.func,emptyText:a.PropTypes.func,scroll:a.PropTypes.object,rowRef:a.PropTypes.func,getBodyWrapper:a.PropTypes.func},getDefaultProps:function(){return{data:[],useFixedHeader:!1,expandIconAsCell:!1,columns:[],defaultExpandAllRows:!1,defaultExpandedRowKeys:[],rowKey:"key",rowClassName:function(){return""},expandedRowClassName:function(){return""},onExpand:function(){},onExpandedRowsChange:function(){},prefixCls:"rc-table",bodyStyle:{},style:{},childrenColumnName:"children",indentSize:15,columnsPageSize:5,expandIconColumnIndex:0,showHeader:!0,scroll:{},rowRef:function(){return null},getBodyWrapper:function(e){return e},emptyText:function(){return"No Data"}}},getInitialState:function(){var e=this.props,t=[],n=[].concat(o(e.data));if(e.defaultExpandAllRows)for(var r=0;r<n.length;r++){var i=n[r];t.push(this.getRowKey(i)),n=n.concat(i[e.childrenColumnName]||[])}else t=e.expandedRowKeys||e.defaultExpandedRowKeys;return{expandedRowKeys:t,data:e.data,currentColumnsPage:0,currentHoverKey:null,scrollPosition:"left",fixedColumnsHeadRowsHeight:[],fixedColumnsBodyRowsHeight:[]}},componentDidMount:function(){this.resetScrollY();var e=this.isAnyColumnsFixed();e&&(this.syncFixedTableRowHeight(),this.resizeEvent=(0,h["default"])(window,"resize",(0,c.debounce)(this.syncFixedTableRowHeight,150)))},componentWillReceiveProps:function(e){"data"in e&&(this.setState({data:e.data}),e.data&&0!==e.data.length||this.resetScrollY()),"expandedRowKeys"in e&&this.setState({expandedRowKeys:e.expandedRowKeys}),e.columns!==this.props.columns&&(delete this.isAnyColumnsFixedCache,delete this.isAnyColumnsLeftFixedCache,delete this.isAnyColumnsRightFixedCache)},componentDidUpdate:function(){this.syncFixedTableRowHeight()},componentWillUnmount:function(){clearTimeout(this.timer),this.resizeEvent&&this.resizeEvent.remove()},onExpandedRowsChange:function(e){this.props.expandedRowKeys||this.setState({expandedRowKeys:e}),this.props.onExpandedRowsChange(e)},onExpanded:function(e,t,n){n&&(n.preventDefault(),n.stopPropagation());var r=this.findExpandedRow(t);if("undefined"==typeof r||e){if(!r&&e){var o=this.getExpandedRows().concat();o.push(this.getRowKey(t)),this.onExpandedRowsChange(o)}}else this.onRowDestroy(t);this.props.onExpand(e,t)},onRowDestroy:function(e){var t=this.getExpandedRows().concat(),n=this.getRowKey(e),r=-1;t.forEach(function(e,t){e===n&&(r=t)}),r!==-1&&t.splice(r,1),this.onExpandedRowsChange(t)},getRowKey:function(e,t){var n=this.props.rowKey;return"function"==typeof n?n(e,t):"undefined"!=typeof e[n]?e[n]:t},getExpandedRows:function(){return this.props.expandedRowKeys||this.state.expandedRowKeys},getHeader:function(e,t){var n=this.props,r=n.showHeader,o=n.expandIconAsCell,i=n.prefixCls,a=[];o&&"right"!==t&&a.push({key:"rc-table-expandIconAsCell",className:i+"-expand-icon-th",title:""}),a=a.concat(e||this.getCurrentColumns()).map(function(e){if(0!==e.colSpan)return s["default"].createElement("th",{key:e.key,colSpan:e.colSpan,className:e.className||""},e.title)});var l=this.state.fixedColumnsHeadRowsHeight,u=l[0]&&e?{height:l[0]}:null;return r?s["default"].createElement("thead",{className:i+"-thead"},s["default"].createElement("tr",{style:u},a)):null},getExpandedRow:function(e,t,n,r,o){var i=this.props.prefixCls;return s["default"].createElement("tr",{key:e+"-extra-row",style:{display:n?"":"none"},className:i+"-expanded-row "+r},this.props.expandIconAsCell&&"right"!==o?s["default"].createElement("td",{key:"rc-table-expand-icon-placeholder"}):null,s["default"].createElement("td",{colSpan:this.props.columns.length},"right"!==o?t:" "))},getRowsByData:function(e,t,n,r,o){for(var a=this.props,l=a.childrenColumnName,c=a.expandedRowRender,d=a.expandRowByClick,f=this.state.fixedColumnsBodyRowsHeight,p=[],h=a.rowClassName,m=a.rowRef,v=a.expandedRowClassName,y=a.data.some(function(e){return e[l]}),g=a.onRowClick,b=this.isAnyColumnsFixed(),_="right"!==o&&a.expandIconAsCell,x="right"!==o?a.expandIconColumnIndex:-1,T=0;T<e.length;T++){var C=e[T],w=this.getRowKey(C,T),S=C[l],P=this.isRowExpanded(C),E=void 0;c&&P&&(E=c(C,T,n));var M=h(C,T,n);this.state.currentHoverKey===w&&(M+=" "+a.prefixCls+"-row-hover");var k={};b&&(k.onHover=this.handleRowHover);var O=o&&f[T]?{height:f[T]}:{};p.push(s["default"].createElement(u["default"],i({indent:n,indentSize:a.indentSize,needIndentSpaced:y,className:M,record:C,expandIconAsCell:_,onDestroy:this.onRowDestroy,index:T,visible:t,expandRowByClick:d,onExpand:this.onExpanded,expandable:S||c,expanded:P,prefixCls:a.prefixCls+"-row",childrenColumnName:l,columns:r||this.getCurrentColumns(),expandIconColumnIndex:x,onRowClick:g,style:O},k,{key:w,hoverKey:w,ref:m(C,T,n)})));var N=t&&P;E&&P&&p.push(this.getExpandedRow(w,E,N,v(C,T,n),o)),S&&(p=p.concat(this.getRowsByData(S,N,n+1,r,o)))}return p},getRows:function(e,t){return this.getRowsByData(this.state.data,!0,0,e,t)},getColGroup:function(e,t){var n=[];return this.props.expandIconAsCell&&"right"!==t&&n.push(s["default"].createElement("col",{className:this.props.prefixCls+"-expand-icon-col",key:"rc-table-expand-icon-col"})),n=n.concat((e||this.props.columns).map(function(e){return s["default"].createElement("col",{key:e.key,style:{width:e.width,minWidth:e.width}})})),s["default"].createElement("colgroup",null,n)},getCurrentColumns:function(){var e=this,t=this.props,n=t.columns,r=t.columnsPageRange,o=t.columnsPageSize,a=t.prefixCls,s=this.state.currentColumnsPage;return!r||r[0]>r[1]?n:n.map(function(t,n){var l=i({},t);if(n>=r[0]&&n<=r[1]){var u=r[0]+s*o,c=r[0]+(s+1)*o-1;c>r[1]&&(c=r[1]),(n<u||n>c)&&(l.className=l.className||"",l.className+=" "+a+"-column-hidden"),l=e.wrapPageColumn(l,n===u,n===c)}return l})},getLeftFixedTable:function(){var e=this.props.columns,t=e.filter(function(e){return"left"===e.fixed||e.fixed===!0});return this.getTable({columns:t,fixed:"left"})},getRightFixedTable:function(){var e=this.props.columns,t=e.filter(function(e){return"right"===e.fixed});return this.getTable({columns:t,fixed:"right"})},getTable:function(){var e=this,t=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=t.columns,r=t.fixed,o=this.props,a=o.prefixCls,l=o.scroll,u=void 0===l?{}:l,d=o.getBodyWrapper,f=this.props.useFixedHeader,p=i({},this.props.bodyStyle),h={},m="";if((u.x||n)&&(m=a+"-fixed",p.overflowX=p.overflowX||"auto"),u.y){r?p.height=p.height||u.y:p.maxHeight=p.maxHeight||u.y,p.overflowY=p.overflowY||"scroll",f=!0;var v=(0,c.measureScrollbar)();v>0&&((r?p:h).marginBottom="-"+v+"px",(r?p:h).paddingBottom="0px")}var y=function(){var t=arguments.length<=0||void 0===arguments[0]||arguments[0],o=arguments.length<=1||void 0===arguments[1]||arguments[1],i={};!n&&u.x&&(u.x===!0?i.tableLayout="fixed":i.width=u.x);var l=o?d(s["default"].createElement("tbody",{className:a+"-tbody"},e.getRows(n,r))):null;return s["default"].createElement("table",{className:m,style:i},e.getColGroup(n,r),t?e.getHeader(n,r):null,l)},g=void 0;f&&(g=s["default"].createElement("div",{className:a+"-header",ref:n?null:"headTable",style:h,onMouseOver:this.detectScrollTarget,onTouchStart:this.detectScrollTarget,onScroll:this.handleBodyScroll},y(!0,!1)));var b=s["default"].createElement("div",{className:a+"-body",style:p,ref:"bodyTable",onMouseOver:this.detectScrollTarget,onTouchStart:this.detectScrollTarget,onScroll:this.handleBodyScroll},y(!f));if(n&&n.length){var _=void 0;"left"===n[0].fixed||n[0].fixed===!0?_="fixedColumnsBodyLeft":"right"===n[0].fixed&&(_="fixedColumnsBodyRight"),delete p.overflowX,delete p.overflowY,b=s["default"].createElement("div",{className:a+"-body-outer",style:i({},p)},s["default"].createElement("div",{className:a+"-body-inner",ref:_,onMouseOver:this.detectScrollTarget,onTouchStart:this.detectScrollTarget,onScroll:this.handleBodyScroll},y(!f)))}return s["default"].createElement("span",null,g,b)},getTitle:function(){var e=this.props,t=e.title,n=e.prefixCls;return t?s["default"].createElement("div",{className:n+"-title"},t(this.state.data)):null},getFooter:function(){var e=this.props,t=e.footer,n=e.prefixCls;return t?s["default"].createElement("div",{className:n+"-footer"},t(this.state.data)):null},getEmptyText:function(){var e=this.props,t=e.emptyText,n=e.prefixCls,r=e.data;return r.length?null:s["default"].createElement("div",{className:n+"-placeholder"},t())},getMaxColumnsPage:function(){var e=this.props,t=e.columnsPageRange,n=e.columnsPageSize;return Math.ceil((t[1]-t[0]+1)/n)-1},goToColumnsPage:function(e){var t=this.getMaxColumnsPage(),n=e;n<0&&(n=0),n>t&&(n=t),this.setState({currentColumnsPage:n})},syncFixedTableRowHeight:function(){var e=this,t=this.props.prefixCls,n=this.refs.headTable?this.refs.headTable.querySelectorAll("tr"):[],r=this.refs.bodyTable.querySelectorAll("."+t+"-row")||[],o=[].map.call(n,function(e){return e.getBoundingClientRect().height||"auto"}),i=[].map.call(r,function(e){return e.getBoundingClientRect().height||"auto"});(0,f["default"])(this.state.fixedColumnsHeadRowsHeight,o)&&(0,f["default"])(this.state.fixedColumnsBodyRowsHeight,i)||(this.timer=setTimeout(function(){e.setState({fixedColumnsHeadRowsHeight:o,fixedColumnsBodyRowsHeight:i})}))},resetScrollY:function(){this.refs.headTable&&(this.refs.headTable.scrollLeft=0),this.refs.bodyTable&&(this.refs.bodyTable.scrollLeft=0)},prevColumnsPage:function(){this.goToColumnsPage(this.state.currentColumnsPage-1)},nextColumnsPage:function(){this.goToColumnsPage(this.state.currentColumnsPage+1)},wrapPageColumn:function(e,t,n){var r=this.props.prefixCls,o=this.state.currentColumnsPage,i=this.getMaxColumnsPage(),a=r+"-prev-columns-page";0===o&&(a+=" "+r+"-prev-columns-page-disabled");var l=s["default"].createElement("span",{className:a,onClick:this.prevColumnsPage}),u=r+"-next-columns-page";o===i&&(u+=" "+r+"-next-columns-page-disabled");var c=s["default"].createElement("span",{className:u,onClick:this.nextColumnsPage});return t&&(e.title=s["default"].createElement("span",null,l,e.title),e.className=(e.className||"")+" "+r+"-column-has-prev"),n&&(e.title=s["default"].createElement("span",null,e.title,c),e.className=(e.className||"")+" "+r+"-column-has-next"),e},findExpandedRow:function(e){var t=this,n=this.getExpandedRows().filter(function(n){return n===t.getRowKey(e)});return n[0]},isRowExpanded:function(e){return"undefined"!=typeof this.findExpandedRow(e)},detectScrollTarget:function(e){this.scrollTarget!==e.currentTarget&&(this.scrollTarget=e.currentTarget)},isAnyColumnsFixed:function(){return"isAnyColumnsFixedCache"in this?this.isAnyColumnsFixedCache:(this.isAnyColumnsFixedCache=this.getCurrentColumns().some(function(e){return!!e.fixed}),this.isAnyColumnsFixedCache)},isAnyColumnsLeftFixed:function(){return"isAnyColumnsLeftFixedCache"in this?this.isAnyColumnsLeftFixedCache:(this.isAnyColumnsLeftFixedCache=this.getCurrentColumns().some(function(e){return"left"===e.fixed||e.fixed===!0}),this.isAnyColumnsLeftFixedCache)},isAnyColumnsRightFixed:function(){return"isAnyColumnsRightFixedCache"in this?this.isAnyColumnsRightFixedCache:(this.isAnyColumnsRightFixedCache=this.getCurrentColumns().some(function(e){return"right"===e.fixed}),this.isAnyColumnsRightFixedCache)},handleBodyScroll:function(e){if(e.target===this.scrollTarget){var t=this.props.scroll,n=void 0===t?{}:t,r=this.refs,o=r.headTable,i=r.bodyTable,a=r.fixedColumnsBodyLeft,s=r.fixedColumnsBodyRight;n.x&&(e.target===i&&o?o.scrollLeft=e.target.scrollLeft:e.target===o&&i&&(i.scrollLeft=e.target.scrollLeft),0===e.target.scrollLeft?this.setState({scrollPosition:"left"}):e.target.scrollLeft+1>=e.target.children[0].getBoundingClientRect().width-e.target.getBoundingClientRect().width?this.setState({scrollPosition:"right"}):"middle"!==this.state.scrollPosition&&this.setState({scrollPosition:"middle"})),n.y&&(a&&e.target!==a&&(a.scrollTop=e.target.scrollTop),s&&e.target!==s&&(s.scrollTop=e.target.scrollTop),i&&e.target!==i&&(i.scrollTop=e.target.scrollTop))}},handleRowHover:function(e,t){this.setState({currentHoverKey:e?t:null})},render:function(){var e=this.props,t=e.prefixCls,n=e.prefixCls;e.className&&(n+=" "+e.className),e.columnsPageRange&&(n+=" "+t+"-columns-paging"),(e.useFixedHeader||e.scroll&&e.scroll.y)&&(n+=" "+t+"-fixed-header"),n+=" "+t+"-scroll-position-"+this.state.scrollPosition;var r=this.isAnyColumnsFixed()||e.scroll.x||e.scroll.y;return s["default"].createElement("div",{className:n,style:e.style},this.getTitle(),s["default"].createElement("div",{className:t+"-content"},this.isAnyColumnsLeftFixed()&&s["default"].createElement("div",{className:t+"-fixed-left"},this.getLeftFixedTable()),s["default"].createElement("div",{className:r?t+"-scroll":""},this.getTable(),this.getEmptyText(),this.getFooter()),this.isAnyColumnsRightFixed()&&s["default"].createElement("div",{className:t+"-fixed-right"},this.getRightFixedTable())))}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(346),s=r(a),l=n(45),u=r(l),c=n(109),d=r(c),f=i["default"].createClass({displayName:"TableCell",propTypes:{record:o.PropTypes.object,prefixCls:o.PropTypes.string,isColumnHaveExpandIcon:o.PropTypes.bool,index:o.PropTypes.number,expanded:o.PropTypes.bool,expandable:o.PropTypes.any,onExpand:o.PropTypes.func,needIndentSpaced:o.PropTypes.bool,indent:o.PropTypes.number,indentSize:o.PropTypes.number,column:o.PropTypes.object},shouldComponentUpdate:function(e){return!(0,u["default"])(e,this.props)},isInvalidRenderCellText:function(e){return e&&!i["default"].isValidElement(e)&&"[object Object]"===Object.prototype.toString.call(e)},render:function p(){var e=this.props,t=e.record,n=e.indentSize,r=e.prefixCls,o=e.indent,a=e.isColumnHaveExpandIcon,l=e.index,u=e.expandable,c=e.onExpand,f=e.needIndentSpaced,h=e.expanded,m=e.column,v=m.dataIndex,p=m.render,y=m.className,g=s["default"].get(t,v),b=void 0,_=void 0,x=void 0;p&&(g=p(g,t,l),this.isInvalidRenderCellText(g)&&(b=g.props||{},x=b.rowSpan,_=b.colSpan,g=g.children)),this.isInvalidRenderCellText(g)&&(g=null);var T=i["default"].createElement(d["default"],{expandable:u,prefixCls:r,onExpand:c,needIndentSpaced:f,expanded:h,record:t}),C=i["default"].createElement("span",{style:{paddingLeft:n*o+"px"},className:r+"-indent indent-level-"+o});return 0===x||0===_?null:i["default"].createElement("td",{colSpan:_,rowSpan:x,className:y||""},a?C:null,a?T:null,g)}});t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),a=r(i),s=n(45),l=r(s),u=n(382),c=r(u),d=n(109),f=r(d),p=a["default"].createClass({displayName:"TableRow",propTypes:{onDestroy:i.PropTypes.func,onRowClick:i.PropTypes.func,record:i.PropTypes.object,prefixCls:i.PropTypes.string,expandIconColumnIndex:i.PropTypes.number,onHover:i.PropTypes.func,columns:i.PropTypes.array,style:i.PropTypes.object,visible:i.PropTypes.bool,index:i.PropTypes.number,hoverKey:i.PropTypes.any,expanded:i.PropTypes.bool,expandable:i.PropTypes.any,onExpand:i.PropTypes.func,needIndentSpaced:i.PropTypes.bool,className:i.PropTypes.string,indent:i.PropTypes.number,indentSize:i.PropTypes.number,expandIconAsCell:i.PropTypes.bool,expandRowByClick:i.PropTypes.bool},getDefaultProps:function(){return{onRowClick:function(){},onDestroy:function(){},expandIconColumnIndex:0,expandRowByClick:!1,onHover:function(){}}},shouldComponentUpdate:function(e){return!(0,l["default"])(e,this.props)},componentWillUnmount:function(){this.props.onDestroy(this.props.record)},onRowClick:function h(e){var t=this.props,n=t.record,r=t.index,h=t.onRowClick,o=t.expandable,i=t.expandRowByClick,a=t.expanded,s=t.onExpand;o&&i&&s(!a,n),h(n,r,e)},onMouseEnter:function(){var e=this.props,t=e.onHover,n=e.hoverKey;t(!0,n)},onMouseLeave:function(){var e=this.props,t=e.onHover,n=e.hoverKey;t(!1,n)},render:function(){for(var e=this.props,t=e.prefixCls,n=e.columns,r=e.record,i=e.style,s=e.visible,l=e.index,u=e.expandIconColumnIndex,d=e.expandIconAsCell,p=e.expanded,h=e.expandRowByClick,m=e.expandable,v=e.onExpand,y=e.needIndentSpaced,g=e.className,b=e.indent,_=e.indentSize,x=[],T=0;T<n.length;T++){d&&0===T&&x.push(a["default"].createElement("td",{className:t+"-expand-icon-cell",key:"rc-table-expand-icon-cell"},a["default"].createElement(f["default"],{expandable:m,prefixCls:t,onExpand:v,needIndentSpaced:y,expanded:p,record:r})));var C=!d&&!h&&T===u;x.push(a["default"].createElement(c["default"],{prefixCls:t,record:r,indentSize:_,indent:b,index:l,expandable:m,onExpand:v,needIndentSpaced:y,expanded:p,isColumnHaveExpandIcon:C,column:n[T],key:n[T].key}))}return a["default"].createElement("tr",{onClick:this.onRowClick,onMouseEnter:this.onMouseEnter,onMouseLeave:this.onMouseLeave,className:t+" "+g+" "+t+"-level-"+b,style:s?i:o({},i,{display:"none"})},x)}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(381)},function(e,t){"use strict";function n(){if("undefined"==typeof document||"undefined"==typeof window)return 0;if(o)return o;var e=document.createElement("div");for(var t in i)i.hasOwnProperty(t)&&(e.style[t]=i[t]);document.body.appendChild(e);var n=e.offsetWidth-e.clientWidth;return document.body.removeChild(e),o=n}function r(e,t,n){var r=void 0;return function(){var o=this,i=arguments;i[0]&&i[0].persist&&i[0].persist();var a=function(){r=null,n||e.apply(o,i)},s=n&&!r;clearTimeout(r),r=setTimeout(a,t),s&&e.apply(o,i)}}Object.defineProperty(t,"__esModule",{value:!0}),t.measureScrollbar=n,t.debounce=r;var o=void 0,i={position:"absolute",top:"-9999px",width:"50px",height:"50px",overflow:"scroll"}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(387),s=r(a),l=n(110),u=r(l),c=i["default"].createClass({displayName:"InkTabBar",mixins:[u["default"],s["default"]],render:function(){var e=this.getInkBarNode(),t=this.getTabs();return this.getRootNode([e,t])}});t["default"]=c,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function i(e){var t=void 0,n=void 0,r=void 0,i=e.ownerDocument,a=i.body,s=i&&i.documentElement;t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=s.clientLeft||a.clientLeft||0,r-=s.clientTop||a.clientTop||0;var l=i.defaultView||i.parentWindow;return n+=o(l),r+=o(l,!0),{left:n,top:r}}function a(e,t){var n=e.refs,r=n.nav||n.root,o=i(r),a=n.inkBar,s=n.activeTab,l=a.style,c=e.props.tabBarPosition;if(t&&(l.display="none"),s){var d=s,f=i(d),p=(0,u.isTransformSupported)(l);if("top"===c||"bottom"===c){var h=f.left-o.left;p?((0,u.setTransform)(l,"translate3d("+h+"px,0,0)"),l.width=d.offsetWidth+"px",l.height=""):(l.left=h+"px",l.top="",l.bottom="",l.right=r.offsetWidth-h-d.offsetWidth+"px")}else{var m=f.top-o.top;p?((0,u.setTransform)(l,"translate3d(0,"+m+"px,0)"),l.height=d.offsetHeight+"px",l.width=""):(l.left="",l.right="",l.top=m+"px",l.bottom=r.offsetHeight-m-d.offsetHeight+"px")}}l.display=s?"block":"none"}Object.defineProperty(t,"__esModule",{value:!0});var s=n(6),l=r(s);t.getScroll=o;var u=n(68),c=n(1),d=r(c),f=n(5),p=r(f);t["default"]={getDefaultProps:function(){return{inkBarAnimated:!0}},componentDidUpdate:function(){a(this)},componentDidMount:function(){a(this,!0)},getInkBarNode:function(){var e,t=this.props,n=t.prefixCls,r=t.styles,o=t.inkBarAnimated,i=n+"-ink-bar",a=(0,p["default"])((e={},(0,l["default"])(e,i,!0),(0,l["default"])(e,o?i+"-animated":i+"-no-animated",!0),e));return d["default"].createElement("div",{style:r.inkBar,className:a,key:"inkBar",ref:"inkBar"})}}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={LEFT:37,UP:38,RIGHT:39,DOWN:40},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.maxIndex,n=e.startIndex,r=e.delta,o=e.viewSize,i=n+-r/o;return i<0?i=Math.exp(i*y)-1:i>t&&(i=t+1-Math.exp((t-i)*y)),i}function i(e){var t=(0,v.isVertical)(this.props.tabBarPosition)?e.deltaY:e.deltaX,n=o({maxIndex:this.maxIndex,viewSize:this.viewSize,startIndex:this.startIndex,delta:t}),r=t<0?Math.floor(n+1):Math.floor(n);if(r<0?r=0:r>this.maxIndex&&(r=this.maxIndex),!this.children[r].props.disabled)return n}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),s=r(a),l=n(67),u=r(l),c=n(1),d=r(c),f=n(69),p=r(f),h=n(9),m=r(h),v=n(68),y=.6,g=d["default"].createClass({displayName:"SwipeableTabContent",propTypes:{tabBarPosition:c.PropTypes.string,onChange:c.PropTypes.func,children:c.PropTypes.any,hammerOptions:c.PropTypes.any,animated:c.PropTypes.bool,activeKey:c.PropTypes.string},getDefaultProps:function(){return{animated:!0}},componentDidMount:function(){this.rootNode=m["default"].findDOMNode(this)},onPanStart:function(){var e=this.props,t=e.tabBarPosition,n=e.children,r=e.activeKey,o=e.animated,i=this.startIndex=(0,v.getActiveIndex)(n,r);i!==-1&&(o&&(0,v.setTransition)(this.rootNode.style,"none"),this.startDrag=!0,this.children=(0,v.toArray)(n),this.maxIndex=this.children.length-1,this.viewSize=(0,v.isVertical)(t)?this.rootNode.offsetHeight:this.rootNode.offsetWidth)},onPan:function(e){if(this.startDrag){var t=this.props.tabBarPosition,n=i.call(this,e);void 0!==n&&(0,v.setTransform)(this.rootNode.style,(0,v.getTransformByIndex)(n,t))}},onPanEnd:function(e){this.startDrag&&this.end(e)},onSwipe:function(e){this.end(e,!0)},end:function(e,t){var n=this.props,r=n.tabBarPosition,o=n.animated;this.startDrag=!1,o&&(0,v.setTransition)(this.rootNode.style,"");var a=i.call(this,e),s=this.startIndex;if(void 0!==a)if(a<0)s=0;else if(a>this.maxIndex)s=this.maxIndex;else if(t){var l=(0,v.isVertical)(r)?e.deltaY:e.deltaX;s=l<0?Math.ceil(a):Math.floor(a)}else{var u=Math.floor(a);s=a-u>.6?u+1:u}this.children[s].props.disabled||(this.startIndex===s?o&&(0,v.setTransform)(this.rootNode.style,(0,v.getTransformByIndex)(s,this.props.tabBarPosition)):this.props.onChange((0,v.getActiveKey)(this.props.children,s)))},render:function(){var e=this.props,t=e.tabBarPosition,n=e.hammerOptions,r=e.animated,o={};(0,v.isVertical)(t)&&(o={vertical:!0});var i={onSwipe:this.onSwipe,onPanStart:this.onPanStart};return r!==!1&&(i=(0,s["default"])({},i,{onPan:this.onPan,onPanEnd:this.onPanEnd})),d["default"].createElement(p["default"],(0,s["default"])({},i,o,{options:n}),d["default"].createElement(u["default"],this.props))}});t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(110),s=r(a),l=i["default"].createClass({displayName:"TabBar",mixins:[s["default"]],render:function(){var e=this.getTabs();return this.getRootNode(e)}});t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(e){var t=void 0;return u["default"].Children.forEach(e.children,function(e){t||e.props.disabled||(t=e.key)}),t}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),s=r(a),l=n(1),u=r(l),c=n(388),d=r(c),f=n(111),p=r(f),h=n(5),m=r(h),v=u["default"].createClass({displayName:"Tabs",propTypes:{destroyInactiveTabPane:l.PropTypes.bool,renderTabBar:l.PropTypes.func.isRequired,renderTabContent:l.PropTypes.func.isRequired,onChange:l.PropTypes.func,children:l.PropTypes.any,prefixCls:l.PropTypes.string,className:l.PropTypes.string,tabBarPosition:l.PropTypes.string,style:l.PropTypes.object},getDefaultProps:function(){return{prefixCls:"rc-tabs",destroyInactiveTabPane:!1,onChange:o,tabBarPosition:"top",style:{}}},getInitialState:function(){var e=this.props,t=void 0;return t="activeKey"in e?e.activeKey:"defaultActiveKey"in e?e.defaultActiveKey:i(e),{activeKey:t}},componentWillReceiveProps:function(e){"activeKey"in e&&this.setState({activeKey:e.activeKey})},onTabClick:function(e){this.tabBar.props.onTabClick&&this.tabBar.props.onTabClick(e),this.setActiveKey(e)},onNavKeyDown:function(e){var t=e.keyCode;if(t===d["default"].RIGHT||t===d["default"].DOWN){e.preventDefault();var n=this.getNextActiveKey(!0);this.onTabClick(n)}else if(t===d["default"].LEFT||t===d["default"].UP){e.preventDefault();var r=this.getNextActiveKey(!1);this.onTabClick(r)}},setActiveKey:function(e){this.state.activeKey!==e&&("activeKey"in this.props||this.setState({activeKey:e}),this.props.onChange(e))},getNextActiveKey:function(e){var t=this.state.activeKey,n=[];u["default"].Children.forEach(this.props.children,function(t){t.props.disabled||(e?n.push(t):n.unshift(t))});var r=n.length,o=r&&n[0].key;return n.forEach(function(e,i){e.key===t&&(o=i===r-1?n[0].key:n[i+1].key)}),o},render:function(){var e,t=this.props,n=t.prefixCls,r=t.tabBarPosition,o=t.className,i=t.renderTabContent,a=t.renderTabBar,l=(0,m["default"])((e={},(0,s["default"])(e,n,1),(0,s["default"])(e,n+"-"+r,1),(0,s["default"])(e,o,!!o),e));this.tabBar=a();var c=[u["default"].cloneElement(this.tabBar,{prefixCls:n,key:"tabBar",onKeyDown:this.onNavKeyDown,tabBarPosition:r,onTabClick:this.onTabClick,panels:t.children,activeKey:this.state.activeKey}),u["default"].cloneElement(i(),{prefixCls:n,tabBarPosition:r,activeKey:this.state.activeKey,destroyInactiveTabPane:t.destroyInactiveTabPane,children:t.children,onChange:this.setActiveKey,key:"tabContent"})];return"bottom"===r&&c.reverse(),u["default"].createElement("div",{className:l,style:t.style},c)}});v.TabPane=p["default"],t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),s=r(a),l=n(393),u=n(397),c=r(u),d=s["default"].createClass({displayName:"Tooltip",propTypes:{trigger:a.PropTypes.any,children:a.PropTypes.any,defaultVisible:a.PropTypes.bool,visible:a.PropTypes.bool,placement:a.PropTypes.string,transitionName:a.PropTypes.string,animation:a.PropTypes.any,onVisibleChange:a.PropTypes.func,afterVisibleChange:a.PropTypes.func,overlay:a.PropTypes.oneOfType([s["default"].PropTypes.node,s["default"].PropTypes.func]).isRequired,overlayStyle:a.PropTypes.object,overlayClassName:a.PropTypes.string,prefixCls:a.PropTypes.string,
mouseEnterDelay:a.PropTypes.number,mouseLeaveDelay:a.PropTypes.number,getTooltipContainer:a.PropTypes.func,destroyTooltipOnHide:a.PropTypes.bool,align:a.PropTypes.object,arrowContent:a.PropTypes.any},getDefaultProps:function(){return{prefixCls:"rc-tooltip",mouseEnterDelay:0,destroyTooltipOnHide:!1,mouseLeaveDelay:.1,align:{},placement:"right",trigger:["hover"],arrowContent:null}},getPopupElement:function(){var e=this.props,t=e.arrowContent,n=e.overlay,r=e.prefixCls;return[s["default"].createElement("div",{className:r+"-arrow",key:"arrow"},t),s["default"].createElement("div",{className:r+"-inner",key:"content"},"function"==typeof n?n():n)]},getPopupDomNode:function(){return this.refs.trigger.getPopupDomNode()},render:function(){var e=this.props,t=e.overlayClassName,n=e.trigger,r=e.mouseEnterDelay,a=e.mouseLeaveDelay,u=e.overlayStyle,d=e.prefixCls,f=e.children,p=e.onVisibleChange,h=e.transitionName,m=e.animation,v=e.placement,y=e.align,g=e.destroyTooltipOnHide,b=e.defaultVisible,_=e.getTooltipContainer,x=o(e,["overlayClassName","trigger","mouseEnterDelay","mouseLeaveDelay","overlayStyle","prefixCls","children","onVisibleChange","transitionName","animation","placement","align","destroyTooltipOnHide","defaultVisible","getTooltipContainer"]),T=i({},x);return"visible"in this.props&&(T.popupVisible=this.props.visible),s["default"].createElement(c["default"],i({popupClassName:t,ref:"trigger",prefixCls:d,popup:this.getPopupElement,action:n,builtinPlacements:l.placements,popupPlacement:v,popupAlign:y,getPopupContainer:_,onPopupVisibleChange:p,popupTransitionName:h,popupAnimation:m,defaultPopupVisible:b,destroyPopupOnHide:g,mouseLeaveDelay:a,popupStyle:u,mouseEnterDelay:r},T),f)}});t["default"]=d,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={adjustX:1,adjustY:1},r=[0,0],o=t.placements={left:{points:["cr","cl"],overflow:n,offset:[-4,0],targetOffset:r},right:{points:["cl","cr"],overflow:n,offset:[4,0],targetOffset:r},top:{points:["bc","tc"],overflow:n,offset:[0,-4],targetOffset:r},bottom:{points:["tc","bc"],overflow:n,offset:[0,4],targetOffset:r},topLeft:{points:["bl","tl"],overflow:n,offset:[0,-4],targetOffset:r},leftTop:{points:["tr","tl"],overflow:n,offset:[-4,0],targetOffset:r},topRight:{points:["br","tr"],overflow:n,offset:[0,-4],targetOffset:r},rightTop:{points:["tl","tr"],overflow:n,offset:[4,0],targetOffset:r},bottomRight:{points:["tr","br"],overflow:n,offset:[0,4],targetOffset:r},rightBottom:{points:["bl","br"],overflow:n,offset:[4,0],targetOffset:r},bottomLeft:{points:["tl","bl"],overflow:n,offset:[0,4],targetOffset:r},leftBottom:{points:["br","bl"],overflow:n,offset:[-4,0],targetOffset:r}};t["default"]=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),a=r(i),s=n(9),l=r(s),u=n(349),c=r(u),d=n(42),f=r(d),p=n(395),h=r(p),m=n(114),v=r(m),y=a["default"].createClass({displayName:"Popup",propTypes:{visible:i.PropTypes.bool,style:i.PropTypes.object,getClassNameFromAlign:i.PropTypes.func,onAlign:i.PropTypes.func,getRootDomNode:i.PropTypes.func,onMouseEnter:i.PropTypes.func,align:i.PropTypes.any,destroyPopupOnHide:i.PropTypes.bool,className:i.PropTypes.string,prefixCls:i.PropTypes.string,onMouseLeave:i.PropTypes.func},componentDidMount:function(){this.rootNode=this.getPopupDomNode()},onAlign:function(e,t){var n=this.props,r=n.getClassNameFromAlign(n.align),o=n.getClassNameFromAlign(t);r!==o&&(this.currentAlignClassName=o,e.className=this.getClassName(o)),n.onAlign(e,t)},getPopupDomNode:function(){return l["default"].findDOMNode(this.refs.popup)},getTarget:function(){return this.props.getRootDomNode()},getMaskTransitionName:function(){var e=this.props,t=e.maskTransitionName,n=e.maskAnimation;return!t&&n&&(t=e.prefixCls+"-"+n),t},getTransitionName:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=e.prefixCls+"-"+e.animation),t},getClassName:function(e){return this.props.prefixCls+" "+this.props.className+" "+e},getPopupElement:function(){var e=this.props,t=e.align,n=e.style,r=e.visible,i=e.prefixCls,s=e.destroyPopupOnHide,l=this.getClassName(this.currentAlignClassName||e.getClassNameFromAlign(t)),u=i+"-hidden";r||(this.currentAlignClassName=null);var d=o({},n,this.getZIndexStyle()),p={className:l,prefixCls:i,ref:"popup",onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,style:d};return s?a["default"].createElement(f["default"],{component:"",exclusive:!0,transitionAppear:!0,transitionName:this.getTransitionName()},r?a["default"].createElement(c["default"],{target:this.getTarget,key:"popup",ref:this.saveAlign,monitorWindowResize:!0,align:t,onAlign:this.onAlign},a["default"].createElement(h["default"],o({visible:!0},p),e.children)):null):a["default"].createElement(f["default"],{component:"",exclusive:!0,transitionAppear:!0,transitionName:this.getTransitionName(),showProp:"xVisible"},a["default"].createElement(c["default"],{target:this.getTarget,key:"popup",ref:this.saveAlign,monitorWindowResize:!0,xVisible:r,childrenProps:{visible:"xVisible"},disabled:!r,align:t,onAlign:this.onAlign},a["default"].createElement(h["default"],o({hiddenClassName:u},p),e.children)))},getZIndexStyle:function(){var e={},t=this.props;return void 0!==t.zIndex&&(e.zIndex=t.zIndex),e},getMaskElement:function(){var e=this.props,t=void 0;if(e.mask){var n=this.getMaskTransitionName();t=a["default"].createElement(v["default"],{style:this.getZIndexStyle(),key:"mask",className:e.prefixCls+"-mask",hiddenClassName:e.prefixCls+"-mask-hidden",visible:e.visible}),n&&(t=a["default"].createElement(f["default"],{key:"mask",showProp:"visible",transitionAppear:!0,component:"",transitionName:n},t))}return t},saveAlign:function(e){this.alignInstance=e},render:function(){return a["default"].createElement("div",null,this.getMaskElement(),this.getPopupElement())}});t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(114),s=r(a),l=i["default"].createClass({displayName:"PopupInner",propTypes:{hiddenClassName:o.PropTypes.string,className:o.PropTypes.string,prefixCls:o.PropTypes.string,onMouseEnter:o.PropTypes.func,onMouseLeave:o.PropTypes.func,children:o.PropTypes.any},render:function(){var e=this.props,t=e.className;return e.visible||(t+=" "+e.hiddenClassName),i["default"].createElement("div",{className:t,onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,style:e.style},i["default"].createElement(s["default"],{className:e.prefixCls+"-content",visible:e.visible},e.children))}});t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function i(){return""}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(1),l=r(s),u=n(9),c=r(u),d=n(399),f=r(d),p=n(44),h=r(p),m=n(394),v=r(m),y=n(398),g=n(115),b=r(g),_=["onClick","onMouseDown","onTouchStart","onMouseEnter","onMouseLeave","onFocus","onBlur"],x=l["default"].createClass({displayName:"Trigger",propTypes:{children:s.PropTypes.any,action:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.arrayOf(s.PropTypes.string)]),showAction:s.PropTypes.any,hideAction:s.PropTypes.any,getPopupClassNameFromAlign:s.PropTypes.any,onPopupVisibleChange:s.PropTypes.func,afterPopupVisibleChange:s.PropTypes.func,popup:s.PropTypes.oneOfType([s.PropTypes.node,s.PropTypes.func]).isRequired,popupStyle:s.PropTypes.object,prefixCls:s.PropTypes.string,popupClassName:s.PropTypes.string,popupPlacement:s.PropTypes.string,builtinPlacements:s.PropTypes.object,popupTransitionName:s.PropTypes.string,popupAnimation:s.PropTypes.any,mouseEnterDelay:s.PropTypes.number,mouseLeaveDelay:s.PropTypes.number,zIndex:s.PropTypes.number,focusDelay:s.PropTypes.number,blurDelay:s.PropTypes.number,getPopupContainer:s.PropTypes.func,destroyPopupOnHide:s.PropTypes.bool,mask:s.PropTypes.bool,onPopupAlign:s.PropTypes.func,popupAlign:s.PropTypes.object,popupVisible:s.PropTypes.bool,maskTransitionName:s.PropTypes.string,maskAnimation:s.PropTypes.string},mixins:[(0,b["default"])({autoMount:!1,isVisible:function(e){return e.state.popupVisible},getContainer:function(e){var t=document.createElement("div"),n=e.props.getPopupContainer?e.props.getPopupContainer((0,u.findDOMNode)(e)):document.body;return n.appendChild(t),t},getComponent:function(e){var t=e.props,n=e.state,r={};return e.isMouseEnterToShow()&&(r.onMouseEnter=e.onPopupMouseEnter),e.isMouseLeaveToHide()&&(r.onMouseLeave=e.onPopupMouseLeave),l["default"].createElement(v["default"],a({prefixCls:t.prefixCls,destroyPopupOnHide:t.destroyPopupOnHide,visible:n.popupVisible,className:t.popupClassName,action:t.action,align:e.getPopupAlign(),onAlign:t.onPopupAlign,animation:t.popupAnimation,getClassNameFromAlign:e.getPopupClassNameFromAlign},r,{getRootDomNode:e.getRootDomNode,style:t.popupStyle,mask:t.mask,zIndex:t.zIndex,transitionName:t.popupTransitionName,maskAnimation:t.maskAnimation,maskTransitionName:t.maskTransitionName}),"function"==typeof t.popup?t.popup():t.popup)}})],getDefaultProps:function(){return{prefixCls:"rc-trigger-popup",getPopupClassNameFromAlign:i,onPopupVisibleChange:o,afterPopupVisibleChange:o,onPopupAlign:o,popupClassName:"",mouseEnterDelay:0,mouseLeaveDelay:.1,focusDelay:0,blurDelay:.15,popupStyle:{},destroyPopupOnHide:!1,popupAlign:{},defaultPopupVisible:!1,mask:!1,action:[],showAction:[],hideAction:[]}},getInitialState:function(){var e=this.props,t=void 0;return t="popupVisible"in e?!!e.popupVisible:!!e.defaultPopupVisible,{popupVisible:t}},componentWillMount:function(){var e=this;_.forEach(function(t){e["fire"+t]=function(n){e.fireEvents(t,n)}})},componentDidMount:function(){this.componentDidUpdate({},{popupVisible:this.state.popupVisible})},componentWillReceiveProps:function(e){var t=e.popupVisible;void 0!==t&&this.setState({popupVisible:t})},componentDidUpdate:function(e,t){var n=this.props,r=this.state;return this.renderComponent(null,function(){t.popupVisible!==r.popupVisible&&n.afterPopupVisibleChange(r.popupVisible)}),this.isClickToHide()&&r.popupVisible?void(this.clickOutsideHandler||(this.clickOutsideHandler=(0,h["default"])(document,"mousedown",this.onDocumentClick),this.touchOutsideHandler=(0,h["default"])(document,"touchstart",this.onDocumentClick))):void(this.clickOutsideHandler&&(this.clickOutsideHandler.remove(),this.touchOutsideHandler.remove(),this.clickOutsideHandler=null,this.touchOutsideHandler=null))},componentWillUnmount:function(){this.clearDelayTimer(),this.clickOutsideHandler&&(this.clickOutsideHandler.remove(),this.touchOutsideHandler.remove(),this.clickOutsideHandler=null,this.touchOutsideHandler=null)},onMouseEnter:function(e){this.fireEvents("onMouseEnter",e),this.delaySetPopupVisible(!0,this.props.mouseEnterDelay)},onMouseLeave:function(e){this.fireEvents("onMouseLeave",e),this.delaySetPopupVisible(!1,this.props.mouseLeaveDelay)},onPopupMouseEnter:function(){this.clearDelayTimer()},onPopupMouseLeave:function(e){e.relatedTarget&&!e.relatedTarget.setTimeout&&this._component&&(0,f["default"])(this._component.getPopupDomNode(),e.relatedTarget)||this.delaySetPopupVisible(!1,this.props.mouseLeaveDelay)},onFocus:function(e){this.fireEvents("onFocus",e),this.clearDelayTimer(),this.isFocusToShow()&&(this.focusTime=Date.now(),this.delaySetPopupVisible(!0,this.props.focusDelay))},onMouseDown:function(e){this.fireEvents("onMouseDown",e),this.preClickTime=Date.now()},onTouchStart:function(e){this.fireEvents("onTouchStart",e),this.preTouchTime=Date.now()},onBlur:function(e){this.fireEvents("onBlur",e),this.clearDelayTimer(),this.isBlurToHide()&&this.delaySetPopupVisible(!1,this.props.blurDelay)},onClick:function(e){if(this.fireEvents("onClick",e),this.focusTime){var t=void 0;if(this.preClickTime&&this.preTouchTime?t=Math.min(this.preClickTime,this.preTouchTime):this.preClickTime?t=this.preClickTime:this.preTouchTime&&(t=this.preTouchTime),Math.abs(t-this.focusTime)<20)return;this.focusTime=0}this.preClickTime=0,this.preTouchTime=0,e.preventDefault();var n=!this.state.popupVisible;(this.isClickToHide()&&!n||n&&this.isClickToShow())&&this.setPopupVisible(!this.state.popupVisible)},onDocumentClick:function(e){var t=e.target,n=(0,u.findDOMNode)(this),r=this.getPopupDomNode();(0,f["default"])(n,t)||(0,f["default"])(r,t)||this.setPopupVisible(!1)},getPopupDomNode:function(){return this._component&&this._component.isMounted()?this._component.getPopupDomNode():null},getRootDomNode:function(){return c["default"].findDOMNode(this)},getPopupClassNameFromAlign:function(e){var t=[],n=this.props,r=n.popupPlacement,o=n.builtinPlacements,i=n.prefixCls;return r&&o&&t.push((0,y.getPopupClassNameFromAlign)(o,i,e)),n.getPopupClassNameFromAlign&&t.push(n.getPopupClassNameFromAlign(e)),t.join(" ")},getPopupAlign:function(){var e=this.props,t=e.popupPlacement,n=e.popupAlign,r=e.builtinPlacements;return t&&r?(0,y.getAlignFromPlacement)(r,t,n):n},setPopupVisible:function(e){this.clearDelayTimer(),this.state.popupVisible!==e&&("popupVisible"in this.props||this.setState({popupVisible:e}),this.props.onPopupVisibleChange(e))},delaySetPopupVisible:function(e,t){var n=this,r=1e3*t;this.clearDelayTimer(),r?this.delayTimer=setTimeout(function(){n.setPopupVisible(e),n.clearDelayTimer()},r):this.setPopupVisible(e)},clearDelayTimer:function(){this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null)},createTwoChains:function(e){var t=this.props.children.props,n=this.props;return t[e]&&n[e]?this["fire"+e]:t[e]||n[e]},isClickToShow:function(){var e=this.props,t=e.action,n=e.showAction;return t.indexOf("click")!==-1||n.indexOf("click")!==-1},isClickToHide:function(){var e=this.props,t=e.action,n=e.hideAction;return t.indexOf("click")!==-1||n.indexOf("click")!==-1},isMouseEnterToShow:function(){var e=this.props,t=e.action,n=e.showAction;return t.indexOf("hover")!==-1||n.indexOf("mouseEnter")!==-1},isMouseLeaveToHide:function(){var e=this.props,t=e.action,n=e.hideAction;return t.indexOf("hover")!==-1||n.indexOf("mouseLeave")!==-1},isFocusToShow:function(){var e=this.props,t=e.action,n=e.showAction;return t.indexOf("focus")!==-1||n.indexOf("focus")!==-1},isBlurToHide:function(){var e=this.props,t=e.action,n=e.hideAction;return t.indexOf("focus")!==-1||n.indexOf("blur")!==-1},forcePopupAlign:function(){this.state.popupVisible&&this.popupInstance&&this.popupInstance.alignInstance&&this.popupInstance.alignInstance.forceAlign()},fireEvents:function(e,t){var n=this.props.children.props[e];n&&n(t);var r=this.props[e];r&&r(t)},render:function(){var e=this.props,t=e.children,n=l["default"].Children.only(t),r={};return this.isClickToHide()||this.isClickToShow()?(r.onClick=this.onClick,r.onMouseDown=this.onMouseDown,r.onTouchStart=this.onTouchStart):(r.onClick=this.createTwoChains("onClick"),r.onMouseDown=this.createTwoChains("onMouseDown"),r.onTouchStart=this.createTwoChains("onTouchStart")),this.isMouseEnterToShow()?r.onMouseEnter=this.onMouseEnter:r.onMouseEnter=this.createTwoChains("onMouseEnter"),this.isMouseLeaveToHide()?r.onMouseLeave=this.onMouseLeave:r.onMouseLeave=this.createTwoChains("onMouseLeave"),this.isFocusToShow()||this.isBlurToHide()?(r.onFocus=this.onFocus,r.onBlur=this.onBlur):(r.onFocus=this.createTwoChains("onFocus"),r.onBlur=this.createTwoChains("onBlur")),l["default"].cloneElement(n,r)}});t["default"]=x,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(396)},function(e,t){"use strict";function n(e,t){return e[0]===t[0]&&e[1]===t[1]}function r(e,t,n){var r=e[t]||{};return i({},r,n)}function o(e,t,r){var o=r.points;for(var i in e)if(e.hasOwnProperty(i)&&n(e[i].points,o))return t+"-placement-"+i;return""}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.getAlignFromPlacement=r,t.getPopupClassNameFromAlign=o},function(e,t){"use strict";e.exports=function(e,t){for(var n=t;n;){if(n===e)return!0;n=n.parentNode}return!1}},function(e,t){"use strict";var n={MAC_ENTER:3,BACKSPACE:8,TAB:9,NUM_CENTER:12,ENTER:13,SHIFT:16,CTRL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PRINT_SCREEN:44,INSERT:45,DELETE:46,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,QUESTION_MARK:63,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,META:91,WIN_KEY_RIGHT:92,CONTEXT_MENU:93,NUM_ZERO:96,NUM_ONE:97,NUM_TWO:98,NUM_THREE:99,NUM_FOUR:100,NUM_FIVE:101,NUM_SIX:102,NUM_SEVEN:103,NUM_EIGHT:104,NUM_NINE:105,NUM_MULTIPLY:106,NUM_PLUS:107,NUM_MINUS:109,NUM_PERIOD:110,NUM_DIVISION:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,NUMLOCK:144,SEMICOLON:186,DASH:189,EQUALS:187,COMMA:188,PERIOD:190,SLASH:191,APOSTROPHE:192,SINGLE_QUOTE:222,OPEN_SQUARE_BRACKET:219,BACKSLASH:220,CLOSE_SQUARE_BRACKET:221,WIN_KEY:224,MAC_FF_META:224,WIN_IME:229};n.isTextModifyingKeyEvent=function(e){var t=e.keyCode;if(e.altKey&&!e.ctrlKey||e.metaKey||t>=n.F1&&t<=n.F12)return!1;switch(t){case n.ALT:case n.CAPS_LOCK:case n.CONTEXT_MENU:case n.CTRL:case n.DOWN:case n.END:case n.ESC:case n.HOME:case n.INSERT:case n.LEFT:case n.MAC_FF_META:case n.META:case n.NUMLOCK:case n.NUM_CENTER:case n.PAGE_DOWN:case n.PAGE_UP:case n.PAUSE:case n.PRINT_SCREEN:case n.RIGHT:case n.SHIFT:case n.UP:case n.WIN_KEY:case n.WIN_KEY_RIGHT:return!1;default:return!0}},n.isCharacterKey=function(e){if(e>=n.ZERO&&e<=n.NINE)return!0;if(e>=n.NUM_ZERO&&e<=n.NUM_MULTIPLY)return!0;if(e>=n.A&&e<=n.Z)return!0;if(window.navigation.userAgent.indexOf("WebKit")!==-1&&0===e)return!0;switch(e){case n.SPACE:case n.QUESTION_MARK:case n.NUM_PLUS:case n.NUM_MINUS:case n.NUM_PERIOD:case n.NUM_DIVISION:case n.SEMICOLON:case n.DASH:case n.EQUALS:case n.COMMA:case n.PERIOD:case n.SLASH:case n.APOSTROPHE:case n.SINGLE_QUOTE:case n.OPEN_SQUARE_BRACKET:case n.BACKSLASH:case n.CLOSE_SQUARE_BRACKET:return!0;default:return!1}},e.exports=n},function(e,t){"use strict";function n(){var e=arguments;return function(){for(var t=0;t<e.length;t++)e[t]&&e[t].apply&&e[t].apply(this,arguments)}}e.exports=n},function(e,t){"use strict";function n(e){if(e||void 0===r){var t=document.createElement("div");t.style.width="100%",t.style.height="200px";var n=document.createElement("div"),o=n.style;o.position="absolute",o.top=0,o.left=0,o.pointerEvents="none",o.visibility="hidden",o.width="200px",o.height="150px",o.overflow="hidden",n.appendChild(t),document.body.appendChild(n);var i=t.offsetWidth;n.style.overflow="scroll";var a=t.offsetWidth;i===a&&(a=n.clientWidth),document.body.removeChild(n),r=i-a}return r}var r=void 0;e.exports=n},function(e,t,n){e.exports=n(409)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=n(1),u=r(l),c=n(9),d=r(c),f=n(117),p=r(f),h=function(e){function t(e){o(this,t);var n=i(this,Object.getPrototypeOf(t).call(this,e));return n.updateOffset=function(e){var t=e.inherited,r=e.offset;n.channel.update(function(e){e.inherited=t+r})},n.channel=new p["default"]({inherited:0,offset:0,node:null}),n}return a(t,e),s(t,[{key:"getChildContext",value:function(){return{"sticky-channel":this.channel}}},{key:"componentWillMount",value:function(){var e=this.context["sticky-channel"];e&&e.subscribe(this.updateOffset)}},{key:"componentDidMount",value:function(){var e=d["default"].findDOMNode(this);this.channel.update(function(t){t.node=e})}},{key:"componentWillUnmount",value:function(){this.channel.update(function(e){e.node=null});var e=this.context["sticky-channel"];e&&e.unsubscribe(this.updateOffset)}},{key:"render",value:function(){return u["default"].createElement("div",this.props,this.props.children)}}]),t}(u["default"].Component);h.contextTypes={"sticky-channel":u["default"].PropTypes.any},h.childContextTypes={"sticky-channel":u["default"].PropTypes.any},t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Channel=t.StickyContainer=t.Sticky=void 0;var o=n(406),i=r(o),a=n(404),s=r(a),l=n(117),u=r(l);t.Sticky=i["default"],t.StickyContainer=s["default"],t.Channel=u["default"],t["default"]=i["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),c=n(1),d=r(c),f=n(9),p=r(f),h=function(e){function t(e){i(this,t);var n=a(this,Object.getPrototypeOf(t).call(this,e));return n.updateContext=function(e){var t=e.inherited,r=e.node;n.containerNode=r,n.setState({containerOffset:t,distanceFromBottom:n.getDistanceFromBottom()})},n.recomputeState=function(){var e=n.isSticky(),t=n.getHeight(),r=n.getWidth(),o=n.getXOffset(),i=n.getDistanceFromBottom(),a=n.state.isSticky!==e;n.setState({isSticky:e,height:t,width:r,xOffset:o,distanceFromBottom:i}),a&&(n.channel&&n.channel.update(function(t){t.offset=e?n.state.height:0}),n.props.onStickyStateChange(e))},n.state={},n}return s(t,e),u(t,[{key:"componentWillMount",value:function(){this.channel=this.context["sticky-channel"],this.channel.subscribe(this.updateContext)}},{key:"componentDidMount",value:function(){this.on(["resize","scroll","touchstart","touchmove","touchend","pageshow","load"],this.recomputeState),this.recomputeState()}},{key:"componentWillReceiveProps",value:function(){this.recomputeState()}},{key:"componentWillUnmount",value:function(){this.off(["resize","scroll","touchstart","touchmove","touchend","pageshow","load"],this.recomputeState),this.channel.unsubscribe(this.updateContext)}},{key:"getXOffset",value:function(){return this.refs.placeholder.getBoundingClientRect().left}},{key:"getWidth",value:function(){return this.refs.placeholder.getBoundingClientRect().width}},{key:"getHeight",value:function(){return p["default"].findDOMNode(this.refs.children).getBoundingClientRect().height}},{key:"getDistanceFromTop",value:function(){return this.refs.placeholder.getBoundingClientRect().top}},{key:"getDistanceFromBottom",value:function(){return this.containerNode?this.containerNode.getBoundingClientRect().bottom:0}},{key:"isSticky",value:function(){if(!this.props.isActive)return!1;var e=this.getDistanceFromTop(),t=this.getDistanceFromBottom(),n=this.state.containerOffset-this.props.topOffset,r=this.state.containerOffset+this.props.bottomOffset;return e<=n&&t>=r}},{key:"on",value:function(e,t){e.forEach(function(e){window.addEventListener(e,t)})}},{key:"off",value:function(e,t){e.forEach(function(e){window.removeEventListener(e,t)})}},{key:"shouldComponentUpdate",value:function(e,t){var n=this,r=Object.keys(this.props);if(Object.keys(e).length!=r.length)return!0;var o=r.every(function(t){return e.hasOwnProperty(t)&&e[t]===n.props[t]});if(!o)return!0;var i=this.state;if(t.isSticky!==i.isSticky)return!0;if(i.isSticky){if(t.height!==i.height)return!0;if(t.width!==i.width)return!0;if(t.xOffset!==i.xOffset)return!0;if(t.containerOffset!==i.containerOffset)return!0;if(t.distanceFromBottom!==i.distanceFromBottom)return!0}return!1}},{key:"render",value:function(){var e={paddingBottom:0},t=this.props.className,n=l({},{transform:"translateZ(0)"},this.props.style);if(this.state.isSticky){var r={position:"fixed",top:this.state.containerOffset,left:this.state.xOffset,width:this.state.width},i=this.state.distanceFromBottom-this.state.height-this.props.bottomOffset;this.state.containerOffset>i&&(r.top=i),e.paddingBottom=this.state.height,t+=" "+this.props.stickyClassName,n=l({},n,r,this.props.stickyStyle)}var a=this.props,s=(a.topOffset,a.isActive,a.stickyClassName,a.stickyStyle,a.bottomOffset,a.onStickyStateChange,o(a,["topOffset","isActive","stickyClassName","stickyStyle","bottomOffset","onStickyStateChange"]));return d["default"].createElement("div",null,d["default"].createElement("div",{ref:"placeholder",style:e}),d["default"].createElement("div",l({},s,{ref:"children",className:t,style:n}),this.props.children))}}]),t}(d["default"].Component);h.propTypes={isActive:d["default"].PropTypes.bool,className:d["default"].PropTypes.string,style:d["default"].PropTypes.object,stickyClassName:d["default"].PropTypes.string,stickyStyle:d["default"].PropTypes.object,topOffset:d["default"].PropTypes.number,bottomOffset:d["default"].PropTypes.number,onStickyStateChange:d["default"].PropTypes.func},h.defaultProps={isActive:!0,className:"",style:{},stickyClassName:"sticky",stickyStyle:{},topOffset:0,bottomOffset:0,onStickyStateChange:function(){}},h.contextTypes={"sticky-channel":d["default"].PropTypes.any},t["default"]=h,e.exports=t["default"]},function(e,t){(function(t){"use strict";var n="undefined"==typeof window?t:window,r=function(e,t,n){return function(r,o){var i=e(function(){t.call(this,i),r.apply(this,arguments)}.bind(this),o);return this[n]?this[n].push(i):this[n]=[i],i}},o=function(e,t){return function(n){if(this[t]){var r=this[t].indexOf(n);r!==-1&&this[t].splice(r,1)}e(n)}},i="TimerMixin_timeouts",a=o(n.clearTimeout,i),s=r(n.setTimeout,a,i),l="TimerMixin_intervals",u=o(n.clearInterval,l),c=r(n.setInterval,function(){},l),d="TimerMixin_immediates",f=o(n.clearImmediate,d),p=r(n.setImmediate,f,d),h="TimerMixin_rafs",m=o(n.cancelAnimationFrame,h),v=r(n.requestAnimationFrame,m,h),y={componentWillUnmount:function(){this[i]&&this[i].forEach(function(e){n.clearTimeout(e)}),this[i]=null,this[l]&&this[l].forEach(function(e){n.clearInterval(e)}),this[l]=null,this[d]&&this[d].forEach(function(e){n.clearImmediate(e)}),this[d]=null,this[h]&&this[h].forEach(function(e){n.cancelAnimationFrame(e)}),this[h]=null},setTimeout:s,clearTimeout:a,setInterval:c,clearInterval:u,setImmediate:p,clearImmediate:f,requestAnimationFrame:v,cancelAnimationFrame:m};e.exports=y}).call(t,function(){return this}())},function(e,t,n){"use strict";var r=n(118),o=n(325),i=(n(410),n(327),n(411)),a=n(330),s=n(332),l=(n(41),s(function(e){return a(e)})),u=!1,c="cssFloat";if(o.canUseDOM){var d=document.createElement("div").style;try{d.font=""}catch(f){u=!0}void 0===document.documentElement.style.cssFloat&&(c="styleFloat")}var p={createMarkupForStyles:function(e,t){var n="";for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];null!=o&&(n+=l(r)+":",n+=i(r,o,t)+";")}return n||null},setValueForStyles:function(e,t,n){var o=e.style;for(var a in t)if(t.hasOwnProperty(a)){var s=i(a,t[a],n);if("float"!==a&&"cssFloat"!==a||(a=c),s)o[a]=s;else{var l=u&&r.shorthandPropertyExpansions[a];if(l)for(var d in l)o[d]="";else o[a]=""}}}};e.exports=p},function(e,t,n){"use strict";var r=n(412),o={shouldComponentUpdate:function(e,t){return r(this,e,t)}};e.exports=o},function(e,t,n){"use strict";var r=null;e.exports={debugTool:r}},function(e,t,n){"use strict";function r(e,t,n){var r=null==t||"boolean"==typeof t||""===t;if(r)return"";var o=isNaN(t);if(o||0===t||i.hasOwnProperty(e)&&i[e])return""+t;if("string"==typeof t){t=t.trim()}return t+"px"}var o=n(118),i=(n(41),o.isUnitlessNumber);e.exports=r},function(e,t,n){"use strict";function r(e,t,n){return!o(e.props,t)||!o(e.state,n)}var o=n(333);e.exports=r},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=o(i),s=n(1),l=r(s),u=n(5),c=o(u),d=n(121),f=o(d),p=n(414),h=o(p),m=l.createClass({displayName:"Cascader",mixins:[h["default"]],getDefaultProps:function(){return{prefixCls:"rmc-cascader",pickerPrefixCls:"rmc-picker",data:[],disabled:!1}},render:function(){var e=this,t=this.props,n=t.prefixCls,r=t.pickerPrefixCls,o=t.className,i=t.rootNativeProps,s=t.disabled,u=this.state.value,d=this.getChildrenTree(),p=this.getColArray().map(function(t,o){return l.createElement("div",{key:o,className:n+"-item"},l.createElement(f["default"],{disabled:s,prefixCls:r,selectedValue:u[o],onValueChange:e.onValueChange.bind(e,o)},d[o]||[]))});return l.createElement("div",(0,a["default"])({},i,{className:(0,c["default"])(o,n)}),p)}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(71),i=r(o);t["default"]={getDefaultProps:function(){return{cols:3}},getInitialState:function(){return{value:this.getValue(this.props.data,this.props.defaultValue||this.props.value)}},componentWillReceiveProps:function(e){"value"in e&&this.setState({value:this.getValue(e.data,e.value)})},onValueChange:function(e,t){var n=this.state.value.concat();n[e]=t;var r=(0,i["default"])(this.props.data,function(t,r){return r<=e&&t.value===n[r]}),o=r[e],a=void 0;for(a=e+1;o&&o.children&&o.children.length&&a<this.props.cols;a++)o=o.children[0],n[a]=o.value;n.length=a,"value"in this.props||this.setState({value:n}),this.props.onChange(n)},getValue:function(e,t){var n=e||this.props.data,r=t||this.props.value||this.props.defaultValue;if(!r||!r.length){r=[];for(var o=0;o<this.props.cols;o++)n&&n.length?(r[o]=n[0].value,n=n[0].children):r[o]=void 0}return r},getColArray:function(){for(var e=[],t=0;t<this.props.cols;t++)e[t]=void 0;return e},getChildrenTree:function(){var e=this.props,t=e.data,n=e.cols,r=this.state.value,o=(0,i["default"])(t,function(e,t){return e.value===r[t]}).map(function(e){return e.children});return o.length=n-1,o.unshift(t),o}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);
return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}function i(){}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),s=o(a),l=n(2),u=o(l),c=n(4),d=o(c),f=n(3),p=o(f),h=n(1),m=r(h),v=n(122),y=o(v),g=function(e){function t(n){(0,u["default"])(this,t);var r=(0,d["default"])(this,e.call(this,n));return r.onPickerChange=function(e){r.setState({pickerValue:e}),r.props.cascader.props.onChange&&r.props.cascader.props.onChange(e)},r.onOk=function(){r.props.onChange(r.cascader.getValue().filter(function(e){return!!e}))},r.saveRef=function(e){r.cascader=e},r.fireVisibleChange=function(e){r.state.visible!==e&&("visible"in r.props||r.setVisibleState(e),r.props.onVisibleChange(e))},r.state={pickerValue:null,visible:r.props.visible||!1},r}return(0,p["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){"visible"in e&&this.setVisibleState(e.visible)},t.prototype.setVisibleState=function(e){this.setState({visible:e}),e||this.setState({pickerValue:null})},t.prototype.render=function(){var e=m.cloneElement(this.props.cascader,{value:this.state.pickerValue||this.props.value,onChange:this.onPickerChange,ref:this.saveRef,data:this.props.cascader.props.data});return m.createElement(y["default"],(0,s["default"])({},this.props,{onVisibleChange:this.fireVisibleChange,onOk:this.onOk,content:e,visible:this.state.visible}))},t}(m.Component);t["default"]=g,g.defaultProps={prefixCls:"rmc-picker-popup",onVisibleChange:i,onChange:i},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),a=o(i),s=n(1),l=r(s),u=n(434),c=o(u),d=n(5),f=o(d),p=n(417),h=o(p),m=l.createClass({displayName:"DatePickerWeb",mixins:[h["default"]],getDefaultProps:function(){return{prefixCls:"rmc-date-picker",pickerPrefixCls:"rmc-picker",disabled:!1}},render:function(){var e=this,t=this.props,n=t.prefixCls,r=t.pickerPrefixCls,o=t.className,i=t.rootNativeProps,s=t.disabled,u=this.getValueDataSource(),d=u.value,p=u.dataSource,h=p.map(function(t,o){return l.createElement("div",{key:o,className:n+"-item"},l.createElement(c["default"],{disabled:s,prefixCls:r,pure:!1,selectedValue:d[o],onValueChange:function(t){e.onValueChange(o,t)}},t))});return l.createElement("div",(0,a["default"])({},i,{className:(0,f["default"])(o,n)}),h)}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return e.clone().year(t).month(n).endOf("month").date()}Object.defineProperty(t,"__esModule",{value:!0});var i=n(50),a=r(i),s=n(106),l=r(s),u=n(419),c=r(u),d="datetime",f="date",p="time";t["default"]={getDefaultProps:function(){return{locale:c["default"],mode:f,onDateChange:function(){}}},getInitialState:function(){return{date:this.props.date||this.props.defaultDate}},componentWillReceiveProps:function(e){"date"in e&&this.setState({date:e.date||e.defaultDate})},onValueChange:function(e,t){var n=this.props,r=this.getDate().clone();if(n.mode===d||n.mode===f)switch(e){case 0:r.year(t);break;case 1:r.month(t);break;case 2:r.date(t);break;case 3:r.hour(t);break;case 4:r.minute(t)}else switch(e){case 0:r.hour(t);break;case 1:r.minute(t)}r=this.clipDate(r),"date"in this.props||this.setState({date:r}),n.onDateChange(r)},getDefaultMinDate:function(){return this.defaultMinDate||(this.defaultMinDate=this.getGregorianCalendar([2e3,1,1,0,0,0])),this.defaultMinDate},getDefaultMaxDate:function(){return this.defaultMaxDate||(this.defaultMaxDate=this.getGregorianCalendar([2030,1,1,23,59,59])),this.defaultMaxDate},getDate:function(){return this.state.date||this.getDefaultMinDate()},getMinYear:function(){return this.getMinDate().year()},getMaxYear:function(){return this.getMaxDate().year()},getMinMonth:function(){return this.getMinDate().month()},getMaxMonth:function(){return this.getMaxDate().month()},getMinDay:function(){return this.getMinDate().date()},getMaxDay:function(){return this.getMaxDate().date()},getMinHour:function(){return this.getMinDate().hour()},getMaxHour:function(){return this.getMaxDate().hour()},getMinMinute:function(){return this.getMinDate().minute()},getMaxMinute:function(){return this.getMaxDate().minute()},getMinDate:function(){return this.props.minDate||this.getDefaultMinDate()},getMaxDate:function(){return this.props.maxDate||this.getDefaultMaxDate()},getDateData:function(){for(var e=this.props.locale,t=this.getDate(),n=t.year(),r=t.month(),i=this.getMinYear(),a=this.getMaxYear(),s=this.getMinMonth(),l=this.getMaxMonth(),u=this.getMinDay(),c=this.getMaxDay(),d=[],f=i;f<=a;f++)d.push({value:f,label:f+e.year});var p=[],h=0,m=11;i===n&&(h=s),a===n&&(m=l);for(var v=h;v<=m;v++)p.push({value:v,label:v+1+e.month});var y=[],g=1,b=o(t,n,r);i===n&&s===r&&(g=u),a===n&&l===r&&(b=c);for(var _=g;_<=b;_++)y.push({value:_,label:_+e.day});return[d,p,y]},getTimeData:function(){var e=0,t=23,n=0,r=59,o=this.props,i=o.mode,a=o.locale,s=this.getDate(),l=this.getMinMinute(),u=this.getMaxMinute(),c=this.getMinHour(),f=this.getMaxHour(),p=s.hour();if(i===d){var h=s.year(),m=s.month(),v=s.date(),y=this.getMinYear(),g=this.getMaxYear(),b=this.getMinMonth(),_=this.getMaxMonth(),x=this.getMinDay(),T=this.getMaxDay();y===h&&b===m&&x===v&&(e=c,c===p&&(n=l)),g===h&&_===m&&T===v&&(t=f,f===p&&(r=u))}else e=c,c===p&&(n=l),t=f,f===p&&(r=u);for(var C=[],w=e;w<=t;w++)C.push({value:w,label:w+a.hour});for(var S=[],P=n;P<=r;P++)S.push({value:P,label:P+a.minute});return[C,S]},getGregorianCalendar:function(e){return(0,l["default"])(e)},clipDate:function(e){var t=this.props.mode,n=this.getMinDate(),r=this.getMaxDate();if(t===d){if(e.isBefore(n))return n.clone();if(e.isAfter(r))return r.clone()}else if(t===f){if(e.isBefore(n,"day")<0)return n.clone();if(e.isAfter(r,"day")>0)return r.clone()}else{var o=r.hour(),i=r.minute(),a=n.hour(),s=n.minute(),l=e.hour(),u=e.minute();if(l<a||l===a&&u<s)return n.clone();if(l>o||l===o&&u>i)return r.clone()}return e},getValueDataSource:function(){var e=this.props.mode,t=this.getDate(),n=[],r=[];return e!==d&&e!==f||(n=[].concat((0,a["default"])(this.getDateData())),r=[t.year(),t.month(),t.date()]),e!==d&&e!==p||(n=n.concat(this.getTimeData()),r=r.concat([t.hour(),t.minute()])),{value:r,dataSource:n}}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}function i(){}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),s=o(a),l=n(2),u=o(l),c=n(4),d=o(c),f=n(3),p=o(f),h=n(1),m=r(h),v=n(122),y=o(v),g=function(e){function t(n){(0,u["default"])(this,t);var r=(0,d["default"])(this,e.call(this,n));return r.onPickerChange=function(e){r.setState({pickerDate:e}),r.props.datePicker.props.onDateChange&&r.props.datePicker.props.onDateChange(e)},r.onOk=function(){r.props.onChange(r.datePicker.getDate())},r.saveRef=function(e){r.datePicker=e},r.fireVisibleChange=function(e){r.state.visible!==e&&("visible"in r.props||r.setVisibleState(e),r.props.onVisibleChange(e))},r.state={pickerDate:null,visible:r.props.visible||!1},r}return(0,p["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){"visible"in e&&this.setVisibleState(e.visible)},t.prototype.setVisibleState=function(e){this.setState({visible:e}),e||this.setState({pickerDate:null})},t.prototype.render=function(){var e=m.cloneElement(this.props.datePicker,{date:this.state.pickerDate||this.props.date,onDateChange:this.onPickerChange,ref:this.saveRef});return m.createElement(y["default"],(0,s["default"])({},this.props,{onVisibleChange:this.fireVisibleChange,onOk:this.onOk,content:e,visible:this.state.visible}))},t}(m.Component);t["default"]=g,g.defaultProps={onVisibleChange:i,prefixCls:"rmc-picker-popup",onChange:i,onDismiss:i,onPickerChange:i},e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={year:"",month:"",day:"",hour:"",minute:""},e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={year:"\u5e74",month:"\u6708",day:"\u65e5",hour:"\u65f6",minute:"\u5206"},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),i=r(o),a=n(6),s=r(a),l=n(49),u=r(l),c=n(2),d=r(c),f=n(4),p=r(f),h=n(3),m=r(h),v=n(1),y=r(v),g=n(9),b=r(g),_=n(5),x=r(_),T=n(119),C=r(T),w=n(432),S=function(e){function t(n){(0,d["default"])(this,t);var r=(0,p["default"])(this,e.call(this,n));return P.call(r),r.state={pageSize:n.pageSize,_delay:!1},r}return(0,m["default"])(t,e),t.prototype.componentWillReceiveProps=function(e){this.props.dataSource!==e.dataSource&&this.dataChange(e)},t.prototype.componentWillUnmount=function(){this._timer&&clearTimeout(this._timer),this._hCache=null},t.prototype.componentDidMount=function(){this.dataChange(this.props);var e=this.refs.quickSearchBar,t=e.offsetHeight,n=[];[].slice.call(e.querySelectorAll("[data-qf-target]")).forEach(function(e){n.push([e])});for(var r=t/n.length,o=0,i=0,a=n.length;i<a;i++)o=i*r,n[i][1]=[o,o+r];this._qsHeight=t,this._avgH=r,this._hCache=n},t.prototype.renderQuickSearchBar=function(e,t){var n=this,r=this.props,o=r.dataSource,i=r.prefixCls,a=o.sectionIdentities.map(function(e){return{value:e,label:o._getSectionHeaderData(o._dataBlob,e)}});return y["default"].createElement("ul",{ref:"quickSearchBar",className:i+"-quick-search-bar",style:t,onTouchStart:this.onTouchStart,onTouchMove:this.onTouchMove,onTouchEnd:this.onTouchEnd,onTouchCancel:this.onTouchEnd},y["default"].createElement("li",{"data-qf-target":e.value,onClick:function(){return n.onQuickSearchTop(void 0,e.value)}},e.label),a.map(function(e){return y["default"].createElement("li",{key:e.value,"data-qf-target":e.value,onClick:function(){return n.onQuickSearch(e.value)}},e.label)}))},t.prototype.render=function(){var e,t=this,n=this.state,r=n._delay,o=n.pageSize,a=this.props,l=a.className,c=a.prefixCls,d=a.children,f=a.quickSearchBarTop,p=a.quickSearchBarStyle,h=a.initialListSize,m=void 0===h?Math.min(20,this.props.dataSource.getRowCount()):h,v=a.renderSectionHeader,g=(0,u["default"])(a,["className","prefixCls","children","quickSearchBarTop","quickSearchBarStyle","initialListSize","renderSectionHeader"]),b=(0,x["default"])((e={},(0,s["default"])(e,l,l),(0,s["default"])(e,c,!0),e));return y["default"].createElement("div",{className:c+"-container"},r&&this.props.delayActivityIndicator,y["default"].createElement(C["default"],(0,i["default"])({},g,{ref:"indexedListView",className:b,initialListSize:m,pageSize:o,renderSectionHeader:function(e,n){return y["default"].createElement("div",{className:c+"-section-header",ref:function(e){t.sectionComponents[n]=e}},v(e,n))}}),d),this.renderQuickSearchBar(f,p))},t}(y["default"].Component);S.propTypes={prefixCls:v.PropTypes.string,quickSearchBarTop:v.PropTypes.object,onQuickSearch:v.PropTypes.func},S.defaultProps={prefixCls:"am-indexed-list",quickSearchBarTop:{value:"#",label:"#"},onQuickSearch:function(){},delayTime:100,delayActivityIndicator:""};var P=function(){var e=this;this.dataChange=function(t){var n=t.dataSource.getRowCount();n&&(e.setState({_delay:!0}),e._timer&&clearTimeout(e._timer),e._timer=setTimeout(function(){e.setState({pageSize:n,_delay:!1},function(){return e.refs.indexedListView._pageInNewRows()})},t.delayTime))},this.sectionComponents={},this.onQuickSearchTop=function(t,n){e.props.stickyHeader?window.document.body.scrollTop=0:b["default"].findDOMNode(e.refs.indexedListView.refs.listviewscroll).scrollTop=0,e.props.onQuickSearch(t,n)},this.onQuickSearch=function(t){var n=b["default"].findDOMNode(e.refs.indexedListView.refs.listviewscroll),r=b["default"].findDOMNode(e.sectionComponents[t]);if(e.props.stickyHeader){var o=e.refs.indexedListView.stickyRefs[t];o&&o.refs.placeholder&&(r=b["default"].findDOMNode(o.refs.placeholder)),window.document.body.scrollTop=r.getBoundingClientRect().top-n.getBoundingClientRect().top+(0,w.getOffsetTop)(n)}else n.scrollTop+=r.getBoundingClientRect().top-n.getBoundingClientRect().top;e.props.onQuickSearch(t)},this.onTouchStart=function(t){e._target=t.target,e._basePos=e.refs.quickSearchBar.getBoundingClientRect(),document.addEventListener("touchmove",e._disableParent,!1),document.body.className=document.body.className+" "+e.props.prefixCls+"-qsb-moving",e.updateCls(e._target)},this.onTouchMove=function(t){if(t.preventDefault(),e._target){var n=(0,w._event)(t),r=e._basePos,o=void 0;if(n.clientY>=r.top&&n.clientY<=r.top+e._qsHeight){o=Math.floor((n.clientY-r.top)/e._avgH);var i=void 0;if(o in e._hCache&&(i=e._hCache[o][0]),i){var a=i.getAttribute("data-qf-target");e._target!==i&&(e.props.quickSearchBarTop.value===a?e.onQuickSearchTop(void 0,a):e.onQuickSearch(a),e.updateCls(i)),e._target=i}}}},this.onTouchEnd=function(t){e._target&&(document.removeEventListener("touchmove",e._disableParent,!1),document.body.className=document.body.className.replace(new RegExp(e.props.prefixCls+"-qsb-moving","g"),""),e.updateCls(e._target,!0),e._target=null)},this.updateCls=function(t,n){var r=e.props.prefixCls+"-quick-search-bar-over";e._hCache.forEach(function(e){e[0].className=e[0].className.replace(r,"")}),n||(t.className=t.className+" "+r)},this._disableParent=function(e){e.preventDefault(),e.stopPropagation()}};t["default"]=S,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return e[t][n]}function i(e,t){return e[t]}function a(e){for(var t=0,n=0;n<e.length;n++){var r=e[n];t+=r.length}return t}function s(e){if((0,p["default"])(e))return{};for(var t={},n=0;n<e.length;n++){var r=e[n];(0,m["default"])(!t[r],"Value appears more than once in array: "+r),t[r]=!0}return t}var l=n(2),u=r(l),c=n(66),d=r(c),f=n(331),p=r(f),h=n(41),m=r(h),v=function(){function e(t){(0,u["default"])(this,e),(0,d["default"])(t&&"function"==typeof t.rowHasChanged,"Must provide a rowHasChanged function."),this._rowHasChanged=t.rowHasChanged,this._getRowData=t.getRowData||o,this._sectionHeaderHasChanged=t.sectionHeaderHasChanged,this._getSectionHeaderData=t.getSectionHeaderData||i,this._dataBlob=null,this._dirtyRows=[],this._dirtySections=[],this._cachedRowCount=0,this.rowIdentities=[],this.sectionIdentities=[]}return e.prototype.cloneWithRows=function(e,t){var n=t?[t]:null;return this._sectionHeaderHasChanged||(this._sectionHeaderHasChanged=function(){return!1}),this.cloneWithRowsAndSections({s1:e},["s1"],n)},e.prototype.cloneWithRowsAndSections=function(t,n,r){(0,d["default"])("function"==typeof this._sectionHeaderHasChanged,"Must provide a sectionHeaderHasChanged function with section data."),(0,d["default"])(!n||!r||n.length===r.length,"row and section ids lengths must be the same");var o=new e({getRowData:this._getRowData,getSectionHeaderData:this._getSectionHeaderData,rowHasChanged:this._rowHasChanged,sectionHeaderHasChanged:this._sectionHeaderHasChanged});return o._dataBlob=t,n?o.sectionIdentities=n:o.sectionIdentities=Object.keys(t),r?o.rowIdentities=r:(o.rowIdentities=[],o.sectionIdentities.forEach(function(e){o.rowIdentities.push(Object.keys(t[e]))})),o._cachedRowCount=a(o.rowIdentities),o._calculateDirtyArrays(this._dataBlob,this.sectionIdentities,this.rowIdentities),o},e.prototype.getRowCount=function(){return this._cachedRowCount},e.prototype.getRowAndSectionCount=function(){return this._cachedRowCount+this.sectionIdentities.length},e.prototype.rowShouldUpdate=function(e,t){var n=this._dirtyRows[e][t];return(0,m["default"])(void 0!==n,"missing dirtyBit for section, row: "+e+", "+t),n},e.prototype.getRowData=function(e,t){var n=this.sectionIdentities[e],r=this.rowIdentities[e][t];return(0,m["default"])(void 0!==n&&void 0!==r,"rendering invalid section, row: "+e+", "+t),this._getRowData(this._dataBlob,n,r)},e.prototype.getRowIDForFlatIndex=function(e){for(var t=e,n=0;n<this.sectionIdentities.length;n++){if(!(t>=this.rowIdentities[n].length))return this.rowIdentities[n][t];t-=this.rowIdentities[n].length}return null},e.prototype.getSectionIDForFlatIndex=function(e){for(var t=e,n=0;n<this.sectionIdentities.length;n++){if(!(t>=this.rowIdentities[n].length))return this.sectionIdentities[n];t-=this.rowIdentities[n].length}return null},e.prototype.getSectionLengths=function(){for(var e=[],t=0;t<this.sectionIdentities.length;t++)e.push(this.rowIdentities[t].length);return e},e.prototype.sectionHeaderShouldUpdate=function(e){var t=this._dirtySections[e];return(0,m["default"])(void 0!==t,"missing dirtyBit for section: "+e),t},e.prototype.getSectionHeaderData=function(e){if(!this._getSectionHeaderData)return null;var t=this.sectionIdentities[e];return(0,m["default"])(void 0!==t,"renderSection called on invalid section: "+e),this._getSectionHeaderData(this._dataBlob,t)},e.prototype._calculateDirtyArrays=function(e,t,n){for(var r=s(t),o={},i=0;i<n.length;i++){var a=t[i];(0,m["default"])(!o[a],"SectionID appears more than once: "+a),o[a]=s(n[i])}this._dirtySections=[],this._dirtyRows=[];for(var l,u=0;u<this.sectionIdentities.length;u++){var a=this.sectionIdentities[u];l=!r[a];var c=this._sectionHeaderHasChanged;!l&&c&&(l=c(this._getSectionHeaderData(e,a),this._getSectionHeaderData(this._dataBlob,a))),this._dirtySections.push(!!l),this._dirtyRows[u]=[];for(var d=0;d<this.rowIdentities[u].length;d++){var f=this.rowIdentities[u][d];l=!r[a]||!o[a][f]||this._rowHasChanged(this._getRowData(e,a,f),this._getRowData(this._dataBlob,a,f)),this._dirtyRows[u].push(!!l)}}},e}();e.exports=v},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),i=r(o),a=n(49),s=r(a),l=n(2),u=r(l),c=n(4),d=r(c),f=n(3),p=r(f),h=n(1),m=r(h),v=n(9),y=r(v),g=n(120),b=r(g),_=n(425),x=r(_),T=n(431),C=r(T),w=n(116),S=r(w),P=n(72),E=r(P),M=n(105),k=(n(66),"ScrollView"),O="InnerScrollView",N=["padding","paddingTop","paddingBottom","paddingLeft","paddingRight"],D=function(e){function t(){var n,r,o;(0,u["default"])(this,t);for(var i=arguments.length,a=Array(i),s=0;s<i;s++)a[s]=arguments[s];return n=r=(0,d["default"])(this,e.call.apply(e,[this].concat(a))),r.state=r.scrollResponderMixinGetInitialState(),o=n,(0,d["default"])(r,o)}return(0,p["default"])(t,e),t.prototype.componentDidMount=function(){if(!this.props.stickyHeader&&!this.props.useBodyScroll){var e=y["default"].findDOMNode(this.refs[k]);this.__handleScroll=this._handleScroll(),e.addEventListener("scroll",this.__handleScroll)}},t.prototype.componentWillUnmount=function(){if(!this.props.stickyHeader&&!this.props.useBodyScroll){var e=y["default"].findDOMNode(this.refs[k]);e.removeEventListener("scroll",this.__handleScroll)}},t.prototype.getScrollResponder=function(){return this},t.prototype.getInnerViewNode=function(){return this.refs[O]},t.prototype.scrollTo=function(e,t){this.scrollWithoutAnimationTo(e,t)},t.prototype.scrollWithoutAnimationTo=function(e,t){var n=y["default"].findDOMNode(this.refs[k]);n.scrollTop=e||0,n.scrollLeft=t||0},t.prototype._handleScroll=function(e){var t=function(){};return this.props.scrollEventThrottle&&this.props.onScroll&&(t=M(this.handleScroll,this.props.scrollEventThrottle)),t},t.prototype.handleScroll=function(e){this.props.onScroll&&this.props.onScroll(e)},t.prototype.render=function(){for(var e=this.props,t=e.style,n=void 0===t?{}:t,r=(0,s["default"])(e,["style"]),o={},a=0;a<N.length;a++)"number"==typeof n[N[a]]&&(o[N[a]]=n[N[a]]);var l=[R.contentContainer,this.props.horizontal&&R.contentContainerHorizontal,this.props.contentContainerStyle,o],u={},c=m["default"].createElement(C["default"],(0,i["default"])({},u,{ref:O,style:x["default"].flattenStyle(l),removeClippedSubviews:this.props.removeClippedSubviews,collapsable:!1}),this.props.children),d=void 0!==this.props.alwaysBounceHorizontal?this.props.alwaysBounceHorizontal:this.props.horizontal,f=void 0!==this.props.alwaysBounceVertical?this.props.alwaysBounceVertical:!this.props.horizontal,p=(0,i["default"])({},r,{alwaysBounceHorizontal:d,alwaysBounceVertical:f,style:x["default"].flattenStyle([r.stickyHeader||r.useBodyScroll?null:R.base,this.props.style]),onTouchStart:this.scrollResponderHandleTouchStart,onTouchMove:this.scrollResponderHandleTouchMove,onTouchEnd:this.scrollResponderHandleTouchEnd,onScrollBeginDrag:this.scrollResponderHandleScrollBeginDrag,onScrollEndDrag:this.scrollResponderHandleScrollEndDrag,onMomentumScrollBegin:this.scrollResponderHandleMomentumScrollBegin,onMomentumScrollEnd:this.scrollResponderHandleMomentumScrollEnd,onStartShouldSetResponder:this.scrollResponderHandleStartShouldSetResponder,onStartShouldSetResponderCapture:this.scrollResponderHandleStartShouldSetResponderCapture,onResponderGrant:this.scrollResponderHandleResponderGrant,onResponderTerminationRequest:this.scrollResponderHandleTerminationRequest,onResponderTerminate:this.scrollResponderHandleTerminate,onResponderRelease:this.scrollResponderHandleResponderRelease,onResponderReject:this.scrollResponderHandleResponderReject});delete p.onScroll;var h=this.props.decelerationRate;h&&(p.decelerationRate=processDecelerationRate(h));var v=C["default"],y=this.props.refreshControl;return y?p.stickyHeader||p.useBodyScroll?m["default"].createElement(v,(0,i["default"])({},p,{ref:k}),y,this.props.children):m["default"].createElement(v,(0,i["default"])({},p,{ref:k}),y,c):p.stickyHeader||p.useBodyScroll?m["default"].createElement(v,(0,i["default"])({},p,{ref:k}),this.props.children):m["default"].createElement(v,(0,i["default"])({},p,{ref:k}),c)},t}(m["default"].Component);D.propTypes={automaticallyAdjustContentInsets:h.PropTypes.bool,bounces:h.PropTypes.bool,bouncesZoom:h.PropTypes.bool,alwaysBounceHorizontal:h.PropTypes.bool,alwaysBounceVertical:h.PropTypes.bool,centerContent:h.PropTypes.bool,decelerationRate:h.PropTypes.number,horizontal:h.PropTypes.bool,directionalLockEnabled:h.PropTypes.bool,canCancelContentTouches:h.PropTypes.bool,keyboardDismissMode:h.PropTypes.oneOf(["none","interactive","on-drag"]),keyboardShouldPersistTaps:h.PropTypes.bool,maximumZoomScale:h.PropTypes.number,minimumZoomScale:h.PropTypes.number,onScroll:h.PropTypes.func,onScrollAnimationEnd:h.PropTypes.func,pagingEnabled:h.PropTypes.bool,scrollEnabled:h.PropTypes.bool,scrollEventThrottle:h.PropTypes.number,scrollsToTop:h.PropTypes.bool,showsHorizontalScrollIndicator:h.PropTypes.bool,showsVerticalScrollIndicator:h.PropTypes.bool,stickyHeaderIndices:h.PropTypes.arrayOf(h.PropTypes.number),snapToInterval:h.PropTypes.number,snapToAlignment:h.PropTypes.oneOf(["start","center","end"]),removeClippedSubviews:h.PropTypes.bool,zoomScale:h.PropTypes.number,refreshControl:h.PropTypes.element};var R=x["default"].create({base:{position:"relative",overflow:"auto",WebkitOverflowScrolling:"touch",flex:1},contentContainer:{position:"absolute",minWidth:"100%"},contentContainerHorizontal:{alignSelf:"flex-start",flexDirection:"row"}});(0,S["default"])(D.prototype,b["default"].Mixin),(0,E["default"])(D),D.isReactNativeComponent=!0,t["default"]=D,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),i=r(o),a=n(4),s=r(a),l=n(3),u=r(l),c=n(1),d=r(c),f=function(e){function t(){return(0,i["default"])(this,t),(0,s["default"])(this,e.apply(this,arguments))}return(0,u["default"])(t,e),t.prototype.shouldComponentUpdate=function(e){return e.shouldUpdate},t.prototype.render=function(){return this.props.render()},t}(d["default"].Component);f.propTypes={shouldUpdate:c.PropTypes.bool.isRequired,render:c.PropTypes.func.isRequired},t["default"]=f,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={create:function(e){return e},flattenStyle:function n(e,t){if(e){if(!Array.isArray(e))return t&&t(e)||e;for(var r={},o=0;o<e.length;++o){var i=n(e[o]);if(i)for(var a in i)i.hasOwnProperty(a)&&(r[a]=i[a])}return t&&t(r)||r}}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=n(1),i=(r(o),n(9)),a=r(i),s=n(429),l=r(s),u={getInitialState:function(){return{layout:{}}},componentDidMount:function(){this.layoutHandle()},componentDidUpdate:function(){this.layoutHandle()},layoutHandle:function(){if(this.props.onLayout){var e=(0,l["default"])(a["default"].findDOMNode(this)),t=this.state.layout;t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height||(this.props.onLayout({nativeEvent:{layout:e}}),this.setState({layout:e}))}}};e.exports={Mixin:u}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=n(428),i=r(o),a=n(9),s=r(a),l=n(430),u=r(l),c={measure:function(e){i["default"].measure(s["default"].findDOMNode(this),d(this,e))},measureLayout:function(e,t,n){i["default"].measureLayout(s["default"].findDOMNode(this),e,d(this,n),d(this,t))},setNativeProps:function(e){(0,u["default"])(s["default"].findDOMNode(this),e)},focus:function(){s["default"].findDOMNode(this).focus()},blur:function(){s["default"].findDOMNode(this).blur()}},d=function(e,t){return function(){if(t&&(!e.isMounted||e.isMounted()))return t.apply(e,arguments)}};e.exports={Mixin:c}},function(e,t){"use strict";var n={measure:function(e,t){var n=e.getBoundingClientRect();t(0,0,n.width,n.height,n.left,n.top)},measureLayout:function(e,t,n,r){var o=e.getBoundingClientRect(),i=t.getBoundingClientRect();r(o.left-i.left,o.top-i.top,o.width,o.height)}};e.exports=n},function(e,t){"use strict";function n(e){var t,n;if(t=n=0,e.offsetParent)do t+=e.offsetLeft,n+=e.offsetTop;while(e=e.offsetParent);return{x:t,y:n}}function r(e){var t=n(e);return{x:t.x,y:t.y,width:e.offsetWidth,height:e.offsetHeight}}e.exports=r},function(e,t,n){"use strict";function r(e){var t={};for(var n in e)"transformMatrix"===n?t.transform="matrix3d("+e[n].join(",")+") ":t[n]=e[n];return t}function o(e,t){for(var n in t)if("style"===n){var o=t[n];"transformMatrix"in o&&(o=r(o)),i.setValueForStyles(e,o)}else e.setAttribute(n,t[n])}var i=n(408);e.exports=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),a=n(426),s=n(427),l=i["default"].createClass({displayName:"View",mixins:[a.Mixin,s.Mixin],propTypes:{accessible:o.PropTypes.bool,accessibilityLabel:o.PropTypes.string,onAccessibilityTap:o.PropTypes.func,onMagicTap:o.PropTypes.func,testID:o.PropTypes.string,onResponderGrant:o.PropTypes.func,onResponderMove:o.PropTypes.func,onResponderReject:o.PropTypes.func,onResponderRelease:o.PropTypes.func,onResponderTerminate:o.PropTypes.func,onResponderTerminationRequest:o.PropTypes.func,onStartShouldSetResponder:o.PropTypes.func,onStartShouldSetResponderCapture:o.PropTypes.func,onMoveShouldSetResponder:o.PropTypes.func,onMoveShouldSetResponderCapture:o.PropTypes.func,onLayout:o.PropTypes.func,pointerEvents:o.PropTypes.oneOf(["box-none","none","box-only","auto"]),style:o.PropTypes.oneOfType([o.PropTypes.object,o.PropTypes.array]),removeClippedSubviews:o.PropTypes.bool},render:function(){var e=this.props,t=e.children,n=e.className,r=e.style,o=e.onScroll,a=e.onCick,s=void 0===a?function(){}:a,l={className:n,style:r,onScroll:o,onClick:s};return i["default"].createElement("div",l,t)}});l.isReactNativeComponent=!0,t["default"]=l,e.exports=t["default"]},function(e,t){"use strict";function n(e){var t=0;do isNaN(e.offsetTop)||(t+=e.offsetTop);while(e=e.offsetParent);return t}function r(e){return e.touches&&e.touches.length?e.touches[0]:e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:e}Object.defineProperty(t,"__esModule",{value:!0}),t.getOffsetTop=n,t._event=r;var o=t.isTouchable="ontouchstart"in window;t.START=o?"touchstart":"mousedown",t.MOVE=o?"touchmove":"mousemove",t.END=o?"touchend":"mouseup",t.CANCEL=o?"touchcancel":"mousecancel",t.CLICK=o?"touchstart":"click",/Android[^\d]*(1|2|3|4\.0)/.test(window.navigator.appVersion)||/iPhone[^\d]*(5)/.test(window.navigator.appVersion)},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),a=r(i);t["default"]={getDefaultProps:function(){return{onVisibleChange:o,okText:"Ok",dismissText:"Dismiss",title:"",onOk:o,onDismiss:o}},getInitialState:function(){return{visible:this.props.visible||!1}},componentWillReceiveProps:function(e){"visible"in e&&this.setVisibleState(e.visible)},setVisibleState:function(e){this.setState({visible:e})},fireVisibleChange:function(e){this.state.visible!==e&&("visible"in this.props||this.setVisibleState(e),this.props.onVisibleChange(e))},getRender:function(){var e=this.props,t=e.children;if(!t)return this.getModal();var n=this.props,r=n.WrapComponent,o=n.disabled,i=t,s={};return o||(s[e.triggerType]=this.onTriggerClick),a.createElement(r,{style:e.wrapStyle},a.cloneElement(i,s),this.getModal())},onTriggerClick:function(e){var t=this.props.children,n=t.props||{};n[this.props.triggerType]&&n[this.props.triggerType](e),this.fireVisibleChange(!this.state.visible)},onOk:function(){this.props.onOk(),this.fireVisibleChange(!1)},onDismiss:function(){this.props.onDismiss(),this.fireVisibleChange(!1)},hide:function(){this.fireVisibleChange(!1)}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(121);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r(o)["default"]}}),e.exports=t["default"]},function(e,t){"use strict";function n(e){return!e||!e.length}function r(e,t,r){if(n(e)&&n(t))return!0;if(r)return e===t;if(e.length!==t.length)return!1;for(var o=e.length,i=0;i<o;i++)if(e[i].value!==t[i].value||e[i].label!==t[i].label)return!1;return!0}Object.defineProperty(t,"__esModule",{value:!0}),t.isEmptyArray=n,t["default"]=r},function(e,t){function n(e){return Object.prototype.toString.call(e)}function r(e){return e}function o(e){return"function"!=typeof e?e:function(){return e.apply(this,arguments)}}function i(e,t,n){t in e?e[t]=n:Object.defineProperty(e,t,{value:n,writable:!0,configurable:!0})}function a(e,t,r){if(void 0!==e&&void 0!==t){var o=function(e){return e&&e.constructor&&e.constructor.name?e.constructor.name:n(e).slice(8,-1)};throw new TypeError("Cannot mixin key "+r+" because it is provided by multiple sources, and the types are "+o(e)+" and "+o(t))}return void 0===e?t:e}function s(e,t){var r=n(e);if("[object Object]"!==r){var o=e.constructor?e.constructor.name:"Unknown",i=t.constructor?t.constructor.name:"Unknown";throw new Error("cannot merge returned value of type "+o+" with an "+i)}}var l=e.exports=function(e,t){var n=t||{};return n.unknownFunction||(n.unknownFunction=l.ONCE),n.nonFunctionProperty||(n.nonFunctionProperty=a),function(t,r){Object.keys(r).forEach(function(a){var s=t[a],l=r[a],u=e[a];if(void 0!==s||void 0!==l){if(u){var c=u(s,l,a);return void i(t,a,o(c))}var d="function"==typeof s,f="function"==typeof l;return d&&void 0===l||f&&void 0===s||d&&f?void i(t,a,o(n.unknownFunction(s,l,a))):void(t[a]=n.nonFunctionProperty(s,l,a))}})}};l._mergeObjects=function(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);s(e,t),s(t,e);var n={};return Object.keys(e).forEach(function(r){if(Object.prototype.hasOwnProperty.call(t,r))throw new Error("cannot merge returns because both have the "+JSON.stringify(r)+" key");n[r]=e[r]}),Object.keys(t).forEach(function(e){n[e]=t[e]}),n},l.ONCE=function(e,t,n){if(e&&t)throw new TypeError("Cannot mixin "+n+" because it has a unique constraint.");return e||t},l.MANY=function(e,t,n){return function(){return t&&t.apply(this,arguments),
e?e.apply(this,arguments):void 0}},l.MANY_MERGED_LOOSE=function(e,t,n){return e&&t?l._mergeObjects(e,t):e||t},l.MANY_MERGED=function(e,t,n){return function(){var n=t&&t.apply(this,arguments),r=e&&e.apply(this,arguments);return n&&r?l._mergeObjects(n,r):r||n}},l.REDUCE_LEFT=function(e,t,n){var o=e||r,i=t||r;return function(){return i.call(this,o.apply(this,arguments))}},l.REDUCE_RIGHT=function(e,t,n){var o=e||r,i=t||r;return function(){return o.call(this,i.apply(this,arguments))}}},function(e,t,n){"use strict";var r=function(){};e.exports=r},function(e,t,n){"use strict";function r(e,t){e.transform=t,e.webkitTransform=t,e.MozTransform=t}function o(e,t){e.transformOrigin=t,e.webkitTransformOrigin=t,e.MozTransformOrigin=t}function i(e){var t=this,n=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],i=void 0,u=void 0,c=void 0,d=void 0,f=void 0,p=void 0,h=void 0,m=void 0;this.content=e,this.container=e.parentNode,this.options=a({},n,{scrollingComplete:function(){t.clearScrollbarTimer(),t.timer=setTimeout(function(){n.scrollingComplete&&n.scrollingComplete(),i&&["x","y"].forEach(function(e){i[e]&&t.setScrollbarOpacity(e,0)})},0)}}),this.options.scrollbars&&(i=this.scrollbars={},u=this.indicators={},c=this.indicatorsSize={},d=this.scrollbarsSize={},f=this.indicatorsPos={},p=this.scrollbarsOpacity={},h=this.contentSize={},m=this.clientSize={},["x","y"].forEach(function(e){var n="x"===e?"scrollingX":"scrollingY";t.options[n]!==!1&&(i[e]=document.createElement("div"),i[e].className="zscroller-scrollbar-"+e,u[e]=document.createElement("div"),u[e].className="zscroller-indicator-"+e,i[e].appendChild(u[e]),c[e]=-1,p[e]=0,f[e]=0,t.container.appendChild(i[e]))}));var v=!0,y=e.style;this.scroller=new s(function(e,o,a){!v&&n.onScroll&&n.onScroll(),r(y,"translate3d("+-e+"px,"+-o+"px,0) scale("+a+")"),i&&["x","y"].forEach(function(n){if(i[n]){var r="x"===n?e:o;if(m[n]>=h[n])t.setScrollbarOpacity(n,0);else{v||t.setScrollbarOpacity(n,1);var a=m[n]/h[n]*d[n],s=a,u=void 0;r<0?(s=Math.max(a+r,l),u=0):r>h[n]-m[n]?(s=Math.max(a+h[n]-m[n]-r,l),u=d[n]-s):u=r/h[n]*d[n],t.setIndicatorSize(n,s),t.setIndicatorPos(n,u)}}}),v=!1},this.options),this.bindEvents(),o(e.style,"left top"),this.reflow()}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(440),l=8;i.prototype.setDisabled=function(e){this.disabled=e},i.prototype.clearScrollbarTimer=function(){this.timer&&(clearTimeout(this.timer),this.timer=null)},i.prototype.setScrollbarOpacity=function(e,t){this.scrollbarsOpacity[e]!==t&&(this.scrollbars[e].style.opacity=t,this.scrollbarsOpacity[e]=t)},i.prototype.setIndicatorPos=function(e,t){this.indicatorsPos[e]!==t&&("x"===e?r(this.indicators[e].style,"translate3d("+t+"px,0,0)"):r(this.indicators[e].style,"translate3d(0, "+t+"px,0)"),this.indicatorsPos[e]=t)},i.prototype.setIndicatorSize=function(e,t){this.indicatorsSize[e]!==t&&(this.indicators[e].style["x"===e?"width":"height"]=t+"px",this.indicatorsSize[e]=t)},i.prototype.reflow=function(){this.scrollbars&&(this.contentSize.x=this.content.offsetWidth,this.contentSize.y=this.content.offsetHeight,this.clientSize.x=this.container.clientWidth,this.clientSize.y=this.container.clientHeight,this.scrollbars.x&&(this.scrollbarsSize.x=this.scrollbars.x.offsetWidth),this.scrollbars.y&&(this.scrollbarsSize.y=this.scrollbars.y.offsetHeight)),this.scroller.setDimensions(this.container.clientWidth,this.container.clientHeight,this.content.offsetWidth,this.content.offsetHeight);var e=this.container.getBoundingClientRect();this.scroller.setPosition(e.x+this.container.clientLeft,e.y+this.container.clientTop)},i.prototype.destroy=function(){window.removeEventListener("resize",this.onResize,!1),this.container.removeEventListener("touchstart",this.onTouchStart,!1),this.container.removeEventListener("touchmove",this.onTouchMove,!1),this.container.removeEventListener("touchend",this.onTouchEnd,!1),this.container.removeEventListener("touchcancel",this.onTouchCancel,!1),this.container.removeEventListener("mousedown",this.onMouseDown,!1),document.removeEventListener("mousemove",this.onMouseMove,!1),document.removeEventListener("mouseup",this.onMouseUp,!1),this.container.removeEventListener("mousewheel",this.onMouseWheel,!1)},i.prototype.bindEvents=function(){var e=this,t=this;window.addEventListener("resize",this.onResize=function(){t.reflow()},!1),"ontouchstart"in window?(this.container.addEventListener("touchstart",this.onTouchStart=function(n){n.touches[0]&&n.touches[0].target&&n.touches[0].target.tagName.match(/input|textarea|select/i)||e.disabled||(e.clearScrollbarTimer(),t.reflow(),t.scroller.doTouchStart(n.touches,n.timeStamp))},!1),this.container.addEventListener("touchmove",this.onTouchMove=function(e){e.preventDefault(),t.scroller.doTouchMove(e.touches,e.timeStamp,e.scale)},!1),this.container.addEventListener("touchend",this.onTouchEnd=function(e){t.scroller.doTouchEnd(e.timeStamp)},!1),this.container.addEventListener("touchcancel",this.onTouchCancel=function(e){t.scroller.doTouchEnd(e.timeStamp)},!1)):!function(){var n=!1;e.container.addEventListener("mousedown",e.onMouseDown=function(r){r.target.tagName.match(/input|textarea|select/i)||e.disabled||(e.clearScrollbarTimer(),t.scroller.doTouchStart([{pageX:r.pageX,pageY:r.pageY}],r.timeStamp),n=!0,t.reflow(),r.preventDefault())},!1),document.addEventListener("mousemove",e.onMouseMove=function(e){n&&(t.scroller.doTouchMove([{pageX:e.pageX,pageY:e.pageY}],e.timeStamp),n=!0)},!1),document.addEventListener("mouseup",e.onMouseUp=function(e){n&&(t.scroller.doTouchEnd(e.timeStamp),n=!1)},!1),e.container.addEventListener("mousewheel",e.onMouseWheel=function(e){t.options.zooming&&(t.scroller.doMouseZoom(e.wheelDelta,e.timeStamp,e.pageX,e.pageY),e.preventDefault())},!1)}()},e.exports=i},function(e,t){(function(t){var n=60,r=1e3,o={},i=1,a=void 0!==typeof window?window:void 0;a||(a=void 0!==typeof t?t:{});var s={requestAnimationFrame:function(){var e=a.requestAnimationFrame||a.webkitRequestAnimationFrame||a.mozRequestAnimationFrame||a.oRequestAnimationFrame,t=!!e;if(e&&!/requestAnimationFrame\(\)\s*\{\s*\[native code\]\s*\}/i.test(e.toString())&&(t=!1),t)return function(t,n){e(t,n)};var n=60,r={},o=0,i=1,s=null,l=+new Date;return function(e,t){var a=i++;return r[a]=e,o++,null===s&&(s=setInterval(function(){var e=+new Date,t=r;r={},o=0;for(var n in t)t.hasOwnProperty(n)&&(t[n](e),l=e);e-l>2500&&(clearInterval(s),s=null)},1e3/n)),a}}(),stop:function(e){var t=null!=o[e];return t&&(o[e]=null),t},isRunning:function(e){return null!=o[e]},start:function(e,t,a,l,u,c){var d=+new Date,f=d,p=0,h=0,m=i++;if(c||(c=document.body),m%20===0){var v={};for(var y in o)v[y]=!0;o=v}var g=function(i){var v=i!==!0,y=+new Date;if(!o[m]||t&&!t(m))return o[m]=null,void(a&&a(n-h/((y-d)/r),m,!1));if(v)for(var b=Math.round((y-f)/(r/n))-1,_=0;_<Math.min(b,4);_++)g(!0),h++;l&&(p=(y-d)/l,p>1&&(p=1));var x=u?u(p):p;e(x,y,v)!==!1&&1!==p||!v?v&&(f=y,s.requestAnimationFrame(g,c)):(o[m]=null,a&&a(n-h/((y-d)/r),m,1===p||null==l))};return o[m]=!0,s.requestAnimationFrame(g,c),m}};e.exports=s}).call(t,function(){return this}())},function(e,t,n){var r,o=n(439),i=function(){};r=function(e,t){this.__callback=e,this.options={scrollingX:!0,scrollingY:!0,animating:!0,animationDuration:250,bouncing:!0,locking:!0,paging:!1,snapping:!1,zooming:!1,minZoom:.5,maxZoom:3,speedMultiplier:1,scrollingComplete:i,penetrationDeceleration:.03,penetrationAcceleration:.08};for(var n in t)this.options[n]=t[n]};var a=function(e){return Math.pow(e-1,3)+1},s=function(e){return(e/=.5)<1?.5*Math.pow(e,3):.5*(Math.pow(e-2,3)+2)},l={__isSingleTouch:!1,__isTracking:!1,__didDecelerationComplete:!1,__isGesturing:!1,__isDragging:!1,__isDecelerating:!1,__isAnimating:!1,__clientLeft:0,__clientTop:0,__clientWidth:0,__clientHeight:0,__contentWidth:0,__contentHeight:0,__snapWidth:100,__snapHeight:100,__refreshHeight:null,__refreshActive:!1,__refreshActivate:null,__refreshDeactivate:null,__refreshStart:null,__zoomLevel:1,__scrollLeft:0,__scrollTop:0,__maxScrollLeft:0,__maxScrollTop:0,__scheduledLeft:0,__scheduledTop:0,__scheduledZoom:0,__lastTouchLeft:null,__lastTouchTop:null,__lastTouchMove:null,__positions:null,__minDecelerationScrollLeft:null,__minDecelerationScrollTop:null,__maxDecelerationScrollLeft:null,__maxDecelerationScrollTop:null,__decelerationVelocityX:null,__decelerationVelocityY:null,setDimensions:function(e,t,n,r){var o=this;e===+e&&(o.__clientWidth=e),t===+t&&(o.__clientHeight=t),n===+n&&(o.__contentWidth=n),r===+r&&(o.__contentHeight=r),o.__computeScrollMax(),o.scrollTo(o.__scrollLeft,o.__scrollTop,!0)},setPosition:function(e,t){var n=this;n.__clientLeft=e||0,n.__clientTop=t||0},setSnapSize:function(e,t){var n=this;n.__snapWidth=e,n.__snapHeight=t},activatePullToRefresh:function(e,t,n,r){var o=this;o.__refreshHeight=e,o.__refreshActivate=t,o.__refreshDeactivate=n,o.__refreshStart=r},triggerPullToRefresh:function(){this.__publish(this.__scrollLeft,-this.__refreshHeight,this.__zoomLevel,!0),this.__refreshStart&&this.__refreshStart()},finishPullToRefresh:function(){var e=this;e.__refreshActive=!1,e.__refreshDeactivate&&e.__refreshDeactivate(),e.scrollTo(e.__scrollLeft,e.__scrollTop,!0)},getValues:function(){var e=this;return{left:e.__scrollLeft,top:e.__scrollTop,zoom:e.__zoomLevel}},getScrollMax:function(){var e=this;return{left:e.__maxScrollLeft,top:e.__maxScrollTop}},zoomTo:function(e,t,n,r,i){var a=this;if(!a.options.zooming)throw new Error("Zooming is not enabled!");i&&(a.__zoomComplete=i),a.__isDecelerating&&(o.stop(a.__isDecelerating),a.__isDecelerating=!1);var s=a.__zoomLevel;null==n&&(n=a.__clientWidth/2),null==r&&(r=a.__clientHeight/2),e=Math.max(Math.min(e,a.options.maxZoom),a.options.minZoom),a.__computeScrollMax(e);var l=(n+a.__scrollLeft)*e/s-n,u=(r+a.__scrollTop)*e/s-r;l>a.__maxScrollLeft?l=a.__maxScrollLeft:l<0&&(l=0),u>a.__maxScrollTop?u=a.__maxScrollTop:u<0&&(u=0),a.__publish(l,u,e,t)},zoomBy:function(e,t,n,r,o){var i=this;i.zoomTo(i.__zoomLevel*e,t,n,r,o)},scrollTo:function(e,t,n,r,i){var a=this;if(a.__isDecelerating&&(o.stop(a.__isDecelerating),a.__isDecelerating=!1),null!=r&&r!==a.__zoomLevel){if(!a.options.zooming)throw new Error("Zooming is not enabled!");e*=r,t*=r,a.__computeScrollMax(r)}else r=a.__zoomLevel;a.options.scrollingX?a.options.paging?e=Math.round(e/a.__clientWidth)*a.__clientWidth:a.options.snapping&&(e=Math.round(e/a.__snapWidth)*a.__snapWidth):e=a.__scrollLeft,a.options.scrollingY?a.options.paging?t=Math.round(t/a.__clientHeight)*a.__clientHeight:a.options.snapping&&(t=Math.round(t/a.__snapHeight)*a.__snapHeight):t=a.__scrollTop,e=Math.max(Math.min(a.__maxScrollLeft,e),0),t=Math.max(Math.min(a.__maxScrollTop,t),0),e===a.__scrollLeft&&t===a.__scrollTop&&(n=!1,i&&i()),a.__isTracking||a.__publish(e,t,r,n)},scrollBy:function(e,t,n){var r=this,o=r.__isAnimating?r.__scheduledLeft:r.__scrollLeft,i=r.__isAnimating?r.__scheduledTop:r.__scrollTop;r.scrollTo(o+(e||0),i+(t||0),n)},doMouseZoom:function(e,t,n,r){var o=this,i=e>0?.97:1.03;return o.zoomTo(o.__zoomLevel*i,!1,n-o.__clientLeft,r-o.__clientTop)},doTouchStart:function(e,t){if(null==e.length)throw new Error("Invalid touch list: "+e);if(t instanceof Date&&(t=t.valueOf()),"number"!=typeof t)throw new Error("Invalid timestamp value: "+t);var n=this;n.__interruptedAnimation=!0,n.__isDecelerating&&(o.stop(n.__isDecelerating),n.__isDecelerating=!1,n.__interruptedAnimation=!0),n.__isAnimating&&(o.stop(n.__isAnimating),n.__isAnimating=!1,n.__interruptedAnimation=!0);var r,i,a=1===e.length;a?(r=e[0].pageX,i=e[0].pageY):(r=Math.abs(e[0].pageX+e[1].pageX)/2,i=Math.abs(e[0].pageY+e[1].pageY)/2),n.__initialTouchLeft=r,n.__initialTouchTop=i,n.__zoomLevelStart=n.__zoomLevel,n.__lastTouchLeft=r,n.__lastTouchTop=i,n.__lastTouchMove=t,n.__lastScale=1,n.__enableScrollX=!a&&n.options.scrollingX,n.__enableScrollY=!a&&n.options.scrollingY,n.__isTracking=!0,n.__didDecelerationComplete=!1,n.__isDragging=!a,n.__isSingleTouch=a,n.__positions=[]},doTouchMove:function(e,t,n){if(null==e.length)throw new Error("Invalid touch list: "+e);if(t instanceof Date&&(t=t.valueOf()),"number"!=typeof t)throw new Error("Invalid timestamp value: "+t);var r=this;if(r.__isTracking){var o,i;2===e.length?(o=Math.abs(e[0].pageX+e[1].pageX)/2,i=Math.abs(e[0].pageY+e[1].pageY)/2):(o=e[0].pageX,i=e[0].pageY);var a=r.__positions;if(r.__isDragging){var s=o-r.__lastTouchLeft,l=i-r.__lastTouchTop,u=r.__scrollLeft,c=r.__scrollTop,d=r.__zoomLevel;if(null!=n&&r.options.zooming){var f=d;if(d=d/r.__lastScale*n,d=Math.max(Math.min(d,r.options.maxZoom),r.options.minZoom),f!==d){var p=o-r.__clientLeft,h=i-r.__clientTop;u=(p+u)*d/f-p,c=(h+c)*d/f-h,r.__computeScrollMax(d)}}if(r.__enableScrollX){u-=s*this.options.speedMultiplier;var m=r.__maxScrollLeft;(u>m||u<0)&&(r.options.bouncing?u+=s/2*this.options.speedMultiplier:u=u>m?m:0)}if(r.__enableScrollY){c-=l*this.options.speedMultiplier;var v=r.__maxScrollTop;(c>v||c<0)&&(r.options.bouncing?(c+=l/2*this.options.speedMultiplier,r.__enableScrollX||null==r.__refreshHeight||(!r.__refreshActive&&c<=-r.__refreshHeight?(r.__refreshActive=!0,r.__refreshActivate&&r.__refreshActivate()):r.__refreshActive&&c>-r.__refreshHeight&&(r.__refreshActive=!1,r.__refreshDeactivate&&r.__refreshDeactivate()))):c=c>v?v:0)}a.length>60&&a.splice(0,30),a.push(u,c,t),r.__publish(u,c,d)}else{var y=r.options.locking?3:0,g=5,b=Math.abs(o-r.__initialTouchLeft),_=Math.abs(i-r.__initialTouchTop);r.__enableScrollX=r.options.scrollingX&&b>=y,r.__enableScrollY=r.options.scrollingY&&_>=y,a.push(r.__scrollLeft,r.__scrollTop,t),r.__isDragging=(r.__enableScrollX||r.__enableScrollY)&&(b>=g||_>=g),r.__isDragging&&(r.__interruptedAnimation=!1)}r.__lastTouchLeft=o,r.__lastTouchTop=i,r.__lastTouchMove=t,r.__lastScale=n}},doTouchEnd:function(e){if(e instanceof Date&&(e=e.valueOf()),"number"!=typeof e)throw new Error("Invalid timestamp value: "+e);var t=this;if(t.__isTracking){if(t.__isTracking=!1,t.__isDragging)if(t.__isDragging=!1,t.__isSingleTouch&&t.options.animating&&e-t.__lastTouchMove<=100){for(var n=t.__positions,r=n.length-1,o=r,i=r;i>0&&n[i]>t.__lastTouchMove-100;i-=3)o=i;if(o!==r){var a=n[r]-n[o],s=t.__scrollLeft-n[o-2],l=t.__scrollTop-n[o-1];t.__decelerationVelocityX=s/a*(1e3/60),t.__decelerationVelocityY=l/a*(1e3/60);var u=t.options.paging||t.options.snapping?4:1;Math.abs(t.__decelerationVelocityX)>u||Math.abs(t.__decelerationVelocityY)>u?t.__refreshActive||t.__startDeceleration(e):t.options.scrollingComplete()}else t.options.scrollingComplete()}else e-t.__lastTouchMove>100&&t.options.scrollingComplete();t.__isDecelerating||(t.__refreshActive&&t.__refreshStart?(t.__publish(t.__scrollLeft,-t.__refreshHeight,t.__zoomLevel,!0),t.__refreshStart&&t.__refreshStart()):((t.__interruptedAnimation||t.__isDragging)&&t.options.scrollingComplete(),t.scrollTo(t.__scrollLeft,t.__scrollTop,!0,t.__zoomLevel),t.__refreshActive&&(t.__refreshActive=!1,t.__refreshDeactivate&&t.__refreshDeactivate()))),t.__positions.length=0}},__publish:function(e,t,n,r){var i=this,l=i.__isAnimating;if(l&&(o.stop(l),i.__isAnimating=!1),r&&i.options.animating){i.__scheduledLeft=e,i.__scheduledTop=t,i.__scheduledZoom=n;var u=i.__scrollLeft,c=i.__scrollTop,d=i.__zoomLevel,f=e-u,p=t-c,h=n-d,m=function(e,t,n){n&&(i.__scrollLeft=u+f*e,i.__scrollTop=c+p*e,i.__zoomLevel=d+h*e,i.__callback&&i.__callback(i.__scrollLeft,i.__scrollTop,i.__zoomLevel))},v=function(e){return i.__isAnimating===e},y=function(e,t,n){t===i.__isAnimating&&(i.__isAnimating=!1),(i.__didDecelerationComplete||n)&&i.options.scrollingComplete(),i.options.zooming&&(i.__computeScrollMax(),i.__zoomComplete&&(i.__zoomComplete(),i.__zoomComplete=null))};i.__isAnimating=o.start(m,v,y,i.options.animationDuration,l?a:s)}else i.__scheduledLeft=i.__scrollLeft=e,i.__scheduledTop=i.__scrollTop=t,i.__scheduledZoom=i.__zoomLevel=n,i.__callback&&i.__callback(e,t,n),i.options.zooming&&(i.__computeScrollMax(),i.__zoomComplete&&(i.__zoomComplete(),i.__zoomComplete=null))},__computeScrollMax:function(e){var t=this;null==e&&(e=t.__zoomLevel),t.__maxScrollLeft=Math.max(t.__contentWidth*e-t.__clientWidth,0),t.__maxScrollTop=Math.max(t.__contentHeight*e-t.__clientHeight,0)},__startDeceleration:function(e){var t=this;if(t.options.paging){var n=Math.max(Math.min(t.__scrollLeft,t.__maxScrollLeft),0),r=Math.max(Math.min(t.__scrollTop,t.__maxScrollTop),0),i=t.__clientWidth,a=t.__clientHeight;t.__minDecelerationScrollLeft=Math.floor(n/i)*i,t.__minDecelerationScrollTop=Math.floor(r/a)*a,t.__maxDecelerationScrollLeft=Math.ceil(n/i)*i,t.__maxDecelerationScrollTop=Math.ceil(r/a)*a}else t.__minDecelerationScrollLeft=0,t.__minDecelerationScrollTop=0,t.__maxDecelerationScrollLeft=t.__maxScrollLeft,t.__maxDecelerationScrollTop=t.__maxScrollTop;var s=function(e,n,r){t.__stepThroughDeceleration(r)},l=t.options.minVelocityToKeepDecelerating;l||(l=t.options.snapping?4:.001);var u=function(){var e=Math.abs(t.__decelerationVelocityX)>=l||Math.abs(t.__decelerationVelocityY)>=l;return e||(t.__didDecelerationComplete=!0),e},c=function(e,n,r){t.__isDecelerating=!1,t.scrollTo(t.__scrollLeft,t.__scrollTop,t.options.snapping,null,t.__didDecelerationComplete&&t.options.scrollingComplete)};t.__isDecelerating=o.start(s,u,c)},__stepThroughDeceleration:function(e){var t=this,n=t.__scrollLeft+t.__decelerationVelocityX,r=t.__scrollTop+t.__decelerationVelocityY;if(!t.options.bouncing){var o=Math.max(Math.min(t.__maxDecelerationScrollLeft,n),t.__minDecelerationScrollLeft);o!==n&&(n=o,t.__decelerationVelocityX=0);var i=Math.max(Math.min(t.__maxDecelerationScrollTop,r),t.__minDecelerationScrollTop);i!==r&&(r=i,t.__decelerationVelocityY=0)}if(e?t.__publish(n,r,t.__zoomLevel):(t.__scrollLeft=n,t.__scrollTop=r),!t.options.paging){var a=.95;t.__decelerationVelocityX*=a,t.__decelerationVelocityY*=a}if(t.options.bouncing){var s=0,l=0,u=t.options.penetrationDeceleration,c=t.options.penetrationAcceleration;n<t.__minDecelerationScrollLeft?s=t.__minDecelerationScrollLeft-n:n>t.__maxDecelerationScrollLeft&&(s=t.__maxDecelerationScrollLeft-n),r<t.__minDecelerationScrollTop?l=t.__minDecelerationScrollTop-r:r>t.__maxDecelerationScrollTop&&(l=t.__maxDecelerationScrollTop-r),0!==s&&(s*t.__decelerationVelocityX<=0?t.__decelerationVelocityX+=s*u:t.__decelerationVelocityX=s*c),0!==l&&(l*t.__decelerationVelocityY<=0?t.__decelerationVelocityY+=l*u:t.__decelerationVelocityY=l*c)}}};for(var u in l)r.prototype[u]=l[u];e.exports=r},function(e,t,n,r){"use strict";n(7),n(r)},function(e,t,n,r){"use strict";n(7),n(23),n(r)},function(e,t,n,r){"use strict";n(7),n(25),n(r)}]))});
//# sourceMappingURL=antd-mobile.min.js.map |
src/index.js | cannap/learning-react-client | import React from 'react';
import {render} from 'react-dom';
import Router from './router';
import { createHistory, createHashHistory } from 'history';
render(<Router />,document.getElementById('root'));
|
client/index.js | Captain-Million/Captain-Million | /**
* Client entry point
*/
import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import App from './App';
import { configureStore } from './store';
// Initialize store
const store = configureStore(window.__INITIAL_STATE__);
const mountApp = document.getElementById('root');
render(
<AppContainer>
<App store={store} />
</AppContainer>,
mountApp
);
// For hot reloading of react components
if (module.hot) {
module.hot.accept('./App', () => {
// If you use Webpack 2 in ES modules mode, you can
// use <App /> here rather than require() a <NextApp />.
const NextApp = require('./App').default; // eslint-disable-line global-require
render(
<AppContainer>
<NextApp store={store} />
</AppContainer>,
mountApp
);
});
}
|
docs/src/pages/index.js | fosterfarrell9/mampf | import React from 'react';
import clsx from 'clsx';
import Layout from '@theme/Layout';
import Link from '@docusaurus/Link';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import useBaseUrl from '@docusaurus/useBaseUrl';
import styles from './styles.module.css';
const features = [
{
title: 'Built for mathematical sciences',
imageUrl: 'img/undraw_teaching.svg',
description: (
<>
MaMpf (Mathematische Medienplattform) is an innovative open source E-Learning platform for the mathematical sciences.
Central point is the interconnection between different content in the sense of a hypermedia system.
</>
),
},
{
title: 'Hypermedia plattform',
imageUrl: 'img/undraw_youtube_tutorial.svg',
description: (
<>
MaMpf comes with its own hypermedia player and editor THymE (The hypermedia Experience). ThymeE uses the internal structure of mathematical content (consisting of theorems, remarks, definitions etc.) and allows exact navigation between content that is related, but temporally apart. References can be created not only to content within the same video, but within the whole MaMpf database.
</>
),
},
{
title: 'Homework support',
imageUrl: 'img/undraw_studying.svg',
description: (
<>
MaMpf allows managing homework for classes and submissions by students.
Tutors can upload solutions foreach individual student.
</>
),
},
];
function Feature({imageUrl, title, description}) {
const imgUrl = useBaseUrl(imageUrl);
return (
<div className={clsx('col col--4', styles.feature)}>
{imgUrl && (
<div className="text--center">
<img className={styles.featureImage} src={imgUrl} alt={title} />
</div>
)}
<h3>{title}</h3>
<p>{description}</p>
</div>
);
}
export default function Home() {
const context = useDocusaurusContext();
const {siteConfig = {}} = context;
return (
<Layout
title={`Hello from ${siteConfig.title}`}
description="Description will go into a meta tag in <head />">
<header className={clsx('hero hero--primary', styles.heroBanner)}>
<div className="container">
<h1 className="hero__title">{siteConfig.title}</h1>
<p className="hero__subtitle">{siteConfig.tagline}</p>
<div className={styles.buttons}>
<Link
className={clsx(
'button button--outline button--secondary button--lg',
styles.getStarted,
)}
to={useBaseUrl('docs/')}>
Get Started
</Link>
</div>
</div>
</header>
<main>
{features && features.length > 0 && (
<section className={styles.features}>
<div className="container">
<div className="row">
{features.map((props, idx) => (
<Feature key={idx} {...props} />
))}
</div>
</div>
</section>
)}
</main>
</Layout>
);
}
|
Libraries/CustomComponents/Navigator/Navigator.js | rebeccahughes/react-native | /**
* Copyright (c) 2015, Facebook, Inc. All rights reserved.
*
* Facebook, Inc. ("Facebook") owns all right, title and interest, including
* all intellectual property and other proprietary rights, in and to the React
* Native CustomComponents software (the "Software"). Subject to your
* compliance with these terms, you are hereby granted a non-exclusive,
* worldwide, royalty-free copyright license to (1) use and copy the Software;
* and (2) reproduce and distribute the Software as part of your own software
* ("Your Software"). Facebook reserves all rights not expressly granted to
* you in this license agreement.
*
* THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "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 FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR
* EMPLOYEES 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 THE SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @providesModule Navigator
*/
/* eslint-disable no-extra-boolean-cast*/
'use strict';
var AnimationsDebugModule = require('NativeModules').AnimationsDebugModule;
var Dimensions = require('Dimensions');
var InteractionMixin = require('InteractionMixin');
var NavigationContext = require('NavigationContext');
var NavigatorBreadcrumbNavigationBar = require('NavigatorBreadcrumbNavigationBar');
var NavigatorNavigationBar = require('NavigatorNavigationBar');
var NavigatorSceneConfigs = require('NavigatorSceneConfigs');
var PanResponder = require('PanResponder');
var React = require('React');
var StyleSheet = require('StyleSheet');
var Subscribable = require('Subscribable');
var TimerMixin = require('react-timer-mixin');
var View = require('View');
var clamp = require('clamp');
var deprecatedPropType = require('deprecatedPropType');
var flattenStyle = require('flattenStyle');
var invariant = require('fbjs/lib/invariant');
var rebound = require('rebound');
var PropTypes = React.PropTypes;
// TODO: this is not ideal because there is no guarantee that the navigator
// is full screen, however we don't have a good way to measure the actual
// size of the navigator right now, so this is the next best thing.
var SCREEN_WIDTH = Dimensions.get('window').width;
var SCREEN_HEIGHT = Dimensions.get('window').height;
var SCENE_DISABLED_NATIVE_PROPS = {
pointerEvents: 'none',
style: {
top: SCREEN_HEIGHT,
bottom: -SCREEN_HEIGHT,
opacity: 0,
},
};
var __uid = 0;
function getuid() {
return __uid++;
}
function getRouteID(route) {
if (route === null || typeof route !== 'object') {
return String(route);
}
var key = '__navigatorRouteID';
if (!route.hasOwnProperty(key)) {
Object.defineProperty(route, key, {
enumerable: false,
configurable: false,
writable: false,
value: getuid(),
});
}
return route[key];
}
// styles moved to the top of the file so getDefaultProps can refer to it
var styles = StyleSheet.create({
container: {
flex: 1,
overflow: 'hidden',
},
defaultSceneStyle: {
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
top: 0,
},
baseScene: {
position: 'absolute',
overflow: 'hidden',
left: 0,
right: 0,
bottom: 0,
top: 0,
},
disabledScene: {
top: SCREEN_HEIGHT,
bottom: -SCREEN_HEIGHT,
},
transitioner: {
flex: 1,
backgroundColor: 'transparent',
overflow: 'hidden',
}
});
var GESTURE_ACTIONS = [
'pop',
'jumpBack',
'jumpForward',
];
/**
* Use `Navigator` to transition between different scenes in your app. To
* accomplish this, provide route objects to the navigator to identify each
* scene, and also a `renderScene` function that the navigator can use to
* render the scene for a given route.
*
* To change the animation or gesture properties of the scene, provide a
* `configureScene` prop to get the config object for a given route. See
* `Navigator.SceneConfigs` for default animations and more info on
* scene config options.
*
* ### Basic Usage
*
* ```
* <Navigator
* initialRoute={{name: 'My First Scene', index: 0}}
* renderScene={(route, navigator) =>
* <MySceneComponent
* name={route.name}
* onForward={() => {
* var nextIndex = route.index + 1;
* navigator.push({
* name: 'Scene ' + nextIndex,
* index: nextIndex,
* });
* }}
* onBack={() => {
* if (route.index > 0) {
* navigator.pop();
* }
* }}
* />
* }
* />
* ```
*
* ### Navigator Methods
*
* If you have a ref to the Navigator element, you can invoke several methods
* on it to trigger navigation:
*
* - `getCurrentRoutes()` - returns the current list of routes
* - `jumpBack()` - Jump backward without unmounting the current scene
* - `jumpForward()` - Jump forward to the next scene in the route stack
* - `jumpTo(route)` - Transition to an existing scene without unmounting
* - `push(route)` - Navigate forward to a new scene, squashing any scenes
* that you could `jumpForward` to
* - `pop()` - Transition back and unmount the current scene
* - `replace(route)` - Replace the current scene with a new route
* - `replaceAtIndex(route, index)` - Replace a scene as specified by an index
* - `replacePrevious(route)` - Replace the previous scene
* - `resetTo(route)` - Navigate to a new scene and reset route stack
* - `immediatelyResetRouteStack(routeStack)` - Reset every scene with an
* array of routes
* - `popToRoute(route)` - Pop to a particular scene, as specified by its
* route. All scenes after it will be unmounted
* - `popToTop()` - Pop to the first scene in the stack, unmounting every
* other scene
*
*/
var Navigator = React.createClass({
propTypes: {
/**
* Optional function that allows configuration about scene animations and
* gestures. Will be invoked with the route and the routeStack and should
* return a scene configuration object
*
* ```
* (route, routeStack) => Navigator.SceneConfigs.FloatFromRight
* ```
*/
configureScene: PropTypes.func,
/**
* Required function which renders the scene for a given route. Will be
* invoked with the route and the navigator object
*
* ```
* (route, navigator) =>
* <MySceneComponent title={route.title} navigator={navigator} />
* ```
*/
renderScene: PropTypes.func.isRequired,
/**
* Specify a route to start on. A route is an object that the navigator
* will use to identify each scene to render. `initialRoute` must be
* a route in the `initialRouteStack` if both props are provided. The
* `initialRoute` will default to the last item in the `initialRouteStack`.
*/
initialRoute: PropTypes.object,
/**
* Provide a set of routes to initially mount. Required if no initialRoute
* is provided. Otherwise, it will default to an array containing only the
* `initialRoute`
*/
initialRouteStack: PropTypes.arrayOf(PropTypes.object),
/**
* Will emit the target route upon mounting and before each nav transition
*/
onWillFocus: PropTypes.func,
/**
* Will be called with the new route of each scene after the transition is
* complete or after the initial mounting
*/
onDidFocus: PropTypes.func,
/**
* Optionally provide a navigation bar that persists across scene
* transitions
*/
navigationBar: PropTypes.node,
/**
* Optionally provide the navigator object from a parent Navigator
*/
navigator: PropTypes.object,
/**
* Styles to apply to the container of each scene
*/
sceneStyle: View.propTypes.style,
},
statics: {
BreadcrumbNavigationBar: NavigatorBreadcrumbNavigationBar,
NavigationBar: NavigatorNavigationBar,
SceneConfigs: NavigatorSceneConfigs,
},
mixins: [TimerMixin, InteractionMixin, Subscribable.Mixin],
getDefaultProps: function() {
return {
configureScene: () => NavigatorSceneConfigs.PushFromRight,
sceneStyle: styles.defaultSceneStyle,
};
},
getInitialState: function() {
this._navigationBarNavigator = this.props.navigationBarNavigator || this;
this._renderedSceneMap = new Map();
var routeStack = this.props.initialRouteStack || [this.props.initialRoute];
invariant(
routeStack.length >= 1,
'Navigator requires props.initialRoute or props.initialRouteStack.'
);
var initialRouteIndex = routeStack.length - 1;
if (this.props.initialRoute) {
initialRouteIndex = routeStack.indexOf(this.props.initialRoute);
invariant(
initialRouteIndex !== -1,
'initialRoute is not in initialRouteStack.'
);
}
return {
sceneConfigStack: routeStack.map(
(route) => this.props.configureScene(route, routeStack)
),
routeStack,
presentedIndex: initialRouteIndex,
transitionFromIndex: null,
activeGesture: null,
pendingGestureProgress: null,
transitionQueue: [],
};
},
componentWillMount: function() {
// TODO(t7489503): Don't need this once ES6 Class landed.
this.__defineGetter__('navigationContext', this._getNavigationContext);
this._subRouteFocus = [];
this.parentNavigator = this.props.navigator;
this._handlers = {};
this.springSystem = new rebound.SpringSystem();
this.spring = this.springSystem.createSpring();
this.spring.setRestSpeedThreshold(0.05);
this.spring.setCurrentValue(0).setAtRest();
this.spring.addListener({
onSpringEndStateChange: () => {
if (!this._interactionHandle) {
this._interactionHandle = this.createInteractionHandle();
}
},
onSpringUpdate: () => {
this._handleSpringUpdate();
},
onSpringAtRest: () => {
this._completeTransition();
},
});
this.panGesture = PanResponder.create({
onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder,
onPanResponderRelease: this._handlePanResponderRelease,
onPanResponderMove: this._handlePanResponderMove,
onPanResponderTerminate: this._handlePanResponderTerminate,
});
this._interactionHandle = null;
this._emitWillFocus(this.state.routeStack[this.state.presentedIndex]);
},
componentDidMount: function() {
this._handleSpringUpdate();
this._emitDidFocus(this.state.routeStack[this.state.presentedIndex]);
},
componentWillUnmount: function() {
if (this._navigationContext) {
this._navigationContext.dispose();
this._navigationContext = null;
}
this.spring.destroy();
if (this._interactionHandle) {
this.clearInteractionHandle(this._interactionHandle);
}
},
/**
* @param {RouteStack} nextRouteStack Next route stack to reinitialize. This
* doesn't accept stack item `id`s, which implies that all existing items are
* destroyed, and then potentially recreated according to `routeStack`. Does
* not animate, immediately replaces and rerenders navigation bar and stack
* items.
*/
immediatelyResetRouteStack: function(nextRouteStack) {
var destIndex = nextRouteStack.length - 1;
this.setState({
routeStack: nextRouteStack,
sceneConfigStack: nextRouteStack.map(
route => this.props.configureScene(route, nextRouteStack)
),
presentedIndex: destIndex,
activeGesture: null,
transitionFromIndex: null,
transitionQueue: [],
}, () => {
this._handleSpringUpdate();
this._navBar && this._navBar.immediatelyRefresh();
this._emitDidFocus(this.state.routeStack[this.state.presentedIndex]);
});
},
_transitionTo: function(destIndex, velocity, jumpSpringTo, cb) {
if (destIndex === this.state.presentedIndex) {
return;
}
if (this.state.transitionFromIndex !== null) {
this.state.transitionQueue.push({
destIndex,
velocity,
cb,
});
return;
}
this.state.transitionFromIndex = this.state.presentedIndex;
this.state.presentedIndex = destIndex;
this.state.transitionCb = cb;
this._onAnimationStart();
if (AnimationsDebugModule) {
AnimationsDebugModule.startRecordingFps();
}
var sceneConfig = this.state.sceneConfigStack[this.state.transitionFromIndex] ||
this.state.sceneConfigStack[this.state.presentedIndex];
invariant(
sceneConfig,
'Cannot configure scene at index ' + this.state.transitionFromIndex
);
if (jumpSpringTo != null) {
this.spring.setCurrentValue(jumpSpringTo);
}
this.spring.setOvershootClampingEnabled(true);
this.spring.getSpringConfig().friction = sceneConfig.springFriction;
this.spring.getSpringConfig().tension = sceneConfig.springTension;
this.spring.setVelocity(velocity || sceneConfig.defaultTransitionVelocity);
this.spring.setEndValue(1);
},
/**
* This happens for each frame of either a gesture or a transition. If both are
* happening, we only set values for the transition and the gesture will catch up later
*/
_handleSpringUpdate: function() {
if (!this.isMounted()) {
return;
}
// Prioritize handling transition in progress over a gesture:
if (this.state.transitionFromIndex != null) {
this._transitionBetween(
this.state.transitionFromIndex,
this.state.presentedIndex,
this.spring.getCurrentValue()
);
} else if (this.state.activeGesture != null) {
var presentedToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
this._transitionBetween(
this.state.presentedIndex,
presentedToIndex,
this.spring.getCurrentValue()
);
}
},
/**
* This happens at the end of a transition started by transitionTo, and when the spring catches up to a pending gesture
*/
_completeTransition: function() {
if (!this.isMounted()) {
return;
}
if (this.spring.getCurrentValue() !== 1 && this.spring.getCurrentValue() !== 0) {
// The spring has finished catching up to a gesture in progress. Remove the pending progress
// and we will be in a normal activeGesture state
if (this.state.pendingGestureProgress) {
this.state.pendingGestureProgress = null;
}
return;
}
this._onAnimationEnd();
var presentedIndex = this.state.presentedIndex;
var didFocusRoute = this._subRouteFocus[presentedIndex] || this.state.routeStack[presentedIndex];
this._emitDidFocus(didFocusRoute);
if (AnimationsDebugModule) {
AnimationsDebugModule.stopRecordingFps(Date.now());
}
this.state.transitionFromIndex = null;
this.spring.setCurrentValue(0).setAtRest();
this._hideScenes();
if (this.state.transitionCb) {
this.state.transitionCb();
this.state.transitionCb = null;
}
if (this._interactionHandle) {
this.clearInteractionHandle(this._interactionHandle);
this._interactionHandle = null;
}
if (this.state.pendingGestureProgress) {
// A transition completed, but there is already another gesture happening.
// Enable the scene and set the spring to catch up with the new gesture
var gestureToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
this._enableScene(gestureToIndex);
this.spring.setEndValue(this.state.pendingGestureProgress);
return;
}
if (this.state.transitionQueue.length) {
var queuedTransition = this.state.transitionQueue.shift();
this._enableScene(queuedTransition.destIndex);
this._emitWillFocus(this.state.routeStack[queuedTransition.destIndex]);
this._transitionTo(
queuedTransition.destIndex,
queuedTransition.velocity,
null,
queuedTransition.cb
);
}
},
_emitDidFocus: function(route) {
this.navigationContext.emit('didfocus', {route: route});
if (this.props.onDidFocus) {
this.props.onDidFocus(route);
}
},
_emitWillFocus: function(route) {
this.navigationContext.emit('willfocus', {route: route});
var navBar = this._navBar;
if (navBar && navBar.handleWillFocus) {
navBar.handleWillFocus(route);
}
if (this.props.onWillFocus) {
this.props.onWillFocus(route);
}
},
/**
* Hides all scenes that we are not currently on, gesturing to, or transitioning from
*/
_hideScenes: function() {
var gesturingToIndex = null;
if (this.state.activeGesture) {
gesturingToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
}
for (var i = 0; i < this.state.routeStack.length; i++) {
if (i === this.state.presentedIndex ||
i === this.state.transitionFromIndex ||
i === gesturingToIndex) {
continue;
}
this._disableScene(i);
}
},
/**
* Push a scene off the screen, so that opacity:0 scenes will not block touches sent to the presented scenes
*/
_disableScene: function(sceneIndex) {
this.refs['scene_' + sceneIndex] &&
this.refs['scene_' + sceneIndex].setNativeProps(SCENE_DISABLED_NATIVE_PROPS);
},
/**
* Put the scene back into the state as defined by props.sceneStyle, so transitions can happen normally
*/
_enableScene: function(sceneIndex) {
// First, determine what the defined styles are for scenes in this navigator
var sceneStyle = flattenStyle([styles.baseScene, this.props.sceneStyle]);
// Then restore the pointer events and top value for this scene
var enabledSceneNativeProps = {
pointerEvents: 'auto',
style: {
top: sceneStyle.top,
bottom: sceneStyle.bottom,
},
};
if (sceneIndex !== this.state.transitionFromIndex &&
sceneIndex !== this.state.presentedIndex) {
// If we are not in a transition from this index, make sure opacity is 0
// to prevent the enabled scene from flashing over the presented scene
enabledSceneNativeProps.style.opacity = 0;
}
this.refs['scene_' + sceneIndex] &&
this.refs['scene_' + sceneIndex].setNativeProps(enabledSceneNativeProps);
},
_onAnimationStart: function() {
var fromIndex = this.state.presentedIndex;
var toIndex = this.state.presentedIndex;
if (this.state.transitionFromIndex != null) {
fromIndex = this.state.transitionFromIndex;
} else if (this.state.activeGesture) {
toIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
}
this._setRenderSceneToHardwareTextureAndroid(fromIndex, true);
this._setRenderSceneToHardwareTextureAndroid(toIndex, true);
var navBar = this._navBar;
if (navBar && navBar.onAnimationStart) {
navBar.onAnimationStart(fromIndex, toIndex);
}
},
_onAnimationEnd: function() {
var max = this.state.routeStack.length - 1;
for (var index = 0; index <= max; index++) {
this._setRenderSceneToHardwareTextureAndroid(index, false);
}
var navBar = this._navBar;
if (navBar && navBar.onAnimationEnd) {
navBar.onAnimationEnd();
}
},
_setRenderSceneToHardwareTextureAndroid: function(sceneIndex, shouldRenderToHardwareTexture) {
var viewAtIndex = this.refs['scene_' + sceneIndex];
if (viewAtIndex === null || viewAtIndex === undefined) {
return;
}
viewAtIndex.setNativeProps({renderToHardwareTextureAndroid: shouldRenderToHardwareTexture});
},
_handleTouchStart: function() {
this._eligibleGestures = GESTURE_ACTIONS;
},
_handleMoveShouldSetPanResponder: function(e, gestureState) {
var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex];
if (!sceneConfig) {
return false;
}
this._expectingGestureGrant =
this._matchGestureAction(this._eligibleGestures, sceneConfig.gestures, gestureState);
return !!this._expectingGestureGrant;
},
_doesGestureOverswipe: function(gestureName) {
var wouldOverswipeBack = this.state.presentedIndex <= 0 &&
(gestureName === 'pop' || gestureName === 'jumpBack');
var wouldOverswipeForward = this.state.presentedIndex >= this.state.routeStack.length - 1 &&
gestureName === 'jumpForward';
return wouldOverswipeForward || wouldOverswipeBack;
},
_deltaForGestureAction: function(gestureAction) {
switch (gestureAction) {
case 'pop':
case 'jumpBack':
return -1;
case 'jumpForward':
return 1;
default:
invariant(false, 'Unsupported gesture action ' + gestureAction);
return;
}
},
_handlePanResponderRelease: function(e, gestureState) {
var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex];
var releaseGestureAction = this.state.activeGesture;
if (!releaseGestureAction) {
// The gesture may have been detached while responder, so there is no action here
return;
}
var releaseGesture = sceneConfig.gestures[releaseGestureAction];
var destIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
if (this.spring.getCurrentValue() === 0) {
// The spring is at zero, so the gesture is already complete
this.spring.setCurrentValue(0).setAtRest();
this._completeTransition();
return;
}
var isTravelVertical = releaseGesture.direction === 'top-to-bottom' || releaseGesture.direction === 'bottom-to-top';
var isTravelInverted = releaseGesture.direction === 'right-to-left' || releaseGesture.direction === 'bottom-to-top';
var velocity, gestureDistance;
if (isTravelVertical) {
velocity = isTravelInverted ? -gestureState.vy : gestureState.vy;
gestureDistance = isTravelInverted ? -gestureState.dy : gestureState.dy;
} else {
velocity = isTravelInverted ? -gestureState.vx : gestureState.vx;
gestureDistance = isTravelInverted ? -gestureState.dx : gestureState.dx;
}
var transitionVelocity = clamp(-10, velocity, 10);
if (Math.abs(velocity) < releaseGesture.notMoving) {
// The gesture velocity is so slow, is "not moving"
var hasGesturedEnoughToComplete = gestureDistance > releaseGesture.fullDistance * releaseGesture.stillCompletionRatio;
transitionVelocity = hasGesturedEnoughToComplete ? releaseGesture.snapVelocity : -releaseGesture.snapVelocity;
}
if (transitionVelocity < 0 || this._doesGestureOverswipe(releaseGestureAction)) {
// This gesture is to an overswiped region or does not have enough velocity to complete
// If we are currently mid-transition, then this gesture was a pending gesture. Because this gesture takes no action, we can stop here
if (this.state.transitionFromIndex == null) {
// There is no current transition, so we need to transition back to the presented index
var transitionBackToPresentedIndex = this.state.presentedIndex;
// slight hack: change the presented index for a moment in order to transitionTo correctly
this.state.presentedIndex = destIndex;
this._transitionTo(
transitionBackToPresentedIndex,
-transitionVelocity,
1 - this.spring.getCurrentValue()
);
}
} else {
// The gesture has enough velocity to complete, so we transition to the gesture's destination
this._emitWillFocus(this.state.routeStack[destIndex]);
this._transitionTo(
destIndex,
transitionVelocity,
null,
() => {
if (releaseGestureAction === 'pop') {
this._cleanScenesPastIndex(destIndex);
}
}
);
}
this._detachGesture();
},
_handlePanResponderTerminate: function(e, gestureState) {
if (this.state.activeGesture == null) {
return;
}
var destIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
this._detachGesture();
var transitionBackToPresentedIndex = this.state.presentedIndex;
// slight hack: change the presented index for a moment in order to transitionTo correctly
this.state.presentedIndex = destIndex;
this._transitionTo(
transitionBackToPresentedIndex,
null,
1 - this.spring.getCurrentValue()
);
},
_attachGesture: function(gestureId) {
this.state.activeGesture = gestureId;
var gesturingToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
this._enableScene(gesturingToIndex);
},
_detachGesture: function() {
this.state.activeGesture = null;
this.state.pendingGestureProgress = null;
this._hideScenes();
},
_handlePanResponderMove: function(e, gestureState) {
if (this._isMoveGestureAttached !== undefined) {
invariant(
this._expectingGestureGrant,
'Responder granted unexpectedly.'
);
this._attachGesture(this._expectingGestureGrant);
this._onAnimationStart();
this._expectingGestureGrant = undefined;
}
var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex];
if (this.state.activeGesture) {
var gesture = sceneConfig.gestures[this.state.activeGesture];
return this._moveAttachedGesture(gesture, gestureState);
}
var matchedGesture = this._matchGestureAction(GESTURE_ACTIONS, sceneConfig.gestures, gestureState);
if (matchedGesture) {
this._attachGesture(matchedGesture);
}
},
_moveAttachedGesture: function(gesture, gestureState) {
var isTravelVertical = gesture.direction === 'top-to-bottom' || gesture.direction === 'bottom-to-top';
var isTravelInverted = gesture.direction === 'right-to-left' || gesture.direction === 'bottom-to-top';
var distance = isTravelVertical ? gestureState.dy : gestureState.dx;
distance = isTravelInverted ? -distance : distance;
var gestureDetectMovement = gesture.gestureDetectMovement;
var nextProgress = (distance - gestureDetectMovement) /
(gesture.fullDistance - gestureDetectMovement);
if (nextProgress < 0 && gesture.isDetachable) {
var gesturingToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture);
this._transitionBetween(this.state.presentedIndex, gesturingToIndex, 0);
this._detachGesture();
if (this.state.pendingGestureProgress != null) {
this.spring.setCurrentValue(0);
}
return;
}
if (this._doesGestureOverswipe(this.state.activeGesture)) {
var frictionConstant = gesture.overswipe.frictionConstant;
var frictionByDistance = gesture.overswipe.frictionByDistance;
var frictionRatio = 1 / ((frictionConstant) + (Math.abs(nextProgress) * frictionByDistance));
nextProgress *= frictionRatio;
}
nextProgress = clamp(0, nextProgress, 1);
if (this.state.transitionFromIndex != null) {
this.state.pendingGestureProgress = nextProgress;
} else if (this.state.pendingGestureProgress) {
this.spring.setEndValue(nextProgress);
} else {
this.spring.setCurrentValue(nextProgress);
}
},
_matchGestureAction: function(eligibleGestures, gestures, gestureState) {
if (!gestures || !eligibleGestures || !eligibleGestures.some) {
return null;
}
var matchedGesture = null;
eligibleGestures.some((gestureName, gestureIndex) => {
var gesture = gestures[gestureName];
if (!gesture) {
return;
}
if (gesture.overswipe == null && this._doesGestureOverswipe(gestureName)) {
// cannot swipe past first or last scene without overswiping
return false;
}
var isTravelVertical = gesture.direction === 'top-to-bottom' || gesture.direction === 'bottom-to-top';
var isTravelInverted = gesture.direction === 'right-to-left' || gesture.direction === 'bottom-to-top';
var currentLoc = isTravelVertical ? gestureState.moveY : gestureState.moveX;
var travelDist = isTravelVertical ? gestureState.dy : gestureState.dx;
var oppositeAxisTravelDist =
isTravelVertical ? gestureState.dx : gestureState.dy;
var edgeHitWidth = gesture.edgeHitWidth;
if (isTravelInverted) {
currentLoc = -currentLoc;
travelDist = -travelDist;
oppositeAxisTravelDist = -oppositeAxisTravelDist;
edgeHitWidth = isTravelVertical ?
-(SCREEN_HEIGHT - edgeHitWidth) :
-(SCREEN_WIDTH - edgeHitWidth);
}
var moveStartedInRegion = gesture.edgeHitWidth == null ||
currentLoc < edgeHitWidth;
if (!moveStartedInRegion) {
return false;
}
var moveTravelledFarEnough = travelDist >= gesture.gestureDetectMovement;
if (!moveTravelledFarEnough) {
return false;
}
var directionIsCorrect = Math.abs(travelDist) > Math.abs(oppositeAxisTravelDist) * gesture.directionRatio;
if (directionIsCorrect) {
matchedGesture = gestureName;
return true;
} else {
this._eligibleGestures = this._eligibleGestures.slice().splice(gestureIndex, 1);
}
});
return matchedGesture || null;
},
_transitionSceneStyle: function(fromIndex, toIndex, progress, index) {
var viewAtIndex = this.refs['scene_' + index];
if (viewAtIndex === null || viewAtIndex === undefined) {
return;
}
// Use toIndex animation when we move forwards. Use fromIndex when we move back
var sceneConfigIndex = fromIndex < toIndex ? toIndex : fromIndex;
var sceneConfig = this.state.sceneConfigStack[sceneConfigIndex];
// this happens for overswiping when there is no scene at toIndex
if (!sceneConfig) {
sceneConfig = this.state.sceneConfigStack[sceneConfigIndex - 1];
}
var styleToUse = {};
var useFn = index < fromIndex || index < toIndex ?
sceneConfig.animationInterpolators.out :
sceneConfig.animationInterpolators.into;
var directionAdjustedProgress = fromIndex < toIndex ? progress : 1 - progress;
var didChange = useFn(styleToUse, directionAdjustedProgress);
if (didChange) {
viewAtIndex.setNativeProps({style: styleToUse});
}
},
_transitionBetween: function(fromIndex, toIndex, progress) {
this._transitionSceneStyle(fromIndex, toIndex, progress, fromIndex);
this._transitionSceneStyle(fromIndex, toIndex, progress, toIndex);
var navBar = this._navBar;
if (navBar && navBar.updateProgress && toIndex >= 0 && fromIndex >= 0) {
navBar.updateProgress(progress, fromIndex, toIndex);
}
},
_handleResponderTerminationRequest: function() {
return false;
},
_getDestIndexWithinBounds: function(n) {
var currentIndex = this.state.presentedIndex;
var destIndex = currentIndex + n;
invariant(
destIndex >= 0,
'Cannot jump before the first route.'
);
var maxIndex = this.state.routeStack.length - 1;
invariant(
maxIndex >= destIndex,
'Cannot jump past the last route.'
);
return destIndex;
},
_jumpN: function(n) {
var destIndex = this._getDestIndexWithinBounds(n);
this._enableScene(destIndex);
this._emitWillFocus(this.state.routeStack[destIndex]);
this._transitionTo(destIndex);
},
jumpTo: function(route) {
var destIndex = this.state.routeStack.indexOf(route);
invariant(
destIndex !== -1,
'Cannot jump to route that is not in the route stack'
);
this._jumpN(destIndex - this.state.presentedIndex);
},
jumpForward: function() {
this._jumpN(1);
},
jumpBack: function() {
this._jumpN(-1);
},
push: function(route) {
invariant(!!route, 'Must supply route to push');
var activeLength = this.state.presentedIndex + 1;
var activeStack = this.state.routeStack.slice(0, activeLength);
var activeAnimationConfigStack = this.state.sceneConfigStack.slice(0, activeLength);
var nextStack = activeStack.concat([route]);
var destIndex = nextStack.length - 1;
var nextAnimationConfigStack = activeAnimationConfigStack.concat([
this.props.configureScene(route, nextStack),
]);
this._emitWillFocus(nextStack[destIndex]);
this.setState({
routeStack: nextStack,
sceneConfigStack: nextAnimationConfigStack,
}, () => {
this._enableScene(destIndex);
this._transitionTo(destIndex);
});
},
_popN: function(n) {
if (n === 0) {
return;
}
invariant(
this.state.presentedIndex - n >= 0,
'Cannot pop below zero'
);
var popIndex = this.state.presentedIndex - n;
this._enableScene(popIndex);
this._emitWillFocus(this.state.routeStack[popIndex]);
this._transitionTo(
popIndex,
null, // default velocity
null, // no spring jumping
() => {
this._cleanScenesPastIndex(popIndex);
}
);
},
pop: function() {
if (this.state.transitionQueue.length) {
// This is the workaround to prevent user from firing multiple `pop()`
// calls that may pop the routes beyond the limit.
// Because `this.state.presentedIndex` does not update until the
// transition starts, we can't reliably use `this.state.presentedIndex`
// to know whether we can safely keep popping the routes or not at this
// moment.
return;
}
if (this.state.presentedIndex > 0) {
this._popN(1);
}
},
/**
* Replace a route in the navigation stack.
*
* `index` specifies the route in the stack that should be replaced.
* If it's negative, it counts from the back.
*/
replaceAtIndex: function(route, index, cb) {
invariant(!!route, 'Must supply route to replace');
if (index < 0) {
index += this.state.routeStack.length;
}
if (this.state.routeStack.length <= index) {
return;
}
var nextRouteStack = this.state.routeStack.slice();
var nextAnimationModeStack = this.state.sceneConfigStack.slice();
nextRouteStack[index] = route;
nextAnimationModeStack[index] = this.props.configureScene(route, nextRouteStack);
if (index === this.state.presentedIndex) {
this._emitWillFocus(route);
}
this.setState({
routeStack: nextRouteStack,
sceneConfigStack: nextAnimationModeStack,
}, () => {
if (index === this.state.presentedIndex) {
this._emitDidFocus(route);
}
cb && cb();
});
},
/**
* Replaces the current scene in the stack.
*/
replace: function(route) {
this.replaceAtIndex(route, this.state.presentedIndex);
},
/**
* Replace the current route's parent.
*/
replacePrevious: function(route) {
this.replaceAtIndex(route, this.state.presentedIndex - 1);
},
popToTop: function() {
this.popToRoute(this.state.routeStack[0]);
},
popToRoute: function(route) {
var indexOfRoute = this.state.routeStack.indexOf(route);
invariant(
indexOfRoute !== -1,
'Calling popToRoute for a route that doesn\'t exist!'
);
var numToPop = this.state.presentedIndex - indexOfRoute;
this._popN(numToPop);
},
replacePreviousAndPop: function(route) {
if (this.state.routeStack.length < 2) {
return;
}
this.replacePrevious(route);
this.pop();
},
resetTo: function(route) {
invariant(!!route, 'Must supply route to push');
this.replaceAtIndex(route, 0, () => {
// Do not use popToRoute here, because race conditions could prevent the
// route from existing at this time. Instead, just go to index 0
if (this.state.presentedIndex > 0) {
this._popN(this.state.presentedIndex);
}
});
},
getCurrentRoutes: function() {
// Clone before returning to avoid caller mutating the stack
return this.state.routeStack.slice();
},
_cleanScenesPastIndex: function(index) {
var newStackLength = index + 1;
// Remove any unneeded rendered routes.
if (newStackLength < this.state.routeStack.length) {
this.setState({
sceneConfigStack: this.state.sceneConfigStack.slice(0, newStackLength),
routeStack: this.state.routeStack.slice(0, newStackLength),
});
}
},
_renderScene: function(route, i) {
var disabledSceneStyle = null;
var disabledScenePointerEvents = 'auto';
if (i !== this.state.presentedIndex) {
disabledSceneStyle = styles.disabledScene;
disabledScenePointerEvents = 'none';
}
return (
<View
key={'scene_' + getRouteID(route)}
ref={'scene_' + i}
onStartShouldSetResponderCapture={() => {
return (this.state.transitionFromIndex != null) || (this.state.transitionFromIndex != null);
}}
pointerEvents={disabledScenePointerEvents}
style={[styles.baseScene, this.props.sceneStyle, disabledSceneStyle]}>
{this.props.renderScene(
route,
this
)}
</View>
);
},
_renderNavigationBar: function() {
let { navigationBar } = this.props;
if (!navigationBar) {
return null;
}
return React.cloneElement(navigationBar, {
ref: (navBar) => {
this._navBar = navBar;
if (navigationBar && typeof navigationBar.ref === 'function') {
navigationBar.ref(navBar);
}
},
navigator: this._navigationBarNavigator,
navState: this.state,
});
},
render: function() {
var newRenderedSceneMap = new Map();
var scenes = this.state.routeStack.map((route, index) => {
var renderedScene;
if (this._renderedSceneMap.has(route) &&
index !== this.state.presentedIndex) {
renderedScene = this._renderedSceneMap.get(route);
} else {
renderedScene = this._renderScene(route, index);
}
newRenderedSceneMap.set(route, renderedScene);
return renderedScene;
});
this._renderedSceneMap = newRenderedSceneMap;
return (
<View style={[styles.container, this.props.style]}>
<View
style={styles.transitioner}
{...this.panGesture.panHandlers}
onTouchStart={this._handleTouchStart}
onResponderTerminationRequest={
this._handleResponderTerminationRequest
}>
{scenes}
</View>
{this._renderNavigationBar()}
</View>
);
},
_getNavigationContext: function() {
if (!this._navigationContext) {
this._navigationContext = new NavigationContext();
}
return this._navigationContext;
}
});
module.exports = Navigator;
|
app/pages/_app.js | jaredpalmer/formik | import React from 'react';
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
export default MyApp;
|
stories/Breadcrubms/ExampleThemes.js | nirhart/wix-style-react | import React from 'react';
import styles from './ExampleBreadcrumbs.scss';
import Breadcrumbs from '../../src/Breadcrumbs/Breadcrumbs';
const items = [{id: '1', value: 'first item'}, {id: '2', value: 'second item'}, {id: '3', value: 'third item'}];
export default () =>
<div>
<div className={`${styles.onGrayBackground} ${styles.exampleWrapper}`}>
<Breadcrumbs items={items}
theme={'onGrayBackground'}/>
</div>
<div className={`${styles.onWhiteBackground} ${styles.exampleWrapper}`}>
<Breadcrumbs items={items}
theme={'onWhiteBackground'}/>
</div>
<div className={`${styles.onDarkBackground} ${styles.exampleWrapper}`}>
<Breadcrumbs items={items}
theme={'onDarkBackground'}/>
</div>
</div>;
|
assets/js/react/betForm.js | ChrisBr/duell-um-die-geld | import React, { Component } from 'react';
class BetForm extends React.Component {
constructor(props) {
super(props);
this.state = { value: 0 };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.check = this.check.bind(this);
this.getBet = this.getBet.bind(this);
this.allAnswered = this.allAnswered.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value });
}
handleSubmit(event) {
this.props.updateBet(this.state.value);
event.preventDefault();
}
check(event){
this.props.updateBet(0);
}
getBet(){
// First round, no bets yet
// TODO: doesnt work!
if(this.props.game.betRound === 0){
return "";
}
var bet = "Check";
if(this.props.user.bet !== 0){
bet = this.props.bet
}
return(
<p className="lead">
Your Bet: { bet }
</p>
)
}
allAnswered(){
if(this.props.users != null){
var result = true;
this.props.users.forEach(function(user){
if(user.answer === ""){
result = false;
return false;
}
});
return result;
}
return false;
}
render() {
if(this.props.user.answer === ""){
return(null);
} else if(!this.allAnswered()){
return(<p>Waiting for other player to submit their answer ...</p>);
} else {
return (
<div className="row" id="betFormRow">
<div className="col-md-4 col-md-offset-4" id="betFormColumn">
{ this.getBet() }
<form className="form-inline" onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="bet">Set your bet:</label>
<input type="text" value={this.state.value} onChange={this.handleChange} className="form-control" id="bet" placeholder="Set your bet ..." />
<button type="submit" className="btn btn-success">Bet now!</button>
<button type="button" className="btn btn-success"onClick={this.check}>Check!</button>
</div>
</form>
</div>
</div>
);
}
}
}
export default BetForm;
|
src/admin/BedChart.js | ocelotconsulting/global-hack-6 | /* eslint no-new: "off" */
import React from 'react'
import { v4 } from 'uuid'
import ChartKey from './ChartKey'
import Row from 'react-bootstrap/lib/Row'
import Col from 'react-bootstrap/lib/Col'
import ChartistGraph from 'react-chartist'
export default class BedChart extends React.Component {
constructor(props) {
super(props)
this.state = {
id: `chart_${v4().replace(/-/g, '')}`
}
}
render() {
const { total, available, pending } = this.props
const data = {
series: [total - available - pending, pending, available]
}
const options = {
startAngle: 270,
showLabel: false
}
return (
<div className='summary-chart'>
<Row>
<Col md={3}>
<ChartKey/>
</Col>
<Col md={3}>
<ChartistGraph data={data} options={options} type='Pie'/>
</Col>
</Row>
</div>
)
}
}
|
ajax/libs/react-data-grid/1.0.41/react-data-grid.ui-plugins.min.js | emmy41124/cdnjs | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports.ReactDataGrid=t(require("react"),require("react-dom")):e.ReactDataGrid=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}(function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))switch(typeof e[t]){case"function":break;case"object":e[t]=function(t){var n=t.slice(1),r=e[t[0]];return function(e,t,o){r.apply(this,[e,t,o].concat(n))}}(e[t]);break;default:e[t]=e[e[t]]}return e}([function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.Filters=t.Draggable=t.ToolsPanel=t.Data=t.Menu=t.Toolbar=t.Formatters=t.Editors=void 0;var o=n(97),i=r(o),u=n(101),s=n(104),a=n(111),l=n(112),c=n(92),p=n(107),f=n(88);window.ReactDataGridPlugins={Editors:u,Formatters:s,Toolbar:a,Menu:p,Data:c,ToolsPanel:l,Draggable:i["default"],Filters:f},t.Editors=u,t.Formatters=s,t.Toolbar=a,t.Menu=p,t.Data=c,t.ToolsPanel=l,t.Draggable=i["default"],t.Filters=f},function(t,n){t.exports=e},function(e,t,n){"use strict";var r=function(e,t,n,r,o,i,u,s){if(!e){var a;if(void 0===t)a=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,r,o,i,u,s],c=0;a=new Error(t.replace(/%s/g,function(){return l[c++]})),a.name="Invariant Violation"}throw a.framesToPop=1,a}};e.exports=r},function(e,n){e.exports=t},function(e,t,n){function r(e){if(!u(e)||d.call(e)!=s||i(e))return!1;var t=o(e);if(null===t)return!0;var n=p.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&c.call(n)==f}var o=n(171),i=n(55),u=n(60),s="[object Object]",a=Function.prototype,l=Object.prototype,c=a.toString,p=l.hasOwnProperty,f=c.call(Object),d=l.toString;e.exports=r},function(e,t){var n=Array.isArray;e.exports=n},function(e,t,n){function r(e,t){return t=i(void 0===t?e.length-1:t,0),function(){for(var n=arguments,r=-1,u=i(n.length-t,0),s=Array(u);++r<u;)s[r]=n[t+r];r=-1;for(var a=Array(t+1);++r<t;)a[r]=n[r];return a[t]=s,o(e,this,a)}}var o=n(50),i=Math.max;e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e["default"]:e}t.__esModule=!0;var o=n(222);t.DragDropContext=r(o);var i=n(223);t.DragLayer=r(i);var u=n(224);t.DragSource=r(u);var s=n(225);t.DropTarget=r(s)},function(e,t,n){"use strict";var r=n(1),o={name:r.PropTypes.node.isRequired,key:r.PropTypes.string.isRequired,width:r.PropTypes.number.isRequired,filterable:r.PropTypes.bool};e.exports=o},function(e,t){"use strict";e.exports=!("undefined"==typeof window||!window.document||!window.document.createElement)},function(e,t,n){function r(e){return i(e)&&o(e)}var o=n(30),i=n(60);e.exports=r},function(e,t){function n(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=t.publishSource,r=void 0===n||n,o=t.clientOffset,i=void 0===o?null:o,u=t.getSourceClientOffset;f["default"](h["default"](e),"Expected sourceIds to be an array.");var s=this.getMonitor(),a=this.getRegistry();f["default"](!s.isDragging(),"Cannot call beginDrag while dragging.");for(var l=0;l<e.length;l++)f["default"](a.getSource(e[l]),"Expected sourceIds to be registered.");for(var c=null,l=e.length-1;l>=0;l--)if(s.canDragSource(e[l])){c=e[l];break}if(null!==c){var p=null;i&&(f["default"]("function"==typeof u,"When clientOffset is provided, getSourceClientOffset must be a function."),p=u(c));var d=a.getSource(c),g=d.beginDrag(s,c);f["default"](y["default"](g),"Item must be an object."),a.pinSource(c);var m=a.getSourceType(c);return{type:v,itemType:m,item:g,sourceId:c,clientOffset:i,sourceClientOffset:p,isSourcePublic:r}}}function i(e){var t=this.getMonitor();if(t.isDragging())return{type:m}}function u(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=t.clientOffset,r=void 0===n?null:n;f["default"](h["default"](e),"Expected targetIds to be an array."),e=e.slice(0);var o=this.getMonitor(),i=this.getRegistry();f["default"](o.isDragging(),"Cannot call hover while not dragging."),f["default"](!o.didDrop(),"Cannot call hover after drop.");for(var u=0;u<e.length;u++){var s=e[u];f["default"](e.lastIndexOf(s)===u,"Expected targetIds to be unique in the passed array.");var a=i.getTarget(s);f["default"](a,"Expected targetIds to be registered.")}for(var l=o.getItemType(),u=e.length-1;u>=0;u--){var s=e[u],p=i.getTargetType(s);c["default"](p,l)||e.splice(u,1)}for(var u=0;u<e.length;u++){var s=e[u],a=i.getTarget(s);a.hover(o,s)}return{type:b,targetIds:e,clientOffset:r}}function s(){var e=this,t=this.getMonitor(),n=this.getRegistry();f["default"](t.isDragging(),"Cannot call drop while not dragging."),f["default"](!t.didDrop(),"Cannot call drop twice during one drag operation.");var r=t.getTargetIds().filter(t.canDropOnTarget,t);r.reverse(),r.forEach(function(r,o){var i=n.getTarget(r),u=i.drop(t,r);f["default"]("undefined"==typeof u||y["default"](u),"Drop result must either be an object or undefined."),"undefined"==typeof u&&(u=0===o?{}:t.getDropResult()),e.store.dispatch({type:E,dropResult:u})})}function a(){var e=this.getMonitor(),t=this.getRegistry();f["default"](e.isDragging(),"Cannot call endDrag while not dragging.");var n=e.getSourceId(),r=t.getSource(n,!0);return r.endDrag(e,n),t.unpinSource(),{type:w}}t.__esModule=!0,t.beginDrag=o,t.publishDragSource=i,t.hover=u,t.drop=s,t.endDrag=a;var l=n(45),c=r(l),p=n(2),f=r(p),d=n(5),h=r(d),g=n(11),y=r(g),v="dnd-core/BEGIN_DRAG";t.BEGIN_DRAG=v;var m="dnd-core/PUBLISH_DRAG_SOURCE";t.PUBLISH_DRAG_SOURCE=m;var b="dnd-core/HOVER";t.HOVER=b;var E="dnd-core/DROP";t.DROP=E;var w="dnd-core/END_DRAG";t.END_DRAG=w},function(e,t){"use strict";function n(e){return{type:u,sourceId:e}}function r(e){return{type:s,targetId:e}}function o(e){return{type:a,sourceId:e}}function i(e){return{type:l,targetId:e}}t.__esModule=!0,t.addSource=n,t.addTarget=r,t.removeSource=o,t.removeTarget=i;var u="dnd-core/ADD_SOURCE";t.ADD_SOURCE=u;var s="dnd-core/ADD_TARGET";t.ADD_TARGET=s;var a="dnd-core/REMOVE_SOURCE";t.REMOVE_SOURCE=a;var l="dnd-core/REMOVE_TARGET";t.REMOVE_TARGET=l},function(e,t,n){function r(e,t){for(var n=e.length;n--;)if(o(e[n][0],t))return n;return-1}var o=n(18);e.exports=r},function(e,t,n){function r(e,t){var n=e.__data__;return o(t)?n["string"==typeof t?"string":"hash"]:n.map}var o=n(180);e.exports=r},function(e,t,n){var r=n(29),o=r(Object,"create");e.exports=o},function(e,t,n){var r=n(170),o="object"==typeof self&&self&&self.Object===Object&&self,i=r||o||Function("return this")();e.exports=i},function(e,t){function n(e,t){return e===t||e!==e&&t!==t}e.exports=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(251),i=n(211),u=r(i);t["default"]=(0,o.createStore)(u["default"])},function(e,t,n){"use strict";function r(e,t){}t.__esModule=!0,t["default"]=r,e.exports=t["default"]},function(e,t,n){var r,o;!function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var o=typeof r;if("string"===o||"number"===o)e.push(r);else if(Array.isArray(r))e.push(n.apply(null,r));else if("object"===o)for(var u in r)i.call(r,u)&&r[u]&&e.push(u)}}return e.join(" ")}var i={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=n:(r=[],o=function(){return n}.apply(t,r),!(void 0!==o&&(e.exports=o)))}()},function(e,t){"use strict";function n(e){return Boolean(e&&"function"==typeof e.dispose)}t.__esModule=!0,t["default"]=n,e.exports=t["default"]},function(e,t){"use strict";function n(e){return e&&e.ownerDocument||document}t.__esModule=!0,t["default"]=n,e.exports=t["default"]},function(e,t,n){function r(e){var t=-1,n=e?e.length:0;for(this.__data__=new o;++t<n;)this.add(e[t])}var o=n(49),i=n(195),u=n(196);r.prototype.add=r.prototype.push=i,r.prototype.has=u,e.exports=r},function(e,t,n){function r(e,t){var n=e?e.length:0;return!!n&&o(e,t,0)>-1}var o=n(158);e.exports=r},function(e,t){function n(e,t,n){for(var r=-1,o=e?e.length:0;++r<o;)if(n(t,e[r]))return!0;return!1}e.exports=n},function(e,t){function n(e,t){for(var n=-1,r=e?e.length:0,o=Array(r);++n<r;)o[n]=t(e[n],n,e);return o}e.exports=n},function(e,t){function n(e,t){return e.has(t)}e.exports=n},function(e,t,n){function r(e,t){var n=i(e,t);return o(n)?n:void 0}var o=n(161),i=n(172);e.exports=r},function(e,t,n){function r(e){return null!=e&&i(e.length)&&!o(e)}var o=n(59),i=n(201);e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(19),i=r(o);t["default"]={getItem:function(){return i["default"].getState().currentItem},getPosition:function(){var e=i["default"].getState(),t=e.x,n=e.y;return{x:t,y:n}},hideMenu:function(){i["default"].dispatch({type:"SET_PARAMS",data:{isVisible:!1,currentItem:{}}})}}},function(e,t){"use strict";t.__esModule=!0;var n="__NATIVE_FILE__";t.FILE=n;var r="__NATIVE_URL__";t.URL=r;var o="__NATIVE_TEXT__";t.TEXT=o},function(e,t){"use strict";function n(e,t){if(e===t)return!0;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(var o=Object.prototype.hasOwnProperty,i=0;i<n.length;i++){if(!o.call(t,n[i])||e[n[i]]!==t[n[i]])return!1;var u=e[n[i]],s=t[n[i]];if(u!==s)return!1}return!0}t.__esModule=!0,t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function u(e){return"string"==typeof e?e:"object"==typeof e?JSON.stringify(e):e||0===e?String(e):""}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),l=r(a),c=n(3),p=r(c),f=n(235),d=r(f),h=n(21),g=r(h),y=n(76),v=r(y),m=n(77),b=r(m),E=n(244),w=r(E),T=n(245),_=r(T),D=n(246),O=r(D),C=n(247),x=r(C),P=l["default"].PropTypes.oneOfType([l["default"].PropTypes.string,l["default"].PropTypes.node]),S=1,M=l["default"].createClass({displayName:"Select",propTypes:{addLabelText:l["default"].PropTypes.string,"aria-label":l["default"].PropTypes.string,"aria-labelledby":l["default"].PropTypes.string,autoBlur:l["default"].PropTypes.bool,autofocus:l["default"].PropTypes.bool,autosize:l["default"].PropTypes.bool,backspaceRemoves:l["default"].PropTypes.bool,backspaceToRemoveMessage:l["default"].PropTypes.string,className:l["default"].PropTypes.string,clearAllText:P,clearValueText:P,clearable:l["default"].PropTypes.bool,delimiter:l["default"].PropTypes.string,disabled:l["default"].PropTypes.bool,escapeClearsValue:l["default"].PropTypes.bool,filterOption:l["default"].PropTypes.func,filterOptions:l["default"].PropTypes.any,ignoreAccents:l["default"].PropTypes.bool,ignoreCase:l["default"].PropTypes.bool,inputProps:l["default"].PropTypes.object,inputRenderer:l["default"].PropTypes.func,instanceId:l["default"].PropTypes.string,isLoading:l["default"].PropTypes.bool,joinValues:l["default"].PropTypes.bool,labelKey:l["default"].PropTypes.string,matchPos:l["default"].PropTypes.string,matchProp:l["default"].PropTypes.string,menuBuffer:l["default"].PropTypes.number,menuContainerStyle:l["default"].PropTypes.object,menuRenderer:l["default"].PropTypes.func,menuStyle:l["default"].PropTypes.object,multi:l["default"].PropTypes.bool,name:l["default"].PropTypes.string,noResultsText:P,onBlur:l["default"].PropTypes.func,onBlurResetsInput:l["default"].PropTypes.bool,onChange:l["default"].PropTypes.func,onClose:l["default"].PropTypes.func,onCloseResetsInput:l["default"].PropTypes.bool,onFocus:l["default"].PropTypes.func,onInputChange:l["default"].PropTypes.func,onInputKeyDown:l["default"].PropTypes.func,onMenuScrollToBottom:l["default"].PropTypes.func,onOpen:l["default"].PropTypes.func,onValueClick:l["default"].PropTypes.func,openAfterFocus:l["default"].PropTypes.bool,openOnFocus:l["default"].PropTypes.bool,optionClassName:l["default"].PropTypes.string,optionComponent:l["default"].PropTypes.func,optionRenderer:l["default"].PropTypes.func,options:l["default"].PropTypes.array,pageSize:l["default"].PropTypes.number,placeholder:P,required:l["default"].PropTypes.bool,resetValue:l["default"].PropTypes.any,scrollMenuIntoView:l["default"].PropTypes.bool,searchable:l["default"].PropTypes.bool,simpleValue:l["default"].PropTypes.bool,style:l["default"].PropTypes.object,tabIndex:l["default"].PropTypes.string,tabSelectsValue:l["default"].PropTypes.bool,value:l["default"].PropTypes.any,valueComponent:l["default"].PropTypes.func,valueKey:l["default"].PropTypes.string,valueRenderer:l["default"].PropTypes.func,wrapperStyle:l["default"].PropTypes.object},statics:{Async:w["default"],Creatable:_["default"]},getDefaultProps:function(){return{addLabelText:'Add "{label}"?',autosize:!0,backspaceRemoves:!0,backspaceToRemoveMessage:"Press backspace to remove {label}",clearable:!0,clearAllText:"Clear all",clearValueText:"Clear value",delimiter:",",disabled:!1,escapeClearsValue:!0,filterOptions:v["default"],ignoreAccents:!0,ignoreCase:!0,inputProps:{},isLoading:!1,joinValues:!1,labelKey:"label",matchPos:"any",matchProp:"any",menuBuffer:0,menuRenderer:b["default"],multi:!1,noResultsText:"No results found",onBlurResetsInput:!0,onCloseResetsInput:!0,openAfterFocus:!1,optionComponent:O["default"],pageSize:5,placeholder:"Select...",required:!1,scrollMenuIntoView:!0,searchable:!0,simpleValue:!1,tabSelectsValue:!0,valueComponent:x["default"],valueKey:"value"}},getInitialState:function(){return{inputValue:"",isFocused:!1,isOpen:!1,isPseudoFocused:!1,required:!1}},componentWillMount:function(){this._instancePrefix="react-select-"+(this.props.instanceId||++S)+"-";var e=this.getValueArray(this.props.value);this.props.required&&this.setState({required:this.handleRequired(e[0],this.props.multi)})},componentDidMount:function(){this.props.autofocus&&this.focus()},componentWillReceiveProps:function(e){var t=this.getValueArray(e.value,e);e.required&&this.setState({required:this.handleRequired(t[0],e.multi)})},componentWillUpdate:function(e,t){if(t.isOpen!==this.state.isOpen){this.toggleTouchOutsideEvent(t.isOpen);var n=t.isOpen?e.onOpen:e.onClose;n&&n()}},componentDidUpdate:function(e,t){if(this.menu&&this.focused&&this.state.isOpen&&!this.hasScrolledToOption){var n=p["default"].findDOMNode(this.focused),r=p["default"].findDOMNode(this.menu);r.scrollTop=n.offsetTop,this.hasScrolledToOption=!0}else this.state.isOpen||(this.hasScrolledToOption=!1);if(this._scrollToFocusedOptionOnUpdate&&this.focused&&this.menu){this._scrollToFocusedOptionOnUpdate=!1;var o=p["default"].findDOMNode(this.focused),i=p["default"].findDOMNode(this.menu),u=o.getBoundingClientRect(),s=i.getBoundingClientRect();(u.bottom>s.bottom||u.top<s.top)&&(i.scrollTop=o.offsetTop+o.clientHeight-i.offsetHeight)}if(this.props.scrollMenuIntoView&&this.menuContainer){var a=this.menuContainer.getBoundingClientRect();window.innerHeight<a.bottom+this.props.menuBuffer&&window.scrollBy(0,a.bottom+this.props.menuBuffer-window.innerHeight)}e.disabled!==this.props.disabled&&(this.setState({isFocused:!1}),this.closeMenu())},componentWillUnmount:function(){document.removeEventListener("touchstart",this.handleTouchOutside)},toggleTouchOutsideEvent:function(e){e?document.addEventListener("touchstart",this.handleTouchOutside):document.removeEventListener("touchstart",this.handleTouchOutside)},handleTouchOutside:function(e){this.wrapper&&!this.wrapper.contains(e.target)&&this.closeMenu()},focus:function(){this.input&&(this.input.focus(),this.props.openAfterFocus&&this.setState({isOpen:!0}))},blurInput:function(){this.input&&this.input.blur()},handleTouchMove:function(e){this.dragging=!0},handleTouchStart:function(e){this.dragging=!1},handleTouchEnd:function(e){this.dragging||this.handleMouseDown(e)},handleTouchEndClearValue:function(e){this.dragging||this.clearValue(e)},handleMouseDown:function(e){if(!(this.props.disabled||"mousedown"===e.type&&0!==e.button)&&"INPUT"!==e.target.tagName){if(e.stopPropagation(),e.preventDefault(),!this.props.searchable)return this.focus(),this.setState({isOpen:!this.state.isOpen});if(this.state.isFocused){this.focus();var t=this.input;"function"==typeof t.getInput&&(t=t.getInput()),t.value="",this.setState({isOpen:!0,isPseudoFocused:!1})}else this._openAfterFocus=!0,this.focus()}},handleMouseDownOnArrow:function(e){this.props.disabled||"mousedown"===e.type&&0!==e.button||this.state.isOpen&&(e.stopPropagation(),e.preventDefault(),this.closeMenu())},handleMouseDownOnMenu:function(e){this.props.disabled||"mousedown"===e.type&&0!==e.button||(e.stopPropagation(),e.preventDefault(),this._openAfterFocus=!0,this.focus())},closeMenu:function(){this.props.onCloseResetsInput?this.setState({isOpen:!1,isPseudoFocused:this.state.isFocused&&!this.props.multi,inputValue:""}):this.setState({isOpen:!1,isPseudoFocused:this.state.isFocused&&!this.props.multi,inputValue:this.state.inputValue}),this.hasScrolledToOption=!1},handleInputFocus:function(e){var t=this.state.isOpen||this._openAfterFocus||this.props.openOnFocus;this.props.onFocus&&this.props.onFocus(e),this.setState({isFocused:!0,isOpen:t}),this._openAfterFocus=!1},handleInputBlur:function(e){if(this.menu&&(this.menu===document.activeElement||this.menu.contains(document.activeElement)))return void this.focus();this.props.onBlur&&this.props.onBlur(e);var t={isFocused:!1,isOpen:!1,isPseudoFocused:!1};this.props.onBlurResetsInput&&(t.inputValue=""),this.setState(t)},handleInputChange:function(e){var t=e.target.value;if(this.state.inputValue!==e.target.value&&this.props.onInputChange){var n=this.props.onInputChange(t);null!=n&&"object"!=typeof n&&(t=""+n)}this.setState({isOpen:!0,isPseudoFocused:!1,inputValue:t})},handleKeyDown:function(e){if(!(this.props.disabled||"function"==typeof this.props.onInputKeyDown&&(this.props.onInputKeyDown(e),e.defaultPrevented))){switch(e.keyCode){case 8:return void(!this.state.inputValue&&this.props.backspaceRemoves&&(e.preventDefault(),this.popValue()));case 9:if(e.shiftKey||!this.state.isOpen||!this.props.tabSelectsValue)return;return void this.selectFocusedOption();case 13:if(!this.state.isOpen)return;e.stopPropagation(),this.selectFocusedOption();break;case 27:this.state.isOpen?(this.closeMenu(),e.stopPropagation()):this.props.clearable&&this.props.escapeClearsValue&&(this.clearValue(e),e.stopPropagation());break;case 38:this.focusPreviousOption();break;case 40:this.focusNextOption();break;case 33:this.focusPageUpOption();break;case 34:this.focusPageDownOption();break;case 35:this.focusEndOption();break;case 36:this.focusStartOption();break;default:return}e.preventDefault()}},handleValueClick:function(e,t){this.props.onValueClick&&this.props.onValueClick(e,t)},handleMenuScroll:function(e){if(this.props.onMenuScrollToBottom){var t=e.target;t.scrollHeight>t.offsetHeight&&!(t.scrollHeight-t.offsetHeight-t.scrollTop)&&this.props.onMenuScrollToBottom()}},handleRequired:function(e,t){return!e||(t?0===e.length:0===Object.keys(e).length)},getOptionLabel:function(e){return e[this.props.labelKey]},getValueArray:function(e,t){var n=this,r="object"==typeof t?t:this.props;if(r.multi){if("string"==typeof e&&(e=e.split(r.delimiter)),!Array.isArray(e)){if(null===e||void 0===e)return[];e=[e]}return e.map(function(e){return n.expandValue(e,r)}).filter(function(e){return e})}var o=this.expandValue(e,r);return o?[o]:[]},expandValue:function(e,t){if("string"!=typeof e&&"number"!=typeof e)return e;var n=t.options,r=t.valueKey;if(n)for(var o=0;o<n.length;o++)if(n[o][r]===e)return n[o]},setValue:function(e){var t=this;if(this.props.autoBlur&&this.blurInput(),this.props.onChange){if(this.props.required){var n=this.handleRequired(e,this.props.multi);this.setState({required:n})}this.props.simpleValue&&e&&(e=this.props.multi?e.map(function(e){return e[t.props.valueKey]}).join(this.props.delimiter):e[this.props.valueKey]),this.props.onChange(e)}},selectValue:function(e){var t=this;this.hasScrolledToOption=!1,this.props.multi?this.setState({inputValue:"",focusedIndex:null},function(){t.addValue(e)}):this.setState({isOpen:!1,inputValue:"",isPseudoFocused:this.state.isFocused},function(){t.setValue(e)})},addValue:function(e){var t=this.getValueArray(this.props.value);this.setValue(t.concat(e))},popValue:function(){var e=this.getValueArray(this.props.value);e.length&&e[e.length-1].clearableValue!==!1&&this.setValue(e.slice(0,e.length-1))},removeValue:function(e){var t=this.getValueArray(this.props.value);this.setValue(t.filter(function(t){return t!==e})),this.focus()},clearValue:function(e){e&&"mousedown"===e.type&&0!==e.button||(e.stopPropagation(),e.preventDefault(),this.setValue(this.getResetValue()),this.setState({isOpen:!1,inputValue:""},this.focus))},getResetValue:function(){return void 0!==this.props.resetValue?this.props.resetValue:this.props.multi?[]:null},focusOption:function(e){this.setState({focusedOption:e})},focusNextOption:function(){this.focusAdjacentOption("next")},focusPreviousOption:function(){this.focusAdjacentOption("previous")},focusPageUpOption:function(){this.focusAdjacentOption("page_up")},focusPageDownOption:function(){this.focusAdjacentOption("page_down")},focusStartOption:function(){this.focusAdjacentOption("start")},focusEndOption:function(){this.focusAdjacentOption("end")},focusAdjacentOption:function(e){var t=this._visibleOptions.map(function(e,t){return{option:e,index:t}}).filter(function(e){return!e.option.disabled});if(this._scrollToFocusedOptionOnUpdate=!0,!this.state.isOpen)return void this.setState({isOpen:!0,inputValue:"",focusedOption:this._focusedOption||t["next"===e?0:t.length-1].option});if(t.length){for(var n=-1,r=0;r<t.length;r++)if(this._focusedOption===t[r].option){n=r;break}if("next"===e&&n!==-1)n=(n+1)%t.length;else if("previous"===e)n>0?n-=1:n=t.length-1;else if("start"===e)n=0;else if("end"===e)n=t.length-1;else if("page_up"===e){var o=n-this.props.pageSize;n=o<0?0:o}else if("page_down"===e){var o=n+this.props.pageSize;n=o>t.length-1?t.length-1:o}n===-1&&(n=0),this.setState({focusedIndex:t[n].index,focusedOption:t[n].option})}},getFocusedOption:function(){return this._focusedOption},getInputValue:function(){return this.state.inputValue},selectFocusedOption:function(){if(this._focusedOption)return this.selectValue(this._focusedOption)},renderLoading:function(){if(this.props.isLoading)return l["default"].createElement("span",{className:"Select-loading-zone","aria-hidden":"true"},l["default"].createElement("span",{className:"Select-loading"}))},renderValue:function(e,t){var n=this,r=this.props.valueRenderer||this.getOptionLabel,o=this.props.valueComponent;if(!e.length)return this.state.inputValue?null:l["default"].createElement("div",{className:"Select-placeholder"},this.props.placeholder);var i=this.props.onValueClick?this.handleValueClick:null;return this.props.multi?e.map(function(e,t){return l["default"].createElement(o,{id:n._instancePrefix+"-value-"+t,instancePrefix:n._instancePrefix,disabled:n.props.disabled||e.clearableValue===!1,key:"value-"+t+"-"+e[n.props.valueKey],onClick:i,onRemove:n.removeValue,value:e},r(e,t),l["default"].createElement("span",{className:"Select-aria-only"}," "))}):this.state.inputValue?void 0:(t&&(i=null),l["default"].createElement(o,{id:this._instancePrefix+"-value-item",disabled:this.props.disabled,instancePrefix:this._instancePrefix,onClick:i,value:e[0]},r(e[0])))},renderInput:function(e,t){var n=this;if(this.props.inputRenderer)return this.props.inputRenderer();var r,u=(0,g["default"])("Select-input",this.props.inputProps.className),a=!!this.state.isOpen,c=(0,g["default"])((r={},i(r,this._instancePrefix+"-list",a),i(r,this._instancePrefix+"-backspace-remove-message",this.props.multi&&!this.props.disabled&&this.state.isFocused&&!this.state.inputValue),r)),p=s({},this.props.inputProps,{role:"combobox","aria-expanded":""+a,"aria-owns":c,"aria-haspopup":""+a,"aria-activedescendant":a?this._instancePrefix+"-option-"+t:this._instancePrefix+"-value","aria-labelledby":this.props["aria-labelledby"],"aria-label":this.props["aria-label"],className:u,tabIndex:this.props.tabIndex,onBlur:this.handleInputBlur,onChange:this.handleInputChange,onFocus:this.handleInputFocus,ref:function(e){return n.input=e},required:this.state.required,value:this.state.inputValue});if(this.props.disabled||!this.props.searchable){var f=this.props.inputProps,h=(f.inputClassName,o(f,["inputClassName"]));return l["default"].createElement("div",s({},h,{role:"combobox","aria-expanded":a,"aria-owns":a?this._instancePrefix+"-list":this._instancePrefix+"-value","aria-activedescendant":a?this._instancePrefix+"-option-"+t:this._instancePrefix+"-value",className:u,tabIndex:this.props.tabIndex||0,onBlur:this.handleInputBlur,onFocus:this.handleInputFocus,ref:function(e){return n.input=e},"aria-readonly":""+!!this.props.disabled,style:{border:0,width:1,display:"inline-block"}}))}return this.props.autosize?l["default"].createElement(d["default"],s({},p,{minWidth:"5px"})):l["default"].createElement("div",{className:u},l["default"].createElement("input",p))},renderClear:function(){if(this.props.clearable&&this.props.value&&0!==this.props.value&&(!this.props.multi||this.props.value.length)&&!this.props.disabled&&!this.props.isLoading)return l["default"].createElement("span",{className:"Select-clear-zone",title:this.props.multi?this.props.clearAllText:this.props.clearValueText,"aria-label":this.props.multi?this.props.clearAllText:this.props.clearValueText,onMouseDown:this.clearValue,onTouchStart:this.handleTouchStart,onTouchMove:this.handleTouchMove,onTouchEnd:this.handleTouchEndClearValue},l["default"].createElement("span",{className:"Select-clear",dangerouslySetInnerHTML:{__html:"×"}}))},renderArrow:function(){return l["default"].createElement("span",{className:"Select-arrow-zone",onMouseDown:this.handleMouseDownOnArrow},l["default"].createElement("span",{className:"Select-arrow",onMouseDown:this.handleMouseDownOnArrow}))},filterOptions:function I(e){var t=this.state.inputValue,n=this.props.options||[];if(this.props.filterOptions){var I="function"==typeof this.props.filterOptions?this.props.filterOptions:v["default"];return I(n,t,e,{filterOption:this.props.filterOption,ignoreAccents:this.props.ignoreAccents,ignoreCase:this.props.ignoreCase,labelKey:this.props.labelKey,matchPos:this.props.matchPos,matchProp:this.props.matchProp,valueKey:this.props.valueKey})}return n},renderMenu:function(e,t,n){return e&&e.length?this.props.menuRenderer({focusedOption:n,focusOption:this.focusOption,instancePrefix:this._instancePrefix,labelKey:this.props.labelKey,onFocus:this.focusOption,onSelect:this.selectValue,optionClassName:this.props.optionClassName,optionComponent:this.props.optionComponent,optionRenderer:this.props.optionRenderer||this.getOptionLabel,options:e,selectValue:this.selectValue,valueArray:t,valueKey:this.props.valueKey}):this.props.noResultsText?l["default"].createElement("div",{className:"Select-noresults"},this.props.noResultsText):null},renderHiddenField:function(e){var t=this;if(this.props.name){if(this.props.joinValues){var n=e.map(function(e){return u(e[t.props.valueKey])}).join(this.props.delimiter);return l["default"].createElement("input",{type:"hidden",ref:function(e){return t.value=e},name:this.props.name,value:n,disabled:this.props.disabled})}return e.map(function(e,n){return l["default"].createElement("input",{key:"hidden."+n,type:"hidden",ref:"value"+n,name:t.props.name,value:u(e[t.props.valueKey]),disabled:t.props.disabled})})}},getFocusableOptionIndex:function(e){var t=this._visibleOptions;if(!t.length)return null;var n=this.state.focusedOption||e;if(n&&!n.disabled){var r=t.indexOf(n);if(r!==-1)return r}for(var o=0;o<t.length;o++)if(!t[o].disabled)return o;return null},renderOuter:function(e,t,n){var r=this,o=this.renderMenu(e,t,n);return o?l["default"].createElement("div",{ref:function(e){return r.menuContainer=e},className:"Select-menu-outer",style:this.props.menuContainerStyle},l["default"].createElement("div",{ref:function(e){return r.menu=e},role:"listbox",className:"Select-menu",id:this._instancePrefix+"-list",style:this.props.menuStyle,onScroll:this.handleMenuScroll,onMouseDown:this.handleMouseDownOnMenu},o)):null},render:function(){var e=this,t=this.getValueArray(this.props.value),n=this._visibleOptions=this.filterOptions(this.props.multi?this.getValueArray(this.props.value):null),r=this.state.isOpen;this.props.multi&&!n.length&&t.length&&!this.state.inputValue&&(r=!1);var o=this.getFocusableOptionIndex(t[0]),i=null;i=null!==o?this._focusedOption=n[o]:this._focusedOption=null;var u=(0,g["default"])("Select",this.props.className,{"Select--multi":this.props.multi,"Select--single":!this.props.multi,"is-disabled":this.props.disabled,"is-focused":this.state.isFocused,"is-loading":this.props.isLoading,"is-open":r,"is-pseudo-focused":this.state.isPseudoFocused,"is-searchable":this.props.searchable,"has-value":t.length}),s=null;return this.props.multi&&!this.props.disabled&&t.length&&!this.state.inputValue&&this.state.isFocused&&this.props.backspaceRemoves&&(s=l["default"].createElement("span",{id:this._instancePrefix+"-backspace-remove-message",className:"Select-aria-only","aria-live":"assertive"},this.props.backspaceToRemoveMessage.replace("{label}",t[t.length-1][this.props.labelKey]))),l["default"].createElement("div",{ref:function(t){return e.wrapper=t},className:u,style:this.props.wrapperStyle},this.renderHiddenField(t),l["default"].createElement("div",{ref:function(t){return e.control=t},className:"Select-control",style:this.props.style,onKeyDown:this.handleKeyDown,onMouseDown:this.handleMouseDown,onTouchEnd:this.handleTouchEnd,onTouchStart:this.handleTouchStart,onTouchMove:this.handleTouchMove},l["default"].createElement("span",{className:"Select-multi-value-wrapper",id:this._instancePrefix+"-value"},this.renderValue(t,r),this.renderInput(t,o)),s,this.renderLoading(),this.renderClear(),this.renderArrow()),r?this.renderOuter(n,this.props.multi?null:t,i):null)}});t["default"]=M,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){function r(){v===y&&(v=y.slice())}function i(){return g}function s(e){if("function"!=typeof e)throw new Error("Expected listener to be a function.");var t=!0;return r(),v.push(e),function(){if(t){t=!1,r();var n=v.indexOf(e);v.splice(n,1)}}}function c(e){if(!(0,u["default"])(e))throw new Error("Actions must be plain objects. Use custom middleware for async actions.");if("undefined"==typeof e.type)throw new Error('Actions may not have an undefined "type" property. Have you misspelled a constant?');if(m)throw new Error("Reducers may not dispatch actions.");try{m=!0,g=h(g,e)}finally{m=!1}for(var t=y=v,n=0;n<t.length;n++)t[n]();return e}function p(e){if("function"!=typeof e)throw new Error("Expected the nextReducer to be a function.");h=e,c({type:l.INIT})}function f(){var e,t=s;return e={subscribe:function(e){function n(){e.next&&e.next(i())}if("object"!=typeof e)throw new TypeError("Expected the observer to be an object.");n();var r=t(n);return{unsubscribe:r}}},e[a["default"]]=function(){return this},e}var d;if("function"==typeof t&&"undefined"==typeof n&&(n=t,t=void 0),"undefined"!=typeof n){if("function"!=typeof n)throw new Error("Expected the enhancer to be a function.");return n(o)(e,t)}if("function"!=typeof e)throw new Error("Expected the reducer to be a function.");
var h=e,g=t,y=[],v=y,m=!1;return c({type:l.INIT}),d={dispatch:c,subscribe:s,getState:i,replaceReducer:p},d[a["default"]]=f,d}t.__esModule=!0,t.ActionTypes=void 0,t["default"]=o;var i=n(4),u=r(i),s=n(254),a=r(s),l=t.ActionTypes={INIT:"@@redux/INIT"}},function(e,t){"use strict";t.__esModule=!0;t.DragItemTypes={Column:"column"}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=n(252),i=n(113),u=r(i),s=n(41),a=r(s),l=n(90),c=n(89),p=n(91),f=function(e){return e.rows},d=function(e){return e.filters},h=(0,o.createSelector)([d,f],function(e){var t=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];return!e||(0,u["default"])(e)?t:c(e,t)}),g=function(e){return e.sortColumn},y=function(e){return e.sortDirection},v=(0,o.createSelector)([h,g,y],function(e,t,n){return n||t?p(e,t,n):e}),m=function(e){return e.groupBy},b=function(e){return e.expandedRows},E=(0,o.createSelector)([v,m,b],function(e,t){var n=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return!t||(0,u["default"])(t)||(0,a["default"])(t)?e:l(e,t,n)}),w=function(e){return e.selectedKeys},T=function(e){return e.rowKey},_=(0,o.createSelector)([T,w,f],function(e,t){var n=arguments.length<=2||void 0===arguments[2]?[]:arguments[2];return t.map(function(t){return n.filter(function(n){return n[e]===t})[0]})}),D={getRows:E,getSelectedRowsByKey:_};e.exports=D},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e,t){return{connectDragSource:e.dragSource(),isDragging:t.isDragging(),connectDragPreview:e.dragPreview()}}t.__esModule=!0;var a=n(36),l=n(7),c=n(84),p=r(c),f=n(1),d=r(f),h=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return u(t,e),t.prototype.componentDidMount=function(){var e=this.props.connectDragPreview,t=new Image;t.src="./assets/images/drag_column_full.png",t.onload=function(){e(t)}},t.prototype.setScrollLeft=function(e){var t=ReactDOM.findDOMNode(this);t.style.webkitTransform="translate3d("+e+"px, 0px, 0px)",t.style.transform="translate3d("+e+"px, 0px, 0px)"},t.prototype.render=function(){var e=this.props,t=e.connectDragSource,n=e.isDragging;return n?null:t(d["default"].createElement("div",{style:{cursor:"move"}},d["default"].createElement(p["default"],this.props)))},t}(f.Component);h.propTypes={connectDragSource:f.PropTypes.func.isRequired,connectDragPreview:f.PropTypes.func.isRequired,isDragging:f.PropTypes.bool.isRequired};var g={beginDrag:function(e){return e.column},endDrag:function(e){return e.column}};t["default"]=(0,l.DragSource)(a.DragItemTypes.Column,g,s)(h)},function(e,t,n){"use strict";var r=n(1),o=r.createClass({displayName:"CheckboxEditor",propTypes:{value:r.PropTypes.bool,rowIdx:r.PropTypes.number,column:r.PropTypes.shape({key:r.PropTypes.string,onCellChange:r.PropTypes.func}),dependentValues:r.PropTypes.object},handleChange:function(e){this.props.column.onCellChange(this.props.rowIdx,this.props.column.key,this.props.dependentValues,e)},render:function(){var e=null!=this.props.value&&this.props.value,t="checkbox"+this.props.rowIdx;return r.createElement("div",{className:"react-grid-checkbox-container",onClick:this.handleChange},r.createElement("input",{className:"react-grid-checkbox",type:"checkbox",name:t,checked:e}),r.createElement("label",{htmlFor:t,className:"react-grid-checkbox-label"}))}});e.exports=o},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var u=n(1),s=n(3),a=n(8),l=function(e){function t(){return r(this,t),o(this,e.apply(this,arguments))}return i(t,e),t.prototype.getStyle=function(){return{width:"100%"}},t.prototype.getValue=function(){var e={};return e[this.props.column.key]=this.getInputNode().value,e},t.prototype.getInputNode=function(){var e=s.findDOMNode(this);return"INPUT"===e.tagName?e:e.querySelector("input:not([type=hidden])")},t.prototype.inheritContainerStyles=function(){return!0},t}(u.Component);l.propTypes={onKeyDown:u.PropTypes.func.isRequired,value:u.PropTypes.any.isRequired,onBlur:u.PropTypes.func.isRequired,column:u.PropTypes.shape(a).isRequired,commit:u.PropTypes.func.isRequired},e.exports=l},function(e,t){"use strict";t.__esModule=!0;var n=function(e){return Array.isArray(e)&&0===e.length};t["default"]=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e){return e&&e.constructor===Symbol?"symbol":typeof e}function u(e){f["default"]("function"==typeof e.canDrag,"Expected canDrag to be a function."),f["default"]("function"==typeof e.beginDrag,"Expected beginDrag to be a function."),f["default"]("function"==typeof e.endDrag,"Expected endDrag to be a function.")}function s(e){f["default"]("function"==typeof e.canDrop,"Expected canDrop to be a function."),f["default"]("function"==typeof e.hover,"Expected hover to be a function."),f["default"]("function"==typeof e.drop,"Expected beginDrag to be a function.")}function a(e,t){return t&&h["default"](e)?void e.forEach(function(e){return a(e,!1)}):void f["default"]("string"==typeof e||"symbol"===("undefined"==typeof e?"undefined":i(e)),t?"Type can only be a string, a symbol, or an array of either.":"Type can only be a string or a symbol.")}function l(e){var t=y["default"]().toString();switch(e){case E.SOURCE:return"S"+t;case E.TARGET:return"T"+t;default:f["default"](!1,"Unknown role: "+e)}}function c(e){switch(e[0]){case"S":return E.SOURCE;case"T":return E.TARGET;default:f["default"](!1,"Cannot parse handler ID: "+e)}}t.__esModule=!0;var p=n(2),f=r(p),d=n(5),h=r(d),g=n(129),y=r(g),v=n(13),m=n(81),b=r(m),E={SOURCE:"SOURCE",TARGET:"TARGET"},w=function(){function e(t){o(this,e),this.store=t,this.types={},this.handlers={},this.pinnedSourceId=null,this.pinnedSource=null}return e.prototype.addSource=function(e,t){a(e),u(t);var n=this.addHandler(E.SOURCE,e,t);return this.store.dispatch(v.addSource(n)),n},e.prototype.addTarget=function(e,t){a(e,!0),s(t);var n=this.addHandler(E.TARGET,e,t);return this.store.dispatch(v.addTarget(n)),n},e.prototype.addHandler=function(e,t,n){var r=l(e);return this.types[r]=t,this.handlers[r]=n,r},e.prototype.containsHandler=function(e){var t=this;return Object.keys(this.handlers).some(function(n){return t.handlers[n]===e})},e.prototype.getSource=function(e,t){f["default"](this.isSourceId(e),"Expected a valid source ID.");var n=t&&e===this.pinnedSourceId,r=n?this.pinnedSource:this.handlers[e];return r},e.prototype.getTarget=function(e){return f["default"](this.isTargetId(e),"Expected a valid target ID."),this.handlers[e]},e.prototype.getSourceType=function(e){return f["default"](this.isSourceId(e),"Expected a valid source ID."),this.types[e]},e.prototype.getTargetType=function(e){return f["default"](this.isTargetId(e),"Expected a valid target ID."),this.types[e]},e.prototype.isSourceId=function(e){var t=c(e);return t===E.SOURCE},e.prototype.isTargetId=function(e){var t=c(e);return t===E.TARGET},e.prototype.removeSource=function(e){var t=this;f["default"](this.getSource(e),"Expected an existing source."),this.store.dispatch(v.removeSource(e)),b["default"](function(){delete t.handlers[e],delete t.types[e]})},e.prototype.removeTarget=function(e){var t=this;f["default"](this.getTarget(e),"Expected an existing target."),this.store.dispatch(v.removeTarget(e)),b["default"](function(){delete t.handlers[e],delete t.types[e]})},e.prototype.pinSource=function(e){var t=this.getSource(e);f["default"](t,"Expected an existing source."),this.pinnedSourceId=e,this.pinnedSource=t},e.prototype.unpinSource=function(){f["default"](this.pinnedSource,"No source is pinned at the time."),this.pinnedSourceId=null,this.pinnedSource=null},e}();t["default"]=w,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){switch(void 0===e&&(e=f),t.type){case c.HOVER:break;case p.ADD_SOURCE:case p.ADD_TARGET:case p.REMOVE_TARGET:case p.REMOVE_SOURCE:return f;case c.BEGIN_DRAG:case c.PUBLISH_DRAG_SOURCE:case c.END_DRAG:case c.DROP:default:return d}var r=t.targetIds,o=n.targetIds,i=s["default"](r,o),u=!1;if(0===i.length){for(var a=0;a<r.length;a++)if(r[a]!==o[a]){u=!0;break}}else u=!0;if(!u)return f;var l=o[o.length-1],h=r[r.length-1];return l!==h&&(l&&i.push(l),h&&i.push(h)),i}function i(e,t){return e!==f&&(e===d||"undefined"==typeof t||l["default"](t,e).length>0)}t.__esModule=!0,t["default"]=o,t.areDirty=i;var u=n(205),s=r(u),a=n(200),l=r(a),c=n(12),p=n(13),f=[],d=[]},function(e,t,n){"use strict";function r(e,t){return e===t||e&&t&&e.x===t.x&&e.y===t.y}function o(e,t){switch(void 0===e&&(e=l),t.type){case a.BEGIN_DRAG:return{initialSourceClientOffset:t.sourceClientOffset,initialClientOffset:t.clientOffset,clientOffset:t.clientOffset};case a.HOVER:return r(e.clientOffset,t.clientOffset)?e:s({},e,{clientOffset:t.clientOffset});case a.END_DRAG:case a.DROP:return l;default:return e}}function i(e){var t=e.clientOffset,n=e.initialClientOffset,r=e.initialSourceClientOffset;return t&&n&&r?{x:t.x+r.x-n.x,y:t.y+r.y-n.y}:null}function u(e){var t=e.clientOffset,n=e.initialClientOffset;return t&&n?{x:t.x-n.x,y:t.y-n.y}:null}t.__esModule=!0;var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=o,t.getSourceClientOffset=i,t.getDifferenceFromInitialOffset=u;var a=n(12),l={initialSourceClientOffset:null,initialClientOffset:null,clientOffset:null}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return u["default"](e)?e.some(function(e){return e===t}):e===t}t.__esModule=!0,t["default"]=o;var i=n(5),u=r(i);e.exports=t["default"]},function(e,t){"use strict";e.exports=function(e,t){return e.classList?!!t&&e.classList.contains(t):(" "+e.className+" ").indexOf(" "+t+" ")!==-1}},function(e,t,n){var r,o,i;!function(n,u){o=[t],r=u,i="function"==typeof r?r.apply(t,o):r,!(void 0!==i&&(e.exports=i))}(this,function(e){var t=e;t.interopRequireDefault=function(e){return e&&e.__esModule?e:{"default":e}},t._extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}})},function(e,t,n){"use strict";var r=n(141),o=/^-ms-/;e.exports=function(e){return r(e.replace(o,"ms-"))}},function(e,t,n){function r(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var o=n(188),i=n(189),u=n(190),s=n(191),a=n(192);r.prototype.clear=o,r.prototype["delete"]=i,r.prototype.get=u,r.prototype.has=s,r.prototype.set=a,e.exports=r},function(e,t){function n(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}e.exports=n},function(e,t){function n(e,t){for(var n=-1,r=t.length,o=e.length;++n<r;)e[o+n]=t[n];return e}e.exports=n},function(e,t,n){function r(e,t,n,r){var p=-1,f=i,d=!0,h=e.length,g=[],y=t.length;if(!h)return g;n&&(t=s(t,a(n))),r?(f=u,d=!1):t.length>=c&&(f=l,d=!1,t=new o(t));e:for(;++p<h;){var v=e[p],m=n?n(v):v;if(v=r||0!==v?v:0,d&&m===m){for(var b=y;b--;)if(t[b]===m)continue e;g.push(v)}else f(t,m,r)||g.push(v)}return g}var o=n(24),i=n(25),u=n(26),s=n(27),a=n(53),l=n(28),c=200;e.exports=r},function(e,t){function n(e){return function(t){return e(t)}}e.exports=n},function(e,t,n){function r(e,t,n){var r=-1,p=i,f=e.length,d=!0,h=[],g=h;if(n)d=!1,p=u;else if(f>=c){var y=t?null:a(e);if(y)return l(y);d=!1,p=s,g=new o}else g=t?[]:h;e:for(;++r<f;){var v=e[r],m=t?t(v):v;if(v=n||0!==v?v:0,d&&m===m){for(var b=g.length;b--;)if(g[b]===m)continue e;t&&g.push(m),h.push(v)}else p(g,m,n)||(g!==h&&g.push(m),h.push(v))}return h}var o=n(24),i=n(25),u=n(26),s=n(28),a=n(169),l=n(57),c=200;e.exports=r},function(e,t){function n(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(n){}return t}e.exports=n},function(e,t){function n(e,t){return t=null==t?r:t,!!t&&("number"==typeof e||o.test(e))&&e>-1&&e%1==0&&e<t}var r=9007199254740991,o=/^(?:0|[1-9]\d*)$/;e.exports=n},function(e,t){function n(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}e.exports=n},function(e,t,n){function r(e){return o(e)&&s.call(e,"callee")&&(!l.call(e,"callee")||a.call(e)==i)}var o=n(10),i="[object Arguments]",u=Object.prototype,s=u.hasOwnProperty,a=u.toString,l=u.propertyIsEnumerable;e.exports=r},function(e,t,n){function r(e){var t=o(e)?a.call(e):"";return t==i||t==u}var o=n(11),i="[object Function]",u="[object GeneratorFunction]",s=Object.prototype,a=s.toString;e.exports=r},function(e,t){function n(e){return!!e&&"object"==typeof e}e.exports=n},function(e,t){function n(){}e.exports=n},function(e,t,n){var r=n(52),o=n(6),i=n(10),u=o(function(e,t){return i(e)?r(e,t):[]});e.exports=u},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(207);Object.defineProperty(t,"ContextMenu",{enumerable:!0,get:function(){return r(o)["default"]}});var i=n(209);Object.defineProperty(t,"ContextMenuLayer",{enumerable:!0,get:function(){return r(i)["default"]}});var u=n(210);Object.defineProperty(t,"MenuItem",{enumerable:!0,get:function(){return r(u)["default"]}});var s=n(31);Object.defineProperty(t,"monitor",{enumerable:!0,get:function(){return r(s)["default"]}});var a=n(212);Object.defineProperty(t,"SubMenu",{enumerable:!0,get:function(){return r(a)["default"]}});var l=n(206);Object.defineProperty(t,"connect",{enumerable:!0,get:function(){return r(l)["default"]}})},21,function(e,t){"use strict";function n(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function r(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var o={};return"abcdefghijklmnopqrst".split("").forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(i){return!1}}var o=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;e.exports=r()?Object.assign:function(e,t){for(var r,u,s=n(e),a=1;a<arguments.length;a++){r=Object(arguments[a]);for(var l in r)o.call(r,l)&&(s[l]=r[l]);if(Object.getOwnPropertySymbols){u=Object.getOwnPropertySymbols(r);for(var c=0;c<u.length;c++)i.call(r,u[c])&&(s[u[c]]=r[u[c]])}}return s}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(203),i=r(o),u=i["default"](function(){return/firefox/i.test(navigator.userAgent)});t.isFirefox=u;var s=i["default"](function(){return Boolean(window.safari)});t.isSafari=s},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return t===e||null!==t&&null!==e&&u["default"](t,e)}t.__esModule=!0,t["default"]=o;var i=n(33),u=r(i);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e){var t=e.DecoratedComponent,n=e.createHandler,r=e.createMonitor,u=e.createConnector,f=e.registerHandler,h=e.containerDisplayName,y=e.getType,v=e.collect,b=e.options,E=b.arePropsEqual,w=void 0===E?g["default"]:E,T=t.displayName||t.name||"Component";return function(e){function g(t,i){o(this,g),e.call(this,t,i),this.handleChange=this.handleChange.bind(this),this.handleChildRef=this.handleChildRef.bind(this),m["default"]("object"==typeof this.context.dragDropManager,"Could not find the drag and drop manager in the context of %s. Make sure to wrap the top-level component of your app with DragDropContext. Read more: http://gaearon.github.io/react-dnd/docs-troubleshooting.html#could-not-find-the-drag-and-drop-manager-in-the-context",T,T),this.manager=this.context.dragDropManager,this.handlerMonitor=r(this.manager),this.handlerConnector=u(this.manager.getBackend()),this.handler=n(this.handlerMonitor),this.disposable=new p.SerialDisposable,this.receiveProps(t),this.state=this.getCurrentState(),this.dispose()}return i(g,e),g.prototype.getHandlerId=function(){return this.handlerId},g.prototype.getDecoratedComponentInstance=function(){return this.decoratedComponentInstance},g.prototype.shouldComponentUpdate=function(e,t){return!w(e,this.props)||!d["default"](t,this.state)},a(g,null,[{key:"DecoratedComponent",value:t,enumerable:!0},{key:"displayName",value:h+"("+T+")",enumerable:!0},{key:"contextTypes",value:{dragDropManager:l.PropTypes.object.isRequired},enumerable:!0}]),g.prototype.componentDidMount=function(){this.isCurrentlyMounted=!0,this.disposable=new p.SerialDisposable,this.currentType=null,this.receiveProps(this.props),this.handleChange()},g.prototype.componentWillReceiveProps=function(e){w(e,this.props)||(this.receiveProps(e),this.handleChange())},g.prototype.componentWillUnmount=function(){this.dispose(),this.isCurrentlyMounted=!1},g.prototype.receiveProps=function(e){this.handler.receiveProps(e),this.receiveType(y(e))},g.prototype.receiveType=function(e){if(e!==this.currentType){this.currentType=e;var t=f(e,this.handler,this.manager),n=t.handlerId,r=t.unregister;this.handlerId=n,this.handlerMonitor.receiveHandlerId(n),this.handlerConnector.receiveHandlerId(n);var o=this.manager.getMonitor(),i=o.subscribeToStateChange(this.handleChange,{handlerIds:[n]});this.disposable.setDisposable(new p.CompositeDisposable(new p.Disposable(i),new p.Disposable(r)))}},g.prototype.handleChange=function(){if(this.isCurrentlyMounted){var e=this.getCurrentState();d["default"](e,this.state)||this.setState(e)}},g.prototype.dispose=function(){this.disposable.dispose(),this.handlerConnector.receiveHandlerId(null)},g.prototype.handleChildRef=function(e){this.decoratedComponentInstance=e,this.handler.receiveComponent(e)},g.prototype.getCurrentState=function(){var e=v(this.handlerConnector.hooks,this.handlerMonitor);return e},g.prototype.render=function(){return c["default"].createElement(t,s({},this.props,this.state,{ref:this.handleChildRef}))},g}(l.Component)}t.__esModule=!0;var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}();t["default"]=u;var l=n(1),c=r(l),p=n(118),f=n(33),d=r(f),h=n(70),g=r(h),y=n(4),v=(r(y),n(2)),m=r(v);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return"string"==typeof e||"symbol"==typeof e||t&&u["default"](e)&&e.every(function(e){return o(e,!1)})}t.__esModule=!0,t["default"]=o;var i=n(5),u=r(i);e.exports=t["default"]},function(e,t){"use strict";function n(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(var o=Object.prototype.hasOwnProperty,i=0;i<n.length;i++){if(!o.call(t,n[i]))return!1;var u=e[n[i]],s=t[n[i]];if(u!==s||"object"==typeof u||"object"==typeof s)return!1}return!0}t.__esModule=!0,t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if("string"!=typeof e.type){var t=e.type.displayName||e.type.name||"the component";throw new Error("Only native element nodes can now be passed to React DnD connectors. "+("You can either wrap "+t+" into a <div>, or turn it into a ")+"drag source or a drop target itself.")}}function i(e){return function(){var t=arguments.length<=0||void 0===arguments[0]?null:arguments[0],n=arguments.length<=1||void 0===arguments[1]?null:arguments[1];if(!l.isValidElement(t)){var r=t;return void e(r,n)}var i=t;o(i);var u=n?function(t){return e(t,n)}:e;return a["default"](i,u)}}function u(e){var t={};return Object.keys(e).forEach(function(n){var r=e[n],o=i(r);t[n]=function(){return o}}),t}t.__esModule=!0,t["default"]=u;var s=n(234),a=r(s),l=n(1);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return e="function"==typeof e?e():e,u["default"].findDOMNode(e)||t}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var i=n(3),u=r(i);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=function(e){return(0,s["default"])(i["default"].findDOMNode(e))};var o=n(3),i=r(o),u=n(23),s=r(u);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var u=e[t],a="undefined"==typeof u?"undefined":i(u);return s["default"].isValidElement(u)?new Error("Invalid "+r+" `"+o+"` of type ReactElement "+("supplied to `"+n+"`, expected a ReactComponent or a ")+"DOMElement. You can usually obtain a ReactComponent or DOMElement from a ReactElement by attaching a ref to it."):"object"===a&&"function"==typeof u.render||1===u.nodeType?null:new Error("Invalid "+r+" `"+o+"` of value `"+u+"` "+("supplied to `"+n+"`, expected a ReactComponent or a ")+"DOMElement.")}t.__esModule=!0;var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},u=n(1),s=r(u),a=n(75),l=r(a);t["default"]=(0,l["default"])(o)},function(e,t){"use strict";function n(e){function t(t,n,r,o,i,u){var s=o||"<<anonymous>>",a=u||r;if(null==n[r])return t?new Error("Required "+i+" `"+a+"` was not specified "+("in `"+s+"`.")):null;for(var l=arguments.length,c=Array(l>6?l-6:0),p=6;p<l;p++)c[p-6]=arguments[p];return e.apply(void 0,[n,r,s,i,a].concat(c))}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}t.__esModule=!0,t["default"]=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r){var o=this;return r.ignoreAccents&&(t=(0,u["default"])(t)),r.ignoreCase&&(t=t.toLowerCase()),n&&(n=n.map(function(e){return e[r.valueKey]})),e.filter(function(e){if(n&&n.indexOf(e[r.valueKey])>-1)return!1;if(r.filterOption)return r.filterOption.call(o,e,t);if(!t)return!0;var i=String(e[r.valueKey]),s=String(e[r.labelKey]);return r.ignoreAccents&&("label"!==r.matchProp&&(i=(0,u["default"])(i)),"value"!==r.matchProp&&(s=(0,u["default"])(s))),r.ignoreCase&&("label"!==r.matchProp&&(i=i.toLowerCase()),"value"!==r.matchProp&&(s=s.toLowerCase())),"start"===r.matchPos?"label"!==r.matchProp&&i.substr(0,t.length)===t||"value"!==r.matchProp&&s.substr(0,t.length)===t:"label"!==r.matchProp&&i.indexOf(t)>=0||"value"!==r.matchProp&&s.indexOf(t)>=0})}var i=n(78),u=r(i);e.exports=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.focusedOption,n=e.instancePrefix,r=(e.labelKey,e.onFocus),o=e.onSelect,i=e.optionClassName,s=e.optionComponent,l=e.optionRenderer,c=e.options,p=e.valueArray,f=e.valueKey,d=s;return c.map(function(e,s){var c=p&&p.indexOf(e)>-1,h=e===t,g=h?"focused":null,y=(0,u["default"])(i,{"Select-option":!0,"is-selected":c,"is-focused":h,"is-disabled":e.disabled});return a["default"].createElement(d,{className:y,instancePrefix:n,isDisabled:e.disabled,isFocused:h,isSelected:c,key:"option-"+s+"-"+e[f],onFocus:r,onSelect:o,option:e,optionIndex:s,ref:g},l(e,s))})}var i=n(21),u=r(i),s=n(1),a=r(s);e.exports=o},function(e,t){"use strict";var n=[{base:"A",letters:/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g},{base:"AA",letters:/[\uA732]/g},{base:"AE",letters:/[\u00C6\u01FC\u01E2]/g},{base:"AO",letters:/[\uA734]/g},{base:"AU",letters:/[\uA736]/g},{base:"AV",letters:/[\uA738\uA73A]/g},{base:"AY",letters:/[\uA73C]/g},{base:"B",letters:/[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g},{base:"C",letters:/[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g},{base:"D",letters:/[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g},{base:"DZ",letters:/[\u01F1\u01C4]/g},{base:"Dz",letters:/[\u01F2\u01C5]/g},{base:"E",letters:/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g},{base:"F",letters:/[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g},{base:"G",letters:/[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g},{base:"H",letters:/[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g},{base:"I",letters:/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g},{base:"J",letters:/[\u004A\u24BF\uFF2A\u0134\u0248]/g},{base:"K",letters:/[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g},{base:"L",letters:/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g},{base:"LJ",letters:/[\u01C7]/g},{base:"Lj",letters:/[\u01C8]/g},{base:"M",letters:/[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g},{base:"N",letters:/[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g},{base:"NJ",letters:/[\u01CA]/g},{base:"Nj",letters:/[\u01CB]/g},{base:"O",letters:/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g},{base:"OI",letters:/[\u01A2]/g},{base:"OO",letters:/[\uA74E]/g},{base:"OU",letters:/[\u0222]/g},{base:"P",letters:/[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g},{base:"Q",letters:/[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g},{base:"R",letters:/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g},{base:"S",letters:/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g},{base:"T",letters:/[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g},{base:"TZ",letters:/[\uA728]/g},{base:"U",letters:/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g},{base:"V",letters:/[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g},{base:"VY",letters:/[\uA760]/g},{base:"W",letters:/[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g},{base:"X",letters:/[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g},{base:"Y",letters:/[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g},{base:"Z",letters:/[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g},{base:"a",letters:/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g},{base:"aa",letters:/[\uA733]/g},{base:"ae",letters:/[\u00E6\u01FD\u01E3]/g},{base:"ao",letters:/[\uA735]/g},{base:"au",letters:/[\uA737]/g},{base:"av",letters:/[\uA739\uA73B]/g},{base:"ay",letters:/[\uA73D]/g},{base:"b",letters:/[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g},{base:"c",letters:/[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g},{base:"d",letters:/[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g},{base:"dz",letters:/[\u01F3\u01C6]/g},{base:"e",letters:/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g},{base:"f",letters:/[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g},{base:"g",letters:/[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g},{base:"h",letters:/[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g},{base:"hv",letters:/[\u0195]/g},{base:"i",letters:/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g},{base:"j",letters:/[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g},{base:"k",letters:/[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g},{base:"l",letters:/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g},{base:"lj",letters:/[\u01C9]/g},{base:"m",letters:/[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g},{base:"n",letters:/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g},{base:"nj",letters:/[\u01CC]/g},{base:"o",letters:/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g},{base:"oi",letters:/[\u01A3]/g},{base:"ou",letters:/[\u0223]/g},{base:"oo",letters:/[\uA74F]/g},{base:"p",letters:/[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g},{base:"q",letters:/[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g},{base:"r",letters:/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g},{base:"s",letters:/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g},{base:"t",letters:/[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g},{base:"tz",letters:/[\uA729]/g},{base:"u",letters:/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g
},{base:"v",letters:/[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g},{base:"vy",letters:/[\uA761]/g},{base:"w",letters:/[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g},{base:"x",letters:/[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g},{base:"y",letters:/[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g},{base:"z",letters:/[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g}];e.exports=function(e){for(var t=0;t<n.length;t++)e=e.replace(n[t].letters,n[t].base);return e}},function(e,t){"use strict";function n(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];if(0===t.length)return function(e){return e};if(1===t.length)return t[0];var r=t[t.length-1],o=t.slice(0,-1);return function(){return o.reduceRight(function(e,t){return t(e)},r.apply(void 0,arguments))}}t.__esModule=!0,t["default"]=n},function(e,t){"use strict";function n(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(t){}}t.__esModule=!0,t["default"]=n},function(e,t,n){"use strict";function r(){if(a.length)throw a.shift()}function o(e){var t;t=s.length?s.pop():new i,t.task=e,u(t)}function i(){this.task=null}var u=n(82),s=[],a=[],l=u.makeRequestCallFromTimer(r);e.exports=o,i.prototype.call=function(){try{this.task.call()}catch(e){o.onerror?o.onerror(e):(a.push(e),l())}finally{this.task=null,s[s.length]=this}}},function(e,t,n){"use strict";function r(e){a.length||(s(),l=!0),a[a.length]=e}function o(){for(;c<a.length;){var e=c;if(c+=1,a[e].call(),c>p){for(var t=0,n=a.length-c;t<n;t++)a[t]=a[t+c];a.length-=c,c=0}}a.length=0,c=0,l=!1}function i(e){var t=1,n=new f(e),r=document.createTextNode("");return n.observe(r,{characterData:!0}),function(){t=-t,r.data=t}}function u(e){return function(){function t(){clearTimeout(n),clearInterval(r),e()}var n=setTimeout(t,0),r=setInterval(t,50)}}e.exports=r;var s,a=[],l=!1,c=0,p=1024,f=window.MutationObserver||window.WebKitMutationObserver;s="function"==typeof f?i(o):u(o),r.requestFlush=s,r.makeRequestCallFromTimer=u},function(e,t,n){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=n(1),i=o.PropTypes,u=o.createClass({displayName:"Draggable",propTypes:{onDragStart:i.func,onDragEnd:i.func,onDrag:i.func,component:i.oneOfType([i.func,i.constructor])},getDefaultProps:function(){return{onDragStart:function(){return!0},onDragEnd:function(){},onDrag:function(){}}},getInitialState:function(){return{drag:null}},componentWillUnmount:function(){this.cleanUp()},onMouseDown:function(e){var t=this.props.onDragStart(e);null===t&&0!==e.button||(window.addEventListener("mouseup",this.onMouseUp),window.addEventListener("mousemove",this.onMouseMove),window.addEventListener("touchend",this.onMouseUp),window.addEventListener("touchmove",this.onMouseMove),this.setState({drag:t}))},onMouseMove:function(e){null!==this.state.drag&&(e.preventDefault&&e.preventDefault(),this.props.onDrag(e))},onMouseUp:function(e){this.cleanUp(),this.props.onDragEnd(e,this.state.drag),this.setState({drag:null})},cleanUp:function(){window.removeEventListener("mouseup",this.onMouseUp),window.removeEventListener("mousemove",this.onMouseMove),window.removeEventListener("touchend",this.onMouseUp),window.removeEventListener("touchmove",this.onMouseMove)},render:function(){return o.createElement("div",r({},this.props,{onMouseDown:this.onMouseDown,onTouchStart:this.onMouseDown,className:"react-grid-HeaderCell__draggable"}))}});e.exports=u},function(e,t,n){"use strict";function r(e){return o.createElement("div",{className:"widget-HeaderCell__value"},e.column.name)}var o=n(1),i=n(3),u=n(114),s=n(8),a=n(85),l=o.PropTypes,c=o.createClass({displayName:"HeaderCell",propTypes:{renderer:l.oneOfType([l.func,l.element]).isRequired,column:l.shape(s).isRequired,onResize:l.func.isRequired,height:l.number.isRequired,onResizeEnd:l.func.isRequired,className:l.string},getDefaultProps:function(){return{renderer:r}},getInitialState:function(){return{resizing:!1}},onDragStart:function(e){this.setState({resizing:!0}),e&&e.dataTransfer&&e.dataTransfer.setData&&e.dataTransfer.setData("text/plain","dummy")},onDrag:function(e){var t=this.props.onResize||null;if(t){var n=this.getWidthFromMouseEvent(e);n>0&&t(this.props.column,n)}},onDragEnd:function(e){var t=this.getWidthFromMouseEvent(e);this.props.onResizeEnd(this.props.column,t),this.setState({resizing:!1})},getWidthFromMouseEvent:function(e){var t=e.pageX||e.touches&&e.touches[0]&&e.touches[0].pageX||e.changedTouches&&e.changedTouches[e.changedTouches.length-1].pageX,n=i.findDOMNode(this).getBoundingClientRect().left;return t-n},getCell:function(){return o.isValidElement(this.props.renderer)?o.cloneElement(this.props.renderer,{column:this.props.column,height:this.props.height}):this.props.renderer({column:this.props.column})},getStyle:function(){return{width:this.props.column.width,left:this.props.column.left,display:"inline-block",position:"absolute",height:this.props.height,margin:0,textOverflow:"ellipsis",whiteSpace:"nowrap"}},setScrollLeft:function(e){var t=i.findDOMNode(this);t.style.webkitTransform="translate3d("+e+"px, 0px, 0px)",t.style.transform="translate3d("+e+"px, 0px, 0px)"},render:function(){var e=void 0;this.props.column.resizable&&(e=o.createElement(a,{onDrag:this.onDrag,onDragStart:this.onDragStart,onDragEnd:this.onDragEnd}));var t=u({"react-grid-HeaderCell":!0,"react-grid-HeaderCell--resizing":this.state.resizing,"react-grid-HeaderCell--locked":this.props.column.locked});t=u(t,this.props.className,this.props.column.cellClass);var n=this.getCell();return o.createElement("div",{className:t,style:this.getStyle()},n,e)}});e.exports=c},function(e,t,n){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=n(1),i=n(83),u=o.createClass({displayName:"ResizeHandle",style:{position:"absolute",top:0,right:0,width:6,height:"100%"},render:function(){return o.createElement(i,r({},this.props,{className:"react-grid-HeaderCell__resizeHandle",style:this.style}))}});e.exports=u},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0;var s=n(1),a=r(s),l=n(8),c=r(l),p=n(34),f=r(p),d=n(41),h=r(d),g=function(e){function t(n){o(this,t);var r=i(this,e.call(this,n));return r.getOptions=r.getOptions.bind(r),r.handleChange=r.handleChange.bind(r),r.filterValues=r.filterValues.bind(r),r.state={options:r.getOptions(),rawValue:"",placeholder:"Search..."},r}return u(t,e),t.prototype.componentWillReceiveProps=function(e){this.setState({options:this.getOptions(e)})},t.prototype.getOptions=function(e){var t=e||this.props,n=t.getValidFilterValues(t.column.key);return n=n.map(function(e){return"string"==typeof e?{value:e,label:e}:e})},t.prototype.columnValueContainsSearchTerms=function n(e,t){var n=!1;for(var r in t)if(t.hasOwnProperty(r)){var o=t[r].value,i=e.trim().toLowerCase().indexOf(o.trim().toLowerCase()),u=i!==-1&&(0!==i||e===o);if(u){n=!0;break}}return n},t.prototype.filterValues=function(e,t,n){var r=!0;return null===t?r=!1:(0,h["default"])(t.filterTerm)||(r=this.columnValueContainsSearchTerms(e[n],t.filterTerm)),r},t.prototype.handleChange=function(e){var t=e;this.setState({filters:t}),this.props.onChange({filterTerm:t,column:this.props.column,rawValue:e,filterValues:this.filterValues})},t.prototype.render=function(){var e="filter-"+this.props.column.key;return a["default"].createElement("div",{style:{width:.9*this.props.column.width}},a["default"].createElement(f["default"],{name:e,options:this.state.options,placeholder:this.state.placeholder,onChange:this.handleChange,escapeClearsValue:!0,multi:!0,value:this.state.filters}))},t}(a["default"].Component);g.propTypes={onChange:s.PropTypes.func.isRequired,column:a["default"].PropTypes.shape(c["default"]),getValidFilterValues:s.PropTypes.func},t["default"]=g},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var s=n(1),a=r(s),l=n(8),c=r(l),p={Number:1,Range:2,GreaterThen:3,LessThen:4},f=function(e){function t(n){o(this,t);var r=i(this,e.call(this,n));return r.handleChange=r.handleChange.bind(r),r.handleKeyPress=r.handleKeyPress.bind(r),r.getRules=r.getRules.bind(r),r}return u(t,e),t.prototype.componentDidMount=function(){this.attachTooltip()},t.prototype.componentDidUpdate=function(){this.attachTooltip()},t.prototype.attachTooltip=function(){$?$('[data-toggle="tooltip"]').tooltip():jQuery&&jQuery('[data-toggle="tooltip"]').tooltip()},t.prototype.filterValues=function(e,t,n){if(null==t.filterTerm)return!0;var r=!1,o=parseInt(e[n],10);for(var i in t.filterTerm)if(t.filterTerm.hasOwnProperty(i)){var u=t.filterTerm[i];switch(u.type){case p.Number:u.value===o&&(r=!0);break;case p.GreaterThen:u.value<=o&&(r=!0);break;case p.LessThen:u.value>=o&&(r=!0);break;case p.Range:u.begin<=o&&u.end>=o&&(r=!0)}}return r},t.prototype.getRules=function(e){var t=[];if(""===e)return t;var n=e.split(",");if(n.length>0)for(var r in n)if(n.hasOwnProperty(r)){var o=n[r];if(o.indexOf("-")>0){var i=parseInt(o.split("-")[0],10),u=parseInt(o.split("-")[1],10);t.push({type:p.Range,begin:i,end:u})}else if(o.indexOf(">")>-1){var s=parseInt(o.split(">")[1],10);t.push({type:p.GreaterThen,value:s})}else if(o.indexOf("<")>-1){var a=parseInt(o.split("<")[1],10);t.push({type:p.LessThen,value:a})}else{var l=parseInt(o,10);t.push({type:p.Number,value:l})}}return t},t.prototype.handleKeyPress=function(e){var t=">|<|-|,|([0-9])",n=RegExp(t).test(e.key);n===!1&&e.preventDefault()},t.prototype.handleChange=function(e){var t=e.target.value,n=this.getRules(t);this.props.onChange({filterTerm:n.length>0?n:null,column:this.props.column,rawValue:t,filterValues:this.filterValues})},t.prototype.render=function(){var e="header-filter-"+this.props.column.key,t={"float":"left",marginRight:5,maxWidth:"80%"},n={cursor:"help"},r='<table><tbody><tr><td colspan="2"><strong>Input Methods:</strong></td></tr><tr><td><strong>- </strong></td><td style="text-align:left">Range</td></tr><tr><td><strong>> </strong></td><td style="text-align:left"> Greater Then</td></tr><tr><td><strong>< </strong></td><td style="text-align:left"> Less Then</td></tr></tbody>';return a["default"].createElement("div",null,a["default"].createElement("div",{style:t},a["default"].createElement("input",{key:e,type:"text",placeholder:"e.g. 3,10-15,>20",className:"form-control input-sm",onChange:this.handleChange,onKeyPress:this.handleKeyPress})),a["default"].createElement("div",{className:"input-sm"},a["default"].createElement("span",{className:"badge",style:n,"data-toggle":"tooltip","data-container":"body","data-html":"true",title:r},"?")))},t}(a["default"].Component);f.propTypes={onChange:a["default"].PropTypes.func.isRequired,column:a["default"].PropTypes.shape(c["default"])},e.exports=f},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=n(87),i=r(o),u=n(86),s=r(u),a={NumericFilter:i["default"],AutoCompleteFilter:s["default"]};e.exports=a},function(e,t){"use strict";var n=function(e){var t=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];return t.filter(function(t){var n=!0;for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];if(o.filterValues&&"function"==typeof o.filterValues&&!o.filterValues(t,o,r))n=!1;else if("string"==typeof o.filterTerm){var i=t[r];i?i.toString().toLowerCase().indexOf(o.filterTerm.toLowerCase())===-1&&(n=!1):n=!1}}return n})};e.exports=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var i=n(145),u=r(i),s=function(){function e(t,n){o(this,e),this.columns=t.slice(0),this.expandedRows=n}return e.prototype.isRowExpanded=function(e,t){var n=!0,r=this.expandedRows[e];return r&&r[t]&&(n=r[t].isExpanded),n},e.prototype.groupRowsByColumn=function(e){var t=this,n=arguments.length<=1||void 0===arguments[1]?0:arguments[1],r=n,o=[],i=this.columns[n],s=(0,u["default"])(e,i);return Object.keys(s).forEach(function(e){var u=t.isRowExpanded(i,e),a={name:e,__metaData:{isGroup:!0,treeDepth:n,isExpanded:u,columnGroupName:i}};o.push(a),u&&(r=n+1,t.columns.length>r?(o=o.concat(t.groupRowsByColumn(s[e],r)),r=n-1):o=o.concat(s[e]))}),o},e}(),a=function(e,t,n){var r=new s(t,n);return r.groupRowsByColumn(e,0)};e.exports=a},function(e,t){"use strict";var n=function(e,t,n){var r=function(e,r){return"ASC"===n?e[t]>r[t]?1:-1:"DESC"===n?e[t]<r[t]?1:-1:void 0};return"NONE"===n?e:e.sort(r)};e.exports=n},function(e,t,n){"use strict";e.exports={Selectors:n(37)}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0;var s=n(1),a=r(s),l=n(220),c=r(l),p=n(7),f=n(38),d=r(f),h=n(96),g=r(h),y=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return u(t,e),t.prototype.getRows=function(e,t){for(var n=[],r=0;r<e;r++)n.push(t(r));return n},t.prototype.renderGrid=function(){return a["default"].Children.map(this.props.children,function(e){return a["default"].cloneElement(e,{draggableHeaderCell:d["default"]})})[0]},t.prototype.render=function(){var e=this.renderGrid(),t=this.props.getDragPreviewRow||e.props.rowGetter,n=e.props.rowsCount,r=this.getRows(n,t);return a["default"].createElement("div",null,e,a["default"].createElement(g["default"],{rowSelection:e.props.rowSelection,rows:r}))},t}(s.Component);y.propTypes={children:a["default"].PropTypes.element.isRequired,getDragPreviewRow:a["default"].PropTypes.func},t["default"]=(0,p.DragDropContext)(c["default"])(y)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e,t){return{connectDropTarget:e.dropTarget(),isOver:t.isOver(),canDrop:t.canDrop(),draggedRow:t.getItem()}}t.__esModule=!0;var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(1),c=r(l),p=n(3),f=r(p),d=n(7),h=function(e){return function(t){function n(){return o(this,n),i(this,t.apply(this,arguments))}return u(n,t),n.prototype.moveRow=function(){f["default"].findDOMNode(this).classList.add("slideUp")},n.prototype.render=function(){var t=this.props,n=t.connectDropTarget,r=t.isOver,o=t.canDrop,i=this.props.idx*this.props.height;return n(c["default"].createElement("div",null,c["default"].createElement(e,a({ref:"row"},this.props)),r&&o&&c["default"].createElement("div",{style:{position:"absolute",top:i,left:0,height:this.props.height,width:"100%",zIndex:1,borderBottom:"1px solid black"}})))},n}(c["default"].Component)},g={drop:function(e,t,n){n.moveRow();var r=t.getItem(),o={idx:e.idx,data:e.row};e.onRowDrop({rowSource:r,rowTarget:o})}};t["default"]=function(e){return(0,d.DropTarget)("Row",g,s)(h(e))}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e,t){return{connectDragSource:e.dragSource(),isDragging:t.isDragging(),connectDragPreview:e.dragPreview()}}t.__esModule=!0;var a=n(1),l=r(a),c=n(7),p=n(39),f=r(p),d=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return u(t,e),t.prototype.renderRowIndex=function(){return l["default"].createElement("div",{className:"rdg-row-index"},this.props.rowIdx+1)},t.prototype.render=function(){var e=this.props,t=e.connectDragSource,n=e.rowSelection,r=null!=n?{position:"absolute",marginTop:"5px"}:{},o=this.props.value,i=o?"rdg-actions-checkbox selected":"rdg-actions-checkbox";return t(l["default"].createElement("div",null,l["default"].createElement("div",{className:"rdg-drag-row-handle",style:r}),o?null:this.renderRowIndex(),null!=n&&l["default"].createElement("div",{className:i},l["default"].createElement(f["default"],{column:this.props.column,rowIdx:this.props.rowIdx,dependentValues:this.props.dependentValues,value:this.props.value}))))},t}(l["default"].Component);d.propTypes={rowIdx:a.PropTypes.number.isRequired,connectDragSource:a.PropTypes.func.isRequired,connectDragPreview:a.PropTypes.func.isRequired,isDragging:a.PropTypes.bool.isRequired,isRowHovered:a.PropTypes.bool,column:a.PropTypes.object,dependentValues:a.PropTypes.object,value:a.PropTypes.bool,rowSelection:a.PropTypes.object.isRequired},d.defaultProps={rowIdx:0};var h={beginDrag:function(e){return{idx:e.rowIdx,data:e.dependentValues}},endDrag:function(e){return{idx:e.rowIdx,data:e.dependentValues}}};t["default"]=(0,c.DragSource)("Row",h,s)(d)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e){var t=e.currentOffset;if(!t)return{display:"none"};var n=t.x,r=t.y,o="translate("+n+"px, "+r+"px)";return{transform:o,WebkitTransform:o}}function a(e){return{item:e.getItem(),itemType:e.getItemType(),currentOffset:e.getSourceClientOffset(),isDragging:e.isDragging()}}t.__esModule=!0;var l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},c=n(1),p=r(c),f=n(7),d=n(37),h=r(d),g={cursor:"-webkit-grabbing",position:"fixed",pointerEvents:"none",zIndex:100,left:0,top:0,width:"100%",height:"100%"},y=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return u(t,e),t.prototype.isDraggedRowSelected=function(e){var t=this.props,n=t.item,r=t.rowSelection;if(e&&e.length>0){var o=function(){var t=r.selectBy.keys.rowKey;return{v:e.filter(function(e){return e[t]===n.data[t]}).length>0}}();if("object"===("undefined"==typeof o?"undefined":l(o)))return o.v}return!1},t.prototype.getDraggedRows=function(){var e=void 0,t=this.props.rowSelection;if(t&&t.selectBy.keys){var n=this.props.rows,r=t.selectBy.keys,o=r.rowKey,i=r.values,u=h["default"].getSelectedRowsByKey({rowKey:o,selectedKeys:i,rows:n});e=this.isDraggedRowSelected(u)?u:[this.props.rows[this.props.item.idx]]}else e=[this.props.rows[this.props.item.idx]];return e},t.prototype.renderDraggedRows=function(){var e=this;return this.getDraggedRows().map(function(t,n){return p["default"].createElement("tr",{key:"dragged-row-"+n},e.renderDraggedCells(t,n))})},t.prototype.renderDraggedCells=function(e,t){var n=[];if(null!=e)for(var r in e)e.hasOwnProperty(r)&&n.push(p["default"].createElement("td",{key:"dragged-cell-"+t+"-"+r,className:"react-grid-Cell",style:{padding:"5px"}},e[r]));return n},t.prototype.render=function(){var e=this.props.isDragging;if(!e)return null;var t=this.renderDraggedRows();return p["default"].createElement("div",{style:g,className:"rdg-dragging"},p["default"].createElement("div",{style:s(this.props),className:"rdg-dragging"},p["default"].createElement("table",null,p["default"].createElement("tbody",null,t))))},t}(c.Component);y.propTypes={item:c.PropTypes.object,itemType:c.PropTypes.string,currentOffset:c.PropTypes.shape({x:c.PropTypes.number.isRequired,y:c.PropTypes.number.isRequired}),isDragging:c.PropTypes.bool.isRequired,rowSelection:c.PropTypes.object,rows:c.PropTypes.array.isRequired},t["default"]=(0,f.DragLayer)(a)(y)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(93),i=r(o),u=n(38),s=r(u),a=n(95),l=r(a),c=n(94),p=r(c);t["default"]={Container:i["default"],DraggableHeaderCell:s["default"],RowActionsCell:l["default"],DropTargetRowContainer:p["default"]}},function(e,t,n){"use strict";var r=n(1),o=n(3),i=n(253),u=n(8),s=r.PropTypes.shape({id:r.PropTypes.required,title:r.PropTypes.string}),a=r.createClass({displayName:"AutoCompleteEditor",propTypes:{onCommit:r.PropTypes.func,options:r.PropTypes.arrayOf(s),label:r.PropTypes.any,value:r.PropTypes.any,height:r.PropTypes.number,valueParams:r.PropTypes.arrayOf(r.PropTypes.string),column:r.PropTypes.shape(u),resultIdentifier:r.PropTypes.string,search:r.PropTypes.string,onKeyDown:r.PropTypes.func,onFocus:r.PropTypes.func,editorDisplayValue:r.PropTypes.func},getDefaultProps:function(){return{resultIdentifier:"id"}},handleChange:function(){this.props.onCommit()},getValue:function(){var e=void 0,t={};return this.hasResults()&&this.isFocusedOnSuggestion()?(e=this.getLabel(this.refs.autoComplete.state.focusedValue),this.props.valueParams&&(e=this.constuctValueFromParams(this.refs.autoComplete.state.focusedValue,this.props.valueParams))):e=this.refs.autoComplete.state.searchTerm,t[this.props.column.key]=e,t},getEditorDisplayValue:function(){var e={title:""},t=this.props,n=t.column,r=t.value,o=t.editorDisplayValue;return o&&"function"==typeof o?e.title=o(n,r):e.title=r,e},getInputNode:function(){return o.findDOMNode(this).getElementsByTagName("input")[0]},getLabel:function(e){var t=null!=this.props.label?this.props.label:"title";return"function"==typeof t?t(e):"string"==typeof t?e[t]:void 0},hasResults:function(){return this.refs.autoComplete.state.results.length>0},isFocusedOnSuggestion:function(){var e=this.refs.autoComplete;return null!=e.state.focusedValue},constuctValueFromParams:function(e,t){if(!t)return"";for(var n=[],r=0,o=t.length;r<o;r++)n.push(e[t[r]]);return n.join("|")},render:function(){var e=null!=this.props.label?this.props.label:"title";return r.createElement("div",{height:this.props.height,onKeyDown:this.props.onKeyDown},r.createElement(i,{search:this.props.search,ref:"autoComplete",label:e,onChange:this.handleChange,onFocus:this.props.onFocus,resultIdentifier:this.props.resultIdentifier,options:this.props.options,value:this.getEditorDisplayValue()}))}});e.exports=a},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var s=n(3),a=r(s),l=n(1),c=n(40),p=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return u(t,e),t.prototype.getInputNode=function(){return a["default"].findDOMNode(this)},t.prototype.onClick=function(){this.getInputNode().focus()},t.prototype.onDoubleClick=function(){this.getInputNode().focus()},t.prototype.render=function(){return l.createElement("select",{style:this.getStyle(),defaultValue:this.props.value,onBlur:this.props.onBlur,onChange:this.onChange},this.renderOptions())},t.prototype.renderOptions=function(){var e=[];return this.props.options.forEach(function(t){"string"==typeof t?e.push(l.createElement("option",{key:t,value:t},t)):e.push(l.createElement("option",{key:t.id,value:t.value,title:t.title},t.text||t.value))},this),e},t}(c);p.propTypes={options:l.PropTypes.arrayOf(l.PropTypes.oneOfType([l.PropTypes.string,l.PropTypes.objectOf({id:l.PropTypes.string,title:l.PropTypes.string,value:l.PropTypes.string,text:l.PropTypes.string})])).isRequired},e.exports=p},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var u=n(1),s=n(40),a=function(e){function t(){return r(this,t),o(this,e.apply(this,arguments))}return i(t,e),t.prototype.render=function(){return u.createElement("input",{ref:"input",type:"text",onBlur:this.props.onBlur,className:"form-control",defaultValue:this.props.value})},t}(s);e.exports=a},function(e,t,n){"use strict";var r={AutoComplete:n(98),DropDownEditor:n(99),SimpleTextEditor:n(100),CheckboxEditor:n(39)};e.exports=r},function(e,t,n){"use strict";var r=n(1),o=r.createClass({displayName:"DropDownFormatter",propTypes:{options:r.PropTypes.arrayOf(r.PropTypes.oneOfType([r.PropTypes.string,r.PropTypes.objectOf({id:r.PropTypes.string,title:r.PropTypes.string,value:r.PropTypes.string,text:r.PropTypes.string})])).isRequired,value:r.PropTypes.string.isRequired},shouldComponentUpdate:function(e){return e.value!==this.props.value},render:function(){var e=this.props.value,t=this.props.options.filter(function(t){return t===e||t.value===e})[0];t||(t=e);var n=t.title||t.value||t,o=t.text||t.value||t;return r.createElement("div",{title:n},o)}});e.exports=o},function(e,t,n){"use strict";var r=n(1),o={},i={},u=r.createClass({displayName:"ImageFormatter",propTypes:{value:r.PropTypes.string.isRequired},getInitialState:function(){return{ready:!1}},componentWillMount:function(){this._load(this.props.value)},componentWillReceiveProps:function(e){e.value!==this.props.value&&(this.setState({value:null}),this._load(e.value))},_load:function(e){var t=e;if(i[t])return void this.setState({value:t});if(o[t])return void o[t].push(this._onLoad);o[t]=[this._onLoad];var n=new Image;n.onload=function(){o[t].forEach(function(e){e(t)}),delete o[t],n.onload=null,t=void 0},n.src=t},_onLoad:function(e){this.isMounted()&&e===this.props.value&&this.setState({value:e})},render:function(){var e=this.state.value?{backgroundImage:"url("+this.state.value+")"}:void 0;return r.createElement("div",{className:"react-grid-image",style:e})}});e.exports=u},function(e,t,n){"use strict";var r=n(103),o=n(102),i={ImageFormatter:r,DropDownFormatter:o};e.exports=i},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0;var s=n(1),a=r(s),l=n(63),c=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){return a["default"].createElement(l.ContextMenu,{identifier:"reactDataGridContextMenu"},this.props.children)},t}(a["default"].Component);c.propTypes={children:s.PropTypes.node},t["default"]=c},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0;var s=n(1),a=r(s),l=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){return a["default"].createElement("div",{className:"react-context-menu-header"},this.props.children)},t}(a["default"].Component);l.propTypes={children:s.PropTypes.any},t["default"]=l},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.ContextMenuLayer=t.connect=t.SubMenu=t.monitor=t.MenuItem=t.MenuHeader=t.ContextMenu=void 0;var o=n(63),i=n(105),u=r(i),s=n(106),a=r(s);t.ContextMenu=u["default"],t.MenuHeader=a["default"],t.MenuItem=o.MenuItem,t.monitor=o.monitor,t.SubMenu=o.SubMenu,t.connect=o.connect,t.ContextMenuLayer=o.ContextMenuLayer},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0;var s=n(1),a=r(s),l={children:s.PropTypes.array},c={enableAddRow:!0},p=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){return a["default"].createElement("div",{className:"react-grid-Toolbar"},this.props.children,a["default"].createElement("div",{className:"tools"}))},t}(s.Component);p.defaultProps=c,p.propTypes=l,t["default"]=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}t.__esModule=!0;var s=n(1),a=r(s),l=function(e){function t(){return o(this,t),i(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e={width:"80px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};return a["default"].createElement("button",{className:"btn grouped-col-btn btn-sm"},a["default"].createElement("span",{style:e},this.props.name),a["default"].createElement("span",{className:"glyphicon glyphicon-trash",style:{"float":"right",paddingLeft:"5px"},onClick:this.props.onColumnGroupDeleted.bind(this,this.props.name)}))},t}(s.Component);t["default"]=l,l.propTypes={name:s.PropTypes.object.isRequired,onColumnGroupDeleted:s.PropTypes.func}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e,t){return{connectDropTarget:e.dropTarget(),isOver:t.isOver(),canDrop:t.canDrop(),draggedolumn:t.getItem()}}t.__esModule=!0;var a=n(1),l=r(a),c=n(7),p=n(36),f=n(109),d=r(f),h={isOver:a.PropTypes.bool.isRequired,connectDropTarget:a.PropTypes.func,canDrop:a.PropTypes.bool.isRequired,groupBy:a.PropTypes.array,noColumnsSelectedMessage:a.PropTypes.string,panelDescription:a.PropTypes.string,onColumnGroupDeleted:a.PropTypes.func},g={noColumnsSelectedMessage:"Drag a column header here to group by that column",panelDescription:"Drag a column header here to group by that column"},y=function(e){function t(){return o(this,t),i(this,e.call(this))}return u(t,e),t.prototype.getPanelInstructionMessage=function(){var e=this.props.groupBy;return e&&e.length>0?this.props.panelDescription:this.props.noColumnsSelectedMessage},t.prototype.renderGroupedColumns=function(){var e=this;return this.props.groupBy.map(function(t){return l["default"].createElement(d["default"],{name:t,onColumnGroupDeleted:e.props.onColumnGroupDeleted})})},t.prototype.renderOverlay=function(e){return l["default"].createElement("div",{style:{position:"absolute",top:0,left:0,height:"100%",width:"100%",zIndex:1,opacity:.5,backgroundColor:e}})},t.prototype.render=function(){var e=this.props,t=e.connectDropTarget,n=e.isOver,r=e.canDrop;return t(l["default"].createElement("div",{style:{padding:"2px",position:"relative",margin:"-10px",display:"inline-block",border:"1px solid #eee"}},this.renderGroupedColumns()," ",l["default"].createElement("span",null,this.getPanelInstructionMessage()),n&&r&&this.renderOverlay("yellow"),!n&&r&&this.renderOverlay("#DBECFA")))},t}(a.Component);y.defaultProps=g,y.propTypes=h;var v={drop:function(e,t){var n=t.getItem();"function"==typeof e.onColumnGroupAdded&&e.onColumnGroupAdded(n.key)}};t["default"]=(0,c.DropTarget)(p.DragItemTypes.Column,v,s)(y)},function(e,t,n){"use strict";var r=n(1),o=r.createClass({displayName:"Toolbar",propTypes:{onAddRow:r.PropTypes.func,onToggleFilter:r.PropTypes.func,enableFilter:r.PropTypes.bool,numberOfRows:r.PropTypes.number,addRowButtonText:r.PropTypes.string,filterRowsButtonText:r.PropTypes.string},onAddRow:function(){null!==this.props.onAddRow&&this.props.onAddRow instanceof Function&&this.props.onAddRow({newRowIndex:this.props.numberOfRows})},getDefaultProps:function(){return{enableAddRow:!0,addRowButtonText:"Add Row",filterRowsButtonText:"Filter Rows"}},renderAddRowButton:function(){if(this.props.onAddRow)return r.createElement("button",{type:"button",className:"btn",onClick:this.onAddRow},this.props.addRowButtonText)},renderToggleFilterButton:function(){if(this.props.enableFilter)return r.createElement("button",{type:"button",className:"btn",onClick:this.props.onToggleFilter},this.props.filterRowsButtonText)},render:function(){return r.createElement("div",{className:"react-grid-Toolbar"},r.createElement("div",{className:"tools"},this.renderAddRowButton(),this.renderToggleFilterButton()))}});e.exports=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.GroupedColumnsPanel=t.AdvancedToolbar=void 0;var o=n(108),i=r(o),u=n(110),s=r(u);t.AdvancedToolbar=i["default"],t.GroupedColumnsPanel=s["default"]},function(e,t){"use strict";function n(e){return 0===Object.keys(e).length&&e.constructor===Object}t.__esModule=!0,t["default"]=n},function(e,t,n){function r(){for(var e,t="",n=0;n<arguments.length;n++)if(e=arguments[n])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+r.apply(null,e);else if("object"==typeof e)for(var o in e)e.hasOwnProperty(o)&&e[o]&&(t+=" "+o);return t.substr(1)}var o,i;"undefined"!=typeof e&&e.exports&&(e.exports=r),o=[],i=function(){return r}.apply(t,o),!(void 0!==i&&(e.exports=i))},function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}},o=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")};t.__esModule=!0;var i=n(22),u=r(i),s=function(){function e(){for(var t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];o(this,e),Array.isArray(n[0])&&1===n.length&&(n=n[0]);for(var i=0;i<n.length;i++)if(!u["default"](n[i]))throw new Error("Expected a disposable");this.disposables=n,this.isDisposed=!1}return e.prototype.add=function(e){this.isDisposed?e.dispose():this.disposables.push(e)},e.prototype.remove=function(e){if(this.isDisposed)return!1;var t=this.disposables.indexOf(e);return t!==-1&&(this.disposables.splice(t,1),e.dispose(),!0)},e.prototype.dispose=function(){if(!this.isDisposed){for(var e=this.disposables.length,t=new Array(e),n=0;n<e;n++)t[n]=this.disposables[n];this.isDisposed=!0,this.disposables=[],this.length=0;for(var n=0;n<e;n++)t[n].dispose()}},e}();t["default"]=s,e.exports=t["default"]},function(e,t){"use strict";var n=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},r=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}();t.__esModule=!0;var o=function(){},i=function(){function e(t){n(this,e),this.isDisposed=!1,this.action=t||o}return e.prototype.dispose=function(){this.isDisposed||(this.action.call(null),this.isDisposed=!0)},r(e,null,[{key:"empty",enumerable:!0,value:{dispose:o}}]),e}();t["default"]=i,e.exports=t["default"]},function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}},o=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")};t.__esModule=!0;var i=n(22),u=r(i),s=function(){function e(){o(this,e),this.isDisposed=!1,this.current=null}return e.prototype.getDisposable=function(){return this.current},e.prototype.setDisposable=function(){var e=void 0===arguments[0]?null:arguments[0];if(null!=e&&!u["default"](e))throw new Error("Expected either an empty value or a valid disposable");var t=this.isDisposed,n=void 0;t||(n=this.current,this.current=e),n&&n.dispose(),t&&e&&e.dispose()},e.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;var e=this.current;this.current=null,e&&e.dispose()}},e}();t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";var r=function(e){return e&&e.__esModule?e:{"default":e}};t.__esModule=!0;var o=n(22),i=r(o);t.isDisposable=i["default"];var u=n(116),s=r(u);t.Disposable=s["default"];var a=n(115),l=r(a);t.CompositeDisposable=l["default"];var c=n(117),p=r(c);t.SerialDisposable=p["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}t.__esModule=!0;var u=n(35),s=o(u),a=n(126),l=o(a),c=n(12),p=r(c),f=n(120),d=o(f),h=n(42),g=(o(h),function(){function e(t){i(this,e);var n=s["default"](l["default"]);this.store=n,this.monitor=new d["default"](n),this.registry=this.monitor.registry,this.backend=t(this),n.subscribe(this.handleRefCountChange.bind(this))}return e.prototype.handleRefCountChange=function(){var e=this.store.getState().refCount>0;e&&!this.isSetUp?(this.backend.setup(),this.isSetUp=!0):!e&&this.isSetUp&&(this.backend.teardown(),this.isSetUp=!1)},e.prototype.getMonitor=function(){return this.monitor},e.prototype.getBackend=function(){return this.backend},e.prototype.getRegistry=function(){return this.registry},e.prototype.getActions=function(){function e(e){return function(){var r=e.apply(t,arguments);"undefined"!=typeof r&&n(r)}}var t=this,n=this.store.dispatch;return Object.keys(p).filter(function(e){return"function"==typeof p[e]}).reduce(function(t,n){return t[n]=e(p[n]),t},{})},e}());t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}t.__esModule=!0;var i=n(2),u=r(i),s=n(45),a=r(s),l=n(5),c=r(l),p=n(42),f=r(p),d=n(44),h=n(43),g=function(){function e(t){o(this,e),this.store=t,this.registry=new f["default"](t)}return e.prototype.subscribeToStateChange=function(e){var t=this,n=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r=n.handlerIds;u["default"]("function"==typeof e,"listener must be a function."),u["default"]("undefined"==typeof r||c["default"](r),"handlerIds, when specified, must be an array of strings.");var o=this.store.getState().stateId,i=function(){var n=t.store.getState(),i=n.stateId;try{var u=i===o||i===o+1&&!h.areDirty(n.dirtyHandlerIds,r);u||e()}finally{o=i}};return this.store.subscribe(i)},e.prototype.subscribeToOffsetChange=function(e){var t=this;u["default"]("function"==typeof e,"listener must be a function.");var n=this.store.getState().dragOffset,r=function(){var r=t.store.getState().dragOffset;r!==n&&(n=r,e())};return this.store.subscribe(r)},e.prototype.canDragSource=function(e){var t=this.registry.getSource(e);return u["default"](t,"Expected to find a valid source."),!this.isDragging()&&t.canDrag(this,e)},e.prototype.canDropOnTarget=function(e){var t=this.registry.getTarget(e);if(u["default"](t,"Expected to find a valid target."),!this.isDragging()||this.didDrop())return!1;var n=this.registry.getTargetType(e),r=this.getItemType();return a["default"](n,r)&&t.canDrop(this,e)},e.prototype.isDragging=function(){return Boolean(this.getItemType())},e.prototype.isDraggingSource=function(e){var t=this.registry.getSource(e,!0);if(u["default"](t,"Expected to find a valid source."),!this.isDragging()||!this.isSourcePublic())return!1;var n=this.registry.getSourceType(e),r=this.getItemType();return n===r&&t.isDragging(this,e)},e.prototype.isOverTarget=function(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=t.shallow,r=void 0!==n&&n;if(!this.isDragging())return!1;var o=this.registry.getTargetType(e),i=this.getItemType();if(!a["default"](o,i))return!1;var u=this.getTargetIds();if(!u.length)return!1;var s=u.indexOf(e);return r?s===u.length-1:s>-1},e.prototype.getItemType=function(){return this.store.getState().dragOperation.itemType},e.prototype.getItem=function(){return this.store.getState().dragOperation.item},e.prototype.getSourceId=function(){return this.store.getState().dragOperation.sourceId},e.prototype.getTargetIds=function(){return this.store.getState().dragOperation.targetIds},e.prototype.getDropResult=function(){return this.store.getState().dragOperation.dropResult},e.prototype.didDrop=function(){return this.store.getState().dragOperation.didDrop},e.prototype.isSourcePublic=function(){return this.store.getState().dragOperation.isSourcePublic},e.prototype.getInitialClientOffset=function(){return this.store.getState().dragOffset.initialClientOffset},e.prototype.getInitialSourceClientOffset=function(){return this.store.getState().dragOffset.initialSourceClientOffset},e.prototype.getClientOffset=function(){return this.store.getState().dragOffset.clientOffset},e.prototype.getSourceClientOffset=function(){return d.getSourceClientOffset(this.store.getState().dragOffset)},e.prototype.getDifferenceFromInitialOffset=function(){return d.getDifferenceFromInitialOffset(this.store.getState().dragOffset)},e}();t["default"]=g,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}t.__esModule=!0;var r=function(){function e(){n(this,e)}return e.prototype.canDrag=function(){return!0},e.prototype.isDragging=function(e,t){return t===e.getSourceId()},e.prototype.endDrag=function(){},e}();t["default"]=r,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}t.__esModule=!0;var r=function(){function e(){n(this,e)}return e.prototype.canDrop=function(){return!0},e.prototype.hover=function(){},e.prototype.drop=function(){},e}();t["default"]=r,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e){return new a(e)}t.__esModule=!0,t["default"]=i;var u=n(61),s=r(u),a=function(){function e(t){o(this,e),this.actions=t.getActions()}return e.prototype.setup=function(){this.didCallSetup=!0},e.prototype.teardown=function(){this.didCallTeardown=!0},e.prototype.connectDragSource=function(){return s["default"]},e.prototype.connectDragPreview=function(){return s["default"]},e.prototype.connectDropTarget=function(){return s["default"]},e.prototype.simulateBeginDrag=function(e,t){this.actions.beginDrag(e,t)},e.prototype.simulatePublishDragSource=function(){this.actions.publishDragSource()},e.prototype.simulateHover=function(e,t){this.actions.hover(e,t)},e.prototype.simulateDrop=function(){this.actions.drop()},e.prototype.simulateEndDrag=function(){this.actions.endDrag()},e}();e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e["default"]:e}t.__esModule=!0;var o=n(119);t.DragDropManager=r(o);var i=n(121);t.DragSource=r(i);var u=n(122);t.DropTarget=r(u);var s=n(123);t.createTestBackend=r(s)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){switch(void 0===e&&(e=c),t.type){case u.BEGIN_DRAG:return i({},e,{itemType:t.itemType,item:t.item,sourceId:t.sourceId,isSourcePublic:t.isSourcePublic,dropResult:null,didDrop:!1});case u.PUBLISH_DRAG_SOURCE:return i({},e,{isSourcePublic:!0});case u.HOVER:return i({},e,{targetIds:t.targetIds});case s.REMOVE_TARGET:return e.targetIds.indexOf(t.targetId)===-1?e:i({},e,{targetIds:l["default"](e.targetIds,t.targetId)});case u.DROP:return i({},e,{dropResult:t.dropResult,didDrop:!0,targetIds:[]});case u.END_DRAG:return i({},e,{itemType:null,item:null,sourceId:null,dropResult:null,didDrop:!1,isSourcePublic:null,targetIds:[]});default:return e}}t.__esModule=!0;var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=o;var u=n(12),s=n(13),a=n(62),l=r(a),c={itemType:null,item:null,sourceId:null,targetIds:[],dropResult:null,didDrop:!1,isSourcePublic:null};e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0;var o=n(44),i=r(o),u=n(125),s=r(u),a=n(127),l=r(a),c=n(43),p=r(c),f=n(128),d=r(f);t["default"]=function(e,t){return void 0===e&&(e={}),{dirtyHandlerIds:p["default"](e.dirtyHandlerIds,t,e.dragOperation),dragOffset:i["default"](e.dragOffset,t),refCount:l["default"](e.refCount,t),dragOperation:s["default"](e.dragOperation,t),stateId:d["default"](e.stateId)}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e,t){switch(void 0===e&&(e=0),t.type){case o.ADD_SOURCE:case o.ADD_TARGET:return e+1;case o.REMOVE_SOURCE:case o.REMOVE_TARGET:return e-1;default:return e}}t.__esModule=!0,t["default"]=r;var o=n(13);e.exports=t["default"]},function(e,t){"use strict";function n(){var e=arguments.length<=0||void 0===arguments[0]?0:arguments[0];return e+1}t.__esModule=!0,t["default"]=n,e.exports=t["default"]},function(e,t){"use strict";function n(){return r++}t.__esModule=!0,t["default"]=n;var r=0;e.exports=t["default"]},function(e,t,n){"use strict";function r(){var e=void 0===arguments[0]?document:arguments[0];try{return e.activeElement}catch(t){}}var o=n(47);t.__esModule=!0,t["default"]=r;var i=n(23);o.interopRequireDefault(i);e.exports=t["default"]},function(e,t,n){"use strict";var r=n(46);e.exports=function(e,t){e.classList?e.classList.add(t):r(e)||(e.className=e.className+" "+t)}},function(e,t,n){"use strict";e.exports={addClass:n(131),removeClass:n(133),hasClass:n(46)}},function(e,t){"use strict";e.exports=function(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(new RegExp("(^|\\s)"+t+"(?:\\s|$)","g"),"$1").replace(/\s+/g," ").replace(/^\s*|\s*$/g,"")}},function(e,t,n){"use strict";var r=n(9),o=function(){};r&&(o=function(){return document.addEventListener?function(e,t,n,r){return e.removeEventListener(t,n,r||!1)}:document.attachEvent?function(e,t,n){return e.detachEvent("on"+t,n)}:void 0}()),e.exports=o},function(e,t,n){"use strict";var r=n(9),o=function(){};r&&(o=function(){return document.addEventListener?function(e,t,n,r){return e.addEventListener(t,n,r||!1)}:document.attachEvent?function(e,t,n){return e.attachEvent("on"+t,n)}:void 0}()),e.exports=o},function(e,t,n){"use strict";var r=n(9),o=function(){var e=r&&document.documentElement;return e&&e.contains?function(e,t){return e.contains(t)}:e&&e.compareDocumentPosition?function(e,t){return e===t||!!(16&e.compareDocumentPosition(t))}:function(e,t){if(t)do if(t===e)return!0;while(t=t.parentNode);return!1}}();e.exports=o},function(e,t){"use strict";e.exports=function(e){return e===e.window?e:9===e.nodeType&&(e.defaultView||e.parentWindow)}},function(e,t,n){"use strict";var r=n(47),o=n(48),i=r.interopRequireDefault(o),u=/^(top|right|bottom|left)$/,s=/^([+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|))(?!px)[a-z%]+$/i;e.exports=function(e){if(!e)throw new TypeError("No Element passed to `getComputedStyle()`");var t=e.ownerDocument;return"defaultView"in t?t.defaultView.opener?e.ownerDocument.defaultView.getComputedStyle(e,null):window.getComputedStyle(e,null):{getPropertyValue:function(t){var n=e.style;t=(0,i["default"])(t),"float"==t&&(t="styleFloat");var r=e.currentStyle[t]||null;if(null==r&&n&&n[t]&&(r=n[t]),s.test(r)&&!u.test(t)){var o=n.left,a=e.runtimeStyle,l=a&&a.left;l&&(a.left=e.currentStyle.left),n.left="fontSize"===t?"1em":r,r=n.pixelLeft+"px",n.left=o,l&&(a.left=l)}return r}}}},function(e,t,n){"use strict";var r=n(48),o=n(143),i=n(138),u=n(140),s=Object.prototype.hasOwnProperty;e.exports=function(e,t,n){var a="",l=t;if("string"==typeof t){if(void 0===n)return e.style[r(t)]||i(e).getPropertyValue(o(t));(l={})[t]=n}for(var c in l)s.call(l,c)&&(l[c]||0===l[c]?a+=o(c)+":"+l[c]+";":u(e,o(c)));e.style.cssText+=";"+a}},function(e,t){"use strict";e.exports=function(e,t){return"removeProperty"in e.style?e.style.removeProperty(t):e.style.removeAttribute(t)}},function(e,t){"use strict";var n=/-(.)/g;e.exports=function(e){return e.replace(n,function(e,t){return t.toUpperCase()})}},function(e,t){"use strict";var n=/([A-Z])/g;e.exports=function(e){return e.replace(n,"-$1").toLowerCase()}},function(e,t,n){"use strict";var r=n(142),o=/^ms-/;e.exports=function(e){return r(e).replace(o,"-ms-")}},function(e,t,n){"use strict";var r,o=n(9);e.exports=function(e){if((!r||e)&&o){var t=document.createElement("div");t.style.position="absolute",t.style.top="-9999px",t.style.width="50px",t.style.height="50px",t.style.overflow="scroll",document.body.appendChild(t),r=t.offsetWidth-t.clientWidth,document.body.removeChild(t)}return r}},function(e,t,n){(function(e){function n(e,t,n,r){for(var o=-1,i=e?e.length:0;++o<i;){var u=e[o];t(r,u,n(u),e)}return r}function r(e,t){for(var n=-1,r=e?e.length:0;++n<r;)if(t(e[n],n,e))return!0;return!1}function o(e){return function(t){return null==t?void 0:t[e]}}function i(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function u(e){return function(t){return e(t)}}function s(e,t){return null==e?void 0:e[t]}function a(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(n){}return t}function l(e){var t=-1,n=Array(e.size);return e.forEach(function(e,r){n[++t]=[r,e]}),n}function c(e,t){return function(n){return e(t(n))}}function p(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}function f(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function d(){this.__data__=nn?nn(null):{}}function h(e){return this.has(e)&&delete this.__data__[e]}function g(e){var t=this.__data__;if(nn){var n=t[e];return n===Ue?void 0:n}return Kt.call(t,e)?t[e]:void 0}function y(e){var t=this.__data__;return nn?void 0!==t[e]:Kt.call(t,e)}function v(e,t){var n=this.__data__;return n[e]=nn&&void 0===t?Ue:t,this}function m(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function b(){this.__data__=[]}function E(e){var t=this.__data__,n=L(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():Yt.call(t,n,1),!0}function w(e){var t=this.__data__,n=L(t,e);return n<0?void 0:t[n][1]}function T(e){return L(this.__data__,e)>-1}function _(e,t){var n=this.__data__,r=L(n,e);return r<0?n.push([e,t]):n[r][1]=t,this}function D(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function O(){this.__data__={hash:new f,map:new(Jt||m),string:new f}}function C(e){return ce(this,e)["delete"](e)}function x(e){return ce(this,e).get(e)}function P(e){return ce(this,e).has(e)}function S(e,t){return ce(this,e).set(e,t),this}function M(e){var t=-1,n=e?e.length:0;for(this.__data__=new D;++t<n;)this.add(e[t])}function I(e){return this.__data__.set(e,Ue),this}function R(e){return this.__data__.has(e)}function A(e){this.__data__=new m(e)}function F(){this.__data__=new m}function j(e){return this.__data__["delete"](e)}function N(e){return this.__data__.get(e)}function k(e){return this.__data__.has(e)}function V(e,t){var n=this.__data__;if(n instanceof m){var r=n.__data__;if(!Jt||r.length<Be-1)return r.push([e,t]),this;n=this.__data__=new D(r)}return n.set(e,t),this}function B(e,t){var n=vn(e)||Oe(e)?i(e.length,String):[],r=n.length,o=!!r;for(var u in e)!t&&!Kt.call(e,u)||o&&("length"==u||he(u,r))||n.push(u);return n}function L(e,t){for(var n=e.length;n--;)if(De(e[n][0],t))return n;return-1}function U(e,t,n,r){return fn(e,function(e,o,i){t(r,e,n(e),i)}),r}function q(e,t){return e&&dn(e,t,Ne)}function K(e,t){t=ge(t,e)?[t]:re(t);for(var n=0,r=t.length;null!=e&&n<r;)e=e[we(t[n++])];return n&&n==r?e:void 0}function H(e){return Ht.call(e)}function W(e,t){return null!=e&&t in Object(e)}function G(e,t,n,r,o){return e===t||(null==e||null==t||!Me(e)&&!Ie(t)?e!==e&&t!==t:z(e,t,G,n,r,o))}function z(e,t,n,r,o,i){var u=vn(e),s=vn(t),l=ze,c=ze;u||(l=hn(e),l=l==Ge?tt:l),s||(c=hn(t),c=c==Ge?tt:c);var p=l==tt&&!a(e),f=c==tt&&!a(t),d=l==c;if(d&&!p)return i||(i=new A),u||mn(e)?se(e,t,n,r,o,i):ae(e,t,l,n,r,o,i);if(!(o&Ke)){var h=p&&Kt.call(e,"__wrapped__"),g=f&&Kt.call(t,"__wrapped__");if(h||g){var y=h?e.value():e,v=g?t.value():t;return i||(i=new A),n(y,v,r,o,i)}}return!!d&&(i||(i=new A),le(e,t,n,r,o,i))}function $(e,t,n,r){var o=n.length,i=o,u=!r;if(null==e)return!i;for(e=Object(e);o--;){var s=n[o];if(u&&s[2]?s[1]!==e[s[0]]:!(s[0]in e))return!1}for(;++o<i;){s=n[o];var a=s[0],l=e[a],c=s[1];if(u&&s[2]){if(void 0===l&&!(a in e))return!1}else{var p=new A;if(r)var f=r(l,c,a,e,t,p);if(!(void 0===f?G(c,l,r,qe|Ke,p):f))return!1}}return!0}function Y(e){if(!Me(e)||ve(e))return!1;var t=Pe(e)||a(e)?Wt:Ot;return t.test(Te(e))}function X(e){return Ie(e)&&Se(e.length)&&!!xt[Ht.call(e)]}function Q(e){return"function"==typeof e?e:null==e?ke:"object"==typeof e?vn(e)?ee(e[0],e[1]):Z(e):Ve(e)}function J(e){if(!me(e))return Xt(e);var t=[];for(var n in Object(e))Kt.call(e,n)&&"constructor"!=n&&t.push(n);return t}function Z(e){var t=pe(e);return 1==t.length&&t[0][2]?Ee(t[0][0],t[0][1]):function(n){return n===e||$(n,e,t)}}function ee(e,t){return ge(e)&&be(t)?Ee(we(e),t):function(n){var r=Fe(n,e);return void 0===r&&r===t?je(n,e):G(t,r,void 0,qe|Ke)}}function te(e){return function(t){return K(t,e)}}function ne(e){if("string"==typeof e)return e;if(Re(e))return pn?pn.call(e):"";var t=e+"";return"0"==t&&1/e==-He?"-0":t}function re(e){return vn(e)?e:gn(e)}function oe(e,t){return function(r,o){var i=vn(r)?n:U,u=t?t():{};return i(r,e,Q(o,2),u)}}function ie(e,t){return function(n,r){if(null==n)return n;if(!Ce(n))return e(n,r);for(var o=n.length,i=t?o:-1,u=Object(n);(t?i--:++i<o)&&r(u[i],i,u)!==!1;);return n}}function ue(e){return function(t,n,r){for(var o=-1,i=Object(t),u=r(t),s=u.length;s--;){var a=u[e?s:++o];if(n(i[a],a,i)===!1)break}return t}}function se(e,t,n,o,i,u){var s=i&Ke,a=e.length,l=t.length;if(a!=l&&!(s&&l>a))return!1;var c=u.get(e);if(c&&u.get(t))return c==t;var p=-1,f=!0,d=i&qe?new M:void 0;for(u.set(e,t),u.set(t,e);++p<a;){var h=e[p],g=t[p];if(o)var y=s?o(g,h,p,t,e,u):o(h,g,p,e,t,u);if(void 0!==y){if(y)continue;f=!1;break}if(d){if(!r(t,function(e,t){if(!d.has(t)&&(h===e||n(h,e,o,i,u)))return d.add(t)})){f=!1;break}}else if(h!==g&&!n(h,g,o,i,u)){f=!1;break}}return u["delete"](e),u["delete"](t),f}function ae(e,t,n,r,o,i,u){switch(n){case lt:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case at:return!(e.byteLength!=t.byteLength||!r(new zt(e),new zt(t)));case $e:case Ye:case et:return De(+e,+t);case Xe:return e.name==t.name&&e.message==t.message;case rt:case it:return e==t+"";case Ze:var s=l;case ot:var a=i&Ke;if(s||(s=p),e.size!=t.size&&!a)return!1;var c=u.get(e);if(c)return c==t;i|=qe,u.set(e,t);var f=se(s(e),s(t),r,o,i,u);return u["delete"](e),f;case ut:if(cn)return cn.call(e)==cn.call(t)}return!1}function le(e,t,n,r,o,i){var u=o&Ke,s=Ne(e),a=s.length,l=Ne(t),c=l.length;if(a!=c&&!u)return!1;for(var p=a;p--;){var f=s[p];if(!(u?f in t:Kt.call(t,f)))return!1}var d=i.get(e);if(d&&i.get(t))return d==t;var h=!0;i.set(e,t),i.set(t,e);for(var g=u;++p<a;){f=s[p];var y=e[f],v=t[f];if(r)var m=u?r(v,y,f,t,e,i):r(y,v,f,e,t,i);if(!(void 0===m?y===v||n(y,v,r,o,i):m)){h=!1;break}g||(g="constructor"==f)}if(h&&!g){var b=e.constructor,E=t.constructor;b!=E&&"constructor"in e&&"constructor"in t&&!("function"==typeof b&&b instanceof b&&"function"==typeof E&&E instanceof E)&&(h=!1)}return i["delete"](e),i["delete"](t),h}function ce(e,t){var n=e.__data__;return ye(t)?n["string"==typeof t?"string":"hash"]:n.map}function pe(e){for(var t=Ne(e),n=t.length;n--;){var r=t[n],o=e[r];t[n]=[r,o,be(o)]}return t}function fe(e,t){var n=s(e,t);return Y(n)?n:void 0}function de(e,t,n){t=ge(t,e)?[t]:re(t);for(var r,o=-1,i=t.length;++o<i;){var u=we(t[o]);if(!(r=null!=e&&n(e,u)))break;e=e[u]}if(r)return r;var i=e?e.length:0;return!!i&&Se(i)&&he(u,i)&&(vn(e)||Oe(e))}function he(e,t){return t=null==t?We:t,!!t&&("number"==typeof e||Ct.test(e))&&e>-1&&e%1==0&&e<t}function ge(e,t){if(vn(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!Re(e))||(Et.test(e)||!bt.test(e)||null!=t&&e in Object(t))}function ye(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}function ve(e){return!!Ut&&Ut in e}function me(e){var t=e&&e.constructor,n="function"==typeof t&&t.prototype||Bt;return e===n}function be(e){return e===e&&!Me(e)}function Ee(e,t){return function(n){return null!=n&&(n[e]===t&&(void 0!==t||e in Object(n)))}}function we(e){if("string"==typeof e||Re(e))return e;var t=e+"";return"0"==t&&1/e==-He?"-0":t}function Te(e){if(null!=e){try{return qt.call(e)}catch(t){}try{return e+""}catch(t){}}return""}function _e(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError(Le);var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var u=e.apply(this,r);return n.cache=i.set(o,u),u};return n.cache=new(_e.Cache||D),n}function De(e,t){return e===t||e!==e&&t!==t}function Oe(e){return xe(e)&&Kt.call(e,"callee")&&(!$t.call(e,"callee")||Ht.call(e)==Ge)}function Ce(e){return null!=e&&Se(e.length)&&!Pe(e)}function xe(e){return Ie(e)&&Ce(e)}function Pe(e){var t=Me(e)?Ht.call(e):"";return t==Qe||t==Je}function Se(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=We}function Me(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Ie(e){return!!e&&"object"==typeof e}function Re(e){return"symbol"==typeof e||Ie(e)&&Ht.call(e)==ut}function Ae(e){return null==e?"":ne(e)}function Fe(e,t,n){var r=null==e?void 0:K(e,t);return void 0===r?n:r}function je(e,t){return null!=e&&de(e,t,W)}function Ne(e){return Ce(e)?B(e):J(e)}function ke(e){return e}function Ve(e){return ge(e)?o(we(e)):te(e)}var Be=200,Le="Expected a function",Ue="__lodash_hash_undefined__",qe=1,Ke=2,He=1/0,We=9007199254740991,Ge="[object Arguments]",ze="[object Array]",$e="[object Boolean]",Ye="[object Date]",Xe="[object Error]",Qe="[object Function]",Je="[object GeneratorFunction]",Ze="[object Map]",et="[object Number]",tt="[object Object]",nt="[object Promise]",rt="[object RegExp]",ot="[object Set]",it="[object String]",ut="[object Symbol]",st="[object WeakMap]",at="[object ArrayBuffer]",lt="[object DataView]",ct="[object Float32Array]",pt="[object Float64Array]",ft="[object Int8Array]",dt="[object Int16Array]",ht="[object Int32Array]",gt="[object Uint8Array]",yt="[object Uint8ClampedArray]",vt="[object Uint16Array]",mt="[object Uint32Array]",bt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Et=/^\w*$/,wt=/^\./,Tt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,_t=/[\\^$.*+?()[\]{}|]/g,Dt=/\\(\\)?/g,Ot=/^\[object .+?Constructor\]$/,Ct=/^(?:0|[1-9]\d*)$/,xt={};xt[ct]=xt[pt]=xt[ft]=xt[dt]=xt[ht]=xt[gt]=xt[yt]=xt[vt]=xt[mt]=!0,xt[Ge]=xt[ze]=xt[at]=xt[$e]=xt[lt]=xt[Ye]=xt[Xe]=xt[Qe]=xt[Ze]=xt[et]=xt[tt]=xt[rt]=xt[ot]=xt[it]=xt[st]=!1;
var Pt="object"==typeof window&&window&&window.Object===Object&&window,St="object"==typeof self&&self&&self.Object===Object&&self,Mt=Pt||St||Function("return this")(),It="object"==typeof t&&t&&!t.nodeType&&t,Rt=It&&"object"==typeof e&&e&&!e.nodeType&&e,At=Rt&&Rt.exports===It,Ft=At&&Pt.process,jt=function(){try{return Ft&&Ft.binding("util")}catch(e){}}(),Nt=jt&&jt.isTypedArray,kt=Array.prototype,Vt=Function.prototype,Bt=Object.prototype,Lt=Mt["__core-js_shared__"],Ut=function(){var e=/[^.]+$/.exec(Lt&&Lt.keys&&Lt.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),qt=Vt.toString,Kt=Bt.hasOwnProperty,Ht=Bt.toString,Wt=RegExp("^"+qt.call(Kt).replace(_t,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Gt=Mt.Symbol,zt=Mt.Uint8Array,$t=Bt.propertyIsEnumerable,Yt=kt.splice,Xt=c(Object.keys,Object),Qt=fe(Mt,"DataView"),Jt=fe(Mt,"Map"),Zt=fe(Mt,"Promise"),en=fe(Mt,"Set"),tn=fe(Mt,"WeakMap"),nn=fe(Object,"create"),rn=Te(Qt),on=Te(Jt),un=Te(Zt),sn=Te(en),an=Te(tn),ln=Gt?Gt.prototype:void 0,cn=ln?ln.valueOf:void 0,pn=ln?ln.toString:void 0;f.prototype.clear=d,f.prototype["delete"]=h,f.prototype.get=g,f.prototype.has=y,f.prototype.set=v,m.prototype.clear=b,m.prototype["delete"]=E,m.prototype.get=w,m.prototype.has=T,m.prototype.set=_,D.prototype.clear=O,D.prototype["delete"]=C,D.prototype.get=x,D.prototype.has=P,D.prototype.set=S,M.prototype.add=M.prototype.push=I,M.prototype.has=R,A.prototype.clear=F,A.prototype["delete"]=j,A.prototype.get=N,A.prototype.has=k,A.prototype.set=V;var fn=ie(q),dn=ue(),hn=H;(Qt&&hn(new Qt(new ArrayBuffer(1)))!=lt||Jt&&hn(new Jt)!=Ze||Zt&&hn(Zt.resolve())!=nt||en&&hn(new en)!=ot||tn&&hn(new tn)!=st)&&(hn=function(e){var t=Ht.call(e),n=t==tt?e.constructor:void 0,r=n?Te(n):void 0;if(r)switch(r){case rn:return lt;case on:return Ze;case un:return nt;case sn:return ot;case an:return st}return t});var gn=_e(function(e){e=Ae(e);var t=[];return wt.test(e)&&t.push(""),e.replace(Tt,function(e,n,r,o){t.push(r?o.replace(Dt,"$1"):n||e)}),t}),yn=oe(function(e,t,n){Kt.call(e,n)?e[n].push(t):e[n]=[t]});_e.Cache=D;var vn=Array.isArray,mn=Nt?u(Nt):X;e.exports=yn}).call(t,n(258)(e))},function(e,t){function n(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=n},function(e,t,n){function r(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var o=n(173),i=n(174),u=n(175),s=n(176),a=n(177);r.prototype.clear=o,r.prototype["delete"]=i,r.prototype.get=u,r.prototype.has=s,r.prototype.set=a,e.exports=r},function(e,t,n){function r(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}var o=n(183),i=n(184),u=n(185),s=n(186),a=n(187);r.prototype.clear=o,r.prototype["delete"]=i,r.prototype.get=u,r.prototype.has=s,r.prototype.set=a,e.exports=r},function(e,t,n){var r=n(29),o=n(17),i=r(o,"Map");e.exports=i},function(e,t,n){var r=n(29),o=n(17),i=r(o,"Set");e.exports=i},function(e,t,n){var r=n(17),o=r.Symbol;e.exports=o},function(e,t){function n(e,t){for(var n=-1,r=e?e.length:0,o=0,i=[];++n<r;){var u=e[n];t(u,n,e)&&(i[o++]=u)}return i}e.exports=n},function(e,t,n){function r(e,t){var n=u(e)||i(e)?o(e.length,String):[],r=n.length,a=!!r;for(var c in e)!t&&!l.call(e,c)||a&&("length"==c||s(c,r))||n.push(c);return n}var o=n(163),i=n(58),u=n(5),s=n(56),a=Object.prototype,l=a.hasOwnProperty;e.exports=r},function(e,t,n){function r(e,t,n,r){return void 0===e||o(e,i[n])&&!u.call(r,n)?t:e}var o=n(18),i=Object.prototype,u=i.hasOwnProperty;e.exports=r},function(e,t,n){function r(e,t,n){var r=e[t];u.call(e,t)&&o(r,n)&&(void 0!==n||t in e)||(e[t]=n)}var o=n(18),i=Object.prototype,u=i.hasOwnProperty;e.exports=r},function(e,t){function n(e,t,n,r){for(var o=e.length,i=n+(r?1:-1);r?i--:++i<o;)if(t(e[i],i,e))return i;return-1}e.exports=n},function(e,t,n){function r(e,t,n,u,s){var a=-1,l=e.length;for(n||(n=i),s||(s=[]);++a<l;){var c=e[a];t>0&&n(c)?t>1?r(c,t-1,n,u,s):o(s,c):u||(s[s.length]=c)}return s}var o=n(51),i=n(178);e.exports=r},function(e,t,n){function r(e,t,n){if(t!==t)return o(e,i,n);for(var r=n-1,u=e.length;++r<u;)if(e[r]===t)return r;return-1}var o=n(156),i=n(160);e.exports=r},function(e,t,n){function r(e,t,n){for(var r=n?u:i,p=e[0].length,f=e.length,d=f,h=Array(f),g=1/0,y=[];d--;){var v=e[d];d&&t&&(v=s(v,a(t))),g=c(v.length,g),h[d]=!n&&(t||p>=120&&v.length>=120)?new o(d&&v):void 0}v=e[0];var m=-1,b=h[0];e:for(;++m<p&&y.length<g;){var E=v[m],w=t?t(E):E;if(E=n||0!==E?E:0,!(b?l(b,w):r(y,w,n))){for(d=f;--d;){var T=h[d];if(!(T?l(T,w):r(e[d],w,n)))continue e}b&&b.push(w),y.push(E)}}return y}var o=n(24),i=n(25),u=n(26),s=n(27),a=n(53),l=n(28),c=Math.min;e.exports=r},function(e,t){function n(e){return e!==e}e.exports=n},function(e,t,n){function r(e){if(!s(e)||u(e))return!1;var t=o(e)||i(e)?g:c;return t.test(a(e))}var o=n(59),i=n(55),u=n(181),s=n(11),a=n(197),l=/[\\^$.*+?()[\]{}|]/g,c=/^\[object .+?Constructor\]$/,p=Function.prototype,f=Object.prototype,d=p.toString,h=f.hasOwnProperty,g=RegExp("^"+d.call(h).replace(l,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=r},function(e,t,n){function r(e){if(!o(e))return u(e);var t=i(e),n=[];for(var r in e)("constructor"!=r||!t&&a.call(e,r))&&n.push(r);return n}var o=n(11),i=n(182),u=n(193),s=Object.prototype,a=s.hasOwnProperty;e.exports=r},function(e,t){function n(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}e.exports=n},function(e,t,n){function r(e,t,n){for(var r=-1,s=e.length;++r<s;)var a=a?o(i(a,e[r],t,n),i(e[r],a,t,n)):e[r];return a&&a.length?u(a,t,n):[]}var o=n(51),i=n(52),u=n(54);e.exports=r},function(e,t,n){function r(e){return o(e)?e:[]}var o=n(10);e.exports=r},function(e,t,n){function r(e,t,n,r){n||(n={});for(var i=-1,u=t.length;++i<u;){var s=t[i],a=r?r(n[s],e[s],s,n,e):void 0;o(n,s,void 0===a?e[s]:a)}return n}var o=n(155);e.exports=r},function(e,t,n){var r=n(17),o=r["__core-js_shared__"];e.exports=o},function(e,t,n){function r(e){return o(function(t,n){var r=-1,o=n.length,u=o>1?n[o-1]:void 0,s=o>2?n[2]:void 0;for(u=e.length>3&&"function"==typeof u?(o--,u):void 0,s&&i(n[0],n[1],s)&&(u=o<3?void 0:u,o=1),t=Object(t);++r<o;){var a=n[r];a&&e(t,a,r,u)}return t})}var o=n(6),i=n(179);e.exports=r},function(e,t,n){var r=n(150),o=n(61),i=n(57),u=1/0,s=r&&1/i(new r([,-0]))[1]==u?function(e){return new r(e)}:o;e.exports=s},function(e,t,n){var r="object"==typeof window&&window&&window.Object===Object&&window;e.exports=r},function(e,t,n){var r=n(194),o=r(Object.getPrototypeOf,Object);e.exports=o},function(e,t){function n(e,t){return null==e?void 0:e[t]}e.exports=n},function(e,t,n){function r(){this.__data__=o?o(null):{}}var o=n(16);e.exports=r},function(e,t){function n(e){return this.has(e)&&delete this.__data__[e]}e.exports=n},function(e,t,n){function r(e){var t=this.__data__;if(o){var n=t[e];return n===i?void 0:n}return s.call(t,e)?t[e]:void 0}var o=n(16),i="__lodash_hash_undefined__",u=Object.prototype,s=u.hasOwnProperty;e.exports=r},function(e,t,n){function r(e){var t=this.__data__;return o?void 0!==t[e]:u.call(t,e)}var o=n(16),i=Object.prototype,u=i.hasOwnProperty;e.exports=r},function(e,t,n){function r(e,t){var n=this.__data__;return n[e]=o&&void 0===t?i:t,this}var o=n(16),i="__lodash_hash_undefined__";e.exports=r},function(e,t,n){function r(e){return u(e)||i(e)||!!(s&&e&&e[s])}var o=n(151),i=n(58),u=n(5),s=o?o.isConcatSpreadable:void 0;e.exports=r},function(e,t,n){function r(e,t,n){if(!s(n))return!1;var r=typeof t;return!!("number"==r?i(n)&&u(t,n.length):"string"==r&&t in n)&&o(n[t],e)}var o=n(18),i=n(30),u=n(56),s=n(11);e.exports=r},function(e,t){function n(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}e.exports=n},function(e,t,n){function r(e){return!!i&&i in e}var o=n(167),i=function(){var e=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();e.exports=r},function(e,t){function n(e){var t=e&&e.constructor,n="function"==typeof t&&t.prototype||r;return e===n}var r=Object.prototype;e.exports=n},function(e,t){function n(){this.__data__=[]}e.exports=n},function(e,t,n){function r(e){var t=this.__data__,n=o(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():u.call(t,n,1),!0}var o=n(14),i=Array.prototype,u=i.splice;e.exports=r},function(e,t,n){function r(e){var t=this.__data__,n=o(t,e);return n<0?void 0:t[n][1]}var o=n(14);e.exports=r},function(e,t,n){function r(e){return o(this.__data__,e)>-1}var o=n(14);e.exports=r},function(e,t,n){function r(e,t){var n=this.__data__,r=o(n,e);return r<0?n.push([e,t]):n[r][1]=t,this}var o=n(14);e.exports=r},function(e,t,n){function r(){this.__data__={hash:new o,map:new(u||i),string:new o}}var o=n(147),i=n(148),u=n(149);e.exports=r},function(e,t,n){function r(e){return o(this,e)["delete"](e)}var o=n(15);e.exports=r},function(e,t,n){function r(e){return o(this,e).get(e)}var o=n(15);e.exports=r},function(e,t,n){function r(e){return o(this,e).has(e)}var o=n(15);e.exports=r},function(e,t,n){function r(e,t){return o(this,e).set(e,t),this}var o=n(15);e.exports=r},function(e,t){function n(e){var t=[];if(null!=e)for(var n in Object(e))t.push(n);return t}e.exports=n},function(e,t){function n(e,t){return function(n){return e(t(n))}}e.exports=n},function(e,t){function n(e){return this.__data__.set(e,r),this}var r="__lodash_hash_undefined__";e.exports=n},function(e,t){function n(e){return this.__data__.has(e)}e.exports=n},function(e,t){function n(e){if(null!=e){try{return o.call(e)}catch(t){}try{return e+""}catch(t){}}return""}var r=Function.prototype,o=r.toString;e.exports=n},function(e,t,n){var r=n(166),o=n(168),i=n(202),u=o(function(e,t,n,o){r(t,i(t),e,o)});e.exports=u},function(e,t,n){var r=n(50),o=n(154),i=n(198),u=n(6),s=u(function(e){return e.push(void 0,o),r(i,void 0,e)});e.exports=s},function(e,t,n){var r=n(27),o=n(159),i=n(6),u=n(165),s=i(function(e){var t=r(e,u);return t.length&&t[0]===e[0]?o(t):[]});e.exports=s},function(e,t){function n(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=r}var r=9007199254740991;e.exports=n},function(e,t,n){function r(e){return u(e)?o(e,!0):i(e)}var o=n(153),i=n(162),u=n(30);e.exports=r},function(e,t,n){function r(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError(i);var n=function(){var r=arguments,o=t?t.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var u=e.apply(this,r);return n.cache=i.set(o,u),u};return n.cache=new(r.Cache||o),n}var o=n(49),i="Expected a function";r.Cache=o,e.exports=r},function(e,t,n){var r=n(157),o=n(6),i=n(54),u=n(10),s=o(function(e){return i(r(e,1,u,!0))});e.exports=s},function(e,t,n){var r=n(152),o=n(6),i=n(164),u=n(10),s=o(function(e){return i(r(e,u))});e.exports=s},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=function(e){var t=e.displayName||e.name||"Component";return u["default"].createClass({displayName:"ContextMenuConnector("+t+")",getInitialState:function(){return{item:a["default"].getState().currentItem}},componentDidMount:function(){this.unsubscribe=a["default"].subscribe(this.handleUpdate)},componentWillUnmount:function(){this.unsubscribe()},handleUpdate:function(){this.setState(this.getInitialState())},render:function(){return u["default"].createElement(e,o({},this.props,{item:this.state.item}))}})};var i=n(1),u=r(i),s=n(19),a=r(s)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),u=r(i),s=n(19),a=r(s),l=n(208),c=r(l),p=u["default"].PropTypes,f=u["default"].createClass({displayName:"ContextMenu",propTypes:{identifier:p.string.isRequired},getInitialState:function(){return a["default"].getState()},componentDidMount:function(){this.unsubscribe=a["default"].subscribe(this.handleUpdate)},componentWillUnmount:function(){this.unsubscribe&&this.unsubscribe()},handleUpdate:function(){this.setState(this.getInitialState())},render:function(){return u["default"].createElement(c["default"],o({},this.props,this.state))}});t["default"]=f},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),u=r(i),s=n(31),a=r(s),l=n(236),c=r(l),p={position:"fixed",zIndex:1040,top:0,bottom:0,left:0,right:0},f=o({},p,{zIndex:"auto",backgroundColor:"transparent"}),d={position:"fixed",zIndex:"auto"},h=u["default"].createClass({displayName:"ContextMenuWrapper",getInitialState:function(){return{left:0,top:0}},componentWillReceiveProps:function(e){var t=this;if(e.isVisible===e.identifier){var n=window.requestAnimationFrame||setTimeout;n(function(){t.setState(t.getMenuPosition(e.x,e.y)),t.menu.parentNode.addEventListener("contextmenu",t.hideMenu)})}},shouldComponentUpdate:function(e){return this.props.isVisible!==e.visible},hideMenu:function(e){e.preventDefault(),this.menu.parentNode.removeEventListener("contextmenu",this.hideMenu),a["default"].hideMenu()},getMenuPosition:function(e,t){var n=document.documentElement.scrollTop,r=document.documentElement.scrollLeft,o=window,i=o.innerWidth,u=o.innerHeight,s=this.menu.getBoundingClientRect(),a={top:t+r,left:e+n};return t+s.height>u&&(a.top-=s.height),e+s.width>i&&(a.left-=s.width),a},render:function(){var e=this,t=this.props,n=t.isVisible,r=t.identifier,i=t.children,s=o({},d,this.state);return u["default"].createElement(c["default"],{style:p,backdropStyle:f,show:n===r,onHide:function(){return a["default"].hideMenu()}},u["default"].createElement("nav",{ref:function(t){return e.menu=t},style:s,className:"react-context-menu"},i))}});t["default"]=h},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};t["default"]=function(e,t){return function(n){var r=n.displayName||n.name||"Component";return(0,l["default"])(e&&("string"==typeof e||"symbol"===("undefined"==typeof e?"undefined":i(e))||"function"==typeof e),"Expected identifier to be string, symbol or function. See %s",r),t&&(0,l["default"])("function"==typeof t,"Expected configure to be a function. See %s",r),s["default"].createClass({displayName:r+"ContextMenuLayer",getDefaultProps:function(){return{renderTag:"div",attributes:{}}},mouseDown:!1,handleMouseDown:function(e){var t=this;this.props.holdToDisplay>=0&&0===e.button&&(e.persist(),this.mouseDown=!0,setTimeout(function(){t.mouseDown&&t.handleContextClick(e)},this.props.holdToDisplay))},handleTouchstart:function(e){var t=this;e.persist(),this.mouseDown=!0,setTimeout(function(){t.mouseDown&&t.handleContextClick(e)},this.props.holdToDisplay)},handleTouchEnd:function(e){e.preventDefault(),this.mouseDown=!1},handleMouseUp:function(e){0===e.button&&(this.mouseDown=!1)},handleContextClick:function(n){var o="function"==typeof t?t(this.props):{};(0,l["default"])((0,p["default"])(o),"Expected configure to return an object. See %s",r),n.preventDefault();var i=n.clientX||n.touches&&n.touches[0].pageX,u=n.clientY||n.touches&&n.touches[0].pageY;d["default"].dispatch({type:"SET_PARAMS",data:{x:i,y:u,currentItem:o,isVisible:"function"==typeof e?e(this.props):e}})},render:function(){var e=this.props,t=e.attributes,r=t.className,i=void 0===r?"":r,u=o(t,["className"]),a=e.renderTag,l=o(e,["attributes","renderTag"]);return u.className="react-context-menu-wrapper "+i,u.onContextMenu=this.handleContextClick,u.onMouseDown=this.handleMouseDown,u.onMouseUp=this.handleMouseUp,u.onTouchStart=this.handleTouchstart,u.onTouchEnd=this.handleTouchEnd,u.onMouseOut=this.handleMouseUp,s["default"].createElement(a,u,s["default"].createElement(n,l))}})}};var u=n(1),s=r(u),a=n(2),l=r(a),c=n(146),p=r(c),f=n(19),d=r(f)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(1),s=r(u),a=n(64),l=r(a),c=n(65),p=r(c),f=n(31),d=r(f),h=s["default"].PropTypes,g=s["default"].createClass({displayName:"MenuItem",propTypes:{onClick:h.func.isRequired,data:h.object,disabled:h.bool,preventClose:h.bool},getDefaultProps:function(){return{disabled:!1,data:{},attributes:{}}},handleClick:function(e){var t=this.props,n=t.disabled,r=t.onClick,o=t.data,i=t.preventClose;e.preventDefault(),n||((0,p["default"])(o,d["default"].getItem()),"function"==typeof r&&r(e,o),i||d["default"].hideMenu())},render:function(){var e=this.props,t=e.disabled,n=e.children,r=e.attributes,u=r.className,a=void 0===u?"":u,c=o(r,["className"]),p="react-context-menu-item "+a,f=(0,l["default"])({"react-context-menu-link":!0,disabled:t});return s["default"].createElement("div",i({className:p},c),s["default"].createElement("a",{href:"#",className:f,onClick:this.handleClick},n))}});t["default"]=g},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=function(){var e=arguments.length<=0||void 0===arguments[0]?u:arguments[0],t=arguments[1];return"SET_PARAMS"===t.type?(0,i["default"])({},e,t.data):e};var o=n(65),i=r(o),u={x:0,y:0,isVisible:!1,currentItem:{}}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),u=n(64),s=r(u),a=n(213),l=r(a),c={position:"relative",zIndex:"auto"},p=i["default"].createClass({displayName:"SubMenu",propTypes:{title:i["default"].PropTypes.string.isRequired,disabled:i["default"].PropTypes.bool,hoverDelay:i["default"].PropTypes.number},getDefaultProps:function(){return{hoverDelay:500}},getInitialState:function(){return{visible:!1}},shouldComponentUpdate:function(e,t){return this.state.isVisible!==t.visible},componentWillUnmount:function(){this.opentimer&&clearTimeout(this.opentimer),this.closetimer&&clearTimeout(this.closetimer)},handleClick:function(e){e.preventDefault()},handleMouseEnter:function(){var e=this;this.closetimer&&clearTimeout(this.closetimer),this.props.disabled||this.state.visible||(this.opentimer=setTimeout(function(){return e.setState({visible:!0})},this.props.hoverDelay))},handleMouseLeave:function(){var e=this;this.opentimer&&clearTimeout(this.opentimer),this.state.visible&&(this.closetimer=setTimeout(function(){return e.setState({visible:!1})},this.props.hoverDelay))},render:function(){var e=this,t=this.props,n=t.disabled,r=t.children,o=t.title,u=this.state.visible,a=(0,s["default"])({"react-context-menu-link":!0,disabled:n,active:u}),p="react-context-menu-item submenu";return i["default"].createElement("div",{ref:function(t){return e.item=t},className:p,style:c,onMouseEnter:this.handleMouseEnter,onMouseLeave:this.handleMouseLeave},i["default"].createElement("a",{href:"#",className:a,onClick:this.handleClick},o),i["default"].createElement(l["default"],{visible:u},r))}});t["default"]=p},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),u=r(i),s=u["default"].createClass({displayName:"SubMenuWrapper",propTypes:{visible:u["default"].PropTypes.bool},getInitialState:function(){return{position:{top:!0,right:!0}}},componentWillReceiveProps:function(e){var t=this;if(e.visible){var n=window.requestAnimationFrame||setTimeout;n(function(){t.setState(t.getMenuPosition()),t.forceUpdate()})}else this.setState(this.getInitialState())},shouldComponentUpdate:function(e){return this.props.visible!==e.visible},getMenuPosition:function(){var e=window,t=e.innerWidth,n=e.innerHeight,r=this.menu.getBoundingClientRect(),o={};return r.bottom>n?o.bottom=!0:o.top=!0,r.right>t?o.left=!0:o.right=!0,{position:o}},getPositionStyles:function(){var e={},t=this.state.position;return t.top&&(e.top=0),t.bottom&&(e.bottom=0),t.right&&(e.left="100%"),t.left&&(e.right="100%"),e},render:function(){var e=this,t=this.props,n=t.children,r=t.visible,i=o({display:r?"block":"none",position:"absolute"},this.getPositionStyles());return u["default"].createElement("nav",{ref:function(t){return e.menu=t},style:i,className:"react-context-menu"},n)}});t["default"]=s},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}t.__esModule=!0;var i=n(204),u=r(i),s=n(62),a=r(s),l=function(){function e(){o(this,e),this.entered=[]}return e.prototype.enter=function(e){var t=this.entered.length;return this.entered=u["default"](this.entered.filter(function(t){return document.documentElement.contains(t)&&(!t.contains||t.contains(e))}),[e]),0===t&&this.entered.length>0},e.prototype.leave=function(e){var t=this.entered.length;return this.entered=a["default"](this.entered.filter(function(e){return document.documentElement.contains(e)}),e),t>0&&0===this.entered.length},e.prototype.reset=function(){this.entered=[]},e}();t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}t.__esModule=!0;var u=n(199),s=o(u),a=n(221),l=o(a),c=n(214),p=o(c),f=n(66),d=n(218),h=n(217),g=n(32),y=r(g),v=function(){function e(t){i(this,e),this.actions=t.getActions(),this.monitor=t.getMonitor(),this.registry=t.getRegistry(),this.sourcePreviewNodes={},this.sourcePreviewNodeOptions={},this.sourceNodes={},this.sourceNodeOptions={},this.enterLeaveCounter=new p["default"],this.getSourceClientOffset=this.getSourceClientOffset.bind(this),this.handleTopDragStart=this.handleTopDragStart.bind(this),this.handleTopDragStartCapture=this.handleTopDragStartCapture.bind(this),this.handleTopDragEndCapture=this.handleTopDragEndCapture.bind(this),this.handleTopDragEnter=this.handleTopDragEnter.bind(this),this.handleTopDragEnterCapture=this.handleTopDragEnterCapture.bind(this),this.handleTopDragLeaveCapture=this.handleTopDragLeaveCapture.bind(this),this.handleTopDragOver=this.handleTopDragOver.bind(this),this.handleTopDragOverCapture=this.handleTopDragOverCapture.bind(this),this.handleTopDrop=this.handleTopDrop.bind(this),this.handleTopDropCapture=this.handleTopDropCapture.bind(this),this.handleSelectStart=this.handleSelectStart.bind(this),this.endDragIfSourceWasRemovedFromDOM=this.endDragIfSourceWasRemovedFromDOM.bind(this),this.endDragNativeItem=this.endDragNativeItem.bind(this)}return e.prototype.setup=function(){if("undefined"!=typeof window){if(this.constructor.isSetUp)throw new Error("Cannot have two HTML5 backends at the same time.");this.constructor.isSetUp=!0,this.addEventListeners(window)}},e.prototype.teardown=function(){"undefined"!=typeof window&&(this.constructor.isSetUp=!1,this.removeEventListeners(window),this.clearCurrentDragSourceNode())},e.prototype.addEventListeners=function(e){e.addEventListener("dragstart",this.handleTopDragStart),e.addEventListener("dragstart",this.handleTopDragStartCapture,!0),e.addEventListener("dragend",this.handleTopDragEndCapture,!0),e.addEventListener("dragenter",this.handleTopDragEnter),e.addEventListener("dragenter",this.handleTopDragEnterCapture,!0),e.addEventListener("dragleave",this.handleTopDragLeaveCapture,!0),e.addEventListener("dragover",this.handleTopDragOver),e.addEventListener("dragover",this.handleTopDragOverCapture,!0),e.addEventListener("drop",this.handleTopDrop),e.addEventListener("drop",this.handleTopDropCapture,!0)},e.prototype.removeEventListeners=function(e){e.removeEventListener("dragstart",this.handleTopDragStart),e.removeEventListener("dragstart",this.handleTopDragStartCapture,!0),e.removeEventListener("dragend",this.handleTopDragEndCapture,!0),e.removeEventListener("dragenter",this.handleTopDragEnter),e.removeEventListener("dragenter",this.handleTopDragEnterCapture,!0),e.removeEventListener("dragleave",this.handleTopDragLeaveCapture,!0),e.removeEventListener("dragover",this.handleTopDragOver),e.removeEventListener("dragover",this.handleTopDragOverCapture,!0),e.removeEventListener("drop",this.handleTopDrop),e.removeEventListener("drop",this.handleTopDropCapture,!0)},e.prototype.connectDragPreview=function(e,t,n){var r=this;return this.sourcePreviewNodeOptions[e]=n,this.sourcePreviewNodes[e]=t,function(){delete r.sourcePreviewNodes[e],delete r.sourcePreviewNodeOptions[e]}},e.prototype.connectDragSource=function(e,t,n){var r=this;this.sourceNodes[e]=t,this.sourceNodeOptions[e]=n;var o=function(t){return r.handleDragStart(t,e)},i=function(t){return r.handleSelectStart(t,e)};return t.setAttribute("draggable",!0),t.addEventListener("dragstart",o),t.addEventListener("selectstart",i),function(){delete r.sourceNodes[e],delete r.sourceNodeOptions[e],t.removeEventListener("dragstart",o),t.removeEventListener("selectstart",i),t.setAttribute("draggable",!1)}},e.prototype.connectDropTarget=function(e,t){var n=this,r=function(t){return n.handleDragEnter(t,e)},o=function(t){return n.handleDragOver(t,e)},i=function(t){return n.handleDrop(t,e)};return t.addEventListener("dragenter",r),t.addEventListener("dragover",o),t.addEventListener("drop",i),function(){t.removeEventListener("dragenter",r),t.removeEventListener("dragover",o),t.removeEventListener("drop",i)}},e.prototype.getCurrentSourceNodeOptions=function(){var e=this.monitor.getSourceId(),t=this.sourceNodeOptions[e];return s["default"](t||{},{dropEffect:"move"})},e.prototype.getCurrentDropEffect=function(){return this.isDraggingNativeItem()?"copy":this.getCurrentSourceNodeOptions().dropEffect},e.prototype.getCurrentSourcePreviewNodeOptions=function(){var e=this.monitor.getSourceId(),t=this.sourcePreviewNodeOptions[e];return s["default"](t||{},{anchorX:.5,anchorY:.5,captureDraggingState:!1})},e.prototype.getSourceClientOffset=function(e){return d.getNodeClientOffset(this.sourceNodes[e])},e.prototype.isDraggingNativeItem=function(){var e=this.monitor.getItemType();return Object.keys(y).some(function(t){return y[t]===e})},e.prototype.beginDragNativeItem=function(e){this.clearCurrentDragSourceNode();var t=h.createNativeDragSource(e);this.currentNativeSource=new t,this.currentNativeHandle=this.registry.addSource(e,this.currentNativeSource),this.actions.beginDrag([this.currentNativeHandle]),f.isFirefox()&&window.addEventListener("mousemove",this.endDragNativeItem,!0)},e.prototype.endDragNativeItem=function(){this.isDraggingNativeItem()&&(f.isFirefox()&&window.removeEventListener("mousemove",this.endDragNativeItem,!0),this.actions.endDrag(),this.registry.removeSource(this.currentNativeHandle),this.currentNativeHandle=null,this.currentNativeSource=null)},e.prototype.endDragIfSourceWasRemovedFromDOM=function(){var e=this.currentDragSourceNode;document.body.contains(e)||this.clearCurrentDragSourceNode()&&this.actions.endDrag()},e.prototype.setCurrentDragSourceNode=function(e){this.clearCurrentDragSourceNode(),this.currentDragSourceNode=e,this.currentDragSourceNodeOffset=d.getNodeClientOffset(e),this.currentDragSourceNodeOffsetChanged=!1,window.addEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)},e.prototype.clearCurrentDragSourceNode=function(){return!!this.currentDragSourceNode&&(this.currentDragSourceNode=null,this.currentDragSourceNodeOffset=null,this.currentDragSourceNodeOffsetChanged=!1,window.removeEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0),!0)},e.prototype.checkIfCurrentDragSourceRectChanged=function(){var e=this.currentDragSourceNode;return!!e&&(!!this.currentDragSourceNodeOffsetChanged||(this.currentDragSourceNodeOffsetChanged=!l["default"](d.getNodeClientOffset(e),this.currentDragSourceNodeOffset),this.currentDragSourceNodeOffsetChanged))},e.prototype.handleTopDragStartCapture=function(){this.clearCurrentDragSourceNode(),this.dragStartSourceIds=[]},e.prototype.handleDragStart=function(e,t){this.dragStartSourceIds.unshift(t)},e.prototype.handleTopDragStart=function(e){var t=this,n=this.dragStartSourceIds;this.dragStartSourceIds=null;var r=d.getEventClientOffset(e);this.actions.beginDrag(n,{publishSource:!1,getSourceClientOffset:this.getSourceClientOffset,clientOffset:r});var o=e.dataTransfer,i=h.matchNativeItemType(o);if(this.monitor.isDragging()){if("function"==typeof o.setDragImage){var u=this.monitor.getSourceId(),s=this.sourceNodes[u],a=this.sourcePreviewNodes[u]||s,l=this.getCurrentSourcePreviewNodeOptions(),c=l.anchorX,p=l.anchorY,f={anchorX:c,anchorY:p},g=d.getDragPreviewOffset(s,a,r,f);o.setDragImage(a,g.x,g.y)}try{o.setData("application/json",{})}catch(y){}this.setCurrentDragSourceNode(e.target);var v=this.getCurrentSourcePreviewNodeOptions(),m=v.captureDraggingState;m?this.actions.publishDragSource():setTimeout(function(){return t.actions.publishDragSource()})}else if(i)this.beginDragNativeItem(i);else{if(!(o.types||e.target.hasAttribute&&e.target.hasAttribute("draggable")))return;e.preventDefault()}},e.prototype.handleTopDragEndCapture=function(){this.clearCurrentDragSourceNode()&&this.actions.endDrag()},e.prototype.handleTopDragEnterCapture=function(e){this.dragEnterTargetIds=[];var t=this.enterLeaveCounter.enter(e.target);if(t&&!this.monitor.isDragging()){var n=e.dataTransfer,r=h.matchNativeItemType(n);r&&this.beginDragNativeItem(r)}},e.prototype.handleDragEnter=function(e,t){this.dragEnterTargetIds.unshift(t)},e.prototype.handleTopDragEnter=function(e){var t=this,n=this.dragEnterTargetIds;if(this.dragEnterTargetIds=[],this.monitor.isDragging()){f.isFirefox()||this.actions.hover(n,{clientOffset:d.getEventClientOffset(e)});var r=n.some(function(e){return t.monitor.canDropOnTarget(e)});r&&(e.preventDefault(),e.dataTransfer.dropEffect=this.getCurrentDropEffect())}},e.prototype.handleTopDragOverCapture=function(){this.dragOverTargetIds=[]},e.prototype.handleDragOver=function(e,t){this.dragOverTargetIds.unshift(t)},e.prototype.handleTopDragOver=function(e){var t=this,n=this.dragOverTargetIds;if(this.dragOverTargetIds=[],!this.monitor.isDragging())return e.preventDefault(),void(e.dataTransfer.dropEffect="none");this.actions.hover(n,{clientOffset:d.getEventClientOffset(e)});var r=n.some(function(e){return t.monitor.canDropOnTarget(e)});r?(e.preventDefault(),e.dataTransfer.dropEffect=this.getCurrentDropEffect()):this.isDraggingNativeItem()?(e.preventDefault(),e.dataTransfer.dropEffect="none"):this.checkIfCurrentDragSourceRectChanged()&&(e.preventDefault(),e.dataTransfer.dropEffect="move")},e.prototype.handleTopDragLeaveCapture=function(e){this.isDraggingNativeItem()&&e.preventDefault();var t=this.enterLeaveCounter.leave(e.target);t&&this.isDraggingNativeItem()&&this.endDragNativeItem()},e.prototype.handleTopDropCapture=function(e){this.dropTargetIds=[],e.preventDefault(),this.isDraggingNativeItem()&&this.currentNativeSource.mutateItemByReadingDataTransfer(e.dataTransfer),this.enterLeaveCounter.reset()},e.prototype.handleDrop=function(e,t){
this.dropTargetIds.unshift(t)},e.prototype.handleTopDrop=function(e){var t=this.dropTargetIds;this.dropTargetIds=[],this.actions.hover(t,{clientOffset:d.getEventClientOffset(e)}),this.actions.drop(),this.isDraggingNativeItem()?this.endDragNativeItem():this.endDragIfSourceWasRemovedFromDOM()},e.prototype.handleSelectStart=function(e){var t=e.target;"function"==typeof t.dragDrop&&("INPUT"===t.tagName||"SELECT"===t.tagName||"TEXTAREA"===t.tagName||t.isContentEditable||(e.preventDefault(),t.dragDrop()))},e}();t["default"]=v,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}t.__esModule=!0;var r=function(){function e(t,r){n(this,e);for(var o=t.length,i=[],u=0;u<o;u++)i.push(u);i.sort(function(e,n){return t[e]<t[n]?-1:1});for(var s=[],a=[],l=[],c=void 0,p=void 0,u=0;u<o-1;u++)c=t[u+1]-t[u],p=r[u+1]-r[u],a.push(c),s.push(p),l.push(p/c);for(var f=[l[0]],u=0;u<a.length-1;u++){var d=l[u],h=l[u+1];if(d*h<=0)f.push(0);else{c=a[u];var g=a[u+1],y=c+g;f.push(3*y/((y+g)/d+(y+c)/h))}}f.push(l[l.length-1]);for(var v=[],m=[],b=void 0,u=0;u<f.length-1;u++){b=l[u];var E=f[u],w=1/a[u],y=E+f[u+1]-b-b;v.push((b-E-y)*w),m.push(y*w*w)}this.xs=t,this.ys=r,this.c1s=f,this.c2s=v,this.c3s=m}return e.prototype.interpolate=function(e){var t=this.xs,n=this.ys,r=this.c1s,o=this.c2s,i=this.c3s,u=t.length-1;if(e===t[u])return n[u];for(var s=0,a=i.length-1,l=void 0;s<=a;){l=Math.floor(.5*(s+a));var c=t[l];if(c<e)s=l+1;else{if(!(c>e))return n[l];a=l-1}}u=Math.max(0,a);var p=e-t[u],f=p*p;return n[u]+r[u]*p+o[u]*f+i[u]*p*f},e}();t["default"]=r,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function u(e,t,n){var r=t.reduce(function(t,n){return t||e.getData(n)},null);return null!=r?r:n}function s(e){var t=f[e],n=t.exposeProperty,r=t.matchesTypes,u=t.getData;return function(){function e(){o(this,e),this.item=Object.defineProperties({},i({},n,{get:function(){return console.warn("Browser doesn't allow reading \""+n+'" until the drop event.'),null},configurable:!0,enumerable:!0}))}return e.prototype.mutateItemByReadingDataTransfer=function(e){delete this.item[n],this.item[n]=u(e,r)},e.prototype.canDrag=function(){return!0},e.prototype.beginDrag=function(){return this.item},e.prototype.isDragging=function(e,t){return t===e.getSourceId()},e.prototype.endDrag=function(){},e}()}function a(e){var t=Array.prototype.slice.call(e.types||[]);return Object.keys(f).filter(function(e){var n=f[e].matchesTypes;return n.some(function(e){return t.indexOf(e)>-1})})[0]||null}t.__esModule=!0;var l;t.createNativeDragSource=s,t.matchNativeItemType=a;var c=n(32),p=r(c),f=(l={},i(l,p.FILE,{exposeProperty:"files",matchesTypes:["Files"],getData:function(e){return Array.prototype.slice.call(e.files)}}),i(l,p.URL,{exposeProperty:"urls",matchesTypes:["Url","text/uri-list"],getData:function(e,t){return u(e,t,"").split("\n")}}),i(l,p.TEXT,{exposeProperty:"text",matchesTypes:["Text","text/plain"],getData:function(e,t){return u(e,t,"")}}),l)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.nodeType===c?e:e.parentElement;if(!t)return null;var n=t.getBoundingClientRect(),r=n.top,o=n.left;return{x:o,y:r}}function i(e){return{x:e.clientX,y:e.clientY}}function u(e,t,n,r){var i="IMG"===t.nodeName&&(s.isFirefox()||!document.documentElement.contains(t)),u=i?e:t,a=o(u),c={x:n.x-a.x,y:n.y-a.y},p=e.offsetWidth,f=e.offsetHeight,d=r.anchorX,h=r.anchorY,g=i?t.width:p,y=i?t.height:f;s.isSafari()&&i?(y/=window.devicePixelRatio,g/=window.devicePixelRatio):s.isFirefox()&&!i&&(y*=window.devicePixelRatio,g*=window.devicePixelRatio);var v=new l["default"]([0,.5,1],[c.x,c.x/p*g,c.x+g-p]),m=new l["default"]([0,.5,1],[c.y,c.y/f*y,c.y+y-f]),b=v.interpolate(d),E=m.interpolate(h);return s.isSafari()&&i&&(E+=(window.devicePixelRatio-1)*y),{x:b,y:E}}t.__esModule=!0,t.getNodeClientOffset=o,t.getEventClientOffset=i,t.getDragPreviewOffset=u;var s=n(66),a=n(216),l=r(a),c=1},function(e,t){"use strict";function n(){return r||(r=new Image,r.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="),r}t.__esModule=!0,t["default"]=n;var r=void 0;e.exports=t["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}function i(e){return new s["default"](e)}t.__esModule=!0,t["default"]=i;var u=n(215),s=o(u),a=n(219),l=o(a),c=n(32),p=r(c);t.NativeTypes=p,t.getEmptyImage=l["default"]},33,function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e){y["default"].apply(void 0,["DragDropContext","backend"].concat(a.call(arguments)));var t=void 0;t="object"==typeof e&&"function"==typeof e["default"]?e["default"]:e,h["default"]("function"==typeof t,"Expected the backend to be a function or an ES6 module exporting a default function. Read more: http://gaearon.github.io/react-dnd/docs-drag-drop-context.html");var n={dragDropManager:new f.DragDropManager(t)};return function(e){var t=e.displayName||e.name||"Component";return function(r){function u(){o(this,u),r.apply(this,arguments)}return i(u,r),u.prototype.getDecoratedComponentInstance=function(){return this.refs.child},u.prototype.getManager=function(){return n.dragDropManager},u.prototype.getChildContext=function(){return n},u.prototype.render=function(){return p["default"].createElement(e,s({},this.props,{ref:"child"}))},l(u,null,[{key:"DecoratedComponent",value:e,enumerable:!0},{key:"displayName",value:"DragDropContext("+t+")",enumerable:!0},{key:"childContextTypes",value:{dragDropManager:c.PropTypes.object.isRequired},enumerable:!0}]),u}(c.Component)}}t.__esModule=!0;var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=Array.prototype.slice,l=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}();t["default"]=u;var c=n(1),p=r(c),f=n(124),d=n(2),h=r(d),g=n(20),y=r(g);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function u(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return w["default"].apply(void 0,["DragLayer","collect[, options]"].concat(a.call(arguments))),b["default"]("function"==typeof e,'Expected "collect" provided as the first argument to DragLayer to be a function that collects props to inject into the component. ',"Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-layer.html",e),b["default"](v["default"](t),'Expected "options" provided as the second argument to DragLayer to be a plain object when specified. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-layer.html',t),function(n){var r=t.arePropsEqual,u=void 0===r?g["default"]:r,a=n.displayName||n.name||"Component";return function(t){function r(e,n){o(this,r),t.call(this,e),this.handleChange=this.handleChange.bind(this),this.manager=n.dragDropManager,b["default"]("object"==typeof this.manager,"Could not find the drag and drop manager in the context of %s. Make sure to wrap the top-level component of your app with DragDropContext. Read more: http://gaearon.github.io/react-dnd/docs-troubleshooting.html#could-not-find-the-drag-and-drop-manager-in-the-context",a,a),this.state=this.getCurrentState()}return i(r,t),r.prototype.getDecoratedComponentInstance=function(){return this.refs.child},r.prototype.shouldComponentUpdate=function(e,t){return!u(e,this.props)||!d["default"](t,this.state)},l(r,null,[{key:"DecoratedComponent",value:n,enumerable:!0},{key:"displayName",value:"DragLayer("+a+")",enumerable:!0},{key:"contextTypes",value:{dragDropManager:c.PropTypes.object.isRequired},enumerable:!0}]),r.prototype.componentDidMount=function(){this.isCurrentlyMounted=!0;var e=this.manager.getMonitor();this.unsubscribeFromOffsetChange=e.subscribeToOffsetChange(this.handleChange),this.unsubscribeFromStateChange=e.subscribeToStateChange(this.handleChange),this.handleChange()},r.prototype.componentWillUnmount=function(){this.isCurrentlyMounted=!1,this.unsubscribeFromOffsetChange(),this.unsubscribeFromStateChange()},r.prototype.handleChange=function(){if(this.isCurrentlyMounted){var e=this.getCurrentState();d["default"](e,this.state)||this.setState(e)}},r.prototype.getCurrentState=function(){var t=this.manager.getMonitor();return e(t)},r.prototype.render=function(){return p["default"].createElement(n,s({},this.props,this.state,{ref:"child"}))},r}(c.Component)}}t.__esModule=!0;var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=Array.prototype.slice,l=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}();t["default"]=u;var c=n(1),p=r(c),f=n(33),d=r(f),h=n(70),g=r(h),y=n(4),v=r(y),m=n(2),b=r(m),E=n(20),w=r(E);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){var r=arguments.length<=3||void 0===arguments[3]?{}:arguments[3];p["default"].apply(void 0,["DragSource","type, spec, collect[, options]"].concat(i.call(arguments)));var o=e;"function"!=typeof e&&(s["default"](_["default"](e),'Expected "type" provided as the first argument to DragSource to be a string, or a function that returns a string given the current props. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html',e),o=function(){return e}),s["default"](l["default"](t),'Expected "spec" provided as the second argument to DragSource to be a plain object. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html',t);var u=v["default"](t);return s["default"]("function"==typeof n,'Expected "collect" provided as the third argument to DragSource to be a function that returns a plain object of props to inject. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html',n),s["default"](l["default"](r),'Expected "options" provided as the fourth argument to DragSource to be a plain object when specified. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html',n),function(e){return d["default"]({connectBackend:function(e,t){return e.connectDragSource(t)},containerDisplayName:"DragSource",createHandler:u,registerHandler:g["default"],createMonitor:b["default"],createConnector:w["default"],DecoratedComponent:e,getType:o,collect:n,options:r})}}t.__esModule=!0;var i=Array.prototype.slice;t["default"]=o;var u=n(2),s=r(u),a=n(4),l=r(a),c=n(20),p=r(c),f=n(68),d=r(f),h=n(232),g=r(h),y=n(227),v=r(y),m=n(228),b=r(m),E=n(226),w=r(E),T=n(69),_=r(T);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){var r=arguments.length<=3||void 0===arguments[3]?{}:arguments[3];p["default"].apply(void 0,["DropTarget","type, spec, collect[, options]"].concat(i.call(arguments)));var o=e;"function"!=typeof e&&(s["default"](_["default"](e,!0),'Expected "type" provided as the first argument to DropTarget to be a string, an array of strings, or a function that returns either given the current props. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html',e),o=function(){return e}),s["default"](l["default"](t),'Expected "spec" provided as the second argument to DropTarget to be a plain object. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html',t);var u=v["default"](t);return s["default"]("function"==typeof n,'Expected "collect" provided as the third argument to DropTarget to be a function that returns a plain object of props to inject. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html',n),s["default"](l["default"](r),'Expected "options" provided as the fourth argument to DropTarget to be a plain object when specified. Instead, received %s. Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html',n),function(e){return d["default"]({connectBackend:function(e,t){return e.connectDropTarget(t)},containerDisplayName:"DropTarget",createHandler:u,registerHandler:g["default"],createMonitor:b["default"],createConnector:w["default"],DecoratedComponent:e,getType:o,collect:n,options:r})}}t.__esModule=!0;var i=Array.prototype.slice;t["default"]=o;var u=n(2),s=r(u),a=n(4),l=r(a),c=n(20),p=r(c),f=n(68),d=r(f),h=n(233),g=r(h),y=n(230),v=r(y),m=n(231),b=r(m),E=n(229),w=r(E),T=n(69),_=r(T);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){function t(){l&&(l(),l=null),o&&i&&(l=e.connectDragSource(o,i,s))}function n(){f&&(f(),f=null),o&&c&&(f=e.connectDragPreview(o,c,p))}function r(e){e!==o&&(o=e,t(),n())}var o=void 0,i=void 0,s=void 0,l=void 0,c=void 0,p=void 0,f=void 0,d=u["default"]({dragSource:function(e,n){e===i&&a["default"](n,s)||(i=e,s=n,t())},dragPreview:function(e,t){e===c&&a["default"](t,p)||(c=e,p=t,n())}});return{receiveHandlerId:r,hooks:d}}t.__esModule=!0,t["default"]=o;var i=n(71),u=r(i),s=n(67),a=r(s);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e){Object.keys(e).forEach(function(t){s["default"](l.indexOf(t)>-1,'Expected the drag source specification to only have some of the following keys: %s. Instead received a specification with an unexpected "%s" key. Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html',l.join(", "),t),s["default"]("function"==typeof e[t],"Expected %s in the drag source specification to be a function. Instead received a specification with %s: %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html",t,t,e[t])}),c.forEach(function(t){s["default"]("function"==typeof e[t],"Expected %s in the drag source specification to be a function. Instead received a specification with %s: %s. Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html",t,t,e[t])});var t=function(){function t(e){o(this,t),this.monitor=e,this.props=null,this.component=null}return t.prototype.receiveProps=function(e){this.props=e},t.prototype.receiveComponent=function(e){this.component=e},t.prototype.canDrag=function(){return!e.canDrag||e.canDrag(this.props,this.monitor)},t.prototype.isDragging=function(t,n){return e.isDragging?e.isDragging(this.props,this.monitor):n===t.getSourceId()},t.prototype.beginDrag=function(){var t=e.beginDrag(this.props,this.monitor,this.component);return t},t.prototype.endDrag=function(){e.endDrag&&e.endDrag(this.props,this.monitor,this.component)},t}();return function(e){return new t(e)}}t.__esModule=!0,t["default"]=i;var u=n(2),s=r(u),a=n(4),l=(r(a),["canDrag","beginDrag","canDrag","isDragging","endDrag"]),c=["beginDrag"];e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e){return new c(e)}t.__esModule=!0,t["default"]=i;var u=n(2),s=r(u),a=!1,l=!1,c=function(){function e(t){o(this,e),this.internalMonitor=t.getMonitor()}return e.prototype.receiveHandlerId=function(e){this.sourceId=e},e.prototype.canDrag=function(){s["default"](!a,"You may not call monitor.canDrag() inside your canDrag() implementation. Read more: http://gaearon.github.io/react-dnd/docs-drag-source-monitor.html");try{return a=!0,this.internalMonitor.canDragSource(this.sourceId)}finally{a=!1}},e.prototype.isDragging=function(){s["default"](!l,"You may not call monitor.isDragging() inside your isDragging() implementation. Read more: http://gaearon.github.io/react-dnd/docs-drag-source-monitor.html");try{return l=!0,this.internalMonitor.isDraggingSource(this.sourceId)}finally{l=!1}},e.prototype.getItemType=function(){return this.internalMonitor.getItemType()},e.prototype.getItem=function(){return this.internalMonitor.getItem()},e.prototype.getDropResult=function(){return this.internalMonitor.getDropResult()},e.prototype.didDrop=function(){return this.internalMonitor.didDrop()},e.prototype.getInitialClientOffset=function(){return this.internalMonitor.getInitialClientOffset()},e.prototype.getInitialSourceClientOffset=function(){return this.internalMonitor.getInitialSourceClientOffset()},e.prototype.getSourceClientOffset=function(){return this.internalMonitor.getSourceClientOffset()},e.prototype.getClientOffset=function(){return this.internalMonitor.getClientOffset()},e.prototype.getDifferenceFromInitialOffset=function(){return this.internalMonitor.getDifferenceFromInitialOffset()},e}();e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){function t(){s&&(s(),s=null),r&&o&&(s=e.connectDropTarget(r,o,i))}function n(e){e!==r&&(r=e,t())}var r=void 0,o=void 0,i=void 0,s=void 0,l=u["default"]({dropTarget:function(e,n){e===o&&a["default"](n,i)||(o=e,i=n,t())}});return{receiveHandlerId:n,hooks:l}}t.__esModule=!0,t["default"]=o;var i=n(71),u=r(i),s=n(67),a=r(s);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e){Object.keys(e).forEach(function(t){s["default"](l.indexOf(t)>-1,'Expected the drop target specification to only have some of the following keys: %s. Instead received a specification with an unexpected "%s" key. Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html',l.join(", "),t),s["default"]("function"==typeof e[t],"Expected %s in the drop target specification to be a function. Instead received a specification with %s: %s. Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html",t,t,e[t])});var t=function(){function t(e){o(this,t),this.monitor=e,this.props=null,this.component=null}return t.prototype.receiveProps=function(e){this.props=e},t.prototype.receiveMonitor=function(e){this.monitor=e},t.prototype.receiveComponent=function(e){this.component=e},t.prototype.canDrop=function(){return!e.canDrop||e.canDrop(this.props,this.monitor)},t.prototype.hover=function(){e.hover&&e.hover(this.props,this.monitor,this.component)},t.prototype.drop=function(){if(e.drop){var t=e.drop(this.props,this.monitor,this.component);return t}},t}();return function(e){return new t(e)}}t.__esModule=!0,t["default"]=i;var u=n(2),s=r(u),a=n(4),l=(r(a),["canDrop","hover","drop"]);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e){return new l(e)}t.__esModule=!0,t["default"]=i;var u=n(2),s=r(u),a=!1,l=function(){function e(t){o(this,e),this.internalMonitor=t.getMonitor()}return e.prototype.receiveHandlerId=function(e){this.targetId=e},e.prototype.canDrop=function(){s["default"](!a,"You may not call monitor.canDrop() inside your canDrop() implementation. Read more: http://gaearon.github.io/react-dnd/docs-drop-target-monitor.html");try{return a=!0,this.internalMonitor.canDropOnTarget(this.targetId)}finally{a=!1}},e.prototype.isOver=function(e){return this.internalMonitor.isOverTarget(this.targetId,e)},e.prototype.getItemType=function(){return this.internalMonitor.getItemType()},e.prototype.getItem=function(){return this.internalMonitor.getItem()},e.prototype.getDropResult=function(){return this.internalMonitor.getDropResult()},e.prototype.didDrop=function(){return this.internalMonitor.didDrop()},e.prototype.getInitialClientOffset=function(){return this.internalMonitor.getInitialClientOffset()},e.prototype.getInitialSourceClientOffset=function(){return this.internalMonitor.getInitialSourceClientOffset()},e.prototype.getSourceClientOffset=function(){return this.internalMonitor.getSourceClientOffset()},e.prototype.getClientOffset=function(){return this.internalMonitor.getClientOffset()},e.prototype.getDifferenceFromInitialOffset=function(){return this.internalMonitor.getDifferenceFromInitialOffset()},e}();e.exports=t["default"]},function(e,t){"use strict";function n(e,t,n){function r(){o.removeSource(i)}var o=n.getRegistry(),i=o.addSource(e,t);return{handlerId:i,unregister:r}}t.__esModule=!0,t["default"]=n,e.exports=t["default"]},function(e,t){"use strict";function n(e,t,n){function r(){o.removeTarget(i)}var o=n.getRegistry(),i=o.addTarget(e,t);return{handlerId:i,unregister:r}}t.__esModule=!0,t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n=e.ref;return u["default"]("string"!=typeof n,"Cannot connect React DnD to an element with an existing string ref. Please convert it to use a callback ref instead, or wrap it into a <span> or <div>. Read more: https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute"),n?s.cloneElement(e,{ref:function(e){t(e),n&&n(e)}}):s.cloneElement(e,{ref:t})}t.__esModule=!0,t["default"]=o;var i=n(2),u=r(i),s=n(1);e.exports=t["default"]},function(e,t,n){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=n(1),i={position:"absolute",top:0,left:0,visibility:"hidden",height:0,overflow:"scroll",whiteSpace:"pre"},u=o.createClass({displayName:"AutosizeInput",propTypes:{className:o.PropTypes.string,defaultValue:o.PropTypes.any,inputClassName:o.PropTypes.string,inputStyle:o.PropTypes.object,minWidth:o.PropTypes.oneOfType([o.PropTypes.number,o.PropTypes.string]),onChange:o.PropTypes.func,placeholder:o.PropTypes.string,placeholderIsMinWidth:o.PropTypes.bool,style:o.PropTypes.object,value:o.PropTypes.any},getDefaultProps:function(){return{minWidth:1}},getInitialState:function(){return{inputWidth:this.props.minWidth}},componentDidMount:function(){this.copyInputStyles(),this.updateInputWidth()},componentDidUpdate:function(){this.updateInputWidth()},copyInputStyles:function(){if(this.isMounted()&&window.getComputedStyle){var e=window.getComputedStyle(this.refs.input);if(e){var t=this.refs.sizer;if(t.style.fontSize=e.fontSize,t.style.fontFamily=e.fontFamily,t.style.fontWeight=e.fontWeight,t.style.fontStyle=e.fontStyle,t.style.letterSpacing=e.letterSpacing,this.props.placeholder){var n=this.refs.placeholderSizer;n.style.fontSize=e.fontSize,n.style.fontFamily=e.fontFamily,n.style.fontWeight=e.fontWeight,n.style.fontStyle=e.fontStyle,n.style.letterSpacing=e.letterSpacing}}}},updateInputWidth:function(){if(this.isMounted()&&"undefined"!=typeof this.refs.sizer.scrollWidth){var e=void 0;e=this.props.placeholder&&(!this.props.value||this.props.value&&this.props.placeholderIsMinWidth)?Math.max(this.refs.sizer.scrollWidth,this.refs.placeholderSizer.scrollWidth)+2:this.refs.sizer.scrollWidth+2,e<this.props.minWidth&&(e=this.props.minWidth),e!==this.state.inputWidth&&this.setState({inputWidth:e})}},getInput:function(){return this.refs.input},focus:function(){this.refs.input.focus()},blur:function(){this.refs.input.blur()},select:function(){this.refs.input.select()},render:function(){var e=this.props.defaultValue||this.props.value||"",t=this.props.style||{};t.display||(t.display="inline-block");var n=r({},this.props.inputStyle);n.width=this.state.inputWidth+"px",n.boxSizing="content-box";var u=r({},this.props);return u.className=this.props.inputClassName,u.style=n,delete u.inputClassName,delete u.inputStyle,delete u.minWidth,delete u.placeholderIsMinWidth,o.createElement("div",{className:this.props.className,style:t},o.createElement("input",r({},u,{ref:"input"})),o.createElement("div",{ref:"sizer",style:i},e),this.props.placeholder?o.createElement("div",{ref:"placeholderSizer",style:i},this.props.placeholder):null)}});e.exports=u},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),u=r(i),s=n(257),a=r(s),l=n(74),c=r(l),p=n(243),f=r(p),d=n(238),h=r(d),g=n(237),y=r(g),v=n(73),m=r(v),b=n(239),E=r(b),w=n(240),T=r(w),_=n(9),D=r(_),O=n(130),C=r(O),x=n(136),P=r(x),S=n(72),M=r(S),I=new y["default"],R=u["default"].createClass({displayName:"Modal",propTypes:o({},h["default"].propTypes,{show:u["default"].PropTypes.bool,container:u["default"].PropTypes.oneOfType([c["default"],u["default"].PropTypes.func]),onShow:u["default"].PropTypes.func,onHide:u["default"].PropTypes.func,backdrop:u["default"].PropTypes.oneOfType([u["default"].PropTypes.bool,u["default"].PropTypes.oneOf(["static"])]),onEscapeKeyUp:u["default"].PropTypes.func,onBackdropClick:u["default"].PropTypes.func,backdropStyle:u["default"].PropTypes.object,backdropClassName:u["default"].PropTypes.string,containerClassName:u["default"].PropTypes.string,keyboard:u["default"].PropTypes.bool,transition:f["default"],dialogTransitionTimeout:u["default"].PropTypes.number,backdropTransitionTimeout:u["default"].PropTypes.number,autoFocus:u["default"].PropTypes.bool,enforceFocus:u["default"].PropTypes.bool,onEnter:u["default"].PropTypes.func,onEntering:u["default"].PropTypes.func,onEntered:u["default"].PropTypes.func,onExit:u["default"].PropTypes.func,onExiting:u["default"].PropTypes.func,onExited:u["default"].PropTypes.func}),getDefaultProps:function(){var e=function(){};return{show:!1,backdrop:!0,keyboard:!0,autoFocus:!0,enforceFocus:!0,onHide:e}},getInitialState:function(){return{exited:!this.props.show}},render:function(){var e=this.props,t=e.show,n=e.container,r=e.children,o=e.transition,s=e.backdrop,a=e.dialogTransitionTimeout,l=e.className,c=e.style,p=e.onExit,f=e.onExiting,d=e.onEnter,g=e.onEntering,y=e.onEntered,v=u["default"].Children.only(r),m=t||o&&!this.state.exited;if(!m)return null;var b=v.props,E=b.role,w=b.tabIndex;return void 0!==E&&void 0!==w||(v=(0,i.cloneElement)(v,{role:void 0===E?"document":E,tabIndex:null==w?"-1":w})),o&&(v=u["default"].createElement(o,{transitionAppear:!0,unmountOnExit:!0,"in":t,timeout:a,onExit:p,onExiting:f,onExited:this.handleHidden,onEnter:d,onEntering:g,onEntered:y},v)),u["default"].createElement(h["default"],{ref:this.setMountNode,container:n},u["default"].createElement("div",{ref:"modal",role:E||"dialog",style:c,className:l},s&&this.renderBackdrop(),v))},renderBackdrop:function(){var e=this.props,t=e.transition,n=e.backdropTransitionTimeout,r=u["default"].createElement("div",{ref:"backdrop",style:this.props.backdropStyle,className:this.props.backdropClassName,onClick:this.handleBackdropClick});return t&&(r=u["default"].createElement(t,{transitionAppear:!0,"in":this.props.show,timeout:n},r)),r},componentWillReceiveProps:function(e){e.show?this.setState({exited:!1}):e.transition||this.setState({exited:!0})},componentWillUpdate:function(e){!this.props.show&&e.show&&this.checkForFocus()},componentDidMount:function(){this.props.show&&this.onShow()},componentDidUpdate:function(e){var t=this.props.transition;!e.show||this.props.show||t?!e.show&&this.props.show&&this.onShow():this.onHide()},componentWillUnmount:function(){var e=this.props,t=e.show,n=e.transition;(t||n&&!this.state.exited)&&this.onHide()},onShow:function(){var e=(0,m["default"])(this),t=(0,M["default"])(this.props.container,e.body);I.add(this,t,this.props.containerClassName),this._onDocumentKeyupListener=(0,E["default"])(e,"keyup",this.handleDocumentKeyUp),this._onFocusinListener=(0,T["default"])(this.enforceFocus),this.focus(),this.props.onShow&&this.props.onShow()},onHide:function(){I.remove(this),this._onDocumentKeyupListener.remove(),this._onFocusinListener.remove(),this.restoreLastFocus()},setMountNode:function(e){this.mountNode=e?e.getMountNode():e},handleHidden:function(){if(this.setState({exited:!0}),this.onHide(),this.props.onExited){var e;(e=this.props).onExited.apply(e,arguments)}},handleBackdropClick:function(e){e.target===e.currentTarget&&(this.props.onBackdropClick&&this.props.onBackdropClick(e),this.props.backdrop===!0&&this.props.onHide())},handleDocumentKeyUp:function(e){this.props.keyboard&&27===e.keyCode&&this.isTopModal()&&(this.props.onEscapeKeyUp&&this.props.onEscapeKeyUp(e),this.props.onHide())},checkForFocus:function(){D["default"]&&(this.lastFocus=(0,C["default"])())},focus:function(){var e=this.props.autoFocus,t=this.getDialogElement(),n=(0,C["default"])((0,m["default"])(this)),r=n&&(0,P["default"])(t,n);t&&e&&!r&&(this.lastFocus=n,t.hasAttribute("tabIndex")||(t.setAttribute("tabIndex",-1),(0,a["default"])(!1,'The modal content node does not accept focus. For the benefit of assistive technologies, the tabIndex of the node is being set to "-1".')),t.focus())},restoreLastFocus:function(){this.lastFocus&&this.lastFocus.focus&&(this.lastFocus.focus(),this.lastFocus=null)},enforceFocus:function A(){var A=this.props.enforceFocus;if(A&&this.isMounted()&&this.isTopModal()){var e=(0,C["default"])((0,m["default"])(this)),t=this.getDialogElement();t&&t!==e&&!(0,P["default"])(t,e)&&t.focus()}},getDialogElement:function(){var e=this.refs.modal;return e&&e.lastChild},isTopModal:function(){return I.isTopModal(this)}});R.manager=I,t["default"]=R,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){var n=-1;return e.some(function(e,r){if(t(e,r))return n=r,!0}),n}function u(e,t){return i(e,function(e){return e.modals.indexOf(t)!==-1})}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),a=n(139),l=r(a),c=n(132),p=r(c),f=n(144),d=r(f),h=n(241),g=r(h),y=n(242),v=function(){function e(){var t=arguments.length<=0||void 0===arguments[0]||arguments[0];o(this,e),this.hideSiblingNodes=t,this.modals=[],this.containers=[],this.data=[]}return s(e,[{key:"add",value:function(e,t,n){var r=this.modals.indexOf(e),o=this.containers.indexOf(t);
if(r!==-1)return r;if(r=this.modals.length,this.modals.push(e),this.hideSiblingNodes&&(0,y.hideSiblings)(t,e.mountNode),o!==-1)return this.data[o].modals.push(e),r;var i={modals:[e],classes:n?n.split(/\s+/):[],style:{overflow:t.style.overflow,paddingRight:t.style.paddingRight}},u={overflow:"hidden"};return i.overflowing=(0,g["default"])(t),i.overflowing&&(u.paddingRight=parseInt((0,l["default"])(t,"paddingRight")||0,10)+(0,d["default"])()+"px"),(0,l["default"])(t,u),i.classes.forEach(p["default"].addClass.bind(null,t)),this.containers.push(t),this.data.push(i),r}},{key:"remove",value:function(e){var t=this.modals.indexOf(e);if(t!==-1){var n=u(this.data,e),r=this.data[n],o=this.containers[n];r.modals.splice(r.modals.indexOf(e),1),this.modals.splice(t,1),0===r.modals.length?(Object.keys(r.style).forEach(function(e){return o.style[e]=r.style[e]}),r.classes.forEach(p["default"].removeClass.bind(null,o)),this.hideSiblingNodes&&(0,y.showSiblings)(o,e.mountNode),this.containers.splice(n,1),this.data.splice(n,1)):this.hideSiblingNodes&&(0,y.ariaHidden)(!1,r.modals[r.modals.length-1].mountNode)}}},{key:"isTopModal",value:function(e){return!!this.modals.length&&this.modals[this.modals.length-1]===e}}]),e}();t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),i=r(o),u=n(3),s=r(u),a=n(74),l=r(a),c=n(73),p=r(c),f=n(72),d=r(f),h=i["default"].createClass({displayName:"Portal",propTypes:{container:i["default"].PropTypes.oneOfType([l["default"],i["default"].PropTypes.func])},componentDidMount:function(){this._renderOverlay()},componentDidUpdate:function(){this._renderOverlay()},componentWillReceiveProps:function(e){this._overlayTarget&&e.container!==this.props.container&&(this._portalContainerNode.removeChild(this._overlayTarget),this._portalContainerNode=(0,d["default"])(e.container,(0,p["default"])(this).body),this._portalContainerNode.appendChild(this._overlayTarget))},componentWillUnmount:function(){this._unrenderOverlay(),this._unmountOverlayTarget()},_mountOverlayTarget:function(){this._overlayTarget||(this._overlayTarget=document.createElement("div"),this._portalContainerNode=(0,d["default"])(this.props.container,(0,p["default"])(this).body),this._portalContainerNode.appendChild(this._overlayTarget))},_unmountOverlayTarget:function(){this._overlayTarget&&(this._portalContainerNode.removeChild(this._overlayTarget),this._overlayTarget=null),this._portalContainerNode=null},_renderOverlay:function(){var e=this.props.children?i["default"].Children.only(this.props.children):null;null!==e?(this._mountOverlayTarget(),this._overlayInstance=s["default"].unstable_renderSubtreeIntoContainer(this,e,this._overlayTarget)):(this._unrenderOverlay(),this._unmountOverlayTarget())},_unrenderOverlay:function(){this._overlayTarget&&(s["default"].unmountComponentAtNode(this._overlayTarget),this._overlayInstance=null)},render:function(){return null},getMountNode:function(){return this._overlayTarget},getOverlayDOMNode:function(){if(!this.isMounted())throw new Error("getOverlayDOMNode(): A component must be mounted to have a DOM node.");return this._overlayInstance?this._overlayInstance.getWrappedDOMNode?this._overlayInstance.getWrappedDOMNode():s["default"].findDOMNode(this._overlayInstance):null}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=function(e,t,n){return(0,i["default"])(e,t,n),{remove:function(){(0,s["default"])(e,t,n)}}};var o=n(135),i=r(o),u=n(134),s=r(u);e.exports=t["default"]},function(e,t){"use strict";function n(e){var t=!document.addEventListener,n=void 0;return t?(document.attachEvent("onfocusin",e),n=function(){return document.detachEvent("onfocusin",e)}):(document.addEventListener("focus",e,!0),n=function(){return document.removeEventListener("focus",e,!0)}),{remove:n}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){return e&&"body"===e.tagName.toLowerCase()}function i(e){var t=(0,c["default"])(e),n=(0,a["default"])(t),r=n.innerWidth;if(!r){var o=t.documentElement.getBoundingClientRect();r=o.right-Math.abs(o.left)}return t.body.clientWidth<r}function u(e){var t=(0,a["default"])(e);return t||o(e)?i(e):e.scrollHeight>e.clientHeight}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=u;var s=n(137),a=r(s),l=n(23),c=r(l);e.exports=t["default"]},function(e,t){"use strict";function n(e,t){t&&(e?t.setAttribute("aria-hidden","true"):t.removeAttribute("aria-hidden"))}function r(e,t){s(e,t,function(e){return n(!0,e)})}function o(e,t){s(e,t,function(e){return n(!1,e)})}Object.defineProperty(t,"__esModule",{value:!0}),t.ariaHidden=n,t.hideSiblings=r,t.showSiblings=o;var i=["template","script","style"],u=function(e){var t=e.nodeType,n=e.tagName;return 1===t&&i.indexOf(n.toLowerCase())===-1},s=function(e,t,n){t=[].concat(t),[].forEach.call(e.children,function(e){t.indexOf(e)===-1&&u(e)&&n(e)})}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var u=e[t],a="undefined"==typeof u?"undefined":i(u);return s["default"].isValidElement(u)?new Error("Invalid "+r+" `"+o+"` of type ReactElement "+("supplied to `"+n+"`, expected an element type (a string ")+"or a ReactClass)."):"function"!==a&&"string"!==a?new Error("Invalid "+r+" `"+o+"` of value `"+u+"` "+("supplied to `"+n+"`, expected an element type (a string ")+"or a ReactClass)."):null}t.__esModule=!0;var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},u=n(1),s=r(u),a=n(75),l=r(a);t["default"]=(0,l["default"])(o)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){return e&&"object"!=typeof e&&(e={}),e?e:null}function i(e,t,n){e&&(e[t]=n)}function u(e,t){if(e)for(var n=t.length;n>=0;--n){var r=t.slice(0,n);if(e[r]&&(t===r||e[r].complete))return e[r]}}function s(e,t){if(e&&"function"==typeof e.then)return e.then(function(e){t(null,e)},function(e){t(e)})}var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(1),c=r(l),p=n(34),f=r(p),d=n(78),h=r(d),g=0,y=c["default"].PropTypes.oneOfType([c["default"].PropTypes.string,c["default"].PropTypes.node]),v=c["default"].createClass({displayName:"Async",propTypes:{cache:c["default"].PropTypes.any,ignoreAccents:c["default"].PropTypes.bool,ignoreCase:c["default"].PropTypes.bool,isLoading:c["default"].PropTypes.bool,loadOptions:c["default"].PropTypes.func.isRequired,loadingPlaceholder:c["default"].PropTypes.string,minimumInput:c["default"].PropTypes.number,noResultsText:y,onInputChange:c["default"].PropTypes.func,placeholder:y,searchPromptText:y,searchingText:c["default"].PropTypes.string},getDefaultProps:function(){return{cache:!0,ignoreAccents:!0,ignoreCase:!0,loadingPlaceholder:"Loading...",minimumInput:0,searchingText:"Searching...",searchPromptText:"Type to search"}},getInitialState:function(){return{cache:o(this.props.cache),isLoading:!1,options:[]}},componentWillMount:function(){this._lastInput=""},componentDidMount:function(){this.loadOptions("")},componentWillReceiveProps:function(e){e.cache!==this.props.cache&&this.setState({cache:o(e.cache)})},focus:function(){this.select.focus()},resetState:function(){this._currentRequestId=-1,this.setState({isLoading:!1,options:[]})},getResponseHandler:function(e){var t=this,n=this._currentRequestId=g++;return function(r,o){if(r)throw r;t.isMounted()&&(i(t.state.cache,e,o),n===t._currentRequestId&&t.setState({isLoading:!1,options:o&&o.options||[]}))}},loadOptions:function(e){if(this.props.onInputChange){var t=this.props.onInputChange(e);null!=t&&(e=""+t)}if(this.props.ignoreAccents&&(e=(0,h["default"])(e)),this.props.ignoreCase&&(e=e.toLowerCase()),this._lastInput=e,e.length<this.props.minimumInput)return this.resetState();var n=u(this.state.cache,e);if(n)return this.setState({options:n.options});this.setState({isLoading:!0});var r=this.getResponseHandler(e),o=s(this.props.loadOptions(e,r),r);return o?o.then(function(){return e}):e},render:function(){var e=this,t=this.props.noResultsText,n=this.state,r=n.isLoading,o=n.options;this.props.isLoading&&(r=!0);var i=r?this.props.loadingPlaceholder:this.props.placeholder;return r?t=this.props.searchingText:!o.length&&this._lastInput.length<this.props.minimumInput&&(t=this.props.searchPromptText),c["default"].createElement(f["default"],a({},this.props,{ref:function(t){return e.select=t},isLoading:r,noResultsText:t,onInputChange:this.loadOptions,options:o,placeholder:i}))}});e.exports=v},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function i(e){var t=e.option,n=e.options,r=e.labelKey,o=e.valueKey;return 0===n.filter(function(e){return e[r]===t[r]||e[o]===t[o]}).length}function u(e){var t=e.label;return!!t}function s(e){var t=e.label,n=e.labelKey,r=e.valueKey,o={};return o[r]=t,o[n]=t,o.className="Select-create-option-placeholder",o}function a(e){return'Create option "'+e+'"'}function l(e){var t=e.keyCode;switch(t){case 9:case 13:case 188:return!0}return!1}var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(34),h=r(d),g=n(76),y=r(g),v=n(77),m=r(v),b=f["default"].createClass({displayName:"CreatableSelect",propTypes:{filterOptions:f["default"].PropTypes.any,isOptionUnique:f["default"].PropTypes.func,isValidNewOption:f["default"].PropTypes.func,menuRenderer:f["default"].PropTypes.any,newOptionCreator:f["default"].PropTypes.func,promptTextCreator:f["default"].PropTypes.func,shouldKeyDownEventCreateNewOption:f["default"].PropTypes.func},statics:{isOptionUnique:i,isValidNewOption:u,newOptionCreator:s,promptTextCreator:a,shouldKeyDownEventCreateNewOption:l},getDefaultProps:function(){return{filterOptions:y["default"],isOptionUnique:i,isValidNewOption:u,menuRenderer:m["default"],newOptionCreator:s,promptTextCreator:a,shouldKeyDownEventCreateNewOption:l}},createNewOption:function(){var e=this.props,t=e.isValidNewOption,n=e.newOptionCreator,r=(e.shouldKeyDownEventCreateNewOption,this.select.props),o=r.labelKey,i=r.options,u=r.valueKey,s=this.select.getInputValue();if(t({label:s})){var a=n({label:s,labelKey:o,valueKey:u}),l=this.isOptionUnique({option:a});l&&(i.unshift(a),this.select.selectValue(a))}},filterOptions:function E(){var e=this.props,E=e.filterOptions,t=e.isValidNewOption,n=e.promptTextCreator,r=E.apply(void 0,arguments),o=this.select?this.select.getInputValue():"";if(t({label:o})){var i=this.props.newOptionCreator,u=this.select.props,s=u.labelKey,a=u.options,l=u.valueKey,c=i({label:o,labelKey:s,valueKey:l}),p=this.isOptionUnique({option:c,options:a});if(p){var f=n(o);this._createPlaceholderOption=i({label:f,labelKey:s,valueKey:l}),r.unshift(this._createPlaceholderOption)}}return r},isOptionUnique:function w(e){var t=e.option,n=e.options;if(!this.select)return!1;var w=this.props.isOptionUnique,r=this.select.props,o=r.labelKey,i=r.valueKey;return n=n||this.select.filterOptions(),w({labelKey:o,option:t,options:n,valueKey:i})},menuRenderer:function T(e){var T=this.props.menuRenderer;return T(c({},e,{onSelect:this.onOptionSelect}))},onInputKeyDown:function(e){var t=this.props.shouldKeyDownEventCreateNewOption,n=this.select.getFocusedOption();n&&n===this._createPlaceholderOption&&t({keyCode:e.keyCode})&&(this.createNewOption(),e.preventDefault())},onOptionSelect:function(e,t){e===this._createPlaceholderOption?this.createNewOption():this.select.selectValue(e)},render:function(){var e=this,t=this.props,n=(t.newOptionCreator,t.shouldKeyDownEventCreateNewOption,o(t,["newOptionCreator","shouldKeyDownEventCreateNewOption"]));return f["default"].createElement(h["default"],c({},n,{allowCreate:!0,filterOptions:this.filterOptions,menuRenderer:this.menuRenderer,onInputKeyDown:this.onInputKeyDown,ref:function(t){return e.select=t}}))}});e.exports=b},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=n(1),i=r(o),u=n(21),s=r(u),a=i["default"].createClass({displayName:"Option",propTypes:{children:i["default"].PropTypes.node,className:i["default"].PropTypes.string,instancePrefix:i["default"].PropTypes.string.isRequired,isDisabled:i["default"].PropTypes.bool,isFocused:i["default"].PropTypes.bool,isSelected:i["default"].PropTypes.bool,onFocus:i["default"].PropTypes.func,onSelect:i["default"].PropTypes.func,onUnfocus:i["default"].PropTypes.func,option:i["default"].PropTypes.object.isRequired,optionIndex:i["default"].PropTypes.number},blockEvent:function(e){e.preventDefault(),e.stopPropagation(),"A"===e.target.tagName&&"href"in e.target&&(e.target.target?window.open(e.target.href,e.target.target):window.location.href=e.target.href)},handleMouseDown:function(e){e.preventDefault(),e.stopPropagation(),this.props.onSelect(this.props.option,e)},handleMouseEnter:function(e){this.onFocus(e)},handleMouseMove:function(e){this.onFocus(e)},handleTouchEnd:function(e){this.dragging||this.handleMouseDown(e)},handleTouchMove:function(e){this.dragging=!0},handleTouchStart:function(e){this.dragging=!1},onFocus:function(e){this.props.isFocused||this.props.onFocus(this.props.option,e)},render:function(){var e=this.props,t=e.option,n=e.instancePrefix,r=e.optionIndex,o=(0,s["default"])(this.props.className,t.className);return t.disabled?i["default"].createElement("div",{className:o,onMouseDown:this.blockEvent,onClick:this.blockEvent},this.props.children):i["default"].createElement("div",{className:o,style:t.style,role:"option",onMouseDown:this.handleMouseDown,onMouseEnter:this.handleMouseEnter,onMouseMove:this.handleMouseMove,onTouchStart:this.handleTouchStart,onTouchMove:this.handleTouchMove,onTouchEnd:this.handleTouchEnd,id:n+"-option-"+r,title:t.title},this.props.children)}});e.exports=a},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=n(1),i=r(o),u=n(21),s=r(u),a=i["default"].createClass({displayName:"Value",propTypes:{children:i["default"].PropTypes.node,disabled:i["default"].PropTypes.bool,id:i["default"].PropTypes.string,onClick:i["default"].PropTypes.func,onRemove:i["default"].PropTypes.func,value:i["default"].PropTypes.object.isRequired},handleMouseDown:function(e){if("mousedown"!==e.type||0===e.button)return this.props.onClick?(e.stopPropagation(),void this.props.onClick(this.props.value,e)):void(this.props.value.href&&e.stopPropagation())},onRemove:function(e){e.preventDefault(),e.stopPropagation(),this.props.onRemove(this.props.value)},handleTouchEndRemove:function(e){this.dragging||this.onRemove(e)},handleTouchMove:function(e){this.dragging=!0},handleTouchStart:function(e){this.dragging=!1},renderRemoveIcon:function(){if(!this.props.disabled&&this.props.onRemove)return i["default"].createElement("span",{className:"Select-value-icon","aria-hidden":"true",onMouseDown:this.onRemove,onTouchEnd:this.handleTouchEndRemove,onTouchStart:this.handleTouchStart,onTouchMove:this.handleTouchMove},"×")},renderLabel:function(){var e="Select-value-label";return this.props.onClick||this.props.value.href?i["default"].createElement("a",{className:e,href:this.props.value.href,target:this.props.value.target,onMouseDown:this.handleMouseDown,onTouchEnd:this.handleMouseDown},this.props.children):i["default"].createElement("span",{className:e,role:"option","aria-selected":"true",id:this.props.id},this.props.children)},render:function(){return i["default"].createElement("div",{className:(0,s["default"])("Select-value",this.props.value.className),style:this.props.value.style,title:this.props.value.title},this.renderRemoveIcon(),this.renderLabel())}});e.exports=a},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(e){return function(n,r,o){var u=e(n,r,o),a=u.dispatch,l=[],c={getState:u.getState,dispatch:function(e){return a(e)}};return l=t.map(function(e){return e(c)}),a=s["default"].apply(void 0,l)(u.dispatch),i({},u,{dispatch:a})}}}t.__esModule=!0;var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=o;var u=n(79),s=r(u)},function(e,t){"use strict";function n(e,t){return function(){return t(e.apply(void 0,arguments))}}function r(e,t){if("function"==typeof e)return n(e,t);if("object"!=typeof e||null===e)throw new Error("bindActionCreators expected an object or a function, instead received "+(null===e?"null":typeof e)+'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');for(var r=Object.keys(e),o={},i=0;i<r.length;i++){var u=r[i],s=e[u];"function"==typeof s&&(o[u]=n(s,t))}return o}t.__esModule=!0,t["default"]=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n=t&&t.type,r=n&&'"'+n.toString()+'"'||"an action";return"Given action "+r+', reducer "'+e+'" returned undefined. To ignore an action, you must explicitly return the previous state.'}function i(e){Object.keys(e).forEach(function(t){var n=e[t],r=n(void 0,{type:s.ActionTypes.INIT});if("undefined"==typeof r)throw new Error('Reducer "'+t+'" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined.');var o="@@redux/PROBE_UNKNOWN_ACTION_"+Math.random().toString(36).substring(7).split("").join(".");if("undefined"==typeof n(void 0,{type:o}))throw new Error('Reducer "'+t+'" returned undefined when probed with a random type. '+("Don't try to handle "+s.ActionTypes.INIT+' or other actions in "redux/*" ')+"namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined.")})}function u(e){for(var t=Object.keys(e),n={},r=0;r<t.length;r++){var u=t[r];"function"==typeof e[u]&&(n[u]=e[u])}var s,a=Object.keys(n);try{i(n)}catch(l){s=l}return function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=arguments[1];if(s)throw s;for(var r=!1,i={},u=0;u<a.length;u++){var l=a[u],c=n[l],p=e[l],f=c(p,t);if("undefined"==typeof f){var d=o(l,t);throw new Error(d)}i[l]=f,r=r||f!==p}return r?i:e}}t.__esModule=!0,t["default"]=u;var s=n(35),a=n(4),l=(r(a),n(80));r(l)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}t.__esModule=!0,t.compose=t.applyMiddleware=t.bindActionCreators=t.combineReducers=t.createStore=void 0;var o=n(35),i=r(o),u=n(250),s=r(u),a=n(249),l=r(a),c=n(248),p=r(c),f=n(79),d=r(f),h=n(80);r(h);t.createStore=i["default"],t.combineReducers=s["default"],t.bindActionCreators=l["default"],t.applyMiddleware=p["default"],t.compose=d["default"]},function(e,t){"use strict";function n(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function r(e,t){return e===t}function o(e){var t=arguments.length<=1||void 0===arguments[1]?r:arguments[1],n=null,o=null;return function(){for(var r=arguments.length,i=Array(r),u=0;u<r;u++)i[u]=arguments[u];return null!==n&&n.length===i.length&&i.every(function(e,r){return t(e,n[r])})?o:(o=e.apply(void 0,i),n=i,o)}}function i(e){var t=Array.isArray(e[0])?e[0]:e;if(!t.every(function(e){return"function"==typeof e})){var n=t.map(function(e){return typeof e}).join(", ");throw new Error("Selector creators expect all input-selectors to be functions, "+("instead received the following types: ["+n+"]"))}return t}function u(e){for(var t=arguments.length,r=Array(t>1?t-1:0),o=1;o<t;o++)r[o-1]=arguments[o];return function(){for(var t=arguments.length,o=Array(t),u=0;u<t;u++)o[u]=arguments[u];var s=0,a=o.pop(),l=i(o),c=e.apply(void 0,[function(){return s++,a.apply(void 0,arguments)}].concat(r)),p=function(e,t){for(var r=arguments.length,o=Array(r>2?r-2:0),i=2;i<r;i++)o[i-2]=arguments[i];var u=l.map(function(n){return n.apply(void 0,[e,t].concat(o))});return c.apply(void 0,n(u))};return p.resultFunc=a,p.recomputations=function(){return s},p.resetRecomputations=function(){return s=0},p}}function s(){return u(o).apply(void 0,arguments)}function a(e){var t=arguments.length<=1||void 0===arguments[1]?s:arguments[1];if("object"!=typeof e)throw new Error("createStructuredSelector expects first argument to be an object where each property is a selector, instead received a "+typeof e);var n=Object.keys(e);return t(n.map(function(t){return e[t]}),function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.reduce(function(e,t,r){return e[n[r]]=t,e},{})})}t.__esModule=!0,t.defaultMemoize=o,t.createSelectorCreator=u,t.createSelector=s,t.createStructuredSelector=a},function(e,t,n){!function(t,r){e.exports=r(n(1))}(this,function(e){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function r(e,t,n){if(!e)return n(null,[]);t=new RegExp(t,"i");for(var r=[],o=0,i=e.length;o<i;o++)t.exec(e[o].title)&&r.push(e[o]);n(null,r)}var o=n(1),i=n(2),u=o.createClass({displayName:"Autocomplete",propTypes:{options:o.PropTypes.any,search:o.PropTypes.func,resultRenderer:o.PropTypes.oneOfType([o.PropTypes.component,o.PropTypes.func]),value:o.PropTypes.object,onChange:o.PropTypes.func,onError:o.PropTypes.func,onFocus:o.PropTypes.func},getDefaultProps:function(){return{search:r}},getInitialState:function(){var e=this.props.searchTerm?this.props.searchTerm:this.props.value?this.props.value.title:"";return{results:[],showResults:!1,showResultsInProgress:!1,searchTerm:e,focusedValue:null}},getResultIdentifier:function(e){return void 0===this.props.resultIdentifier?e.id:e[this.props.resultIdentifier]},render:function(){var e=i(this.props.className,"react-autocomplete-Autocomplete",this.state.showResults?"react-autocomplete-Autocomplete--resultsShown":void 0),t={position:"relative",outline:"none"};return o.createElement("div",{tabIndex:"1",className:e,onFocus:this.onFocus,onBlur:this.onBlur,style:t},o.createElement("input",{ref:"search",className:"react-autocomplete-Autocomplete__search",style:{width:"100%"},onClick:this.showAllResults,onChange:this.onQueryChange,onFocus:this.onSearchInputFocus,onBlur:this.onQueryBlur,onKeyDown:this.onQueryKeyDown,value:this.state.searchTerm}),o.createElement(s,{className:"react-autocomplete-Autocomplete__results",onSelect:this.onValueChange,onFocus:this.onValueFocus,results:this.state.results,focusedValue:this.state.focusedValue,show:this.state.showResults,renderer:this.props.resultRenderer,label:this.props.label,resultIdentifier:this.props.resultIdentifier}))},componentWillReceiveProps:function(e){var t=e.searchTerm?e.searchTerm:e.value?e.value.title:"";this.setState({searchTerm:t})},componentWillMount:function(){this.blurTimer=null},showResults:function(e){this.setState({showResultsInProgress:!0}),this.props.search(this.props.options,e.trim(),this.onSearchComplete)},showAllResults:function(){this.state.showResultsInProgress||this.state.showResults||this.showResults("")},onValueChange:function(e){var t={value:e,showResults:!1};e&&(t.searchTerm=e.title),this.setState(t),this.props.onChange&&this.props.onChange(e)},onSearchComplete:function(e,t){if(e){if(!this.props.onError)throw e;this.props.onError(e)}this.setState({showResultsInProgress:!1,showResults:!0,results:t})},onValueFocus:function(e){this.setState({focusedValue:e})},onQueryChange:function(e){var t=e.target.value;this.setState({searchTerm:t,focusedValue:null}),this.showResults(t)},onFocus:function(){this.blurTimer&&(clearTimeout(this.blurTimer),this.blurTimer=null),this.refs.search.getDOMNode().focus()},onSearchInputFocus:function(){this.props.onFocus&&this.props.onFocus(),this.showAllResults()},onBlur:function(){this.blurTimer=setTimeout(function(){this.isMounted()&&this.setState({showResults:!1})}.bind(this),100)},onQueryKeyDown:function(e){if("Enter"===e.key)e.preventDefault(),this.state.focusedValue&&this.onValueChange(this.state.focusedValue);else if("ArrowUp"===e.key&&this.state.showResults){e.preventDefault();var t=Math.max(this.focusedValueIndex()-1,0);this.setState({focusedValue:this.state.results[t]})}else if("ArrowDown"===e.key)if(e.preventDefault(),this.state.showResults){var n=Math.min(this.focusedValueIndex()+(this.state.showResults?1:0),this.state.results.length-1);this.setState({showResults:!0,focusedValue:this.state.results[n]})}else this.showAllResults()},focusedValueIndex:function(){if(!this.state.focusedValue)return-1;for(var e=0,t=this.state.results.length;e<t;e++)if(this.getResultIdentifier(this.state.results[e])===this.getResultIdentifier(this.state.focusedValue))return e;return-1}}),s=o.createClass({displayName:"Results",getResultIdentifier:function(e){if(void 0===this.props.resultIdentifier){if(!e.id)throw"id property not found on result. You must specify a resultIdentifier and pass as props to autocomplete component";return e.id}return e[this.props.resultIdentifier]},render:function(){var e={display:this.props.show?"block":"none",position:"absolute",listStyleType:"none"},t=this.props,n=t.className,r=function(e,t){var n={},r=Object.prototype.hasOwnProperty;if(null==e)throw new TypeError;for(var o in e)r.call(e,o)&&!r.call(t,o)&&(n[o]=e[o]);return n}(t,{className:1});return o.createElement("ul",o.__spread({},r,{style:e,className:n+" react-autocomplete-Results"}),this.props.results.map(this.renderResult))},renderResult:function(e){var t=this.props.focusedValue&&this.getResultIdentifier(this.props.focusedValue)===this.getResultIdentifier(e),n=this.props.renderer||a;return o.createElement(n,{ref:t?"focused":void 0,key:this.getResultIdentifier(e),result:e,focused:t,onMouseEnter:this.onMouseEnterResult,onClick:this.props.onSelect,label:this.props.label})},componentDidUpdate:function(){this.scrollToFocused()},componentDidMount:function(){this.scrollToFocused()},componentWillMount:function(){this.ignoreFocus=!1},scrollToFocused:function(){var e=this.refs&&this.refs.focused;if(e){var t=this.getDOMNode(),n=t.scrollTop,r=t.offsetHeight,o=e.getDOMNode(),i=o.offsetTop,u=i+o.offsetHeight;i<n?(this.ignoreFocus=!0,t.scrollTop=i):u-n>r&&(this.ignoreFocus=!0,t.scrollTop=u-r)}},onMouseEnterResult:function(e,t){if(this.ignoreFocus)this.ignoreFocus=!1;else{var n=this.getDOMNode(),r=n.scrollTop,o=n.offsetHeight,i=e.target,u=i.offsetTop,s=u+i.offsetHeight;s>r&&u<r+o&&this.props.onFocus(t)}}}),a=o.createClass({displayName:"Result",getDefaultProps:function(){return{label:function(e){return e.title}}},getLabel:function(e){return"function"==typeof this.props.label?this.props.label(e):"string"==typeof this.props.label?e[this.props.label]:void 0},render:function(){var e=i({"react-autocomplete-Result":!0,"react-autocomplete-Result--active":this.props.focused});return o.createElement("li",{style:{listStyleType:"none"},className:e,onClick:this.onClick,onMouseEnter:this.onMouseEnter},o.createElement("a",null,this.getLabel(this.props.result)))},onClick:function(){this.props.onClick(this.props.result)},onMouseEnter:function(e){this.props.onMouseEnter&&this.props.onMouseEnter(e,this.props.result)},shouldComponentUpdate:function(e){return e.result.id!==this.props.result.id||e.focused!==this.props.focused}});e.exports=u},function(t,n){t.exports=e},function(e,t,n){function r(){for(var e,t="",n=0;n<arguments.length;n++)if(e=arguments[n])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+r.apply(null,e);else if("object"==typeof e)for(var o in e)e.hasOwnProperty(o)&&e[o]&&(t+=" "+o);return t.substr(1)}var o,i;"undefined"!=typeof e&&e.exports&&(e.exports=r),o=[],i=function(){return r}.apply(t,o),!(void 0!==i&&(e.exports=i))}])})},function(e,t,n){e.exports=n(255)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(256),i=r(o),u=void 0;"undefined"!=typeof window?u=window:"undefined"!=typeof window&&(u=window);var s=(0,i["default"])(u);t["default"]=s},function(e,t){"use strict";function n(e){var t,n=e.Symbol;return"function"==typeof n?n.observable?t=n.observable:(t=n("observable"),n.observable=t):t="@@observable",t}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t,n){"use strict";var r=function(){};e.exports=r},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children=[],e.webpackPolyfill=1),e}}]))}); |
src/views/reminders/RemindersList.js | project-abigail/app | import React, { Component } from 'react';
import groupBy from 'lodash/groupBy';
import moment from 'moment';
import ReminderItem from './ReminderItem';
import './RemindersList.css';
class RemindersList extends Component {
constructor(props) {
super(props);
this.state = {
reminders: props.reminders,
};
this.server = props.server;
this.analytics = props.analytics;
this.refreshReminders = props.refreshReminders;
this.editDialog = props.editDialog;
}
componentWillReceiveProps(props) {
this.setState({ reminders: props.reminders });
this.editDialog = props.editDialog;
}
onEdit(id) {
const reminder = this.state.reminders
.find((reminder) => reminder.id === id);
this.editDialog.show(reminder);
}
onDelete(id) {
// @todo Nice to have: optimistic update.
this.server.reminders.delete(id)
.then(() => {
this.analytics.event('reminders', 'delete');
const reminders = this.state.reminders
.filter((reminder) => reminder.id !== id);
this.setState({ reminders });
})
.catch(() => {
this.analytics.event('reminders', 'error', 'delete-failed');
console.error(`The reminder ${id} could not be deleted.`);
});
}
render() {
let reminders = this.state.reminders;
if (!reminders) {
return null;
}
// Sort all the reminders chronologically.
reminders = reminders.sort((a, b) => {
return a.due - b.due;
});
// Group the reminders by month.
reminders = groupBy(reminders, (reminder) => {
return moment(reminder.due).format('YYYY/MM');
});
// For each month, group the reminders by day.
Object.keys(reminders).forEach((month) => {
reminders[month] = groupBy(reminders[month], (reminder) => {
return moment(reminder.due).format('YYYY/MM/DD');
});
});
const remindersNode = Object.keys(reminders).map((key) => {
const month = moment(key, 'YYYY/MM').format('MMMM');
const reminderMonth = reminders[key];
return (
<div key={key}>
<h2 className="reminders__month">{month}</h2>
{Object.keys(reminderMonth).map((key) => {
const date = moment(key, 'YYYY/MM/DD');
const remindersDay = reminderMonth[key];
return (
<div key={key} className="reminders__day">
<div className="reminders__day-date">
<div className="reminders__day-mday">
{date.format('DD')}
</div>
<div className="reminders__day-wday">
{date.format('ddd')}
</div>
</div>
<ol className="reminders__list">
{remindersDay.map((reminder) => {
return (<ReminderItem
key={reminder.id}
reminder={reminder}
onDelete={this.onDelete.bind(this, reminder.id)}
onEdit={this.onEdit.bind(this, reminder.id)}
/>);
})}
</ol>
</div>
);
})}
</div>
);
});
return (
<div className="RemindersList">
{remindersNode}
</div>
);
}
}
RemindersList.propTypes = {
server: React.PropTypes.object,
analytics: React.PropTypes.object,
reminders: React.PropTypes.array,
refreshReminders: React.PropTypes.func,
editDialog: React.PropTypes.object,
};
export default RemindersList;
|
ajax/libs/strophe.js/1.1.3/strophe.js | Mrkebubun/cdnjs | // This code was written by Tyler Akins and has been placed in the
// public domain. It would be nice if you left this header intact.
// Base64 code from Tyler Akins -- http://rumkin.com
var Base64 = (function () {
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var obj = {
/**
* Encodes a string in base64
* @param {String} input The string to encode in base64.
*/
encode: function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
do {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
keyStr.charAt(enc3) + keyStr.charAt(enc4);
} while (i < input.length);
return output;
},
/**
* Decodes a base64 string.
* @param {String} input The string to decode.
*/
decode: function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
} while (i < input.length);
return output;
}
};
return obj;
})();
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS PUB 180-1
* Version 2.1a Copyright Paul Johnston 2000 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*/
/* Some functions and variables have been stripped for use with Strophe */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * 8));}
function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * 8));}
function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));}
function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));}
/*
* Calculate the SHA-1 of an array of big-endian words, and a bit length
*/
function core_sha1(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << (24 - len % 32);
x[((len + 64 >> 9) << 4) + 15] = len;
var w = new Array(80);
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var e = -1009589776;
var i, j, t, olda, oldb, oldc, oldd, olde;
for (i = 0; i < x.length; i += 16)
{
olda = a;
oldb = b;
oldc = c;
oldd = d;
olde = e;
for (j = 0; j < 80; j++)
{
if (j < 16) { w[j] = x[i + j]; }
else { w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); }
t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
safe_add(safe_add(e, w[j]), sha1_kt(j)));
e = d;
d = c;
c = rol(b, 30);
b = a;
a = t;
}
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
e = safe_add(e, olde);
}
return [a, b, c, d, e];
}
/*
* Perform the appropriate triplet combination function for the current
* iteration
*/
function sha1_ft(t, b, c, d)
{
if (t < 20) { return (b & c) | ((~b) & d); }
if (t < 40) { return b ^ c ^ d; }
if (t < 60) { return (b & c) | (b & d) | (c & d); }
return b ^ c ^ d;
}
/*
* Determine the appropriate additive constant for the current iteration
*/
function sha1_kt(t)
{
return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
(t < 60) ? -1894007588 : -899497514;
}
/*
* Calculate the HMAC-SHA1 of a key and some data
*/
function core_hmac_sha1(key, data)
{
var bkey = str2binb(key);
if (bkey.length > 16) { bkey = core_sha1(bkey, key.length * 8); }
var ipad = new Array(16), opad = new Array(16);
for (var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * 8);
return core_sha1(opad.concat(hash), 512 + 160);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert an 8-bit or 16-bit string to an array of big-endian words
* In 8-bit function, characters >255 have their hi-byte silently ignored.
*/
function str2binb(str)
{
var bin = [];
var mask = 255;
for (var i = 0; i < str.length * 8; i += 8)
{
bin[i>>5] |= (str.charCodeAt(i / 8) & mask) << (24 - i%32);
}
return bin;
}
/*
* Convert an array of big-endian words to a string
*/
function binb2str(bin)
{
var str = "";
var mask = 255;
for (var i = 0; i < bin.length * 32; i += 8)
{
str += String.fromCharCode((bin[i>>5] >>> (24 - i%32)) & mask);
}
return str;
}
/*
* Convert an array of big-endian words to a base-64 string
*/
function binb2b64(binarray)
{
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
var triplet, j;
for (var i = 0; i < binarray.length * 4; i += 3)
{
triplet = (((binarray[i >> 2] >> 8 * (3 - i %4)) & 0xFF) << 16) |
(((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 ) |
((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
for (j = 0; j < 4; j++)
{
if (i * 8 + j * 6 > binarray.length * 32) { str += "="; }
else { str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); }
}
}
return str;
}
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Everything that isn't used by Strophe has been stripped here!
*/
var MD5 = (function () {
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
var safe_add = function (x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
};
/*
* Bitwise rotate a 32-bit number to the left.
*/
var bit_rol = function (num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
};
/*
* Convert a string to an array of little-endian words
*/
var str2binl = function (str) {
var bin = [];
for(var i = 0; i < str.length * 8; i += 8)
{
bin[i>>5] |= (str.charCodeAt(i / 8) & 255) << (i%32);
}
return bin;
};
/*
* Convert an array of little-endian words to a string
*/
var binl2str = function (bin) {
var str = "";
for(var i = 0; i < bin.length * 32; i += 8)
{
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & 255);
}
return str;
};
/*
* Convert an array of little-endian words to a hex string.
*/
var binl2hex = function (binarray) {
var hex_tab = "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
};
/*
* These functions implement the four basic operations the algorithm uses.
*/
var md5_cmn = function (q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q),safe_add(x, t)), s),b);
};
var md5_ff = function (a, b, c, d, x, s, t) {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
};
var md5_gg = function (a, b, c, d, x, s, t) {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
};
var md5_hh = function (a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
};
var md5_ii = function (a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
};
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
var core_md5 = function (x, len) {
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var olda, oldb, oldc, oldd;
for (var i = 0; i < x.length; i += 16)
{
olda = a;
oldb = b;
oldc = c;
oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return [a, b, c, d];
};
var obj = {
/*
* These are the functions you'll usually want to call.
* They take string arguments and return either hex or base-64 encoded
* strings.
*/
hexdigest: function (s) {
return binl2hex(core_md5(str2binl(s), s.length * 8));
},
hash: function (s) {
return binl2str(core_md5(str2binl(s), s.length * 8));
}
};
return obj;
})();
/*
This program is distributed under the terms of the MIT license.
Please see the LICENSE file for details.
Copyright 2006-2008, OGG, LLC
*/
/* jshint undef: true, unused: true:, noarg: true, latedef: true */
/*global document, window, setTimeout, clearTimeout, console,
ActiveXObject, Base64, MD5, DOMParser */
// from sha1.js
/*global core_hmac_sha1, binb2str, str_hmac_sha1, str_sha1, b64_hmac_sha1*/
/** File: strophe.js
* A JavaScript library for XMPP BOSH/XMPP over Websocket.
*
* This is the JavaScript version of the Strophe library. Since JavaScript
* had no facilities for persistent TCP connections, this library uses
* Bidirectional-streams Over Synchronous HTTP (BOSH) to emulate
* a persistent, stateful, two-way connection to an XMPP server. More
* information on BOSH can be found in XEP 124.
*
* This version of Strophe also works with WebSockets.
* For more information on XMPP-over WebSocket see this RFC draft:
* http://tools.ietf.org/html/draft-ietf-xmpp-websocket-00
*/
/** PrivateFunction: Function.prototype.bind
* Bind a function to an instance.
*
* This Function object extension method creates a bound method similar
* to those in Python. This means that the 'this' object will point
* to the instance you want. See
* <a href='https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind'>MDC's bind() documentation</a> and
* <a href='http://benjamin.smedbergs.us/blog/2007-01-03/bound-functions-and-function-imports-in-javascript/'>Bound Functions and Function Imports in JavaScript</a>
* for a complete explanation.
*
* This extension already exists in some browsers (namely, Firefox 3), but
* we provide it to support those that don't.
*
* Parameters:
* (Object) obj - The object that will become 'this' in the bound function.
* (Object) argN - An option argument that will be prepended to the
* arguments given for the function call
*
* Returns:
* The bound function.
*/
if (!Function.prototype.bind) {
Function.prototype.bind = function (obj /*, arg1, arg2, ... */)
{
var func = this;
var _slice = Array.prototype.slice;
var _concat = Array.prototype.concat;
var _args = _slice.call(arguments, 1);
return function () {
return func.apply(obj ? obj : this,
_concat.call(_args,
_slice.call(arguments, 0)));
};
};
}
/** PrivateFunction: Array.prototype.indexOf
* Return the index of an object in an array.
*
* This function is not supplied by some JavaScript implementations, so
* we provide it if it is missing. This code is from:
* http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:indexOf
*
* Parameters:
* (Object) elt - The object to look for.
* (Integer) from - The index from which to start looking. (optional).
*
* Returns:
* The index of elt in the array or -1 if not found.
*/
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) {
from += len;
}
for (; from < len; from++) {
if (from in this && this[from] === elt) {
return from;
}
}
return -1;
};
}
/* All of the Strophe globals are defined in this special function below so
* that references to the globals become closures. This will ensure that
* on page reload, these references will still be available to callbacks
* that are still executing.
*/
(function (callback) {
var Strophe;
/** Function: $build
* Create a Strophe.Builder.
* This is an alias for 'new Strophe.Builder(name, attrs)'.
*
* Parameters:
* (String) name - The root element name.
* (Object) attrs - The attributes for the root element in object notation.
*
* Returns:
* A new Strophe.Builder object.
*/
function $build(name, attrs) { return new Strophe.Builder(name, attrs); }
/** Function: $msg
* Create a Strophe.Builder with a <message/> element as the root.
*
* Parmaeters:
* (Object) attrs - The <message/> element attributes in object notation.
*
* Returns:
* A new Strophe.Builder object.
*/
function $msg(attrs) { return new Strophe.Builder("message", attrs); }
/** Function: $iq
* Create a Strophe.Builder with an <iq/> element as the root.
*
* Parameters:
* (Object) attrs - The <iq/> element attributes in object notation.
*
* Returns:
* A new Strophe.Builder object.
*/
function $iq(attrs) { return new Strophe.Builder("iq", attrs); }
/** Function: $pres
* Create a Strophe.Builder with a <presence/> element as the root.
*
* Parameters:
* (Object) attrs - The <presence/> element attributes in object notation.
*
* Returns:
* A new Strophe.Builder object.
*/
function $pres(attrs) { return new Strophe.Builder("presence", attrs); }
/** Class: Strophe
* An object container for all Strophe library functions.
*
* This class is just a container for all the objects and constants
* used in the library. It is not meant to be instantiated, but to
* provide a namespace for library objects, constants, and functions.
*/
Strophe = {
/** Constant: VERSION
* The version of the Strophe library. Unreleased builds will have
* a version of head-HASH where HASH is a partial revision.
*/
VERSION: "1.1.3",
/** Constants: XMPP Namespace Constants
* Common namespace constants from the XMPP RFCs and XEPs.
*
* NS.HTTPBIND - HTTP BIND namespace from XEP 124.
* NS.BOSH - BOSH namespace from XEP 206.
* NS.CLIENT - Main XMPP client namespace.
* NS.AUTH - Legacy authentication namespace.
* NS.ROSTER - Roster operations namespace.
* NS.PROFILE - Profile namespace.
* NS.DISCO_INFO - Service discovery info namespace from XEP 30.
* NS.DISCO_ITEMS - Service discovery items namespace from XEP 30.
* NS.MUC - Multi-User Chat namespace from XEP 45.
* NS.SASL - XMPP SASL namespace from RFC 3920.
* NS.STREAM - XMPP Streams namespace from RFC 3920.
* NS.BIND - XMPP Binding namespace from RFC 3920.
* NS.SESSION - XMPP Session namespace from RFC 3920.
* NS.XHTML_IM - XHTML-IM namespace from XEP 71.
* NS.XHTML - XHTML body namespace from XEP 71.
*/
NS: {
HTTPBIND: "http://jabber.org/protocol/httpbind",
BOSH: "urn:xmpp:xbosh",
CLIENT: "jabber:client",
AUTH: "jabber:iq:auth",
ROSTER: "jabber:iq:roster",
PROFILE: "jabber:iq:profile",
DISCO_INFO: "http://jabber.org/protocol/disco#info",
DISCO_ITEMS: "http://jabber.org/protocol/disco#items",
MUC: "http://jabber.org/protocol/muc",
SASL: "urn:ietf:params:xml:ns:xmpp-sasl",
STREAM: "http://etherx.jabber.org/streams",
BIND: "urn:ietf:params:xml:ns:xmpp-bind",
SESSION: "urn:ietf:params:xml:ns:xmpp-session",
VERSION: "jabber:iq:version",
STANZAS: "urn:ietf:params:xml:ns:xmpp-stanzas",
XHTML_IM: "http://jabber.org/protocol/xhtml-im",
XHTML: "http://www.w3.org/1999/xhtml"
},
/** Constants: XHTML_IM Namespace
* contains allowed tags, tag attributes, and css properties.
* Used in the createHtml function to filter incoming html into the allowed XHTML-IM subset.
* See http://xmpp.org/extensions/xep-0071.html#profile-summary for the list of recommended
* allowed tags and their attributes.
*/
XHTML: {
tags: ['a','blockquote','br','cite','em','img','li','ol','p','span','strong','ul','body'],
attributes: {
'a': ['href'],
'blockquote': ['style'],
'br': [],
'cite': ['style'],
'em': [],
'img': ['src', 'alt', 'style', 'height', 'width'],
'li': ['style'],
'ol': ['style'],
'p': ['style'],
'span': ['style'],
'strong': [],
'ul': ['style'],
'body': []
},
css: ['background-color','color','font-family','font-size','font-style','font-weight','margin-left','margin-right','text-align','text-decoration'],
validTag: function(tag)
{
for(var i = 0; i < Strophe.XHTML.tags.length; i++) {
if(tag == Strophe.XHTML.tags[i]) {
return true;
}
}
return false;
},
validAttribute: function(tag, attribute)
{
if(typeof Strophe.XHTML.attributes[tag] !== 'undefined' && Strophe.XHTML.attributes[tag].length > 0) {
for(var i = 0; i < Strophe.XHTML.attributes[tag].length; i++) {
if(attribute == Strophe.XHTML.attributes[tag][i]) {
return true;
}
}
}
return false;
},
validCSS: function(style)
{
for(var i = 0; i < Strophe.XHTML.css.length; i++) {
if(style == Strophe.XHTML.css[i]) {
return true;
}
}
return false;
}
},
/** Constants: Connection Status Constants
* Connection status constants for use by the connection handler
* callback.
*
* Status.ERROR - An error has occurred
* Status.CONNECTING - The connection is currently being made
* Status.CONNFAIL - The connection attempt failed
* Status.AUTHENTICATING - The connection is authenticating
* Status.AUTHFAIL - The authentication attempt failed
* Status.CONNECTED - The connection has succeeded
* Status.DISCONNECTED - The connection has been terminated
* Status.DISCONNECTING - The connection is currently being terminated
* Status.ATTACHED - The connection has been attached
*/
Status: {
ERROR: 0,
CONNECTING: 1,
CONNFAIL: 2,
AUTHENTICATING: 3,
AUTHFAIL: 4,
CONNECTED: 5,
DISCONNECTED: 6,
DISCONNECTING: 7,
ATTACHED: 8
},
/** Constants: Log Level Constants
* Logging level indicators.
*
* LogLevel.DEBUG - Debug output
* LogLevel.INFO - Informational output
* LogLevel.WARN - Warnings
* LogLevel.ERROR - Errors
* LogLevel.FATAL - Fatal errors
*/
LogLevel: {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3,
FATAL: 4
},
/** PrivateConstants: DOM Element Type Constants
* DOM element types.
*
* ElementType.NORMAL - Normal element.
* ElementType.TEXT - Text data element.
* ElementType.FRAGMENT - XHTML fragment element.
*/
ElementType: {
NORMAL: 1,
TEXT: 3,
CDATA: 4,
FRAGMENT: 11
},
/** PrivateConstants: Timeout Values
* Timeout values for error states. These values are in seconds.
* These should not be changed unless you know exactly what you are
* doing.
*
* TIMEOUT - Timeout multiplier. A waiting request will be considered
* failed after Math.floor(TIMEOUT * wait) seconds have elapsed.
* This defaults to 1.1, and with default wait, 66 seconds.
* SECONDARY_TIMEOUT - Secondary timeout multiplier. In cases where
* Strophe can detect early failure, it will consider the request
* failed if it doesn't return after
* Math.floor(SECONDARY_TIMEOUT * wait) seconds have elapsed.
* This defaults to 0.1, and with default wait, 6 seconds.
*/
TIMEOUT: 1.1,
SECONDARY_TIMEOUT: 0.1,
/** Function: addNamespace
* This function is used to extend the current namespaces in
* Strophe.NS. It takes a key and a value with the key being the
* name of the new namespace, with its actual value.
* For example:
* Strophe.addNamespace('PUBSUB', "http://jabber.org/protocol/pubsub");
*
* Parameters:
* (String) name - The name under which the namespace will be
* referenced under Strophe.NS
* (String) value - The actual namespace.
*/
addNamespace: function (name, value)
{
Strophe.NS[name] = value;
},
/** Function: forEachChild
* Map a function over some or all child elements of a given element.
*
* This is a small convenience function for mapping a function over
* some or all of the children of an element. If elemName is null, all
* children will be passed to the function, otherwise only children
* whose tag names match elemName will be passed.
*
* Parameters:
* (XMLElement) elem - The element to operate on.
* (String) elemName - The child element tag name filter.
* (Function) func - The function to apply to each child. This
* function should take a single argument, a DOM element.
*/
forEachChild: function (elem, elemName, func)
{
var i, childNode;
for (i = 0; i < elem.childNodes.length; i++) {
childNode = elem.childNodes[i];
if (childNode.nodeType == Strophe.ElementType.NORMAL &&
(!elemName || this.isTagEqual(childNode, elemName))) {
func(childNode);
}
}
},
/** Function: isTagEqual
* Compare an element's tag name with a string.
*
* This function is case insensitive.
*
* Parameters:
* (XMLElement) el - A DOM element.
* (String) name - The element name.
*
* Returns:
* true if the element's tag name matches _el_, and false
* otherwise.
*/
isTagEqual: function (el, name)
{
return el.tagName.toLowerCase() == name.toLowerCase();
},
/** PrivateVariable: _xmlGenerator
* _Private_ variable that caches a DOM document to
* generate elements.
*/
_xmlGenerator: null,
/** PrivateFunction: _makeGenerator
* _Private_ function that creates a dummy XML DOM document to serve as
* an element and text node generator.
*/
_makeGenerator: function () {
var doc;
// IE9 does implement createDocument(); however, using it will cause the browser to leak memory on page unload.
// Here, we test for presence of createDocument() plus IE's proprietary documentMode attribute, which would be
// less than 10 in the case of IE9 and below.
if (document.implementation.createDocument === undefined ||
document.implementation.createDocument && document.documentMode && document.documentMode < 10) {
doc = this._getIEXmlDom();
doc.appendChild(doc.createElement('strophe'));
} else {
doc = document.implementation
.createDocument('jabber:client', 'strophe', null);
}
return doc;
},
/** Function: xmlGenerator
* Get the DOM document to generate elements.
*
* Returns:
* The currently used DOM document.
*/
xmlGenerator: function () {
if (!Strophe._xmlGenerator) {
Strophe._xmlGenerator = Strophe._makeGenerator();
}
return Strophe._xmlGenerator;
},
/** PrivateFunction: _getIEXmlDom
* Gets IE xml doc object
*
* Returns:
* A Microsoft XML DOM Object
* See Also:
* http://msdn.microsoft.com/en-us/library/ms757837%28VS.85%29.aspx
*/
_getIEXmlDom : function() {
var doc = null;
var docStrings = [
"Msxml2.DOMDocument.6.0",
"Msxml2.DOMDocument.5.0",
"Msxml2.DOMDocument.4.0",
"MSXML2.DOMDocument.3.0",
"MSXML2.DOMDocument",
"MSXML.DOMDocument",
"Microsoft.XMLDOM"
];
for (var d = 0; d < docStrings.length; d++) {
if (doc === null) {
try {
doc = new ActiveXObject(docStrings[d]);
} catch (e) {
doc = null;
}
} else {
break;
}
}
return doc;
},
/** Function: xmlElement
* Create an XML DOM element.
*
* This function creates an XML DOM element correctly across all
* implementations. Note that these are not HTML DOM elements, which
* aren't appropriate for XMPP stanzas.
*
* Parameters:
* (String) name - The name for the element.
* (Array|Object) attrs - An optional array or object containing
* key/value pairs to use as element attributes. The object should
* be in the format {'key': 'value'} or {key: 'value'}. The array
* should have the format [['key1', 'value1'], ['key2', 'value2']].
* (String) text - The text child data for the element.
*
* Returns:
* A new XML DOM element.
*/
xmlElement: function (name)
{
if (!name) { return null; }
var node = Strophe.xmlGenerator().createElement(name);
// FIXME: this should throw errors if args are the wrong type or
// there are more than two optional args
var a, i, k;
for (a = 1; a < arguments.length; a++) {
if (!arguments[a]) { continue; }
if (typeof(arguments[a]) == "string" ||
typeof(arguments[a]) == "number") {
node.appendChild(Strophe.xmlTextNode(arguments[a]));
} else if (typeof(arguments[a]) == "object" &&
typeof(arguments[a].sort) == "function") {
for (i = 0; i < arguments[a].length; i++) {
if (typeof(arguments[a][i]) == "object" &&
typeof(arguments[a][i].sort) == "function") {
node.setAttribute(arguments[a][i][0],
arguments[a][i][1]);
}
}
} else if (typeof(arguments[a]) == "object") {
for (k in arguments[a]) {
if (arguments[a].hasOwnProperty(k)) {
node.setAttribute(k, arguments[a][k]);
}
}
}
}
return node;
},
/* Function: xmlescape
* Excapes invalid xml characters.
*
* Parameters:
* (String) text - text to escape.
*
* Returns:
* Escaped text.
*/
xmlescape: function(text)
{
text = text.replace(/\&/g, "&");
text = text.replace(/</g, "<");
text = text.replace(/>/g, ">");
text = text.replace(/'/g, "'");
text = text.replace(/"/g, """);
return text;
},
/** Function: xmlTextNode
* Creates an XML DOM text node.
*
* Provides a cross implementation version of document.createTextNode.
*
* Parameters:
* (String) text - The content of the text node.
*
* Returns:
* A new XML DOM text node.
*/
xmlTextNode: function (text)
{
return Strophe.xmlGenerator().createTextNode(text);
},
/** Function: xmlHtmlNode
* Creates an XML DOM html node.
*
* Parameters:
* (String) html - The content of the html node.
*
* Returns:
* A new XML DOM text node.
*/
xmlHtmlNode: function (html)
{
var node;
//ensure text is escaped
if (window.DOMParser) {
var parser = new DOMParser();
node = parser.parseFromString(html, "text/xml");
} else {
node = new ActiveXObject("Microsoft.XMLDOM");
node.async="false";
node.loadXML(html);
}
return node;
},
/** Function: getText
* Get the concatenation of all text children of an element.
*
* Parameters:
* (XMLElement) elem - A DOM element.
*
* Returns:
* A String with the concatenated text of all text element children.
*/
getText: function (elem)
{
if (!elem) { return null; }
var str = "";
if (elem.childNodes.length === 0 && elem.nodeType ==
Strophe.ElementType.TEXT) {
str += elem.nodeValue;
}
for (var i = 0; i < elem.childNodes.length; i++) {
if (elem.childNodes[i].nodeType == Strophe.ElementType.TEXT) {
str += elem.childNodes[i].nodeValue;
}
}
return Strophe.xmlescape(str);
},
/** Function: copyElement
* Copy an XML DOM element.
*
* This function copies a DOM element and all its descendants and returns
* the new copy.
*
* Parameters:
* (XMLElement) elem - A DOM element.
*
* Returns:
* A new, copied DOM element tree.
*/
copyElement: function (elem)
{
var i, el;
if (elem.nodeType == Strophe.ElementType.NORMAL) {
el = Strophe.xmlElement(elem.tagName);
for (i = 0; i < elem.attributes.length; i++) {
el.setAttribute(elem.attributes[i].nodeName.toLowerCase(),
elem.attributes[i].value);
}
for (i = 0; i < elem.childNodes.length; i++) {
el.appendChild(Strophe.copyElement(elem.childNodes[i]));
}
} else if (elem.nodeType == Strophe.ElementType.TEXT) {
el = Strophe.xmlGenerator().createTextNode(elem.nodeValue);
}
return el;
},
/** Function: createHtml
* Copy an HTML DOM element into an XML DOM.
*
* This function copies a DOM element and all its descendants and returns
* the new copy.
*
* Parameters:
* (HTMLElement) elem - A DOM element.
*
* Returns:
* A new, copied DOM element tree.
*/
createHtml: function (elem)
{
var i, el, j, tag, attribute, value, css, cssAttrs, attr, cssName, cssValue;
if (elem.nodeType == Strophe.ElementType.NORMAL) {
tag = elem.nodeName.toLowerCase();
if(Strophe.XHTML.validTag(tag)) {
try {
el = Strophe.xmlElement(tag);
for(i = 0; i < Strophe.XHTML.attributes[tag].length; i++) {
attribute = Strophe.XHTML.attributes[tag][i];
value = elem.getAttribute(attribute);
if(typeof value == 'undefined' || value === null || value === '' || value === false || value === 0) {
continue;
}
if(attribute == 'style' && typeof value == 'object') {
if(typeof value.cssText != 'undefined') {
value = value.cssText; // we're dealing with IE, need to get CSS out
}
}
// filter out invalid css styles
if(attribute == 'style') {
css = [];
cssAttrs = value.split(';');
for(j = 0; j < cssAttrs.length; j++) {
attr = cssAttrs[j].split(':');
cssName = attr[0].replace(/^\s*/, "").replace(/\s*$/, "").toLowerCase();
if(Strophe.XHTML.validCSS(cssName)) {
cssValue = attr[1].replace(/^\s*/, "").replace(/\s*$/, "");
css.push(cssName + ': ' + cssValue);
}
}
if(css.length > 0) {
value = css.join('; ');
el.setAttribute(attribute, value);
}
} else {
el.setAttribute(attribute, value);
}
}
for (i = 0; i < elem.childNodes.length; i++) {
el.appendChild(Strophe.createHtml(elem.childNodes[i]));
}
} catch(e) { // invalid elements
el = Strophe.xmlTextNode('');
}
} else {
el = Strophe.xmlGenerator().createDocumentFragment();
for (i = 0; i < elem.childNodes.length; i++) {
el.appendChild(Strophe.createHtml(elem.childNodes[i]));
}
}
} else if (elem.nodeType == Strophe.ElementType.FRAGMENT) {
el = Strophe.xmlGenerator().createDocumentFragment();
for (i = 0; i < elem.childNodes.length; i++) {
el.appendChild(Strophe.createHtml(elem.childNodes[i]));
}
} else if (elem.nodeType == Strophe.ElementType.TEXT) {
el = Strophe.xmlTextNode(elem.nodeValue);
}
return el;
},
/** Function: escapeNode
* Escape the node part (also called local part) of a JID.
*
* Parameters:
* (String) node - A node (or local part).
*
* Returns:
* An escaped node (or local part).
*/
escapeNode: function (node)
{
return node.replace(/^\s+|\s+$/g, '')
.replace(/\\/g, "\\5c")
.replace(/ /g, "\\20")
.replace(/\"/g, "\\22")
.replace(/\&/g, "\\26")
.replace(/\'/g, "\\27")
.replace(/\//g, "\\2f")
.replace(/:/g, "\\3a")
.replace(/</g, "\\3c")
.replace(/>/g, "\\3e")
.replace(/@/g, "\\40");
},
/** Function: unescapeNode
* Unescape a node part (also called local part) of a JID.
*
* Parameters:
* (String) node - A node (or local part).
*
* Returns:
* An unescaped node (or local part).
*/
unescapeNode: function (node)
{
return node.replace(/\\20/g, " ")
.replace(/\\22/g, '"')
.replace(/\\26/g, "&")
.replace(/\\27/g, "'")
.replace(/\\2f/g, "/")
.replace(/\\3a/g, ":")
.replace(/\\3c/g, "<")
.replace(/\\3e/g, ">")
.replace(/\\40/g, "@")
.replace(/\\5c/g, "\\");
},
/** Function: getNodeFromJid
* Get the node portion of a JID String.
*
* Parameters:
* (String) jid - A JID.
*
* Returns:
* A String containing the node.
*/
getNodeFromJid: function (jid)
{
if (jid.indexOf("@") < 0) { return null; }
return jid.split("@")[0];
},
/** Function: getDomainFromJid
* Get the domain portion of a JID String.
*
* Parameters:
* (String) jid - A JID.
*
* Returns:
* A String containing the domain.
*/
getDomainFromJid: function (jid)
{
var bare = Strophe.getBareJidFromJid(jid);
if (bare.indexOf("@") < 0) {
return bare;
} else {
var parts = bare.split("@");
parts.splice(0, 1);
return parts.join('@');
}
},
/** Function: getResourceFromJid
* Get the resource portion of a JID String.
*
* Parameters:
* (String) jid - A JID.
*
* Returns:
* A String containing the resource.
*/
getResourceFromJid: function (jid)
{
var s = jid.split("/");
if (s.length < 2) { return null; }
s.splice(0, 1);
return s.join('/');
},
/** Function: getBareJidFromJid
* Get the bare JID from a JID String.
*
* Parameters:
* (String) jid - A JID.
*
* Returns:
* A String containing the bare JID.
*/
getBareJidFromJid: function (jid)
{
return jid ? jid.split("/")[0] : null;
},
/** Function: log
* User overrideable logging function.
*
* This function is called whenever the Strophe library calls any
* of the logging functions. The default implementation of this
* function does nothing. If client code wishes to handle the logging
* messages, it should override this with
* > Strophe.log = function (level, msg) {
* > (user code here)
* > };
*
* Please note that data sent and received over the wire is logged
* via Strophe.Connection.rawInput() and Strophe.Connection.rawOutput().
*
* The different levels and their meanings are
*
* DEBUG - Messages useful for debugging purposes.
* INFO - Informational messages. This is mostly information like
* 'disconnect was called' or 'SASL auth succeeded'.
* WARN - Warnings about potential problems. This is mostly used
* to report transient connection errors like request timeouts.
* ERROR - Some error occurred.
* FATAL - A non-recoverable fatal error occurred.
*
* Parameters:
* (Integer) level - The log level of the log message. This will
* be one of the values in Strophe.LogLevel.
* (String) msg - The log message.
*/
/* jshint ignore:start */
log: function (level, msg)
{
return;
},
/* jshint ignore:end */
/** Function: debug
* Log a message at the Strophe.LogLevel.DEBUG level.
*
* Parameters:
* (String) msg - The log message.
*/
debug: function(msg)
{
this.log(this.LogLevel.DEBUG, msg);
},
/** Function: info
* Log a message at the Strophe.LogLevel.INFO level.
*
* Parameters:
* (String) msg - The log message.
*/
info: function (msg)
{
this.log(this.LogLevel.INFO, msg);
},
/** Function: warn
* Log a message at the Strophe.LogLevel.WARN level.
*
* Parameters:
* (String) msg - The log message.
*/
warn: function (msg)
{
this.log(this.LogLevel.WARN, msg);
},
/** Function: error
* Log a message at the Strophe.LogLevel.ERROR level.
*
* Parameters:
* (String) msg - The log message.
*/
error: function (msg)
{
this.log(this.LogLevel.ERROR, msg);
},
/** Function: fatal
* Log a message at the Strophe.LogLevel.FATAL level.
*
* Parameters:
* (String) msg - The log message.
*/
fatal: function (msg)
{
this.log(this.LogLevel.FATAL, msg);
},
/** Function: serialize
* Render a DOM element and all descendants to a String.
*
* Parameters:
* (XMLElement) elem - A DOM element.
*
* Returns:
* The serialized element tree as a String.
*/
serialize: function (elem)
{
var result;
if (!elem) { return null; }
if (typeof(elem.tree) === "function") {
elem = elem.tree();
}
var nodeName = elem.nodeName;
var i, child;
if (elem.getAttribute("_realname")) {
nodeName = elem.getAttribute("_realname");
}
result = "<" + nodeName;
for (i = 0; i < elem.attributes.length; i++) {
if(elem.attributes[i].nodeName != "_realname") {
result += " " + elem.attributes[i].nodeName.toLowerCase() +
"='" + elem.attributes[i].value
.replace(/&/g, "&")
.replace(/\'/g, "'")
.replace(/>/g, ">")
.replace(/</g, "<") + "'";
}
}
if (elem.childNodes.length > 0) {
result += ">";
for (i = 0; i < elem.childNodes.length; i++) {
child = elem.childNodes[i];
switch( child.nodeType ){
case Strophe.ElementType.NORMAL:
// normal element, so recurse
result += Strophe.serialize(child);
break;
case Strophe.ElementType.TEXT:
// text element to escape values
result += Strophe.xmlescape(child.nodeValue);
break;
case Strophe.ElementType.CDATA:
// cdata section so don't escape values
result += "<![CDATA["+child.nodeValue+"]]>";
}
}
result += "</" + nodeName + ">";
} else {
result += "/>";
}
return result;
},
/** PrivateVariable: _requestId
* _Private_ variable that keeps track of the request ids for
* connections.
*/
_requestId: 0,
/** PrivateVariable: Strophe.connectionPlugins
* _Private_ variable Used to store plugin names that need
* initialization on Strophe.Connection construction.
*/
_connectionPlugins: {},
/** Function: addConnectionPlugin
* Extends the Strophe.Connection object with the given plugin.
*
* Parameters:
* (String) name - The name of the extension.
* (Object) ptype - The plugin's prototype.
*/
addConnectionPlugin: function (name, ptype)
{
Strophe._connectionPlugins[name] = ptype;
}
};
/** Class: Strophe.Builder
* XML DOM builder.
*
* This object provides an interface similar to JQuery but for building
* DOM element easily and rapidly. All the functions except for toString()
* and tree() return the object, so calls can be chained. Here's an
* example using the $iq() builder helper.
* > $iq({to: 'you', from: 'me', type: 'get', id: '1'})
* > .c('query', {xmlns: 'strophe:example'})
* > .c('example')
* > .toString()
* The above generates this XML fragment
* > <iq to='you' from='me' type='get' id='1'>
* > <query xmlns='strophe:example'>
* > <example/>
* > </query>
* > </iq>
* The corresponding DOM manipulations to get a similar fragment would be
* a lot more tedious and probably involve several helper variables.
*
* Since adding children makes new operations operate on the child, up()
* is provided to traverse up the tree. To add two children, do
* > builder.c('child1', ...).up().c('child2', ...)
* The next operation on the Builder will be relative to the second child.
*/
/** Constructor: Strophe.Builder
* Create a Strophe.Builder object.
*
* The attributes should be passed in object notation. For example
* > var b = new Builder('message', {to: 'you', from: 'me'});
* or
* > var b = new Builder('messsage', {'xml:lang': 'en'});
*
* Parameters:
* (String) name - The name of the root element.
* (Object) attrs - The attributes for the root element in object notation.
*
* Returns:
* A new Strophe.Builder.
*/
Strophe.Builder = function (name, attrs)
{
// Set correct namespace for jabber:client elements
if (name == "presence" || name == "message" || name == "iq") {
if (attrs && !attrs.xmlns) {
attrs.xmlns = Strophe.NS.CLIENT;
} else if (!attrs) {
attrs = {xmlns: Strophe.NS.CLIENT};
}
}
// Holds the tree being built.
this.nodeTree = Strophe.xmlElement(name, attrs);
// Points to the current operation node.
this.node = this.nodeTree;
};
Strophe.Builder.prototype = {
/** Function: tree
* Return the DOM tree.
*
* This function returns the current DOM tree as an element object. This
* is suitable for passing to functions like Strophe.Connection.send().
*
* Returns:
* The DOM tree as a element object.
*/
tree: function ()
{
return this.nodeTree;
},
/** Function: toString
* Serialize the DOM tree to a String.
*
* This function returns a string serialization of the current DOM
* tree. It is often used internally to pass data to a
* Strophe.Request object.
*
* Returns:
* The serialized DOM tree in a String.
*/
toString: function ()
{
return Strophe.serialize(this.nodeTree);
},
/** Function: up
* Make the current parent element the new current element.
*
* This function is often used after c() to traverse back up the tree.
* For example, to add two children to the same element
* > builder.c('child1', {}).up().c('child2', {});
*
* Returns:
* The Stophe.Builder object.
*/
up: function ()
{
this.node = this.node.parentNode;
return this;
},
/** Function: attrs
* Add or modify attributes of the current element.
*
* The attributes should be passed in object notation. This function
* does not move the current element pointer.
*
* Parameters:
* (Object) moreattrs - The attributes to add/modify in object notation.
*
* Returns:
* The Strophe.Builder object.
*/
attrs: function (moreattrs)
{
for (var k in moreattrs) {
if (moreattrs.hasOwnProperty(k)) {
this.node.setAttribute(k, moreattrs[k]);
}
}
return this;
},
/** Function: c
* Add a child to the current element and make it the new current
* element.
*
* This function moves the current element pointer to the child,
* unless text is provided. If you need to add another child, it
* is necessary to use up() to go back to the parent in the tree.
*
* Parameters:
* (String) name - The name of the child.
* (Object) attrs - The attributes of the child in object notation.
* (String) text - The text to add to the child.
*
* Returns:
* The Strophe.Builder object.
*/
c: function (name, attrs, text)
{
var child = Strophe.xmlElement(name, attrs, text);
this.node.appendChild(child);
if (!text) {
this.node = child;
}
return this;
},
/** Function: cnode
* Add a child to the current element and make it the new current
* element.
*
* This function is the same as c() except that instead of using a
* name and an attributes object to create the child it uses an
* existing DOM element object.
*
* Parameters:
* (XMLElement) elem - A DOM element.
*
* Returns:
* The Strophe.Builder object.
*/
cnode: function (elem)
{
var impNode;
var xmlGen = Strophe.xmlGenerator();
try {
impNode = (xmlGen.importNode !== undefined);
}
catch (e) {
impNode = false;
}
var newElem = impNode ?
xmlGen.importNode(elem, true) :
Strophe.copyElement(elem);
this.node.appendChild(newElem);
this.node = newElem;
return this;
},
/** Function: t
* Add a child text element.
*
* This *does not* make the child the new current element since there
* are no children of text elements.
*
* Parameters:
* (String) text - The text data to append to the current element.
*
* Returns:
* The Strophe.Builder object.
*/
t: function (text)
{
var child = Strophe.xmlTextNode(text);
this.node.appendChild(child);
return this;
},
/** Function: h
* Replace current element contents with the HTML passed in.
*
* This *does not* make the child the new current element
*
* Parameters:
* (String) html - The html to insert as contents of current element.
*
* Returns:
* The Strophe.Builder object.
*/
h: function (html)
{
var fragment = document.createElement('body');
// force the browser to try and fix any invalid HTML tags
fragment.innerHTML = html;
// copy cleaned html into an xml dom
var xhtml = Strophe.createHtml(fragment);
while(xhtml.childNodes.length > 0) {
this.node.appendChild(xhtml.childNodes[0]);
}
return this;
}
};
/** PrivateClass: Strophe.Handler
* _Private_ helper class for managing stanza handlers.
*
* A Strophe.Handler encapsulates a user provided callback function to be
* executed when matching stanzas are received by the connection.
* Handlers can be either one-off or persistant depending on their
* return value. Returning true will cause a Handler to remain active, and
* returning false will remove the Handler.
*
* Users will not use Strophe.Handler objects directly, but instead they
* will use Strophe.Connection.addHandler() and
* Strophe.Connection.deleteHandler().
*/
/** PrivateConstructor: Strophe.Handler
* Create and initialize a new Strophe.Handler.
*
* Parameters:
* (Function) handler - A function to be executed when the handler is run.
* (String) ns - The namespace to match.
* (String) name - The element name to match.
* (String) type - The element type to match.
* (String) id - The element id attribute to match.
* (String) from - The element from attribute to match.
* (Object) options - Handler options
*
* Returns:
* A new Strophe.Handler object.
*/
Strophe.Handler = function (handler, ns, name, type, id, from, options)
{
this.handler = handler;
this.ns = ns;
this.name = name;
this.type = type;
this.id = id;
this.options = options || {matchBare: false};
// default matchBare to false if undefined
if (!this.options.matchBare) {
this.options.matchBare = false;
}
if (this.options.matchBare) {
this.from = from ? Strophe.getBareJidFromJid(from) : null;
} else {
this.from = from;
}
// whether the handler is a user handler or a system handler
this.user = true;
};
Strophe.Handler.prototype = {
/** PrivateFunction: isMatch
* Tests if a stanza matches the Strophe.Handler.
*
* Parameters:
* (XMLElement) elem - The XML element to test.
*
* Returns:
* true if the stanza matches and false otherwise.
*/
isMatch: function (elem)
{
var nsMatch;
var from = null;
if (this.options.matchBare) {
from = Strophe.getBareJidFromJid(elem.getAttribute('from'));
} else {
from = elem.getAttribute('from');
}
nsMatch = false;
if (!this.ns) {
nsMatch = true;
} else {
var that = this;
Strophe.forEachChild(elem, null, function (elem) {
if (elem.getAttribute("xmlns") == that.ns) {
nsMatch = true;
}
});
nsMatch = nsMatch || elem.getAttribute("xmlns") == this.ns;
}
if (nsMatch &&
(!this.name || Strophe.isTagEqual(elem, this.name)) &&
(!this.type || elem.getAttribute("type") == this.type) &&
(!this.id || elem.getAttribute("id") == this.id) &&
(!this.from || from == this.from)) {
return true;
}
return false;
},
/** PrivateFunction: run
* Run the callback on a matching stanza.
*
* Parameters:
* (XMLElement) elem - The DOM element that triggered the
* Strophe.Handler.
*
* Returns:
* A boolean indicating if the handler should remain active.
*/
run: function (elem)
{
var result = null;
try {
result = this.handler(elem);
} catch (e) {
if (e.sourceURL) {
Strophe.fatal("error: " + this.handler +
" " + e.sourceURL + ":" +
e.line + " - " + e.name + ": " + e.message);
} else if (e.fileName) {
if (typeof(console) != "undefined") {
console.trace();
console.error(this.handler, " - error - ", e, e.message);
}
Strophe.fatal("error: " + this.handler + " " +
e.fileName + ":" + e.lineNumber + " - " +
e.name + ": " + e.message);
} else {
Strophe.fatal("error: " + e.message + "\n" + e.stack);
}
throw e;
}
return result;
},
/** PrivateFunction: toString
* Get a String representation of the Strophe.Handler object.
*
* Returns:
* A String.
*/
toString: function ()
{
return "{Handler: " + this.handler + "(" + this.name + "," +
this.id + "," + this.ns + ")}";
}
};
/** PrivateClass: Strophe.TimedHandler
* _Private_ helper class for managing timed handlers.
*
* A Strophe.TimedHandler encapsulates a user provided callback that
* should be called after a certain period of time or at regular
* intervals. The return value of the callback determines whether the
* Strophe.TimedHandler will continue to fire.
*
* Users will not use Strophe.TimedHandler objects directly, but instead
* they will use Strophe.Connection.addTimedHandler() and
* Strophe.Connection.deleteTimedHandler().
*/
/** PrivateConstructor: Strophe.TimedHandler
* Create and initialize a new Strophe.TimedHandler object.
*
* Parameters:
* (Integer) period - The number of milliseconds to wait before the
* handler is called.
* (Function) handler - The callback to run when the handler fires. This
* function should take no arguments.
*
* Returns:
* A new Strophe.TimedHandler object.
*/
Strophe.TimedHandler = function (period, handler)
{
this.period = period;
this.handler = handler;
this.lastCalled = new Date().getTime();
this.user = true;
};
Strophe.TimedHandler.prototype = {
/** PrivateFunction: run
* Run the callback for the Strophe.TimedHandler.
*
* Returns:
* true if the Strophe.TimedHandler should be called again, and false
* otherwise.
*/
run: function ()
{
this.lastCalled = new Date().getTime();
return this.handler();
},
/** PrivateFunction: reset
* Reset the last called time for the Strophe.TimedHandler.
*/
reset: function ()
{
this.lastCalled = new Date().getTime();
},
/** PrivateFunction: toString
* Get a string representation of the Strophe.TimedHandler object.
*
* Returns:
* The string representation.
*/
toString: function ()
{
return "{TimedHandler: " + this.handler + "(" + this.period +")}";
}
};
/** Class: Strophe.Connection
* XMPP Connection manager.
*
* This class is the main part of Strophe. It manages a BOSH connection
* to an XMPP server and dispatches events to the user callbacks as
* data arrives. It supports SASL PLAIN, SASL DIGEST-MD5, SASL SCRAM-SHA1
* and legacy authentication.
*
* After creating a Strophe.Connection object, the user will typically
* call connect() with a user supplied callback to handle connection level
* events like authentication failure, disconnection, or connection
* complete.
*
* The user will also have several event handlers defined by using
* addHandler() and addTimedHandler(). These will allow the user code to
* respond to interesting stanzas or do something periodically with the
* connection. These handlers will be active once authentication is
* finished.
*
* To send data to the connection, use send().
*/
/** Constructor: Strophe.Connection
* Create and initialize a Strophe.Connection object.
*
* The transport-protocol for this connection will be chosen automatically
* based on the given service parameter. URLs starting with "ws://" or
* "wss://" will use WebSockets, URLs starting with "http://", "https://"
* or without a protocol will use BOSH.
*
* To make Strophe connect to the current host you can leave out the protocol
* and host part and just pass the path, e.g.
*
* > var conn = new Strophe.Connection("/http-bind/");
*
* WebSocket options:
*
* If you want to connect to the current host with a WebSocket connection you
* can tell Strophe to use WebSockets through a "protocol" attribute in the
* optional options parameter. Valid values are "ws" for WebSocket and "wss"
* for Secure WebSocket.
* So to connect to "wss://CURRENT_HOSTNAME/xmpp-websocket" you would call
*
* > var conn = new Strophe.Connection("/xmpp-websocket/", {protocol: "wss"});
*
* Note that relative URLs _NOT_ starting with a "/" will also include the path
* of the current site.
*
* Also because downgrading security is not permitted by browsers, when using
* relative URLs both BOSH and WebSocket connections will use their secure
* variants if the current connection to the site is also secure (https).
*
* BOSH options:
*
* by adding "sync" to the options, you can control if requests will
* be made synchronously or not. The default behaviour is asynchronous.
* If you want to make requests synchronous, make "sync" evaluate to true:
* > var conn = new Strophe.Connection("/http-bind/", {sync: true});
* You can also toggle this on an already established connection:
* > conn.options.sync = true;
*
*
* Parameters:
* (String) service - The BOSH or WebSocket service URL.
* (Object) options - A hash of configuration options
*
* Returns:
* A new Strophe.Connection object.
*/
Strophe.Connection = function (service, options)
{
// The service URL
this.service = service;
// Configuration options
this.options = options || {};
var proto = this.options.protocol || "";
// Select protocal based on service or options
if (service.indexOf("ws:") === 0 || service.indexOf("wss:") === 0 ||
proto.indexOf("ws") === 0) {
this._proto = new Strophe.Websocket(this);
} else {
this._proto = new Strophe.Bosh(this);
}
/* The connected JID. */
this.jid = "";
/* the JIDs domain */
this.domain = null;
/* stream:features */
this.features = null;
// SASL
this._sasl_data = {};
this.do_session = false;
this.do_bind = false;
// handler lists
this.timedHandlers = [];
this.handlers = [];
this.removeTimeds = [];
this.removeHandlers = [];
this.addTimeds = [];
this.addHandlers = [];
this._authentication = {};
this._idleTimeout = null;
this._disconnectTimeout = null;
this.do_authentication = true;
this.authenticated = false;
this.disconnecting = false;
this.connected = false;
this.errors = 0;
this.paused = false;
this._data = [];
this._uniqueId = 0;
this._sasl_success_handler = null;
this._sasl_failure_handler = null;
this._sasl_challenge_handler = null;
// Max retries before disconnecting
this.maxRetries = 5;
// setup onIdle callback every 1/10th of a second
this._idleTimeout = setTimeout(this._onIdle.bind(this), 100);
// initialize plugins
for (var k in Strophe._connectionPlugins) {
if (Strophe._connectionPlugins.hasOwnProperty(k)) {
var ptype = Strophe._connectionPlugins[k];
// jslint complaints about the below line, but this is fine
var F = function () {}; // jshint ignore:line
F.prototype = ptype;
this[k] = new F();
this[k].init(this);
}
}
};
Strophe.Connection.prototype = {
/** Function: reset
* Reset the connection.
*
* This function should be called after a connection is disconnected
* before that connection is reused.
*/
reset: function ()
{
this._proto._reset();
// SASL
this.do_session = false;
this.do_bind = false;
// handler lists
this.timedHandlers = [];
this.handlers = [];
this.removeTimeds = [];
this.removeHandlers = [];
this.addTimeds = [];
this.addHandlers = [];
this._authentication = {};
this.authenticated = false;
this.disconnecting = false;
this.connected = false;
this.errors = 0;
this._requests = [];
this._uniqueId = 0;
},
/** Function: pause
* Pause the request manager.
*
* This will prevent Strophe from sending any more requests to the
* server. This is very useful for temporarily pausing
* BOSH-Connections while a lot of send() calls are happening quickly.
* This causes Strophe to send the data in a single request, saving
* many request trips.
*/
pause: function ()
{
this.paused = true;
},
/** Function: resume
* Resume the request manager.
*
* This resumes after pause() has been called.
*/
resume: function ()
{
this.paused = false;
},
/** Function: getUniqueId
* Generate a unique ID for use in <iq/> elements.
*
* All <iq/> stanzas are required to have unique id attributes. This
* function makes creating these easy. Each connection instance has
* a counter which starts from zero, and the value of this counter
* plus a colon followed by the suffix becomes the unique id. If no
* suffix is supplied, the counter is used as the unique id.
*
* Suffixes are used to make debugging easier when reading the stream
* data, and their use is recommended. The counter resets to 0 for
* every new connection for the same reason. For connections to the
* same server that authenticate the same way, all the ids should be
* the same, which makes it easy to see changes. This is useful for
* automated testing as well.
*
* Parameters:
* (String) suffix - A optional suffix to append to the id.
*
* Returns:
* A unique string to be used for the id attribute.
*/
getUniqueId: function (suffix)
{
if (typeof(suffix) == "string" || typeof(suffix) == "number") {
return ++this._uniqueId + ":" + suffix;
} else {
return ++this._uniqueId + "";
}
},
/** Function: connect
* Starts the connection process.
*
* As the connection process proceeds, the user supplied callback will
* be triggered multiple times with status updates. The callback
* should take two arguments - the status code and the error condition.
*
* The status code will be one of the values in the Strophe.Status
* constants. The error condition will be one of the conditions
* defined in RFC 3920 or the condition 'strophe-parsererror'.
*
* The Parameters _wait_, _hold_ and _route_ are optional and only relevant
* for BOSH connections. Please see XEP 124 for a more detailed explanation
* of the optional parameters.
*
* Parameters:
* (String) jid - The user's JID. This may be a bare JID,
* or a full JID. If a node is not supplied, SASL ANONYMOUS
* authentication will be attempted.
* (String) pass - The user's password.
* (Function) callback - The connect callback function.
* (Integer) wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* (Integer) hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* (String) route - The optional route value.
*/
connect: function (jid, pass, callback, wait, hold, route)
{
this.jid = jid;
/** Variable: authzid
* Authorization identity.
*/
this.authzid = Strophe.getBareJidFromJid(this.jid);
/** Variable: authcid
* Authentication identity (User name).
*/
this.authcid = Strophe.getNodeFromJid(this.jid);
/** Variable: pass
* Authentication identity (User password).
*/
this.pass = pass;
/** Variable: servtype
* Digest MD5 compatibility.
*/
this.servtype = "xmpp";
this.connect_callback = callback;
this.disconnecting = false;
this.connected = false;
this.authenticated = false;
this.errors = 0;
// parse jid for domain
this.domain = Strophe.getDomainFromJid(this.jid);
this._changeConnectStatus(Strophe.Status.CONNECTING, null);
this._proto._connect(wait, hold, route);
},
/** Function: attach
* Attach to an already created and authenticated BOSH session.
*
* This function is provided to allow Strophe to attach to BOSH
* sessions which have been created externally, perhaps by a Web
* application. This is often used to support auto-login type features
* without putting user credentials into the page.
*
* Parameters:
* (String) jid - The full JID that is bound by the session.
* (String) sid - The SID of the BOSH session.
* (String) rid - The current RID of the BOSH session. This RID
* will be used by the next request.
* (Function) callback The connect callback function.
* (Integer) wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* Other settings will require tweaks to the Strophe.TIMEOUT value.
* (Integer) hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* (Integer) wind - The optional HTTBIND window value. This is the
* allowed range of request ids that are valid. The default is 5.
*/
attach: function (jid, sid, rid, callback, wait, hold, wind)
{
this._proto._attach(jid, sid, rid, callback, wait, hold, wind);
},
/** Function: xmlInput
* User overrideable function that receives XML data coming into the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.xmlInput = function (elem) {
* > (user code)
* > };
*
* Due to limitations of current Browsers' XML-Parsers the opening and closing
* <stream> tag for WebSocket-Connoctions will be passed as selfclosing here.
*
* BOSH-Connections will have all stanzas wrapped in a <body> tag. See
* <Strophe.Bosh.strip> if you want to strip this tag.
*
* Parameters:
* (XMLElement) elem - The XML data received by the connection.
*/
/* jshint unused:false */
xmlInput: function (elem)
{
return;
},
/* jshint unused:true */
/** Function: xmlOutput
* User overrideable function that receives XML data sent to the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.xmlOutput = function (elem) {
* > (user code)
* > };
*
* Due to limitations of current Browsers' XML-Parsers the opening and closing
* <stream> tag for WebSocket-Connoctions will be passed as selfclosing here.
*
* BOSH-Connections will have all stanzas wrapped in a <body> tag. See
* <Strophe.Bosh.strip> if you want to strip this tag.
*
* Parameters:
* (XMLElement) elem - The XMLdata sent by the connection.
*/
/* jshint unused:false */
xmlOutput: function (elem)
{
return;
},
/* jshint unused:true */
/** Function: rawInput
* User overrideable function that receives raw data coming into the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.rawInput = function (data) {
* > (user code)
* > };
*
* Parameters:
* (String) data - The data received by the connection.
*/
/* jshint unused:false */
rawInput: function (data)
{
return;
},
/* jshint unused:true */
/** Function: rawOutput
* User overrideable function that receives raw data sent to the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.rawOutput = function (data) {
* > (user code)
* > };
*
* Parameters:
* (String) data - The data sent by the connection.
*/
/* jshint unused:false */
rawOutput: function (data)
{
return;
},
/* jshint unused:true */
/** Function: send
* Send a stanza.
*
* This function is called to push data onto the send queue to
* go out over the wire. Whenever a request is sent to the BOSH
* server, all pending data is sent and the queue is flushed.
*
* Parameters:
* (XMLElement |
* [XMLElement] |
* Strophe.Builder) elem - The stanza to send.
*/
send: function (elem)
{
if (elem === null) { return ; }
if (typeof(elem.sort) === "function") {
for (var i = 0; i < elem.length; i++) {
this._queueData(elem[i]);
}
} else if (typeof(elem.tree) === "function") {
this._queueData(elem.tree());
} else {
this._queueData(elem);
}
this._proto._send();
},
/** Function: flush
* Immediately send any pending outgoing data.
*
* Normally send() queues outgoing data until the next idle period
* (100ms), which optimizes network use in the common cases when
* several send()s are called in succession. flush() can be used to
* immediately send all pending data.
*/
flush: function ()
{
// cancel the pending idle period and run the idle function
// immediately
clearTimeout(this._idleTimeout);
this._onIdle();
},
/** Function: sendIQ
* Helper function to send IQ stanzas.
*
* Parameters:
* (XMLElement) elem - The stanza to send.
* (Function) callback - The callback function for a successful request.
* (Function) errback - The callback function for a failed or timed
* out request. On timeout, the stanza will be null.
* (Integer) timeout - The time specified in milliseconds for a
* timeout to occur.
*
* Returns:
* The id used to send the IQ.
*/
sendIQ: function(elem, callback, errback, timeout) {
var timeoutHandler = null;
var that = this;
if (typeof(elem.tree) === "function") {
elem = elem.tree();
}
var id = elem.getAttribute('id');
// inject id if not found
if (!id) {
id = this.getUniqueId("sendIQ");
elem.setAttribute("id", id);
}
var handler = this.addHandler(function (stanza) {
// remove timeout handler if there is one
if (timeoutHandler) {
that.deleteTimedHandler(timeoutHandler);
}
var iqtype = stanza.getAttribute('type');
if (iqtype == 'result') {
if (callback) {
callback(stanza);
}
} else if (iqtype == 'error') {
if (errback) {
errback(stanza);
}
} else {
throw {
name: "StropheError",
message: "Got bad IQ type of " + iqtype
};
}
}, null, 'iq', null, id);
// if timeout specified, setup timeout handler.
if (timeout) {
timeoutHandler = this.addTimedHandler(timeout, function () {
// get rid of normal handler
that.deleteHandler(handler);
// call errback on timeout with null stanza
if (errback) {
errback(null);
}
return false;
});
}
this.send(elem);
return id;
},
/** PrivateFunction: _queueData
* Queue outgoing data for later sending. Also ensures that the data
* is a DOMElement.
*/
_queueData: function (element) {
if (element === null ||
!element.tagName ||
!element.childNodes) {
throw {
name: "StropheError",
message: "Cannot queue non-DOMElement."
};
}
this._data.push(element);
},
/** PrivateFunction: _sendRestart
* Send an xmpp:restart stanza.
*/
_sendRestart: function ()
{
this._data.push("restart");
this._proto._sendRestart();
this._idleTimeout = setTimeout(this._onIdle.bind(this), 100);
},
/** Function: addTimedHandler
* Add a timed handler to the connection.
*
* This function adds a timed handler. The provided handler will
* be called every period milliseconds until it returns false,
* the connection is terminated, or the handler is removed. Handlers
* that wish to continue being invoked should return true.
*
* Because of method binding it is necessary to save the result of
* this function if you wish to remove a handler with
* deleteTimedHandler().
*
* Note that user handlers are not active until authentication is
* successful.
*
* Parameters:
* (Integer) period - The period of the handler.
* (Function) handler - The callback function.
*
* Returns:
* A reference to the handler that can be used to remove it.
*/
addTimedHandler: function (period, handler)
{
var thand = new Strophe.TimedHandler(period, handler);
this.addTimeds.push(thand);
return thand;
},
/** Function: deleteTimedHandler
* Delete a timed handler for a connection.
*
* This function removes a timed handler from the connection. The
* handRef parameter is *not* the function passed to addTimedHandler(),
* but is the reference returned from addTimedHandler().
*
* Parameters:
* (Strophe.TimedHandler) handRef - The handler reference.
*/
deleteTimedHandler: function (handRef)
{
// this must be done in the Idle loop so that we don't change
// the handlers during iteration
this.removeTimeds.push(handRef);
},
/** Function: addHandler
* Add a stanza handler for the connection.
*
* This function adds a stanza handler to the connection. The
* handler callback will be called for any stanza that matches
* the parameters. Note that if multiple parameters are supplied,
* they must all match for the handler to be invoked.
*
* The handler will receive the stanza that triggered it as its argument.
* The handler should return true if it is to be invoked again;
* returning false will remove the handler after it returns.
*
* As a convenience, the ns parameters applies to the top level element
* and also any of its immediate children. This is primarily to make
* matching /iq/query elements easy.
*
* The options argument contains handler matching flags that affect how
* matches are determined. Currently the only flag is matchBare (a
* boolean). When matchBare is true, the from parameter and the from
* attribute on the stanza will be matched as bare JIDs instead of
* full JIDs. To use this, pass {matchBare: true} as the value of
* options. The default value for matchBare is false.
*
* The return value should be saved if you wish to remove the handler
* with deleteHandler().
*
* Parameters:
* (Function) handler - The user callback.
* (String) ns - The namespace to match.
* (String) name - The stanza name to match.
* (String) type - The stanza type attribute to match.
* (String) id - The stanza id attribute to match.
* (String) from - The stanza from attribute to match.
* (String) options - The handler options
*
* Returns:
* A reference to the handler that can be used to remove it.
*/
addHandler: function (handler, ns, name, type, id, from, options)
{
var hand = new Strophe.Handler(handler, ns, name, type, id, from, options);
this.addHandlers.push(hand);
return hand;
},
/** Function: deleteHandler
* Delete a stanza handler for a connection.
*
* This function removes a stanza handler from the connection. The
* handRef parameter is *not* the function passed to addHandler(),
* but is the reference returned from addHandler().
*
* Parameters:
* (Strophe.Handler) handRef - The handler reference.
*/
deleteHandler: function (handRef)
{
// this must be done in the Idle loop so that we don't change
// the handlers during iteration
this.removeHandlers.push(handRef);
},
/** Function: disconnect
* Start the graceful disconnection process.
*
* This function starts the disconnection process. This process starts
* by sending unavailable presence and sending BOSH body of type
* terminate. A timeout handler makes sure that disconnection happens
* even if the BOSH server does not respond.
*
* The user supplied connection callback will be notified of the
* progress as this process happens.
*
* Parameters:
* (String) reason - The reason the disconnect is occuring.
*/
disconnect: function (reason)
{
this._changeConnectStatus(Strophe.Status.DISCONNECTING, reason);
Strophe.info("Disconnect was called because: " + reason);
if (this.connected) {
var pres = false;
this.disconnecting = true;
if (this.authenticated) {
pres = $pres({
xmlns: Strophe.NS.CLIENT,
type: 'unavailable'
});
}
// setup timeout handler
this._disconnectTimeout = this._addSysTimedHandler(
3000, this._onDisconnectTimeout.bind(this));
this._proto._disconnect(pres);
}
},
/** PrivateFunction: _changeConnectStatus
* _Private_ helper function that makes sure plugins and the user's
* callback are notified of connection status changes.
*
* Parameters:
* (Integer) status - the new connection status, one of the values
* in Strophe.Status
* (String) condition - the error condition or null
*/
_changeConnectStatus: function (status, condition)
{
// notify all plugins listening for status changes
for (var k in Strophe._connectionPlugins) {
if (Strophe._connectionPlugins.hasOwnProperty(k)) {
var plugin = this[k];
if (plugin.statusChanged) {
try {
plugin.statusChanged(status, condition);
} catch (err) {
Strophe.error("" + k + " plugin caused an exception " +
"changing status: " + err);
}
}
}
}
// notify the user's callback
if (this.connect_callback) {
try {
this.connect_callback(status, condition);
} catch (e) {
Strophe.error("User connection callback caused an " +
"exception: " + e);
}
}
},
/** PrivateFunction: _doDisconnect
* _Private_ function to disconnect.
*
* This is the last piece of the disconnection logic. This resets the
* connection and alerts the user's connection callback.
*/
_doDisconnect: function ()
{
// Cancel Disconnect Timeout
if (this._disconnectTimeout !== null) {
this.deleteTimedHandler(this._disconnectTimeout);
this._disconnectTimeout = null;
}
Strophe.info("_doDisconnect was called");
this._proto._doDisconnect();
this.authenticated = false;
this.disconnecting = false;
// delete handlers
this.handlers = [];
this.timedHandlers = [];
this.removeTimeds = [];
this.removeHandlers = [];
this.addTimeds = [];
this.addHandlers = [];
// tell the parent we disconnected
this._changeConnectStatus(Strophe.Status.DISCONNECTED, null);
this.connected = false;
},
/** PrivateFunction: _dataRecv
* _Private_ handler to processes incoming data from the the connection.
*
* Except for _connect_cb handling the initial connection request,
* this function handles the incoming data for all requests. This
* function also fires stanza handlers that match each incoming
* stanza.
*
* Parameters:
* (Strophe.Request) req - The request that has data ready.
* (string) req - The stanza a raw string (optiona).
*/
_dataRecv: function (req, raw)
{
Strophe.info("_dataRecv called");
var elem = this._proto._reqToData(req);
if (elem === null) { return; }
if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
if (elem.nodeName === this._proto.strip && elem.childNodes.length) {
this.xmlInput(elem.childNodes[0]);
} else {
this.xmlInput(elem);
}
}
if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
if (raw) {
this.rawInput(raw);
} else {
this.rawInput(Strophe.serialize(elem));
}
}
// remove handlers scheduled for deletion
var i, hand;
while (this.removeHandlers.length > 0) {
hand = this.removeHandlers.pop();
i = this.handlers.indexOf(hand);
if (i >= 0) {
this.handlers.splice(i, 1);
}
}
// add handlers scheduled for addition
while (this.addHandlers.length > 0) {
this.handlers.push(this.addHandlers.pop());
}
// handle graceful disconnect
if (this.disconnecting && this._proto._emptyQueue()) {
this._doDisconnect();
return;
}
var typ = elem.getAttribute("type");
var cond, conflict;
if (typ !== null && typ == "terminate") {
// Don't process stanzas that come in after disconnect
if (this.disconnecting) {
return;
}
// an error occurred
cond = elem.getAttribute("condition");
conflict = elem.getElementsByTagName("conflict");
if (cond !== null) {
if (cond == "remote-stream-error" && conflict.length > 0) {
cond = "conflict";
}
this._changeConnectStatus(Strophe.Status.CONNFAIL, cond);
} else {
this._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown");
}
this.disconnect('unknown stream-error');
return;
}
// send each incoming stanza through the handler chain
var that = this;
Strophe.forEachChild(elem, null, function (child) {
var i, newList;
// process handlers
newList = that.handlers;
that.handlers = [];
for (i = 0; i < newList.length; i++) {
var hand = newList[i];
// encapsulate 'handler.run' not to lose the whole handler list if
// one of the handlers throws an exception
try {
if (hand.isMatch(child) &&
(that.authenticated || !hand.user)) {
if (hand.run(child)) {
that.handlers.push(hand);
}
} else {
that.handlers.push(hand);
}
} catch(e) {
// if the handler throws an exception, we consider it as false
Strophe.warn('Removing Strophe handlers due to uncaught exception: ' + e.message);
}
}
});
},
/** Attribute: mechanisms
* SASL Mechanisms available for Conncection.
*/
mechanisms: {},
/** PrivateFunction: _connect_cb
* _Private_ handler for initial connection request.
*
* This handler is used to process the initial connection request
* response from the BOSH server. It is used to set up authentication
* handlers and start the authentication process.
*
* SASL authentication will be attempted if available, otherwise
* the code will fall back to legacy authentication.
*
* Parameters:
* (Strophe.Request) req - The current request.
* (Function) _callback - low level (xmpp) connect callback function.
* Useful for plugins with their own xmpp connect callback (when their)
* want to do something special).
*/
_connect_cb: function (req, _callback, raw)
{
Strophe.info("_connect_cb was called");
this.connected = true;
var bodyWrap = this._proto._reqToData(req);
if (!bodyWrap) { return; }
if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
if (bodyWrap.nodeName === this._proto.strip && bodyWrap.childNodes.length) {
this.xmlInput(bodyWrap.childNodes[0]);
} else {
this.xmlInput(bodyWrap);
}
}
if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
if (raw) {
this.rawInput(raw);
} else {
this.rawInput(Strophe.serialize(bodyWrap));
}
}
var conncheck = this._proto._connect_cb(bodyWrap);
if (conncheck === Strophe.Status.CONNFAIL) {
return;
}
this._authentication.sasl_scram_sha1 = false;
this._authentication.sasl_plain = false;
this._authentication.sasl_digest_md5 = false;
this._authentication.sasl_anonymous = false;
this._authentication.legacy_auth = false;
// Check for the stream:features tag
var hasFeatures = bodyWrap.getElementsByTagName("stream:features").length > 0;
if (!hasFeatures) {
hasFeatures = bodyWrap.getElementsByTagName("features").length > 0;
}
var mechanisms = bodyWrap.getElementsByTagName("mechanism");
var matched = [];
var i, mech, found_authentication = false;
if (!hasFeatures) {
this._proto._no_auth_received(_callback);
return;
}
if (mechanisms.length > 0) {
for (i = 0; i < mechanisms.length; i++) {
mech = Strophe.getText(mechanisms[i]);
if (this.mechanisms[mech]) matched.push(this.mechanisms[mech]);
}
}
this._authentication.legacy_auth =
bodyWrap.getElementsByTagName("auth").length > 0;
found_authentication = this._authentication.legacy_auth ||
matched.length > 0;
if (!found_authentication) {
this._proto._no_auth_received(_callback);
return;
}
if (this.do_authentication !== false)
this.authenticate(matched);
},
/** Function: authenticate
* Set up authentication
*
* Contiunues the initial connection request by setting up authentication
* handlers and start the authentication process.
*
* SASL authentication will be attempted if available, otherwise
* the code will fall back to legacy authentication.
*
*/
authenticate: function (matched)
{
var i;
// Sorting matched mechanisms according to priority.
for (i = 0; i < matched.length - 1; ++i) {
var higher = i;
for (var j = i + 1; j < matched.length; ++j) {
if (matched[j].prototype.priority > matched[higher].prototype.priority) {
higher = j;
}
}
if (higher != i) {
var swap = matched[i];
matched[i] = matched[higher];
matched[higher] = swap;
}
}
// run each mechanism
var mechanism_found = false;
for (i = 0; i < matched.length; ++i) {
if (!matched[i].test(this)) continue;
this._sasl_success_handler = this._addSysHandler(
this._sasl_success_cb.bind(this), null,
"success", null, null);
this._sasl_failure_handler = this._addSysHandler(
this._sasl_failure_cb.bind(this), null,
"failure", null, null);
this._sasl_challenge_handler = this._addSysHandler(
this._sasl_challenge_cb.bind(this), null,
"challenge", null, null);
this._sasl_mechanism = new matched[i]();
this._sasl_mechanism.onStart(this);
var request_auth_exchange = $build("auth", {
xmlns: Strophe.NS.SASL,
mechanism: this._sasl_mechanism.name
});
if (this._sasl_mechanism.isClientFirst) {
var response = this._sasl_mechanism.onChallenge(this, null);
request_auth_exchange.t(Base64.encode(response));
}
this.send(request_auth_exchange.tree());
mechanism_found = true;
break;
}
if (!mechanism_found) {
// if none of the mechanism worked
if (Strophe.getNodeFromJid(this.jid) === null) {
// we don't have a node, which is required for non-anonymous
// client connections
this._changeConnectStatus(Strophe.Status.CONNFAIL,
'x-strophe-bad-non-anon-jid');
this.disconnect('x-strophe-bad-non-anon-jid');
} else {
// fall back to legacy authentication
this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null);
this._addSysHandler(this._auth1_cb.bind(this), null, null,
null, "_auth_1");
this.send($iq({
type: "get",
to: this.domain,
id: "_auth_1"
}).c("query", {
xmlns: Strophe.NS.AUTH
}).c("username", {}).t(Strophe.getNodeFromJid(this.jid)).tree());
}
}
},
_sasl_challenge_cb: function(elem) {
var challenge = Base64.decode(Strophe.getText(elem));
var response = this._sasl_mechanism.onChallenge(this, challenge);
var stanza = $build('response', {
xmlns: Strophe.NS.SASL
});
if (response !== "") {
stanza.t(Base64.encode(response));
}
this.send(stanza.tree());
return true;
},
/** PrivateFunction: _auth1_cb
* _Private_ handler for legacy authentication.
*
* This handler is called in response to the initial <iq type='get'/>
* for legacy authentication. It builds an authentication <iq/> and
* sends it, creating a handler (calling back to _auth2_cb()) to
* handle the result
*
* Parameters:
* (XMLElement) elem - The stanza that triggered the callback.
*
* Returns:
* false to remove the handler.
*/
/* jshint unused:false */
_auth1_cb: function (elem)
{
// build plaintext auth iq
var iq = $iq({type: "set", id: "_auth_2"})
.c('query', {xmlns: Strophe.NS.AUTH})
.c('username', {}).t(Strophe.getNodeFromJid(this.jid))
.up()
.c('password').t(this.pass);
if (!Strophe.getResourceFromJid(this.jid)) {
// since the user has not supplied a resource, we pick
// a default one here. unlike other auth methods, the server
// cannot do this for us.
this.jid = Strophe.getBareJidFromJid(this.jid) + '/strophe';
}
iq.up().c('resource', {}).t(Strophe.getResourceFromJid(this.jid));
this._addSysHandler(this._auth2_cb.bind(this), null,
null, null, "_auth_2");
this.send(iq.tree());
return false;
},
/* jshint unused:true */
/** PrivateFunction: _sasl_success_cb
* _Private_ handler for succesful SASL authentication.
*
* Parameters:
* (XMLElement) elem - The matching stanza.
*
* Returns:
* false to remove the handler.
*/
_sasl_success_cb: function (elem)
{
if (this._sasl_data["server-signature"]) {
var serverSignature;
var success = Base64.decode(Strophe.getText(elem));
var attribMatch = /([a-z]+)=([^,]+)(,|$)/;
var matches = success.match(attribMatch);
if (matches[1] == "v") {
serverSignature = matches[2];
}
if (serverSignature != this._sasl_data["server-signature"]) {
// remove old handlers
this.deleteHandler(this._sasl_failure_handler);
this._sasl_failure_handler = null;
if (this._sasl_challenge_handler) {
this.deleteHandler(this._sasl_challenge_handler);
this._sasl_challenge_handler = null;
}
this._sasl_data = {};
return this._sasl_failure_cb(null);
}
}
Strophe.info("SASL authentication succeeded.");
if(this._sasl_mechanism)
this._sasl_mechanism.onSuccess();
// remove old handlers
this.deleteHandler(this._sasl_failure_handler);
this._sasl_failure_handler = null;
if (this._sasl_challenge_handler) {
this.deleteHandler(this._sasl_challenge_handler);
this._sasl_challenge_handler = null;
}
this._addSysHandler(this._sasl_auth1_cb.bind(this), null,
"stream:features", null, null);
// we must send an xmpp:restart now
this._sendRestart();
return false;
},
/** PrivateFunction: _sasl_auth1_cb
* _Private_ handler to start stream binding.
*
* Parameters:
* (XMLElement) elem - The matching stanza.
*
* Returns:
* false to remove the handler.
*/
_sasl_auth1_cb: function (elem)
{
// save stream:features for future usage
this.features = elem;
var i, child;
for (i = 0; i < elem.childNodes.length; i++) {
child = elem.childNodes[i];
if (child.nodeName == 'bind') {
this.do_bind = true;
}
if (child.nodeName == 'session') {
this.do_session = true;
}
}
if (!this.do_bind) {
this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
return false;
} else {
this._addSysHandler(this._sasl_bind_cb.bind(this), null, null,
null, "_bind_auth_2");
var resource = Strophe.getResourceFromJid(this.jid);
if (resource) {
this.send($iq({type: "set", id: "_bind_auth_2"})
.c('bind', {xmlns: Strophe.NS.BIND})
.c('resource', {}).t(resource).tree());
} else {
this.send($iq({type: "set", id: "_bind_auth_2"})
.c('bind', {xmlns: Strophe.NS.BIND})
.tree());
}
}
return false;
},
/** PrivateFunction: _sasl_bind_cb
* _Private_ handler for binding result and session start.
*
* Parameters:
* (XMLElement) elem - The matching stanza.
*
* Returns:
* false to remove the handler.
*/
_sasl_bind_cb: function (elem)
{
if (elem.getAttribute("type") == "error") {
Strophe.info("SASL binding failed.");
var conflict = elem.getElementsByTagName("conflict"), condition;
if (conflict.length > 0) {
condition = 'conflict';
}
this._changeConnectStatus(Strophe.Status.AUTHFAIL, condition);
return false;
}
// TODO - need to grab errors
var bind = elem.getElementsByTagName("bind");
var jidNode;
if (bind.length > 0) {
// Grab jid
jidNode = bind[0].getElementsByTagName("jid");
if (jidNode.length > 0) {
this.jid = Strophe.getText(jidNode[0]);
if (this.do_session) {
this._addSysHandler(this._sasl_session_cb.bind(this),
null, null, null, "_session_auth_2");
this.send($iq({type: "set", id: "_session_auth_2"})
.c('session', {xmlns: Strophe.NS.SESSION})
.tree());
} else {
this.authenticated = true;
this._changeConnectStatus(Strophe.Status.CONNECTED, null);
}
}
} else {
Strophe.info("SASL binding failed.");
this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
return false;
}
},
/** PrivateFunction: _sasl_session_cb
* _Private_ handler to finish successful SASL connection.
*
* This sets Connection.authenticated to true on success, which
* starts the processing of user handlers.
*
* Parameters:
* (XMLElement) elem - The matching stanza.
*
* Returns:
* false to remove the handler.
*/
_sasl_session_cb: function (elem)
{
if (elem.getAttribute("type") == "result") {
this.authenticated = true;
this._changeConnectStatus(Strophe.Status.CONNECTED, null);
} else if (elem.getAttribute("type") == "error") {
Strophe.info("Session creation failed.");
this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
return false;
}
return false;
},
/** PrivateFunction: _sasl_failure_cb
* _Private_ handler for SASL authentication failure.
*
* Parameters:
* (XMLElement) elem - The matching stanza.
*
* Returns:
* false to remove the handler.
*/
/* jshint unused:false */
_sasl_failure_cb: function (elem)
{
// delete unneeded handlers
if (this._sasl_success_handler) {
this.deleteHandler(this._sasl_success_handler);
this._sasl_success_handler = null;
}
if (this._sasl_challenge_handler) {
this.deleteHandler(this._sasl_challenge_handler);
this._sasl_challenge_handler = null;
}
if(this._sasl_mechanism)
this._sasl_mechanism.onFailure();
this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
return false;
},
/* jshint unused:true */
/** PrivateFunction: _auth2_cb
* _Private_ handler to finish legacy authentication.
*
* This handler is called when the result from the jabber:iq:auth
* <iq/> stanza is returned.
*
* Parameters:
* (XMLElement) elem - The stanza that triggered the callback.
*
* Returns:
* false to remove the handler.
*/
_auth2_cb: function (elem)
{
if (elem.getAttribute("type") == "result") {
this.authenticated = true;
this._changeConnectStatus(Strophe.Status.CONNECTED, null);
} else if (elem.getAttribute("type") == "error") {
this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
this.disconnect('authentication failed');
}
return false;
},
/** PrivateFunction: _addSysTimedHandler
* _Private_ function to add a system level timed handler.
*
* This function is used to add a Strophe.TimedHandler for the
* library code. System timed handlers are allowed to run before
* authentication is complete.
*
* Parameters:
* (Integer) period - The period of the handler.
* (Function) handler - The callback function.
*/
_addSysTimedHandler: function (period, handler)
{
var thand = new Strophe.TimedHandler(period, handler);
thand.user = false;
this.addTimeds.push(thand);
return thand;
},
/** PrivateFunction: _addSysHandler
* _Private_ function to add a system level stanza handler.
*
* This function is used to add a Strophe.Handler for the
* library code. System stanza handlers are allowed to run before
* authentication is complete.
*
* Parameters:
* (Function) handler - The callback function.
* (String) ns - The namespace to match.
* (String) name - The stanza name to match.
* (String) type - The stanza type attribute to match.
* (String) id - The stanza id attribute to match.
*/
_addSysHandler: function (handler, ns, name, type, id)
{
var hand = new Strophe.Handler(handler, ns, name, type, id);
hand.user = false;
this.addHandlers.push(hand);
return hand;
},
/** PrivateFunction: _onDisconnectTimeout
* _Private_ timeout handler for handling non-graceful disconnection.
*
* If the graceful disconnect process does not complete within the
* time allotted, this handler finishes the disconnect anyway.
*
* Returns:
* false to remove the handler.
*/
_onDisconnectTimeout: function ()
{
Strophe.info("_onDisconnectTimeout was called");
this._proto._onDisconnectTimeout();
// actually disconnect
this._doDisconnect();
return false;
},
/** PrivateFunction: _onIdle
* _Private_ handler to process events during idle cycle.
*
* This handler is called every 100ms to fire timed handlers that
* are ready and keep poll requests going.
*/
_onIdle: function ()
{
var i, thand, since, newList;
// add timed handlers scheduled for addition
// NOTE: we add before remove in the case a timed handler is
// added and then deleted before the next _onIdle() call.
while (this.addTimeds.length > 0) {
this.timedHandlers.push(this.addTimeds.pop());
}
// remove timed handlers that have been scheduled for deletion
while (this.removeTimeds.length > 0) {
thand = this.removeTimeds.pop();
i = this.timedHandlers.indexOf(thand);
if (i >= 0) {
this.timedHandlers.splice(i, 1);
}
}
// call ready timed handlers
var now = new Date().getTime();
newList = [];
for (i = 0; i < this.timedHandlers.length; i++) {
thand = this.timedHandlers[i];
if (this.authenticated || !thand.user) {
since = thand.lastCalled + thand.period;
if (since - now <= 0) {
if (thand.run()) {
newList.push(thand);
}
} else {
newList.push(thand);
}
}
}
this.timedHandlers = newList;
clearTimeout(this._idleTimeout);
this._proto._onIdle();
// reactivate the timer only if connected
if (this.connected) {
this._idleTimeout = setTimeout(this._onIdle.bind(this), 100);
}
}
};
if (callback) {
callback(Strophe, $build, $msg, $iq, $pres);
}
/** Class: Strophe.SASLMechanism
*
* encapsulates SASL authentication mechanisms.
*
* User code may override the priority for each mechanism or disable it completely.
* See <priority> for information about changing priority and <test> for informatian on
* how to disable a mechanism.
*
* By default, all mechanisms are enabled and the priorities are
*
* SCRAM-SHA1 - 40
* DIGEST-MD5 - 30
* Plain - 20
*/
/**
* PrivateConstructor: Strophe.SASLMechanism
* SASL auth mechanism abstraction.
*
* Parameters:
* (String) name - SASL Mechanism name.
* (Boolean) isClientFirst - If client should send response first without challenge.
* (Number) priority - Priority.
*
* Returns:
* A new Strophe.SASLMechanism object.
*/
Strophe.SASLMechanism = function(name, isClientFirst, priority) {
/** PrivateVariable: name
* Mechanism name.
*/
this.name = name;
/** PrivateVariable: isClientFirst
* If client sends response without initial server challenge.
*/
this.isClientFirst = isClientFirst;
/** Variable: priority
* Determines which <SASLMechanism> is chosen for authentication (Higher is better).
* Users may override this to prioritize mechanisms differently.
*
* In the default configuration the priorities are
*
* SCRAM-SHA1 - 40
* DIGEST-MD5 - 30
* Plain - 20
*
* Example: (This will cause Strophe to choose the mechanism that the server sent first)
*
* > Strophe.SASLMD5.priority = Strophe.SASLSHA1.priority;
*
* See <SASL mechanisms> for a list of available mechanisms.
*
*/
this.priority = priority;
};
Strophe.SASLMechanism.prototype = {
/**
* Function: test
* Checks if mechanism able to run.
* To disable a mechanism, make this return false;
*
* To disable plain authentication run
* > Strophe.SASLPlain.test = function() {
* > return false;
* > }
*
* See <SASL mechanisms> for a list of available mechanisms.
*
* Parameters:
* (Strophe.Connection) connection - Target Connection.
*
* Returns:
* (Boolean) If mechanism was able to run.
*/
/* jshint unused:false */
test: function(connection) {
return true;
},
/* jshint unused:true */
/** PrivateFunction: onStart
* Called before starting mechanism on some connection.
*
* Parameters:
* (Strophe.Connection) connection - Target Connection.
*/
onStart: function(connection)
{
this._connection = connection;
},
/** PrivateFunction: onChallenge
* Called by protocol implementation on incoming challenge. If client is
* first (isClientFirst == true) challenge will be null on the first call.
*
* Parameters:
* (Strophe.Connection) connection - Target Connection.
* (String) challenge - current challenge to handle.
*
* Returns:
* (String) Mechanism response.
*/
/* jshint unused:false */
onChallenge: function(connection, challenge) {
throw new Error("You should implement challenge handling!");
},
/* jshint unused:true */
/** PrivateFunction: onFailure
* Protocol informs mechanism implementation about SASL failure.
*/
onFailure: function() {
this._connection = null;
},
/** PrivateFunction: onSuccess
* Protocol informs mechanism implementation about SASL success.
*/
onSuccess: function() {
this._connection = null;
}
};
/** Constants: SASL mechanisms
* Available authentication mechanisms
*
* Strophe.SASLAnonymous - SASL Anonymous authentication.
* Strophe.SASLPlain - SASL Plain authentication.
* Strophe.SASLMD5 - SASL Digest-MD5 authentication
* Strophe.SASLSHA1 - SASL SCRAM-SHA1 authentication
*/
// Building SASL callbacks
/** PrivateConstructor: SASLAnonymous
* SASL Anonymous authentication.
*/
Strophe.SASLAnonymous = function() {};
Strophe.SASLAnonymous.prototype = new Strophe.SASLMechanism("ANONYMOUS", false, 10);
Strophe.SASLAnonymous.test = function(connection) {
return connection.authcid === null;
};
Strophe.Connection.prototype.mechanisms[Strophe.SASLAnonymous.prototype.name] = Strophe.SASLAnonymous;
/** PrivateConstructor: SASLPlain
* SASL Plain authentication.
*/
Strophe.SASLPlain = function() {};
Strophe.SASLPlain.prototype = new Strophe.SASLMechanism("PLAIN", true, 20);
Strophe.SASLPlain.test = function(connection) {
return connection.authcid !== null;
};
Strophe.SASLPlain.prototype.onChallenge = function(connection) {
var auth_str = connection.authzid;
auth_str = auth_str + "\u0000";
auth_str = auth_str + connection.authcid;
auth_str = auth_str + "\u0000";
auth_str = auth_str + connection.pass;
return auth_str;
};
Strophe.Connection.prototype.mechanisms[Strophe.SASLPlain.prototype.name] = Strophe.SASLPlain;
/** PrivateConstructor: SASLSHA1
* SASL SCRAM SHA 1 authentication.
*/
Strophe.SASLSHA1 = function() {};
/* TEST:
* This is a simple example of a SCRAM-SHA-1 authentication exchange
* when the client doesn't support channel bindings (username 'user' and
* password 'pencil' are used):
*
* C: n,,n=user,r=fyko+d2lbbFgONRv9qkxdawL
* S: r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,s=QSXCR+Q6sek8bf92,
* i=4096
* C: c=biws,r=fyko+d2lbbFgONRv9qkxdawL3rfcNHYJY1ZVvWVs7j,
* p=v0X8v3Bz2T0CJGbJQyF0X+HI4Ts=
* S: v=rmF9pqV8S7suAoZWja4dJRkFsKQ=
*
*/
Strophe.SASLSHA1.prototype = new Strophe.SASLMechanism("SCRAM-SHA-1", true, 40);
Strophe.SASLSHA1.test = function(connection) {
return connection.authcid !== null;
};
Strophe.SASLSHA1.prototype.onChallenge = function(connection, challenge, test_cnonce) {
var cnonce = test_cnonce || MD5.hexdigest(Math.random() * 1234567890);
var auth_str = "n=" + connection.authcid;
auth_str += ",r=";
auth_str += cnonce;
connection._sasl_data.cnonce = cnonce;
connection._sasl_data["client-first-message-bare"] = auth_str;
auth_str = "n,," + auth_str;
this.onChallenge = function (connection, challenge)
{
var nonce, salt, iter, Hi, U, U_old, i, k;
var clientKey, serverKey, clientSignature;
var responseText = "c=biws,";
var authMessage = connection._sasl_data["client-first-message-bare"] + "," +
challenge + ",";
var cnonce = connection._sasl_data.cnonce;
var attribMatch = /([a-z]+)=([^,]+)(,|$)/;
while (challenge.match(attribMatch)) {
var matches = challenge.match(attribMatch);
challenge = challenge.replace(matches[0], "");
switch (matches[1]) {
case "r":
nonce = matches[2];
break;
case "s":
salt = matches[2];
break;
case "i":
iter = matches[2];
break;
}
}
if (nonce.substr(0, cnonce.length) !== cnonce) {
connection._sasl_data = {};
return connection._sasl_failure_cb();
}
responseText += "r=" + nonce;
authMessage += responseText;
salt = Base64.decode(salt);
salt += "\x00\x00\x00\x01";
Hi = U_old = core_hmac_sha1(connection.pass, salt);
for (i = 1; i < iter; i++) {
U = core_hmac_sha1(connection.pass, binb2str(U_old));
for (k = 0; k < 5; k++) {
Hi[k] ^= U[k];
}
U_old = U;
}
Hi = binb2str(Hi);
clientKey = core_hmac_sha1(Hi, "Client Key");
serverKey = str_hmac_sha1(Hi, "Server Key");
clientSignature = core_hmac_sha1(str_sha1(binb2str(clientKey)), authMessage);
connection._sasl_data["server-signature"] = b64_hmac_sha1(serverKey, authMessage);
for (k = 0; k < 5; k++) {
clientKey[k] ^= clientSignature[k];
}
responseText += ",p=" + Base64.encode(binb2str(clientKey));
return responseText;
}.bind(this);
return auth_str;
};
Strophe.Connection.prototype.mechanisms[Strophe.SASLSHA1.prototype.name] = Strophe.SASLSHA1;
/** PrivateConstructor: SASLMD5
* SASL DIGEST MD5 authentication.
*/
Strophe.SASLMD5 = function() {};
Strophe.SASLMD5.prototype = new Strophe.SASLMechanism("DIGEST-MD5", false, 30);
Strophe.SASLMD5.test = function(connection) {
return connection.authcid !== null;
};
/** PrivateFunction: _quote
* _Private_ utility function to backslash escape and quote strings.
*
* Parameters:
* (String) str - The string to be quoted.
*
* Returns:
* quoted string
*/
Strophe.SASLMD5.prototype._quote = function (str)
{
return '"' + str.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"';
//" end string workaround for emacs
};
Strophe.SASLMD5.prototype.onChallenge = function(connection, challenge, test_cnonce) {
var attribMatch = /([a-z]+)=("[^"]+"|[^,"]+)(?:,|$)/;
var cnonce = test_cnonce || MD5.hexdigest("" + (Math.random() * 1234567890));
var realm = "";
var host = null;
var nonce = "";
var qop = "";
var matches;
while (challenge.match(attribMatch)) {
matches = challenge.match(attribMatch);
challenge = challenge.replace(matches[0], "");
matches[2] = matches[2].replace(/^"(.+)"$/, "$1");
switch (matches[1]) {
case "realm":
realm = matches[2];
break;
case "nonce":
nonce = matches[2];
break;
case "qop":
qop = matches[2];
break;
case "host":
host = matches[2];
break;
}
}
var digest_uri = connection.servtype + "/" + connection.domain;
if (host !== null) {
digest_uri = digest_uri + "/" + host;
}
var A1 = MD5.hash(connection.authcid +
":" + realm + ":" + this._connection.pass) +
":" + nonce + ":" + cnonce;
var A2 = 'AUTHENTICATE:' + digest_uri;
var responseText = "";
responseText += 'charset=utf-8,';
responseText += 'username=' +
this._quote(connection.authcid) + ',';
responseText += 'realm=' + this._quote(realm) + ',';
responseText += 'nonce=' + this._quote(nonce) + ',';
responseText += 'nc=00000001,';
responseText += 'cnonce=' + this._quote(cnonce) + ',';
responseText += 'digest-uri=' + this._quote(digest_uri) + ',';
responseText += 'response=' + MD5.hexdigest(MD5.hexdigest(A1) + ":" +
nonce + ":00000001:" +
cnonce + ":auth:" +
MD5.hexdigest(A2)) + ",";
responseText += 'qop=auth';
this.onChallenge = function ()
{
return "";
}.bind(this);
return responseText;
};
Strophe.Connection.prototype.mechanisms[Strophe.SASLMD5.prototype.name] = Strophe.SASLMD5;
})(function () {
window.Strophe = arguments[0];
window.$build = arguments[1];
window.$msg = arguments[2];
window.$iq = arguments[3];
window.$pres = arguments[4];
});
/*
This program is distributed under the terms of the MIT license.
Please see the LICENSE file for details.
Copyright 2006-2008, OGG, LLC
*/
/* jshint undef: true, unused: true:, noarg: true, latedef: true */
/*global window, setTimeout, clearTimeout,
XMLHttpRequest, ActiveXObject,
Strophe, $build */
/** PrivateClass: Strophe.Request
* _Private_ helper class that provides a cross implementation abstraction
* for a BOSH related XMLHttpRequest.
*
* The Strophe.Request class is used internally to encapsulate BOSH request
* information. It is not meant to be used from user's code.
*/
/** PrivateConstructor: Strophe.Request
* Create and initialize a new Strophe.Request object.
*
* Parameters:
* (XMLElement) elem - The XML data to be sent in the request.
* (Function) func - The function that will be called when the
* XMLHttpRequest readyState changes.
* (Integer) rid - The BOSH rid attribute associated with this request.
* (Integer) sends - The number of times this same request has been
* sent.
*/
Strophe.Request = function (elem, func, rid, sends)
{
this.id = ++Strophe._requestId;
this.xmlData = elem;
this.data = Strophe.serialize(elem);
// save original function in case we need to make a new request
// from this one.
this.origFunc = func;
this.func = func;
this.rid = rid;
this.date = NaN;
this.sends = sends || 0;
this.abort = false;
this.dead = null;
this.age = function () {
if (!this.date) { return 0; }
var now = new Date();
return (now - this.date) / 1000;
};
this.timeDead = function () {
if (!this.dead) { return 0; }
var now = new Date();
return (now - this.dead) / 1000;
};
this.xhr = this._newXHR();
};
Strophe.Request.prototype = {
/** PrivateFunction: getResponse
* Get a response from the underlying XMLHttpRequest.
*
* This function attempts to get a response from the request and checks
* for errors.
*
* Throws:
* "parsererror" - A parser error occured.
*
* Returns:
* The DOM element tree of the response.
*/
getResponse: function ()
{
var node = null;
if (this.xhr.responseXML && this.xhr.responseXML.documentElement) {
node = this.xhr.responseXML.documentElement;
if (node.tagName == "parsererror") {
Strophe.error("invalid response received");
Strophe.error("responseText: " + this.xhr.responseText);
Strophe.error("responseXML: " +
Strophe.serialize(this.xhr.responseXML));
throw "parsererror";
}
} else if (this.xhr.responseText) {
Strophe.error("invalid response received");
Strophe.error("responseText: " + this.xhr.responseText);
Strophe.error("responseXML: " +
Strophe.serialize(this.xhr.responseXML));
}
return node;
},
/** PrivateFunction: _newXHR
* _Private_ helper function to create XMLHttpRequests.
*
* This function creates XMLHttpRequests across all implementations.
*
* Returns:
* A new XMLHttpRequest.
*/
_newXHR: function ()
{
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
if (xhr.overrideMimeType) {
xhr.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// use Function.bind() to prepend ourselves as an argument
xhr.onreadystatechange = this.func.bind(null, this);
return xhr;
}
};
/** Class: Strophe.Bosh
* _Private_ helper class that handles BOSH Connections
*
* The Strophe.Bosh class is used internally by Strophe.Connection
* to encapsulate BOSH sessions. It is not meant to be used from user's code.
*/
/** File: bosh.js
* A JavaScript library to enable BOSH in Strophejs.
*
* this library uses Bidirectional-streams Over Synchronous HTTP (BOSH)
* to emulate a persistent, stateful, two-way connection to an XMPP server.
* More information on BOSH can be found in XEP 124.
*/
/** PrivateConstructor: Strophe.Bosh
* Create and initialize a Strophe.Bosh object.
*
* Parameters:
* (Strophe.Connection) connection - The Strophe.Connection that will use BOSH.
*
* Returns:
* A new Strophe.Bosh object.
*/
Strophe.Bosh = function(connection) {
this._conn = connection;
/* request id for body tags */
this.rid = Math.floor(Math.random() * 4294967295);
/* The current session ID. */
this.sid = null;
// default BOSH values
this.hold = 1;
this.wait = 60;
this.window = 5;
this._requests = [];
};
Strophe.Bosh.prototype = {
/** Variable: strip
*
* BOSH-Connections will have all stanzas wrapped in a <body> tag when
* passed to <Strophe.Connection.xmlInput> or <Strophe.Connection.xmlOutput>.
* To strip this tag, User code can set <Strophe.Bosh.strip> to "body":
*
* > Strophe.Bosh.prototype.strip = "body";
*
* This will enable stripping of the body tag in both
* <Strophe.Connection.xmlInput> and <Strophe.Connection.xmlOutput>.
*/
strip: null,
/** PrivateFunction: _buildBody
* _Private_ helper function to generate the <body/> wrapper for BOSH.
*
* Returns:
* A Strophe.Builder with a <body/> element.
*/
_buildBody: function ()
{
var bodyWrap = $build('body', {
rid: this.rid++,
xmlns: Strophe.NS.HTTPBIND
});
if (this.sid !== null) {
bodyWrap.attrs({sid: this.sid});
}
return bodyWrap;
},
/** PrivateFunction: _reset
* Reset the connection.
*
* This function is called by the reset function of the Strophe Connection
*/
_reset: function ()
{
this.rid = Math.floor(Math.random() * 4294967295);
this.sid = null;
},
/** PrivateFunction: _connect
* _Private_ function that initializes the BOSH connection.
*
* Creates and sends the Request that initializes the BOSH connection.
*/
_connect: function (wait, hold, route)
{
this.wait = wait || this.wait;
this.hold = hold || this.hold;
// build the body tag
var body = this._buildBody().attrs({
to: this._conn.domain,
"xml:lang": "en",
wait: this.wait,
hold: this.hold,
content: "text/xml; charset=utf-8",
ver: "1.6",
"xmpp:version": "1.0",
"xmlns:xmpp": Strophe.NS.BOSH
});
if(route){
body.attrs({
route: route
});
}
var _connect_cb = this._conn._connect_cb;
this._requests.push(
new Strophe.Request(body.tree(),
this._onRequestStateChange.bind(
this, _connect_cb.bind(this._conn)),
body.tree().getAttribute("rid")));
this._throttledRequestHandler();
},
/** PrivateFunction: _attach
* Attach to an already created and authenticated BOSH session.
*
* This function is provided to allow Strophe to attach to BOSH
* sessions which have been created externally, perhaps by a Web
* application. This is often used to support auto-login type features
* without putting user credentials into the page.
*
* Parameters:
* (String) jid - The full JID that is bound by the session.
* (String) sid - The SID of the BOSH session.
* (String) rid - The current RID of the BOSH session. This RID
* will be used by the next request.
* (Function) callback The connect callback function.
* (Integer) wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* Other settings will require tweaks to the Strophe.TIMEOUT value.
* (Integer) hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* (Integer) wind - The optional HTTBIND window value. This is the
* allowed range of request ids that are valid. The default is 5.
*/
_attach: function (jid, sid, rid, callback, wait, hold, wind)
{
this._conn.jid = jid;
this.sid = sid;
this.rid = rid;
this._conn.connect_callback = callback;
this._conn.domain = Strophe.getDomainFromJid(this._conn.jid);
this._conn.authenticated = true;
this._conn.connected = true;
this.wait = wait || this.wait;
this.hold = hold || this.hold;
this.window = wind || this.window;
this._conn._changeConnectStatus(Strophe.Status.ATTACHED, null);
},
/** PrivateFunction: _connect_cb
* _Private_ handler for initial connection request.
*
* This handler is used to process the Bosh-part of the initial request.
* Parameters:
* (Strophe.Request) bodyWrap - The received stanza.
*/
_connect_cb: function (bodyWrap)
{
var typ = bodyWrap.getAttribute("type");
var cond, conflict;
if (typ !== null && typ == "terminate") {
// an error occurred
Strophe.error("BOSH-Connection failed: " + cond);
cond = bodyWrap.getAttribute("condition");
conflict = bodyWrap.getElementsByTagName("conflict");
if (cond !== null) {
if (cond == "remote-stream-error" && conflict.length > 0) {
cond = "conflict";
}
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, cond);
} else {
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown");
}
this._conn._doDisconnect();
return Strophe.Status.CONNFAIL;
}
// check to make sure we don't overwrite these if _connect_cb is
// called multiple times in the case of missing stream:features
if (!this.sid) {
this.sid = bodyWrap.getAttribute("sid");
}
var wind = bodyWrap.getAttribute('requests');
if (wind) { this.window = parseInt(wind, 10); }
var hold = bodyWrap.getAttribute('hold');
if (hold) { this.hold = parseInt(hold, 10); }
var wait = bodyWrap.getAttribute('wait');
if (wait) { this.wait = parseInt(wait, 10); }
},
/** PrivateFunction: _disconnect
* _Private_ part of Connection.disconnect for Bosh
*
* Parameters:
* (Request) pres - This stanza will be sent before disconnecting.
*/
_disconnect: function (pres)
{
this._sendTerminate(pres);
},
/** PrivateFunction: _doDisconnect
* _Private_ function to disconnect.
*
* Resets the SID and RID.
*/
_doDisconnect: function ()
{
this.sid = null;
this.rid = Math.floor(Math.random() * 4294967295);
},
/** PrivateFunction: _emptyQueue
* _Private_ function to check if the Request queue is empty.
*
* Returns:
* True, if there are no Requests queued, False otherwise.
*/
_emptyQueue: function ()
{
return this._requests.length === 0;
},
/** PrivateFunction: _hitError
* _Private_ function to handle the error count.
*
* Requests are resent automatically until their error count reaches
* 5. Each time an error is encountered, this function is called to
* increment the count and disconnect if the count is too high.
*
* Parameters:
* (Integer) reqStatus - The request status.
*/
_hitError: function (reqStatus)
{
this.errors++;
Strophe.warn("request errored, status: " + reqStatus +
", number of errors: " + this.errors);
if (this.errors > 4) {
this._onDisconnectTimeout();
}
},
/** PrivateFunction: _no_auth_received
*
* Called on stream start/restart when no stream:features
* has been received and sends a blank poll request.
*/
_no_auth_received: function (_callback)
{
if (_callback) {
_callback = _callback.bind(this._conn);
} else {
_callback = this._conn._connect_cb.bind(this._conn);
}
var body = this._buildBody();
this._requests.push(
new Strophe.Request(body.tree(),
this._onRequestStateChange.bind(
this, _callback.bind(this._conn)),
body.tree().getAttribute("rid")));
this._throttledRequestHandler();
},
/** PrivateFunction: _onDisconnectTimeout
* _Private_ timeout handler for handling non-graceful disconnection.
*
* Cancels all remaining Requests and clears the queue.
*/
_onDisconnectTimeout: function ()
{
var req;
while (this._requests.length > 0) {
req = this._requests.pop();
req.abort = true;
req.xhr.abort();
// jslint complains, but this is fine. setting to empty func
// is necessary for IE6
req.xhr.onreadystatechange = function () {}; // jshint ignore:line
}
},
/** PrivateFunction: _onIdle
* _Private_ handler called by Strophe.Connection._onIdle
*
* Sends all queued Requests or polls with empty Request if there are none.
*/
_onIdle: function () {
var data = this._conn._data;
// if no requests are in progress, poll
if (this._conn.authenticated && this._requests.length === 0 &&
data.length === 0 && !this._conn.disconnecting) {
Strophe.info("no requests during idle cycle, sending " +
"blank request");
data.push(null);
}
if (this._requests.length < 2 && data.length > 0 &&
!this._conn.paused) {
var body = this._buildBody();
for (var i = 0; i < data.length; i++) {
if (data[i] !== null) {
if (data[i] === "restart") {
body.attrs({
to: this._conn.domain,
"xml:lang": "en",
"xmpp:restart": "true",
"xmlns:xmpp": Strophe.NS.BOSH
});
} else {
body.cnode(data[i]).up();
}
}
}
delete this._conn._data;
this._conn._data = [];
this._requests.push(
new Strophe.Request(body.tree(),
this._onRequestStateChange.bind(
this, this._conn._dataRecv.bind(this._conn)),
body.tree().getAttribute("rid")));
this._processRequest(this._requests.length - 1);
}
if (this._requests.length > 0) {
var time_elapsed = this._requests[0].age();
if (this._requests[0].dead !== null) {
if (this._requests[0].timeDead() >
Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)) {
this._throttledRequestHandler();
}
}
if (time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait)) {
Strophe.warn("Request " +
this._requests[0].id +
" timed out, over " + Math.floor(Strophe.TIMEOUT * this.wait) +
" seconds since last activity");
this._throttledRequestHandler();
}
}
},
/** PrivateFunction: _onRequestStateChange
* _Private_ handler for Strophe.Request state changes.
*
* This function is called when the XMLHttpRequest readyState changes.
* It contains a lot of error handling logic for the many ways that
* requests can fail, and calls the request callback when requests
* succeed.
*
* Parameters:
* (Function) func - The handler for the request.
* (Strophe.Request) req - The request that is changing readyState.
*/
_onRequestStateChange: function (func, req)
{
Strophe.debug("request id " + req.id +
"." + req.sends + " state changed to " +
req.xhr.readyState);
if (req.abort) {
req.abort = false;
return;
}
// request complete
var reqStatus;
if (req.xhr.readyState == 4) {
reqStatus = 0;
try {
reqStatus = req.xhr.status;
} catch (e) {
// ignore errors from undefined status attribute. works
// around a browser bug
}
if (typeof(reqStatus) == "undefined") {
reqStatus = 0;
}
if (this.disconnecting) {
if (reqStatus >= 400) {
this._hitError(reqStatus);
return;
}
}
var reqIs0 = (this._requests[0] == req);
var reqIs1 = (this._requests[1] == req);
if ((reqStatus > 0 && reqStatus < 500) || req.sends > 5) {
// remove from internal queue
this._removeRequest(req);
Strophe.debug("request id " +
req.id +
" should now be removed");
}
// request succeeded
if (reqStatus == 200) {
// if request 1 finished, or request 0 finished and request
// 1 is over Strophe.SECONDARY_TIMEOUT seconds old, we need to
// restart the other - both will be in the first spot, as the
// completed request has been removed from the queue already
if (reqIs1 ||
(reqIs0 && this._requests.length > 0 &&
this._requests[0].age() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait))) {
this._restartRequest(0);
}
// call handler
Strophe.debug("request id " +
req.id + "." +
req.sends + " got 200");
func(req);
this.errors = 0;
} else {
Strophe.error("request id " +
req.id + "." +
req.sends + " error " + reqStatus +
" happened");
if (reqStatus === 0 ||
(reqStatus >= 400 && reqStatus < 600) ||
reqStatus >= 12000) {
this._hitError(reqStatus);
if (reqStatus >= 400 && reqStatus < 500) {
this._conn._changeConnectStatus(Strophe.Status.DISCONNECTING,
null);
this._conn._doDisconnect();
}
}
}
if (!((reqStatus > 0 && reqStatus < 500) ||
req.sends > 5)) {
this._throttledRequestHandler();
}
}
},
/** PrivateFunction: _processRequest
* _Private_ function to process a request in the queue.
*
* This function takes requests off the queue and sends them and
* restarts dead requests.
*
* Parameters:
* (Integer) i - The index of the request in the queue.
*/
_processRequest: function (i)
{
var self = this;
var req = this._requests[i];
var reqStatus = -1;
try {
if (req.xhr.readyState == 4) {
reqStatus = req.xhr.status;
}
} catch (e) {
Strophe.error("caught an error in _requests[" + i +
"], reqStatus: " + reqStatus);
}
if (typeof(reqStatus) == "undefined") {
reqStatus = -1;
}
// make sure we limit the number of retries
if (req.sends > this.maxRetries) {
this._onDisconnectTimeout();
return;
}
var time_elapsed = req.age();
var primaryTimeout = (!isNaN(time_elapsed) &&
time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait));
var secondaryTimeout = (req.dead !== null &&
req.timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait));
var requestCompletedWithServerError = (req.xhr.readyState == 4 &&
(reqStatus < 1 ||
reqStatus >= 500));
if (primaryTimeout || secondaryTimeout ||
requestCompletedWithServerError) {
if (secondaryTimeout) {
Strophe.error("Request " +
this._requests[i].id +
" timed out (secondary), restarting");
}
req.abort = true;
req.xhr.abort();
// setting to null fails on IE6, so set to empty function
req.xhr.onreadystatechange = function () {};
this._requests[i] = new Strophe.Request(req.xmlData,
req.origFunc,
req.rid,
req.sends);
req = this._requests[i];
}
if (req.xhr.readyState === 0) {
Strophe.debug("request id " + req.id +
"." + req.sends + " posting");
try {
req.xhr.open("POST", this._conn.service, this._conn.options.sync ? false : true);
} catch (e2) {
Strophe.error("XHR open failed.");
if (!this._conn.connected) {
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,
"bad-service");
}
this._conn.disconnect();
return;
}
// Fires the XHR request -- may be invoked immediately
// or on a gradually expanding retry window for reconnects
var sendFunc = function () {
req.date = new Date();
if (self._conn.options.customHeaders){
var headers = self._conn.options.customHeaders;
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
req.xhr.setRequestHeader(header, headers[header]);
}
}
}
req.xhr.send(req.data);
};
// Implement progressive backoff for reconnects --
// First retry (send == 1) should also be instantaneous
if (req.sends > 1) {
// Using a cube of the retry number creates a nicely
// expanding retry window
var backoff = Math.min(Math.floor(Strophe.TIMEOUT * this.wait),
Math.pow(req.sends, 3)) * 1000;
setTimeout(sendFunc, backoff);
} else {
sendFunc();
}
req.sends++;
if (this._conn.xmlOutput !== Strophe.Connection.prototype.xmlOutput) {
if (req.xmlData.nodeName === this.strip && req.xmlData.childNodes.length) {
this._conn.xmlOutput(req.xmlData.childNodes[0]);
} else {
this._conn.xmlOutput(req.xmlData);
}
}
if (this._conn.rawOutput !== Strophe.Connection.prototype.rawOutput) {
this._conn.rawOutput(req.data);
}
} else {
Strophe.debug("_processRequest: " +
(i === 0 ? "first" : "second") +
" request has readyState of " +
req.xhr.readyState);
}
},
/** PrivateFunction: _removeRequest
* _Private_ function to remove a request from the queue.
*
* Parameters:
* (Strophe.Request) req - The request to remove.
*/
_removeRequest: function (req)
{
Strophe.debug("removing request");
var i;
for (i = this._requests.length - 1; i >= 0; i--) {
if (req == this._requests[i]) {
this._requests.splice(i, 1);
}
}
// IE6 fails on setting to null, so set to empty function
req.xhr.onreadystatechange = function () {};
this._throttledRequestHandler();
},
/** PrivateFunction: _restartRequest
* _Private_ function to restart a request that is presumed dead.
*
* Parameters:
* (Integer) i - The index of the request in the queue.
*/
_restartRequest: function (i)
{
var req = this._requests[i];
if (req.dead === null) {
req.dead = new Date();
}
this._processRequest(i);
},
/** PrivateFunction: _reqToData
* _Private_ function to get a stanza out of a request.
*
* Tries to extract a stanza out of a Request Object.
* When this fails the current connection will be disconnected.
*
* Parameters:
* (Object) req - The Request.
*
* Returns:
* The stanza that was passed.
*/
_reqToData: function (req)
{
try {
return req.getResponse();
} catch (e) {
if (e != "parsererror") { throw e; }
this._conn.disconnect("strophe-parsererror");
}
},
/** PrivateFunction: _sendTerminate
* _Private_ function to send initial disconnect sequence.
*
* This is the first step in a graceful disconnect. It sends
* the BOSH server a terminate body and includes an unavailable
* presence if authentication has completed.
*/
_sendTerminate: function (pres)
{
Strophe.info("_sendTerminate was called");
var body = this._buildBody().attrs({type: "terminate"});
if (pres) {
body.cnode(pres.tree());
}
var req = new Strophe.Request(body.tree(),
this._onRequestStateChange.bind(
this, this._conn._dataRecv.bind(this._conn)),
body.tree().getAttribute("rid"));
this._requests.push(req);
this._throttledRequestHandler();
},
/** PrivateFunction: _send
* _Private_ part of the Connection.send function for BOSH
*
* Just triggers the RequestHandler to send the messages that are in the queue
*/
_send: function () {
clearTimeout(this._conn._idleTimeout);
this._throttledRequestHandler();
this._conn._idleTimeout = setTimeout(this._conn._onIdle.bind(this._conn), 100);
},
/** PrivateFunction: _sendRestart
*
* Send an xmpp:restart stanza.
*/
_sendRestart: function ()
{
this._throttledRequestHandler();
clearTimeout(this._conn._idleTimeout);
},
/** PrivateFunction: _throttledRequestHandler
* _Private_ function to throttle requests to the connection window.
*
* This function makes sure we don't send requests so fast that the
* request ids overflow the connection window in the case that one
* request died.
*/
_throttledRequestHandler: function ()
{
if (!this._requests) {
Strophe.debug("_throttledRequestHandler called with " +
"undefined requests");
} else {
Strophe.debug("_throttledRequestHandler called with " +
this._requests.length + " requests");
}
if (!this._requests || this._requests.length === 0) {
return;
}
if (this._requests.length > 0) {
this._processRequest(0);
}
if (this._requests.length > 1 &&
Math.abs(this._requests[0].rid -
this._requests[1].rid) < this.window) {
this._processRequest(1);
}
}
};
/*
This program is distributed under the terms of the MIT license.
Please see the LICENSE file for details.
Copyright 2006-2008, OGG, LLC
*/
/* jshint undef: true, unused: true:, noarg: true, latedef: true */
/*global document, window, clearTimeout, WebSocket,
DOMParser, Strophe, $build */
/** Class: Strophe.WebSocket
* _Private_ helper class that handles WebSocket Connections
*
* The Strophe.WebSocket class is used internally by Strophe.Connection
* to encapsulate WebSocket sessions. It is not meant to be used from user's code.
*/
/** File: websocket.js
* A JavaScript library to enable XMPP over Websocket in Strophejs.
*
* This file implements XMPP over WebSockets for Strophejs.
* If a Connection is established with a Websocket url (ws://...)
* Strophe will use WebSockets.
* For more information on XMPP-over WebSocket see this RFC draft:
* http://tools.ietf.org/html/draft-ietf-xmpp-websocket-00
*
* WebSocket support implemented by Andreas Guth ([email protected])
*/
/** PrivateConstructor: Strophe.Websocket
* Create and initialize a Strophe.WebSocket object.
* Currently only sets the connection Object.
*
* Parameters:
* (Strophe.Connection) connection - The Strophe.Connection that will use WebSockets.
*
* Returns:
* A new Strophe.WebSocket object.
*/
Strophe.Websocket = function(connection) {
this._conn = connection;
this.strip = "stream:stream";
var service = connection.service;
if (service.indexOf("ws:") !== 0 && service.indexOf("wss:") !== 0) {
// If the service is not an absolute URL, assume it is a path and put the absolute
// URL together from options, current URL and the path.
var new_service = "";
if (connection.options.protocol === "ws" && window.location.protocol !== "https:") {
new_service += "ws";
} else {
new_service += "wss";
}
new_service += "://" + window.location.host;
if (service.indexOf("/") !== 0) {
new_service += window.location.pathname + service;
} else {
new_service += service;
}
connection.service = new_service;
}
};
Strophe.Websocket.prototype = {
/** PrivateFunction: _buildStream
* _Private_ helper function to generate the <stream> start tag for WebSockets
*
* Returns:
* A Strophe.Builder with a <stream> element.
*/
_buildStream: function ()
{
return $build("stream:stream", {
"to": this._conn.domain,
"xmlns": Strophe.NS.CLIENT,
"xmlns:stream": Strophe.NS.STREAM,
"version": '1.0'
});
},
/** PrivateFunction: _check_streamerror
* _Private_ checks a message for stream:error
*
* Parameters:
* (Strophe.Request) bodyWrap - The received stanza.
* connectstatus - The ConnectStatus that will be set on error.
* Returns:
* true if there was a streamerror, false otherwise.
*/
_check_streamerror: function (bodyWrap, connectstatus) {
var errors = bodyWrap.getElementsByTagName("stream:error");
if (errors.length === 0) {
return false;
}
var error = errors[0];
var condition = "";
var text = "";
var ns = "urn:ietf:params:xml:ns:xmpp-streams";
for (var i = 0; i < error.childNodes.length; i++) {
var e = error.childNodes[i];
if (e.getAttribute("xmlns") !== ns) {
break;
} if (e.nodeName === "text") {
text = e.textContent;
} else {
condition = e.nodeName;
}
}
var errorString = "WebSocket stream error: ";
if (condition) {
errorString += condition;
} else {
errorString += "unknown";
}
if (text) {
errorString += " - " + condition;
}
Strophe.error(errorString);
// close the connection on stream_error
this._conn._changeConnectStatus(connectstatus, condition);
this._conn._doDisconnect();
return true;
},
/** PrivateFunction: _reset
* Reset the connection.
*
* This function is called by the reset function of the Strophe Connection.
* Is not needed by WebSockets.
*/
_reset: function ()
{
return;
},
/** PrivateFunction: _connect
* _Private_ function called by Strophe.Connection.connect
*
* Creates a WebSocket for a connection and assigns Callbacks to it.
* Does nothing if there already is a WebSocket.
*/
_connect: function () {
// Ensure that there is no open WebSocket from a previous Connection.
this._closeSocket();
// Create the new WobSocket
this.socket = new WebSocket(this._conn.service, "xmpp");
this.socket.onopen = this._onOpen.bind(this);
this.socket.onerror = this._onError.bind(this);
this.socket.onclose = this._onClose.bind(this);
this.socket.onmessage = this._connect_cb_wrapper.bind(this);
},
/** PrivateFunction: _connect_cb
* _Private_ function called by Strophe.Connection._connect_cb
*
* checks for stream:error
*
* Parameters:
* (Strophe.Request) bodyWrap - The received stanza.
*/
_connect_cb: function(bodyWrap) {
var error = this._check_streamerror(bodyWrap, Strophe.Status.CONNFAIL);
if (error) {
return Strophe.Status.CONNFAIL;
}
},
/** PrivateFunction: _handleStreamStart
* _Private_ function that checks the opening stream:stream tag for errors.
*
* Disconnects if there is an error and returns false, true otherwise.
*
* Parameters:
* (Node) message - Stanza containing the stream:stream.
*/
_handleStreamStart: function(message) {
var error = false;
// Check for errors in the stream:stream tag
var ns = message.getAttribute("xmlns");
if (typeof ns !== "string") {
error = "Missing xmlns in stream:stream";
} else if (ns !== Strophe.NS.CLIENT) {
error = "Wrong xmlns in stream:stream: " + ns;
}
var ns_stream = message.namespaceURI;
if (typeof ns_stream !== "string") {
error = "Missing xmlns:stream in stream:stream";
} else if (ns_stream !== Strophe.NS.STREAM) {
error = "Wrong xmlns:stream in stream:stream: " + ns_stream;
}
var ver = message.getAttribute("version");
if (typeof ver !== "string") {
error = "Missing version in stream:stream";
} else if (ver !== "1.0") {
error = "Wrong version in stream:stream: " + ver;
}
if (error) {
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, error);
this._conn._doDisconnect();
return false;
}
return true;
},
/** PrivateFunction: _connect_cb_wrapper
* _Private_ function that handles the first connection messages.
*
* On receiving an opening stream tag this callback replaces itself with the real
* message handler. On receiving a stream error the connection is terminated.
*/
_connect_cb_wrapper: function(message) {
if (message.data.indexOf("<stream:stream ") === 0 || message.data.indexOf("<?xml") === 0) {
// Strip the XML Declaration, if there is one
var data = message.data.replace(/^(<\?.*?\?>\s*)*/, "");
if (data === '') return;
//Make the initial stream:stream selfclosing to parse it without a SAX parser.
data = message.data.replace(/<stream:stream (.*[^\/])>/, "<stream:stream $1/>");
var streamStart = new DOMParser().parseFromString(data, "text/xml").documentElement;
this._conn.xmlInput(streamStart);
this._conn.rawInput(message.data);
//_handleStreamSteart will check for XML errors and disconnect on error
if (this._handleStreamStart(streamStart)) {
//_connect_cb will check for stream:error and disconnect on error
this._connect_cb(streamStart);
// ensure received stream:stream is NOT selfclosing and save it for following messages
this.streamStart = message.data.replace(/^<stream:(.*)\/>$/, "<stream:$1>");
}
} else if (message.data === "</stream:stream>") {
this._conn.rawInput(message.data);
this._conn.xmlInput(document.createElement("stream:stream"));
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "Received closing stream");
this._conn._doDisconnect();
return;
} else {
var string = this._streamWrap(message.data);
var elem = new DOMParser().parseFromString(string, "text/xml").documentElement;
this.socket.onmessage = this._onMessage.bind(this);
this._conn._connect_cb(elem, null, message.data);
}
},
/** PrivateFunction: _disconnect
* _Private_ function called by Strophe.Connection.disconnect
*
* Disconnects and sends a last stanza if one is given
*
* Parameters:
* (Request) pres - This stanza will be sent before disconnecting.
*/
_disconnect: function (pres)
{
if (this.socket.readyState !== WebSocket.CLOSED) {
if (pres) {
this._conn.send(pres);
}
var close = '</stream:stream>';
this._conn.xmlOutput(document.createElement("stream:stream"));
this._conn.rawOutput(close);
try {
this.socket.send(close);
} catch (e) {
Strophe.info("Couldn't send closing stream tag.");
}
}
this._conn._doDisconnect();
},
/** PrivateFunction: _doDisconnect
* _Private_ function to disconnect.
*
* Just closes the Socket for WebSockets
*/
_doDisconnect: function ()
{
Strophe.info("WebSockets _doDisconnect was called");
this._closeSocket();
},
/** PrivateFunction _streamWrap
* _Private_ helper function to wrap a stanza in a <stream> tag.
* This is used so Strophe can process stanzas from WebSockets like BOSH
*/
_streamWrap: function (stanza)
{
return this.streamStart + stanza + '</stream:stream>';
},
/** PrivateFunction: _closeSocket
* _Private_ function to close the WebSocket.
*
* Closes the socket if it is still open and deletes it
*/
_closeSocket: function ()
{
if (this.socket) { try {
this.socket.close();
} catch (e) {} }
this.socket = null;
},
/** PrivateFunction: _emptyQueue
* _Private_ function to check if the message queue is empty.
*
* Returns:
* True, because WebSocket messages are send immediately after queueing.
*/
_emptyQueue: function ()
{
return true;
},
/** PrivateFunction: _onClose
* _Private_ function to handle websockets closing.
*
* Nothing to do here for WebSockets
*/
_onClose: function() {
if(this._conn.connected && !this._conn.disconnecting) {
Strophe.error("Websocket closed unexcectedly");
this._conn._doDisconnect();
} else {
Strophe.info("Websocket closed");
}
},
/** PrivateFunction: _no_auth_received
*
* Called on stream start/restart when no stream:features
* has been received.
*/
_no_auth_received: function (_callback)
{
Strophe.error("Server did not send any auth methods");
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "Server did not send any auth methods");
if (_callback) {
_callback = _callback.bind(this._conn);
_callback();
}
this._conn._doDisconnect();
},
/** PrivateFunction: _onDisconnectTimeout
* _Private_ timeout handler for handling non-graceful disconnection.
*
* This does nothing for WebSockets
*/
_onDisconnectTimeout: function () {},
/** PrivateFunction: _onError
* _Private_ function to handle websockets errors.
*
* Parameters:
* (Object) error - The websocket error.
*/
_onError: function(error) {
Strophe.error("Websocket error " + error);
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "The WebSocket connection could not be established was disconnected.");
this._disconnect();
},
/** PrivateFunction: _onIdle
* _Private_ function called by Strophe.Connection._onIdle
*
* sends all queued stanzas
*/
_onIdle: function () {
var data = this._conn._data;
if (data.length > 0 && !this._conn.paused) {
for (var i = 0; i < data.length; i++) {
if (data[i] !== null) {
var stanza, rawStanza;
if (data[i] === "restart") {
stanza = this._buildStream();
rawStanza = this._removeClosingTag(stanza);
stanza = stanza.tree();
} else {
stanza = data[i];
rawStanza = Strophe.serialize(stanza);
}
this._conn.xmlOutput(stanza);
this._conn.rawOutput(rawStanza);
this.socket.send(rawStanza);
}
}
this._conn._data = [];
}
},
/** PrivateFunction: _onMessage
* _Private_ function to handle websockets messages.
*
* This function parses each of the messages as if they are full documents. [TODO : We may actually want to use a SAX Push parser].
*
* Since all XMPP traffic starts with "<stream:stream version='1.0' xml:lang='en' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' id='3697395463' from='SERVER'>"
* The first stanza will always fail to be parsed...
* Addtionnaly, the seconds stanza will always be a <stream:features> with the stream NS defined in the previous stanza... so we need to 'force' the inclusion of the NS in this stanza!
*
* Parameters:
* (string) message - The websocket message.
*/
_onMessage: function(message) {
var elem, data;
// check for closing stream
if (message.data === "</stream:stream>") {
var close = "</stream:stream>";
this._conn.rawInput(close);
this._conn.xmlInput(document.createElement("stream:stream"));
if (!this._conn.disconnecting) {
this._conn._doDisconnect();
}
return;
} else if (message.data.search("<stream:stream ") === 0) {
//Make the initial stream:stream selfclosing to parse it without a SAX parser.
data = message.data.replace(/<stream:stream (.*[^\/])>/, "<stream:stream $1/>");
elem = new DOMParser().parseFromString(data, "text/xml").documentElement;
if (!this._handleStreamStart(elem)) {
return;
}
} else {
data = this._streamWrap(message.data);
elem = new DOMParser().parseFromString(data, "text/xml").documentElement;
}
if (this._check_streamerror(elem, Strophe.Status.ERROR)) {
return;
}
//handle unavailable presence stanza before disconnecting
if (this._conn.disconnecting &&
elem.firstChild.nodeName === "presence" &&
elem.firstChild.getAttribute("type") === "unavailable") {
this._conn.xmlInput(elem);
this._conn.rawInput(Strophe.serialize(elem));
// if we are already disconnecting we will ignore the unavailable stanza and
// wait for the </stream:stream> tag before we close the connection
return;
}
this._conn._dataRecv(elem, message.data);
},
/** PrivateFunction: _onOpen
* _Private_ function to handle websockets connection setup.
*
* The opening stream tag is sent here.
*/
_onOpen: function() {
Strophe.info("Websocket open");
var start = this._buildStream();
this._conn.xmlOutput(start.tree());
var startString = this._removeClosingTag(start);
this._conn.rawOutput(startString);
this.socket.send(startString);
},
/** PrivateFunction: _removeClosingTag
* _Private_ function to Make the first <stream:stream> non-selfclosing
*
* Parameters:
* (Object) elem - The <stream:stream> tag.
*
* Returns:
* The stream:stream tag as String
*/
_removeClosingTag: function(elem) {
var string = Strophe.serialize(elem);
string = string.replace(/<(stream:stream .*[^\/])\/>$/, "<$1>");
return string;
},
/** PrivateFunction: _reqToData
* _Private_ function to get a stanza out of a request.
*
* WebSockets don't use requests, so the passed argument is just returned.
*
* Parameters:
* (Object) stanza - The stanza.
*
* Returns:
* The stanza that was passed.
*/
_reqToData: function (stanza)
{
return stanza;
},
/** PrivateFunction: _send
* _Private_ part of the Connection.send function for WebSocket
*
* Just flushes the messages that are in the queue
*/
_send: function () {
this._conn.flush();
},
/** PrivateFunction: _sendRestart
*
* Send an xmpp:restart stanza.
*/
_sendRestart: function ()
{
clearTimeout(this._conn._idleTimeout);
this._conn._onIdle.bind(this._conn)();
}
};
|
packages/cf-component-card/test/CardControl.js | jroyal/cf-ui | import React from 'react';
import { felaSnapshot } from 'cf-style-provider';
import { CardControl } from '../../cf-component-card/src/index';
test('should render', () => {
const snapshot = felaSnapshot(<CardControl>CardControl</CardControl>);
expect(snapshot.component).toMatchSnapshot();
expect(snapshot.styles).toMatchSnapshot();
});
test('should render wide', () => {
const snapshot = felaSnapshot(<CardControl wide>CardControl</CardControl>);
expect(snapshot.component).toMatchSnapshot();
expect(snapshot.styles).toMatchSnapshot();
});
|
boilerplate/App/Components/RoundedButton.story.js | nonameolsson/ignite-ir-boilerplate | import React from 'react'
import { storiesOf } from '@storybook/react-native'
import RoundedButton from './RoundedButton'
storiesOf('RoundedButton')
.add('Default', () => (
<RoundedButton
text='A simple rounded button'
/>
))
.add('Text as children', () => (
<RoundedButton>
Hello from the children!
</RoundedButton>
))
|
ajax/libs/yui/3.17.1-rc-1/event-focus/event-focus.js | shelsonjava/cdnjs | YUI.add('event-focus', function (Y, NAME) {
/**
* Adds bubbling and delegation support to DOM events focus and blur.
*
* @module event
* @submodule event-focus
*/
var Event = Y.Event,
YLang = Y.Lang,
isString = YLang.isString,
arrayIndex = Y.Array.indexOf,
useActivate = (function() {
// Changing the structure of this test, so that it doesn't use inline JS in HTML,
// which throws an exception in Win8 packaged apps, due to additional security restrictions:
// http://msdn.microsoft.com/en-us/library/windows/apps/hh465380.aspx#differences
var supported = false,
doc = Y.config.doc,
p;
if (doc) {
p = doc.createElement("p");
p.setAttribute("onbeforeactivate", ";");
// onbeforeactivate is a function in IE8+.
// onbeforeactivate is a string in IE6,7 (unfortunate, otherwise we could have just checked for function below).
// onbeforeactivate is a function in IE10, in a Win8 App environment (no exception running the test).
// onbeforeactivate is undefined in Webkit/Gecko.
// onbeforeactivate is a function in Webkit/Gecko if it's a supported event (e.g. onclick).
supported = (p.onbeforeactivate !== undefined);
}
return supported;
}());
function define(type, proxy, directEvent) {
var nodeDataKey = '_' + type + 'Notifiers';
Y.Event.define(type, {
_useActivate : useActivate,
_attach: function (el, notifier, delegate) {
if (Y.DOM.isWindow(el)) {
return Event._attach([type, function (e) {
notifier.fire(e);
}, el]);
} else {
return Event._attach(
[proxy, this._proxy, el, this, notifier, delegate],
{ capture: true });
}
},
_proxy: function (e, notifier, delegate) {
var target = e.target,
currentTarget = e.currentTarget,
notifiers = target.getData(nodeDataKey),
yuid = Y.stamp(currentTarget._node),
defer = (useActivate || target !== currentTarget),
directSub;
notifier.currentTarget = (delegate) ? target : currentTarget;
notifier.container = (delegate) ? currentTarget : null;
// Maintain a list to handle subscriptions from nested
// containers div#a>div#b>input #a.on(focus..) #b.on(focus..),
// use one focus or blur subscription that fires notifiers from
// #b then #a to emulate bubble sequence.
if (!notifiers) {
notifiers = {};
target.setData(nodeDataKey, notifiers);
// only subscribe to the element's focus if the target is
// not the current target (
if (defer) {
directSub = Event._attach(
[directEvent, this._notify, target._node]).sub;
directSub.once = true;
}
} else {
// In old IE, defer is always true. In capture-phase browsers,
// The delegate subscriptions will be encountered first, which
// will establish the notifiers data and direct subscription
// on the node. If there is also a direct subscription to the
// node's focus/blur, it should not call _notify because the
// direct subscription from the delegate sub(s) exists, which
// will call _notify. So this avoids _notify being called
// twice, unnecessarily.
defer = true;
}
if (!notifiers[yuid]) {
notifiers[yuid] = [];
}
notifiers[yuid].push(notifier);
if (!defer) {
this._notify(e);
}
},
_notify: function (e, container) {
var currentTarget = e.currentTarget,
notifierData = currentTarget.getData(nodeDataKey),
axisNodes = currentTarget.ancestors(),
doc = currentTarget.get('ownerDocument'),
delegates = [],
// Used to escape loops when there are no more
// notifiers to consider
count = notifierData ?
Y.Object.keys(notifierData).length :
0,
target, notifiers, notifier, yuid, match, tmp, i, len, sub, ret;
// clear the notifications list (mainly for delegation)
currentTarget.clearData(nodeDataKey);
// Order the delegate subs by their placement in the parent axis
axisNodes.push(currentTarget);
// document.get('ownerDocument') returns null
// which we'll use to prevent having duplicate Nodes in the list
if (doc) {
axisNodes.unshift(doc);
}
// ancestors() returns the Nodes from top to bottom
axisNodes._nodes.reverse();
if (count) {
// Store the count for step 2
tmp = count;
axisNodes.some(function (node) {
var yuid = Y.stamp(node),
notifiers = notifierData[yuid],
i, len;
if (notifiers) {
count--;
for (i = 0, len = notifiers.length; i < len; ++i) {
if (notifiers[i].handle.sub.filter) {
delegates.push(notifiers[i]);
}
}
}
return !count;
});
count = tmp;
}
// Walk up the parent axis, notifying direct subscriptions and
// testing delegate filters.
while (count && (target = axisNodes.shift())) {
yuid = Y.stamp(target);
notifiers = notifierData[yuid];
if (notifiers) {
for (i = 0, len = notifiers.length; i < len; ++i) {
notifier = notifiers[i];
sub = notifier.handle.sub;
match = true;
e.currentTarget = target;
if (sub.filter) {
match = sub.filter.apply(target,
[target, e].concat(sub.args || []));
// No longer necessary to test against this
// delegate subscription for the nodes along
// the parent axis.
delegates.splice(
arrayIndex(delegates, notifier), 1);
}
if (match) {
// undefined for direct subs
e.container = notifier.container;
ret = notifier.fire(e);
}
if (ret === false || e.stopped === 2) {
break;
}
}
delete notifiers[yuid];
count--;
}
if (e.stopped !== 2) {
// delegates come after subs targeting this specific node
// because they would not normally report until they'd
// bubbled to the container node.
for (i = 0, len = delegates.length; i < len; ++i) {
notifier = delegates[i];
sub = notifier.handle.sub;
if (sub.filter.apply(target,
[target, e].concat(sub.args || []))) {
e.container = notifier.container;
e.currentTarget = target;
ret = notifier.fire(e);
}
if (ret === false || e.stopped === 2 ||
// If e.stopPropagation() is called, notify any
// delegate subs from the same container, but break
// once the container changes. This emulates
// delegate() behavior for events like 'click' which
// won't notify delegates higher up the parent axis.
(e.stopped && delegates[i+1] &&
delegates[i+1].container !== notifier.container)) {
break;
}
}
}
if (e.stopped) {
break;
}
}
},
on: function (node, sub, notifier) {
sub.handle = this._attach(node._node, notifier);
},
detach: function (node, sub) {
sub.handle.detach();
},
delegate: function (node, sub, notifier, filter) {
if (isString(filter)) {
sub.filter = function (target) {
return Y.Selector.test(target._node, filter,
node === target ? null : node._node);
};
}
sub.handle = this._attach(node._node, notifier, true);
},
detachDelegate: function (node, sub) {
sub.handle.detach();
}
}, true);
}
// For IE, we need to defer to focusin rather than focus because
// `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate,
// el.onfocusin, doSomething, then el.onfocus. All others support capture
// phase focus, which executes before doSomething. To guarantee consistent
// behavior for this use case, IE's direct subscriptions are made against
// focusin so subscribers will be notified before js following el.focus() is
// executed.
if (useActivate) {
// name capture phase direct subscription
define("focus", "beforeactivate", "focusin");
define("blur", "beforedeactivate", "focusout");
} else {
define("focus", "focus", "focus");
define("blur", "blur", "blur");
}
}, '@VERSION@', {"requires": ["event-synthetic"]});
|
src/images/tooth-icon-medium.js | kakapo2016-projects/tooth-and-pail | import React from 'react'
import IconButton from 'material-ui/lib/icon-button'
const styles = {
button: {
width: 30, height: 30,
padding: 3,
},
icon: {
width: 30, height: 30,
padding: 3,
},
};
const ToothIcon = () => (
<IconButton style={styles.button} iconStyle={styles.icon} iconClassName="tooth-icon" />
);
export default ToothIcon
|
src/pages/home/results.js | ThariqS/NewsCloudsGenerator | import React from 'react';
import Radium from 'radium';
import urlParse from 'url';
import request from 'superagent';
import async from 'async';
import Tabs from 'react-simpletabs';
import moment from 'moment';
import Loader from 'halogen/PulseLoader';
import outlier from 'outlier';
import _ from 'lodash';
let styles = {};
export default class Results extends React.Component {
constructor(props) {
super(props);
this.state = { sources: {}, fetched: false };
}
componentDidMount() {
console.log('mounted!', this.props);
if (this.props.sources && this.props.sources.length >= 1) {
const sources = this.props.sources;
const query = this.props.query;
this.fetchSources(query, sources);
}
}
componentWillReceiveProps(nextProps) {
console.log('got new props', nextProps);
if (nextProps.sources && nextProps.sources.length >= 1) {
const sources = nextProps.sources;
const query = nextProps.query;
this.fetchSources(query, sources);
}
}
fetchSources(query, sources) {
const sourceFuncs = [];
for (const source of sources) {
sourceFuncs.push(this.fetchSource.bind(this, query, source));
}
async.series(sourceFuncs);
}
parseSource(sourceName, body) {
return body.map((article) => {
return { url: article.guid, source: sourceName, title: article.title, date: article.publish_date};
});
}
fetchSource(query, source, callback) {
const newQ = `${query.q} AND ${source.value}`;
console.log('fetching!', newQ);
request
.post('/stories')
.query({ q: newQ, fq: query.fq })
.send({ q: newQ, fq: query.fq })
.end(function(err, res) {
console.log('fetched!!', source);
// const articles = this.state.articles.concat(this.parseSource(source.label, res.body));
const reqdata = JSON.parse(res.text).data;
const articles = this.parseSource(source.label, reqdata);
const sourceObj = this.state.sources;
sourceObj[source.label] = { articles, fetched: true, name: source.label };
this.setState({sources: sourceObj, fetched: true});
this.forceUpdate();
callback(null, articles);
}.bind(this));
}
submitResults() {
const story = this.props.name;
const sourceNames = this.props.sources.map((source) => source.label);
const flattenedArticles = Object.values(this.state.sources).map((source) => source.articles).reduce(function(a, b) { return a.concat(b); }, []);
const newscloudURL = (document.location.hostname == "localhost") ? 'http://localhost:8083' : 'https://newsclouds.herokuapp.com';
request
.post(`${newscloudURL}/createStory`)
.send({ story, articles: flattenedArticles, sourceNames })
.end(function(err, res) {
console.log('fetched!!');
console.log(res);
this.setState({saved: true});
}.bind(this));
}
processOutliers() {
const flattenedArticles = Object.values(this.state.sources).map((source) => source.articles).reduce(function(a, b) { return a.concat(b); }, []);
const minDate = _.min(flattenedArticles, 'date').date;
const dateDistribution = flattenedArticles.map((article) => moment(minDate).diff(moment(article.date),'days'));
console.log(dateDistribution);
const outliers = outlier(dateDistribution).findOutliers(); // [51]
console.log(outliers);
// dateSpread = moment(dateEnd).diff(moment(momentStart),'days')
}
render() {
const newscloudURL = (document.location.hostname == "localhost") ? 'http://localhost:8083' : 'https://newsclouds.herokuapp.com';
if (this.state.fetched) {
this.processOutliers();
}
return (
<div style={styles.overlay}>
{(!this.state.saved) ?
<span>
<h1 style={styles.title}>Results
<span style={[styles.button, styles.createButton]} onClick={this.submitResults.bind(this)}>Create</span>
</h1>
{
(this.state.fetched) ?
<Tabs key="tab">
{
Object.values(this.state.sources).map((sourceObj, index) => {
const articleSources = sourceObj.articles;
return (<Tabs.Panel key={sourceObj.name} title={`${sourceObj.name} (${sourceObj.articles.length})`}>
<div key={`${sourceObj.name}-wrapper`}>
{articleSources.map((article, articleIndex) => {
return (<div key={article.url} style={styles.block}>
<span key={`${article.title}button`} style={styles.button}>Use</span>
<span>{moment(article.date).format("MMM Do YY")}</span>
<a style={styles.link} href={article.url}>{article.title}</a>
</div>);
})}
</div>
</Tabs.Panel>);
})
}
</Tabs>
:
<span key="loader" style={styles.loader}>
<Loader color="#666" size="16px" margin="4px"/>
</span>
}
</span>
: <div>
<h2 style={styles.title}>Saved your NewsCloud "{this.props.name}"!</h2>
<div>It may take 1-2 minutes for processing of the cloud to complete. <a style={{color:'#666'}} href={`${newscloudURL}/?story=${this.props.name}`}>See it here.</a></div>
</div>}
</div>
);
}
}
styles = {
loader: {
width: '100%',
textAlign: 'center',
},
link: {
color: '#222'
},
title: {
color: '#666',
marginBottom: '75px',
fontWeight: 300,
fontSize: '2em'
},
createButton: {
float: 'right',
fontSize: '0.50em',
borderColor: '#666',
},
button: {
display: 'inline-block',
color: '#666',
border: '2px solid black',
margin: '0px 5px',
padding: '3px',
minWidth: '50px',
textAlign: 'center',
cursor: 'pointer',
},
overlay: {
position: 'fixed',
left: '12%',
top: 'calc(4em + 5vh)',
width: '75vw',
height: '85vh',
overflow: 'scroll',
backgroundColor: 'white',
padding: '20px',
boxShadow: '0 1px 3px 0 rgba(0,0,0,.2),0 1px 1px 0 rgba(0,0,0,.14),0 2px 1px -1px rgba(0,0,0,.12)',
zIndex: 1000,
},
block: {
marginTop: '20px',
whiteSpace: 'nowrap',
}
};
export default Radium(Results);
|
jquery.js | Bagyidaw/web-development | /*!
* jQuery JavaScript Library v1.11.3
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2015-04-28T16:19Z
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper window is present,
// execute the factory and get jQuery
// For environments that do not inherently posses a window with a document
// (such as Node.js), expose a jQuery-making factory as module.exports
// This accentuates the need for the creation of a real window
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//
var deletedIds = [];
var slice = deletedIds.slice;
var concat = deletedIds.concat;
var push = deletedIds.push;
var indexOf = deletedIds.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var support = {};
var
version = "1.11.3",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android<4.1, IE<9
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num != null ?
// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: deletedIds.sort,
splice: deletedIds.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
// adding 1 corrects loss of precision from parseFloat (#15100)
return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
isPlainObject: function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( support.ownLast ) {
for ( key in obj ) {
return hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Support: Android<4.1, IE<9
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( indexOf ) {
return indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
while ( j < len ) {
first[ i++ ] = second[ j++ ];
}
// Support: IE<9
// Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
if ( len !== len ) {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: function() {
return +( new Date() );
},
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
// Support: iOS 8.2 (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = "length" in obj && obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.2.0-pre
* http://sizzlejs.com/
*
* Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-12-16
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + 1 * new Date(),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf as it's faster than native
// http://jsperf.com/thor-indexof-vs-for/5
indexOf = function( list, elem ) {
var i = 0,
len = list.length;
for ( ; i < len; i++ ) {
if ( list[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + characterEncoding + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = new RegExp( whitespace + "+", "g" ),
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
nodeType = context.nodeType;
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
if ( !seed && documentIsHTML ) {
// Try to shortcut find operations when possible (e.g., not under DocumentFragment)
if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document (jQuery #6963)
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType !== 1 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== "undefined" && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare, parent,
doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
parent = doc.defaultView;
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent !== parent.top ) {
// IE11 does not have attachEvent, so all must suffer
if ( parent.addEventListener ) {
parent.addEventListener( "unload", unloadHandler, false );
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", unloadHandler );
}
}
/* Support tests
---------------------------------------------------------------------- */
documentIsHTML = !isXML( doc );
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( doc.getElementsByClassName );
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [ m ] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( tag );
// DocumentFragment nodes don't have gEBTN
} else if ( support.qsa ) {
return context.querySelectorAll( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\f]' msallowcapture=''>" +
"<option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( div.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+
if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
rbuggyQSA.push("~=");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibing-combinator selector` fails
if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch (e) {}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
// Don't keep the element (issue #299)
input[0] = null;
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
text = text.replace( runescape, funescape );
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
};
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (oldCache = outerCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
outerCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
// Avoid hanging onto element (issue #299)
checkContext = null;
return ret;
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context !== document && context;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is no seed and only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.extend({
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
jQuery.fn.extend({
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
return this.pushStack(
jQuery.unique(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.unique( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
});
var rnotwhite = (/\S+/g);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !(--remaining) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.triggerHandler ) {
jQuery( document ).triggerHandler( "ready" );
jQuery( document ).off( "ready" );
}
}
});
/**
* Clean-up method for dom ready events
*/
function detach() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
}
/**
* The ready event handler and self cleanup method
*/
function completed() {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
var strundefined = typeof undefined;
// Support: IE<9
// Iteration over object's inherited properties before its own
var i;
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Note: most support tests are defined in their respective modules.
// false until the test is run
support.inlineBlockNeedsLayout = false;
// Execute ASAP in case we need to set body.style.zoom
jQuery(function() {
// Minified: var a,b,c,d
var val, div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Return for frameset docs that don't have a body
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
if ( typeof div.style.zoom !== strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";
support.inlineBlockNeedsLayout = val = div.offsetWidth === 3;
if ( val ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
});
(function() {
var div = document.createElement( "div" );
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( elem ) {
var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ],
nodeType = +elem.nodeType || 1;
// Do not set data on non-element DOM nodes because it will not be cleared (#8335).
return nodeType !== 1 && nodeType !== 9 ?
false :
// Nodes accept data unless otherwise specified; rejection can be conditional
!noData || noData !== true && elem.getAttribute("classid") === noData;
};
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function internalData( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( i-- ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
/* jshint eqeqeq: false */
} else if ( support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// The following elements (space-suffixed to avoid Object.prototype collisions)
// throw uncatchable exceptions if you attempt to set expando properties
noData: {
"applet ": true,
"embed ": true,
// ...but Flash objects (which have this classid) *can* handle expandos
"object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[0],
attrs = elem && elem.attributes;
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE11+
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return arguments.length > 1 ?
// Sets one value
this.each(function() {
jQuery.data( this, key, value );
}) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined;
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
// Minified: var a,b,c
var input = document.createElement( "input" ),
div = document.createElement( "div" ),
fragment = document.createDocumentFragment();
// Setup
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName( "tbody" ).length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName( "link" ).length;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone =
document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
input.type = "checkbox";
input.checked = true;
fragment.appendChild( input );
support.appendChecked = input.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE6-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
// #11217 - WebKit loses check when the name is after the checked attribute
fragment.appendChild( div );
div.innerHTML = "<input type='radio' checked='checked' name='t'/>";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
support.noCloneEvent = true;
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
})();
(function() {
var i, eventName,
div = document.createElement( "div" );
// Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event)
for ( i in { submit: true, change: true, focusin: true }) {
eventName = "on" + i;
if ( !(support[ i + "Bubbles" ] = eventName in window) ) {
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
div.setAttribute( eventName, "t" );
support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
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( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: IE < 9, Android < 4.0
src.returnValue === false ?
returnTrue :
returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && e.stopImmediatePropagation ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
jQuery._removeData( doc, fix );
} else {
jQuery._data( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
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>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!support.noCloneEvent || !support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
deletedIds.push( id );
}
}
}
}
}
});
jQuery.fn.extend({
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, self.html() );
}
self.domManip( args, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[i], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var style,
elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
// Use of this method is a temporary fix (more like optmization) until something better comes along,
// since it was removed from specification and supported only in FF
style.display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
(function() {
var shrinkWrapBlocksVal;
support.shrinkWrapBlocks = function() {
if ( shrinkWrapBlocksVal != null ) {
return shrinkWrapBlocksVal;
}
// Will be changed later if needed.
shrinkWrapBlocksVal = false;
// Minified: var b,c,d
var div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
// Support: IE6
// Check if elements with layout shrink-wrap their children
if ( typeof div.style.zoom !== strundefined ) {
// Reset CSS: box-sizing; display; margin; border
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-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";
div.appendChild( document.createElement( "div" ) ).style.width = "5px";
shrinkWrapBlocksVal = div.offsetWidth !== 3;
}
body.removeChild( container );
return shrinkWrapBlocksVal;
};
})();
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles, curCSS,
rposition = /^(top|right|bottom|left)$/;
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
// Support: IE<=11+, Firefox<=30+ (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
if ( elem.ownerDocument.defaultView.opener ) {
return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
}
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "";
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, computed ) {
var left, rs, rsLeft, ret,
style = elem.style;
computed = computed || getStyles( elem );
ret = computed ? computed[ name ] : undefined;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "" || "auto";
};
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
var condition = conditionFn();
if ( condition == null ) {
// The test was not ready at this point; screw the hook this time
// but check again when needed next time.
return;
}
if ( condition ) {
// Hook not needed (or it's not possible to use it due to missing dependency),
// remove it.
// Since there are no other hooks for marginRight, remove the whole object.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply( this, arguments );
}
};
}
(function() {
// Minified: var b,c,d,e,f,g, h,i
var div, style, a, pixelPositionVal, boxSizingReliableVal,
reliableHiddenOffsetsVal, reliableMarginRightVal;
// Setup
div = document.createElement( "div" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName( "a" )[ 0 ];
style = a && a.style;
// Finish early in limited (non-browser) environments
if ( !style ) {
return;
}
style.cssText = "float:left;opacity:.5";
// Support: IE<9
// Make sure that element opacity exists (as opposed to filter)
support.opacity = style.opacity === "0.5";
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!style.cssFloat;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" ||
style.WebkitBoxSizing === "";
jQuery.extend(support, {
reliableHiddenOffsets: function() {
if ( reliableHiddenOffsetsVal == null ) {
computeStyleTests();
}
return reliableHiddenOffsetsVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computeStyleTests();
}
return boxSizingReliableVal;
},
pixelPosition: function() {
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return pixelPositionVal;
},
// Support: Android 2.3
reliableMarginRight: function() {
if ( reliableMarginRightVal == null ) {
computeStyleTests();
}
return reliableMarginRightVal;
}
});
function computeStyleTests() {
// Minified: var b,c,d,j
var div, body, container, contents;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-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";
// Support: IE<9
// Assume reasonable values in the absence of getComputedStyle
pixelPositionVal = boxSizingReliableVal = false;
reliableMarginRightVal = true;
// Check for getComputedStyle so that this code is not run in IE<9.
if ( window.getComputedStyle ) {
pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
boxSizingReliableVal =
( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Support: Android 2.3
// Div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
contents = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
contents.style.cssText = div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
contents.style.marginRight = contents.style.width = "0";
div.style.width = "1px";
reliableMarginRightVal =
!parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight );
div.removeChild( contents );
}
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
contents = div.getElementsByTagName( "td" );
contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
if ( reliableHiddenOffsetsVal ) {
contents[ 0 ].style.display = "";
contents[ 1 ].style.display = "none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
}
body.removeChild( container );
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.swap = function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
};
var
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Support: IE
// Swallow errors from 'invalid' CSS values (#5509)
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
jQuery.fn.extend({
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
} ]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = jQuery._data( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css( elem, "display" );
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !support.shrinkWrapBlocks() ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
// Any non-fx value stops us from restoring the original display value
} else {
display = undefined;
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = jQuery._data( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
// If this is a noop like .hide().hide(), restore an overwritten display value
} else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
style.display = display;
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
};
(function() {
// Minified: var a,b,c,d,e
var input, div, select, a, opt;
// Setup
div = document.createElement( "div" );
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName("a")[ 0 ];
// First batch of tests.
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute("style") );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.hrefNormalized = a.getAttribute("href") === "/a";
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement("form").enctype;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE8 only
// Check if we can trust getAttribute("value")
input = document.createElement( "input" );
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
})();
var rreturn = /\r/g;
jQuery.fn.extend({
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE10-11+
// option.text throws exceptions (#14686, #14858)
jQuery.trim( jQuery.text( elem ) );
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) {
// Support: IE6
// When new option element is added to select box we need to
// force reflow of newly added node in order to workaround delay
// of initialization properties
try {
option.selected = optionSet = true;
} catch ( _ ) {
// Will be executed only in IE6
option.scrollHeight;
}
} else {
option.selected = false;
}
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return options;
}
}
}
});
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = support.getSetAttribute,
getSetInput = support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
jQuery.extend({
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hook for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
// Retrieve booleans specially
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
} :
function( elem, name, isXML ) {
if ( !isXML ) {
return elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
}
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
if ( name === "value" || value === elem.getAttribute( name ) ) {
return value;
}
}
};
// Some attributes are constructed with empty-string values when not defined
attrHandle.id = attrHandle.name = attrHandle.coords =
function( elem, name, isXML ) {
var ret;
if ( !isXML ) {
return (ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
}
};
// Fixing value retrieval on a button requires this module
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
if ( ret && ret.specified ) {
return ret.value;
}
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
if ( !support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
var rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
}
});
jQuery.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
// Support: Safari, IE9+
// mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( type === strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
}
});
// Return jQuery for attributes-only inclusion
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var nonce = jQuery.now();
var rquery = (/\?/);
var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;
jQuery.parseJSON = function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
// Support: Android 2.3
// Workaround failure to string-cast null input
return window.JSON.parse( data + "" );
}
var requireNonComma,
depth = null,
str = jQuery.trim( data + "" );
// Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
// after removing valid tokens
return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {
// Force termination if we see a misplaced comma
if ( requireNonComma && comma ) {
depth = 0;
}
// Perform no more replacements after returning to outermost depth
if ( depth === 0 ) {
return token;
}
// Commas must not follow "[", "{", or ","
requireNonComma = open || comma;
// Determine new depth
// array/object open ("[" or "{"): depth += true - false (increment)
// array/object close ("]" or "}"): depth += false - true (decrement)
// other cases ("," or primitive): depth += true - true (numeric cast)
depth += !close - !open;
// Remove this token
return "";
}) ) ?
( Function( "return " + str ) )() :
jQuery.error( "Invalid JSON: " + data );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType.charAt( 0 ) === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
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"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
fireGlobals = jQuery.event && s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
jQuery._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!support.reliableHiddenOffsets() &&
((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function() {
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
})
.map(function( i, elem ) {
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ?
// Support: IE6+
function() {
// XHR cannot access local files, always use ActiveX for that case
return !this.isLocal &&
// Support: IE7-8
// oldIE XHR does not support non-RFC2616 methods (#13240)
// See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx
// and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
// Although this check for six methods instead of eight
// since IE also does not support "trace" and "connect"
/^(get|post|head|put|delete|options)$/i.test( this.type ) &&
createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
var xhrId = 0,
xhrCallbacks = {},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE<10
// Open requests must be manually aborted on unload (#5280)
// See https://support.microsoft.com/kb/2856746 for more info
if ( window.attachEvent ) {
window.attachEvent( "onunload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
});
}
// Determine support properties
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( options ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !options.crossDomain || support.cors ) {
var callback;
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
// Open the socket
xhr.open( options.type, options.url, options.async, options.username, options.password );
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
// Support: IE<9
// IE's ActiveXObject throws a 'Type Mismatch' exception when setting
// request header to a null-value.
//
// To keep consistent with other XHR implementations, cast the value
// to string and ignore `undefined`.
if ( headers[ i ] !== undefined ) {
xhr.setRequestHeader( i, headers[ i ] + "" );
}
}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( options.hasContent && options.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, statusText, responses;
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Clean up
delete xhrCallbacks[ id ];
callback = undefined;
xhr.onreadystatechange = jQuery.noop;
// Abort manually if needed
if ( isAbort ) {
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
// Support: IE<10
// Accessing binary-data responseText throws an exception
// (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && options.isLocal && !options.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, xhr.getAllResponseHeaders() );
}
};
if ( !options.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
// Add to the list of active xhr callbacks
xhr.onreadystatechange = xhrCallbacks[ id ] = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = jQuery.trim( url.slice( off, url.length ) );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
});
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -1;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
offset: function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
|
client/src/components/common/FileManager.js | Wiredcraft/jekyllpro-cms | import React, { Component } from 'react';
import NestedFileTreeView from 'react-nested-file-tree';
import {
parseFileTree,
parseFolderPath,
parseFolderObj
} from '../../helpers/utils';
import FileIcon from '../svg/FileIcon';
import FolderIcon from '../svg/FolderIcon';
import HomeIcon from '../svg/HomeIcon';
import ClosedFolderIcon from '../svg/ClosedFolderIcon';
function CustomFolder(props) {
return (
<a onClick={props.onclick}>
<ClosedFolderIcon />
<span>
{props.name}
</span>
</a>
);
}
function CustomFile(props) {
return (
<a>
<FileIcon />
<span>
{props.name}
</span>
</a>
);
}
export default class FileManager extends Component {
constructor(props) {
super(props);
this.state = {
currentPath: '/',
records: props.treeMeta && parseFileTree(props.treeMeta)
};
}
componentWillMount() {
const { fetchRepoTree, currentBranch } = this.props;
fetchRepoTree(currentBranch).then(data => {
this.setState({ records: parseFileTree(data.tree) });
});
}
componentWillReceiveProps(nextProps) {
const { treeMeta } = nextProps;
const thisTreeMeta = this.props.treeMeta;
const { currentPath } = this.state;
if (thisTreeMeta && treeMeta.length !== thisTreeMeta.length) {
this.setState({
records: parseFolderObj(currentPath, parseFileTree(treeMeta))
});
}
}
handleFileClick(file) {
console.log(file);
this.setState({ selectedFile: file.path });
this.props.fileCallback('/' + file.path);
}
handleFolderClick(folderName, path, Obj) {
const { treeMeta, folderCallback } = this.props;
const { currentPath } = this.state;
let newPath =
currentPath === '/' ? '/' + folderName : currentPath + '/' + folderName;
folderCallback(folderName, newPath);
this.setState({
currentPath: newPath,
records: Obj
});
}
handleBreadscrumLink(folderPathArray) {
const { treeMeta, folderCallback } = this.props;
let newPath = '/' + folderPathArray.join('/');
folderCallback('', newPath);
this.setState({
currentPath: newPath,
records: parseFolderObj(newPath, parseFileTree(treeMeta))
});
}
render() {
const { treeMeta } = this.props;
const { records, currentPath } = this.state;
if (!records) {
return <div className="loading" style={{ height: '400px' }} />;
}
return (
<div className="file-manager">
<header className="breadcrumb">
<a
onClick={() => {
this.setState({
currentPath: '/',
records: treeMeta && parseFileTree(treeMeta)
});
}}
>
<HomeIcon />
</a>/
{parseFolderPath(currentPath).map((folder, idx) => {
return (
<span key={idx}>
<a
onClick={this.handleBreadscrumLink.bind(
this,
folder.pathArray
)}
>
{folder.name} /
</a>
</span>
);
})}
</header>
<NestedFileTreeView
selectedFilePath={this.state.selectedFile}
fileTemplate={CustomFile}
folderTemplate={CustomFolder}
fileClickHandler={::this.handleFileClick}
folderClickHandler={::this.handleFolderClick}
directory={records}
/>
</div>
);
}
}
|
system/assets/plugins/mousewheel/test/browserify/bundle.js | judelvis/jp-inmobiliarioa | ;(function(e,t,n,r){function i(r){if(!n[r]){if(!t[r]){if(e)return e(r);throw new Error("Cannot find module '"+r+"'")}var s=n[r]={exports:{}};t[r][0](function(e){var n=t[r][1][e];return i(n?n:e)},s,s.exports)}return n[r].exports}for(var s=0;s<r.length;s++)i(r[s]);return i})(typeof require!=="undefined"&&require,{1:[function(require,module,exports){
/*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
* Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
* Thanks to: Seamus Leahy for adding deltaX and deltaY
*
* Version: 3.1.1
*
* Requires: 1.2.2+
*/
(function (factory) {
if ( typeof define === 'function' && define.amd ) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Browserify
module.exports = factory;
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll'];
var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
var lowestDelta, lowestDeltaXY;
if ( $.event.fixHooks ) {
for ( var i = toFix.length; i; ) {
$.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
setup: function() {
if ( this.addEventListener ) {
for ( var i = toBind.length; i; ) {
this.addEventListener( toBind[--i], handler, false );
}
} else {
this.onmousewheel = handler;
}
},
teardown: function() {
if ( this.removeEventListener ) {
for ( var i = toBind.length; i; ) {
this.removeEventListener( toBind[--i], handler, false );
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
},
unmousewheel: function(fn) {
return this.unbind("mousewheel", fn);
}
});
function handler(event) {
var orgEvent = event || window.event,
args = [].slice.call(arguments, 1),
delta = 0,
deltaX = 0,
deltaY = 0,
absDelta = 0,
absDeltaXY = 0,
fn;
event = $.event.fix(orgEvent);
event.type = "mousewheel";
// Old school scrollwheel delta
if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; }
if ( orgEvent.detail ) { delta = orgEvent.detail * -1; }
// New school wheel delta (wheel event)
if ( orgEvent.deltaY ) {
deltaY = orgEvent.deltaY * -1;
delta = deltaY;
}
if ( orgEvent.deltaX ) {
deltaX = orgEvent.deltaX;
delta = deltaX * -1;
}
// Webkit
if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; }
if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX * -1; }
// Look for lowest delta to normalize the delta values
absDelta = Math.abs(delta);
if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; }
absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX));
if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; }
// Get a whole value for the deltas
fn = delta > 0 ? 'floor' : 'ceil';
delta = Math[fn](delta / lowestDelta);
deltaX = Math[fn](deltaX / lowestDeltaXY);
deltaY = Math[fn](deltaY / lowestDeltaXY);
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
}));
},{}],2:[function(require,module,exports){
var $ = require('jquery-browserify');
require('../../jquery.mousewheel.js')($);
},{"../../jquery.mousewheel.js":1,"jquery-browserify":3}],3:[function(require,module,exports){
(function(global){// Uses Node, AMD or browser globals to create a module.
// If you want something that will work in other stricter CommonJS environments,
// or if you need to create a circular dependency, see commonJsStrict.js
// Defines a module "returnExports" that depends another module called "b".
// Note that the name of the module is implied by the file name. It is best
// if the file name and the exported global have matching names.
// If the 'b' module also uses this type of boilerplate, then
// in the browser, it will create a global .b that is used below.
// If you do not want to support the browser global path, then you
// can remove the `root` use and the passing `this` as the first arg to
// the top function.
(function (root, factory) {
if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else {
// Browser globals
root.returnExports = factory();
}
}(this, function () {/*!
* jQuery JavaScript Library v1.8.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: Thu Aug 30 2012 17:17:22 GMT-0400 (Eastern Daylight Time)
*/
return (function( window, undefined ) {
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
navigator = window.navigator,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// Save a reference to some core methods
core_push = Array.prototype.push,
core_slice = Array.prototype.slice,
core_indexOf = Array.prototype.indexOf,
core_toString = Object.prototype.toString,
core_hasOwn = Object.prototype.hasOwnProperty,
core_trim = String.prototype.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
// Used for detecting and trimming whitespace
core_rnotwhite = /\S/,
core_rspace = /\s+/,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// The ready event handler and self cleanup method
DOMContentLoaded = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
} else if ( document.readyState === "complete" ) {
// we're here because readyState === "complete" in oldIE
// which is good enough for us to call the dom ready!
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
},
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context && context.nodeType ? context.ownerDocument || context : document );
// scripts is true for back-compat
selector = jQuery.parseHTML( match[1], doc, true );
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
this.attr.call( selector, context, true );
}
return jQuery.merge( this, selector );
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.8.1",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ),
"slice", core_slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ core_toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// scripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, scripts ) {
var parsed;
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
scripts = context;
context = 0;
}
context = context || document;
// Single tag
if ( (parsed = rsingleTag.exec( data )) ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );
return jQuery.merge( [],
(parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );
},
parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && core_rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var name,
i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
if ( args ) {
if ( isObj ) {
for ( name in obj ) {
if ( callback.apply( obj[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( obj[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in obj ) {
if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var type,
ret = results || [];
if ( arr != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
type = jQuery.type( arr );
if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {
core_push.call( ret, arr );
} else {
jQuery.merge( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key,
ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready, 1 );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.split( core_rspace ), function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" && ( !options.unique || !self.has( arg ) ) ) {
list.push( arg );
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
return jQuery.inArray( fn, list ) > -1;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
function() {
var returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
} :
newDefer[ action ]
);
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return typeof obj === "object" ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ] = list.fire
deferred[ tuple[0] ] = list.fire;
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
eventName,
i,
isSupported,
clickFn,
div = document.createElement("div");
// Preliminary tests
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
// Can't get basic test support
if ( !all || !all.length || !a ) {
return {};
}
// First batch of supports tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form(#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: ( document.compatMode === "CSS1Compat" ),
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", clickFn = function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent("onclick");
div.detachEvent( "onclick", clickFn );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
input.setAttribute( "checked", "checked" );
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: true,
change: true,
focusin: true
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
// Run tests that need a body at doc ready
jQuery(function() {
var container, div, tds, marginDiv,
divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = document.createElement("div");
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
div.appendChild( marginDiv );
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
container.style.zoom = 1;
}
// Null elements to avoid leaks in IE
body.removeChild( container );
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
fragment.removeChild( div );
all = a = select = opt = input = fragment = div = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
deletedIds: [],
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = jQuery.deletedIds.pop() || ++jQuery.uuid;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery.removeData( elem, type + "queue", true );
jQuery.removeData( elem, key, true );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook, fixSpecified,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea|)$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var removes, className, elem, c, cl, i, l;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
removes = ( value || "" ).split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
className = (" " + elem.className + " ").replace( rclass, " " );
// loop over each item in the removal list
for ( c = 0, cl = removes.length; c < cl; c++ ) {
// Remove until there is nothing to remove,
while ( className.indexOf(" " + removes[ c ] + " ") > -1 ) {
className = className.replace( " " + removes[ c ] + " " , " " );
}
}
elem.className = value ? jQuery.trim( className ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( core_rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, i, max, option,
index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
i = one ? index : 0;
max = one ? index + 1 : options.length;
for ( ; i < max; i++ ) {
option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
// Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9
attrFn: {},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, "" + value );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.split( core_rspace );
for ( ; i < attrNames.length; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.value = value + "" );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = "" + value );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/,
rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var t, tns, type, origType, namespaces, origCount,
j, events, special, eventType, handleObj,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, "events", true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType,
type = event.type || event,
namespaces = [];
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
for ( old = elem; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old === (elem.ownerDocument || document) ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = [].slice.call( arguments ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [];
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
selMatch = {};
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = jQuery( sel, this ).index( cur ) >= 0;
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8)
event.metaKey = !!event.metaKey;
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8 –
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === "undefined" ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "_submit_attached" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "_submit_attached", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "_change_attached", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var dirruns,
cachedruns,
assertGetIdNotName,
Expr,
getText,
isXML,
contains,
compile,
sortOrder,
hasDuplicate,
baseHasDuplicate = true,
strundefined = "undefined",
expando = ( "sizcache" + Math.random() ).replace( ".", "" ),
document = window.document,
docElem = document.documentElement,
done = 0,
slice = [].slice,
push = [].push,
// Augment a function for special use by Sizzle
markFunction = function( fn, value ) {
fn[ expando ] = value || true;
return fn;
},
createCache = function() {
var cache = {},
keys = [];
return markFunction(function( key, value ) {
// Only keep the most recent entries
if ( keys.push( key ) > Expr.cacheLength ) {
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
}, cache );
},
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// Regex
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors)
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments not in parens/brackets,
// then attribute selectors and non-pseudos (denoted by :),
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",
// For matchExpr.POS and matchExpr.needsContext
pos = ":(nth|eq|gt|lt|first|last|even|odd)(?:\\(((?:-\\d)?\\d*)\\)|)(?=[^-]|$)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
rnot = /^:not/,
rsibling = /[\x20\t\r\n\f]*[+~]/,
rendsWithNot = /:not\($/,
rheader = /h\d/i,
rinputs = /input|select|textarea|button/i,
rbackslash = /\\(?!\\)/g,
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|nth|last|first)-child(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"POS": new RegExp( pos, "ig" ),
// For use in libraries implementing .is()
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" )
},
// Support
// Used for testing something on an element
assert = function( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
},
// Check if getElementsByTagName("*") returns only elements
assertTagNameNoComments = assert(function( div ) {
div.appendChild( document.createComment("") );
return !div.getElementsByTagName("*").length;
}),
// Check if getAttribute returns normalized href attributes
assertHrefNotNormalized = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}),
// Check if attributes should be retrieved by attribute nodes
assertAttributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
}),
// Check if getElementsByClassName can be trusted
assertUsableClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
}),
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
assertUsableName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = document.getElementsByName &&
// buggy browsers will return fewer than the correct 2
document.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
document.getElementsByName( expando + 0 ).length;
assertGetIdNotName = !document.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// If slice is not available, provide a backup
try {
slice.call( docElem.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem, results = [];
for ( ; (elem = this[i]); i++ ) {
results.push( elem );
}
return results;
};
}
function Sizzle( selector, context, results, seed ) {
results = results || [];
context = context || document;
var match, elem, xml, m,
nodeType = context.nodeType;
if ( nodeType !== 1 && nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
xml = isXML( context );
if ( !xml && !seed ) {
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
}
// All others
return select( selector, context, results, seed, xml );
}
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
} else {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
}
return ret;
};
isXML = Sizzle.isXML = function isXML( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Element contains another
contains = Sizzle.contains = docElem.contains ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) );
} :
docElem.compareDocumentPosition ?
function( a, b ) {
return b && !!( a.compareDocumentPosition( b ) & 16 );
} :
function( a, b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
return false;
};
Sizzle.attr = function( elem, name ) {
var attr,
xml = isXML( elem );
if ( !xml ) {
name = name.toLowerCase();
}
if ( Expr.attrHandle[ name ] ) {
return Expr.attrHandle[ name ]( elem );
}
if ( assertAttributes || xml ) {
return elem.getAttribute( name );
}
attr = elem.getAttributeNode( name );
return attr ?
typeof elem[ name ] === "boolean" ?
elem[ name ] ? name : null :
attr.specified ? attr.value : null :
null;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
order: new RegExp( "ID|TAG" +
(assertUsableName ? "|NAME" : "") +
(assertUsableClassName ? "|CLASS" : "")
),
// IE6/7 return a modified href
attrHandle: assertHrefNotNormalized ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
},
find: {
"ID": assertGetIdNotName ?
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
} :
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
},
"TAG": assertTagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
var elem,
tmp = [],
i = 0;
for ( ; (elem = results[i]); i++ ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
},
"NAME": function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
},
"CLASS": function( className, context, xml ) {
if ( typeof context.getElementsByClassName !== strundefined && !xml ) {
return context.getElementsByClassName( className );
}
}
},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( rbackslash, "" );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr.CHILD
1 type (only|nth|...)
2 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
3 xn-component of xn+y argument ([+-]?\d*n|)
4 sign of xn-component
5 x of xn-component
6 sign of y-component
7 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1] === "nth" ) {
// nth-child requires argument
if ( !match[2] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) );
match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" );
// other types prohibit arguments
} else if ( match[2] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match, context, xml ) {
var unquoted, excess;
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
if ( match[3] ) {
match[2] = match[3];
} else if ( (unquoted = match[4]) ) {
// Only check arguments that contain a pseudo
if ( rpseudo.test(unquoted) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, context, xml, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
unquoted = unquoted.slice( 0, excess );
match[0] = match[0].slice( 0, excess );
}
match[2] = unquoted;
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"ID": assertGetIdNotName ?
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
return elem.getAttribute("id") === id;
};
} :
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === id;
};
},
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( rbackslash, "" ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ expando ][ className ];
if ( !pattern ) {
pattern = classCache( className, new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)") );
}
return function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
};
},
"ATTR": function( name, operator, check ) {
if ( !operator ) {
return function( elem ) {
return Sizzle.attr( elem, name ) != null;
};
}
return function( elem ) {
var result = Sizzle.attr( elem, name ),
value = result + "";
if ( result == null ) {
return operator === "!=";
}
switch ( operator ) {
case "=":
return value === check;
case "!=":
return value !== check;
case "^=":
return check && value.indexOf( check ) === 0;
case "*=":
return check && value.indexOf( check ) > -1;
case "$=":
return check && value.substr( value.length - check.length ) === check;
case "~=":
return ( " " + value + " " ).indexOf( check ) > -1;
case "|=":
return value === check || value.substr( 0, check.length + 1 ) === check + "-";
}
};
},
"CHILD": function( type, argument, first, last ) {
if ( type === "nth" ) {
var doneName = done++;
return function( elem ) {
var parent, diff,
count = 0,
node = elem;
if ( first === 1 && last === 0 ) {
return true;
}
parent = elem.parentNode;
if ( parent && (parent[ expando ] !== doneName || !elem.sizset) ) {
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.sizset = ++count;
if ( node === elem ) {
break;
}
}
}
parent[ expando ] = doneName;
}
diff = elem.sizset - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
};
}
return function( elem ) {
var node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
}
};
},
"PSEUDO": function( pseudo, argument, context, xml ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
var args,
fn = Expr.pseudos[ pseudo ] || Expr.pseudos[ pseudo.toLowerCase() ];
if ( !fn ) {
Sizzle.error( "unsupported pseudo: " + pseudo );
}
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( !fn[ expando ] ) {
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
return fn( argument, context, xml );
}
},
pseudos: {
"not": markFunction(function( selector, context, xml ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var matcher = compile( selector.replace( rtrim, "$1" ), context, xml );
return function( elem ) {
return !matcher( elem );
};
}),
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
var nodeType;
elem = elem.firstChild;
while ( elem ) {
if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) {
return false;
}
elem = elem.nextSibling;
}
return true;
},
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"text": function( elem ) {
var type, attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
(type = elem.type) === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type );
},
// Input types
"radio": createInputPseudo("radio"),
"checkbox": createInputPseudo("checkbox"),
"file": createInputPseudo("file"),
"password": createInputPseudo("password"),
"image": createInputPseudo("image"),
"submit": createButtonPseudo("submit"),
"reset": createButtonPseudo("reset"),
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"focus": function( elem ) {
var doc = elem.ownerDocument;
return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href);
},
"active": function( elem ) {
return elem === elem.ownerDocument.activeElement;
}
},
setFilters: {
"first": function( elements, argument, not ) {
return not ? elements.slice( 1 ) : [ elements[0] ];
},
"last": function( elements, argument, not ) {
var elem = elements.pop();
return not ? elements : [ elem ];
},
"even": function( elements, argument, not ) {
var results = [],
i = not ? 1 : 0,
len = elements.length;
for ( ; i < len; i = i + 2 ) {
results.push( elements[i] );
}
return results;
},
"odd": function( elements, argument, not ) {
var results = [],
i = not ? 0 : 1,
len = elements.length;
for ( ; i < len; i = i + 2 ) {
results.push( elements[i] );
}
return results;
},
"lt": function( elements, argument, not ) {
return not ? elements.slice( +argument ) : elements.slice( 0, +argument );
},
"gt": function( elements, argument, not ) {
return not ? elements.slice( 0, +argument + 1 ) : elements.slice( +argument + 1 );
},
"eq": function( elements, argument, not ) {
var elem = elements.splice( +argument, 1 );
return not ? elements : elem;
}
}
};
function siblingCheck( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
}
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
return ( !a.compareDocumentPosition || !b.compareDocumentPosition ?
a.compareDocumentPosition :
a.compareDocumentPosition(b) & 4
) ? -1 : 1;
} :
function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
[0, 0].sort( sortOrder );
baseHasDuplicate = !hasDuplicate;
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
i = 1;
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
return results;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
function tokenize( selector, context, xml, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, group, i,
preFilters, filters,
checkContext = !xml && context !== document,
// Token cache should maintain spaces
key = ( checkContext ? "<s>" : "" ) + selector.replace( rtrim, "$1<s>" ),
cached = tokenCache[ expando ][ key ];
if ( cached ) {
return parseOnly ? 0 : slice.call( cached, 0 );
}
soFar = selector;
groups = [];
i = 0;
preFilters = Expr.preFilter;
filters = Expr.filter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
soFar = soFar.slice( match[0].length );
tokens.selector = group;
}
groups.push( tokens = [] );
group = "";
// Need to make sure we're within a narrower context if necessary
// Adding a descendant combinator will generate what is needed
if ( checkContext ) {
soFar = " " + soFar;
}
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
group += match[0];
soFar = soFar.slice( match[0].length );
// Cast descendant combinators to space
matched = tokens.push({
part: match.pop().replace( rtrim, " " ),
string: match[0],
captures: match
});
}
// Filters
for ( type in filters ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
( match = preFilters[ type ](match, context, xml) )) ) {
group += match[0];
soFar = soFar.slice( match[0].length );
matched = tokens.push({
part: type,
string: match.shift(),
captures: match
});
}
}
if ( !matched ) {
break;
}
}
// Attach the full group as a selector
if ( group ) {
tokens.selector = group;
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
slice.call( tokenCache(key, groups), 0 );
}
function addCombinator( matcher, combinator, context, xml ) {
var dir = combinator.dir,
doneName = done++;
if ( !matcher ) {
// If there is no matcher to check, check against the context
matcher = function( elem ) {
return elem === context;
};
}
return combinator.first ?
function( elem ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 ) {
return matcher( elem ) && elem;
}
}
} :
xml ?
function( elem ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 ) {
if ( matcher( elem ) ) {
return elem;
}
}
}
} :
function( elem ) {
var cache,
dirkey = doneName + "." + dirruns,
cachedkey = dirkey + "." + cachedruns;
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 ) {
if ( (cache = elem[ expando ]) === cachedkey ) {
return elem.sizset;
} else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) {
if ( elem.sizset ) {
return elem;
}
} else {
elem[ expando ] = cachedkey;
if ( matcher( elem ) ) {
elem.sizset = true;
return elem;
}
elem.sizset = false;
}
}
}
};
}
function addMatcher( higher, deeper ) {
return higher ?
function( elem ) {
var result = deeper( elem );
return result && higher( result === true ? elem : result );
} :
deeper;
}
// ["TAG", ">", "ID", " ", "CLASS"]
function matcherFromTokens( tokens, context, xml ) {
var token, matcher,
i = 0;
for ( ; (token = tokens[i]); i++ ) {
if ( Expr.relative[ token.part ] ) {
matcher = addCombinator( matcher, Expr.relative[ token.part ], context, xml );
} else {
matcher = addMatcher( matcher, Expr.filter[ token.part ].apply(null, token.captures.concat( context, xml )) );
}
}
return matcher;
}
function matcherFromGroupMatchers( matchers ) {
return function( elem ) {
var matcher,
j = 0;
for ( ; (matcher = matchers[j]); j++ ) {
if ( matcher(elem) ) {
return true;
}
}
return false;
};
}
compile = Sizzle.compile = function( selector, context, xml ) {
var group, i, len,
cached = compilerCache[ expando ][ selector ];
// Return a cached group function if already generated (context dependent)
if ( cached && cached.context === context ) {
return cached;
}
// Generate a function of recursive functions that can be used to check each element
group = tokenize( selector, context, xml );
for ( i = 0, len = group.length; i < len; i++ ) {
group[i] = matcherFromTokens(group[i], context, xml);
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers(group) );
cached.context = context;
cached.runs = cached.dirruns = 0;
return cached;
};
function multipleContexts( selector, contexts, results, seed ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results, seed );
}
}
function handlePOSGroup( selector, posfilter, argument, contexts, seed, not ) {
var results,
fn = Expr.setFilters[ posfilter.toLowerCase() ];
if ( !fn ) {
Sizzle.error( posfilter );
}
if ( selector || !(results = seed) ) {
multipleContexts( selector || "*", contexts, (results = []), seed );
}
return results.length > 0 ? fn( results, argument, not ) : [];
}
function handlePOS( groups, context, results, seed ) {
var group, part, j, groupLen, token, selector,
anchor, elements, match, matched,
lastIndex, currentContexts, not,
i = 0,
len = groups.length,
rpos = matchExpr["POS"],
// This is generated here in case matchExpr["POS"] is extended
rposgroups = new RegExp( "^" + rpos.source + "(?!" + whitespace + ")", "i" ),
// This is for making sure non-participating
// matching groups are represented cross-browser (IE6-8)
setUndefined = function() {
var i = 1,
len = arguments.length - 2;
for ( ; i < len; i++ ) {
if ( arguments[i] === undefined ) {
match[i] = undefined;
}
}
};
for ( ; i < len; i++ ) {
group = groups[i];
part = "";
elements = seed;
for ( j = 0, groupLen = group.length; j < groupLen; j++ ) {
token = group[j];
selector = token.string;
if ( token.part === "PSEUDO" ) {
// Reset regex index to 0
rpos.exec("");
anchor = 0;
while ( (match = rpos.exec( selector )) ) {
matched = true;
lastIndex = rpos.lastIndex = match.index + match[0].length;
if ( lastIndex > anchor ) {
part += selector.slice( anchor, match.index );
anchor = lastIndex;
currentContexts = [ context ];
if ( rcombinators.test(part) ) {
if ( elements ) {
currentContexts = elements;
}
elements = seed;
}
if ( (not = rendsWithNot.test( part )) ) {
part = part.slice( 0, -5 ).replace( rcombinators, "$&*" );
anchor++;
}
if ( match.length > 1 ) {
match[0].replace( rposgroups, setUndefined );
}
elements = handlePOSGroup( part, match[1], match[2], currentContexts, elements, not );
}
part = "";
}
}
if ( !matched ) {
part += selector;
}
matched = false;
}
if ( part ) {
if ( rcombinators.test(part) ) {
multipleContexts( part, elements || [ context ], results, seed );
} else {
Sizzle( part, context, results, seed ? seed.concat(elements) : elements );
}
} else {
push.apply( results, elements );
}
}
// Do not sort if this is a single filter
return len === 1 ? results : Sizzle.uniqueSort( results );
}
function select( selector, context, results, seed, xml ) {
// Remove excessive whitespace
selector = selector.replace( rtrim, "$1" );
var elements, matcher, cached, elem,
i, tokens, token, lastToken, findContext, type,
match = tokenize( selector, context, xml ),
contextNodeType = context.nodeType;
// POS handling
if ( matchExpr["POS"].test(selector) ) {
return handlePOS( match, context, results, seed );
}
if ( seed ) {
elements = slice.call( seed, 0 );
// To maintain document order, only narrow the
// set if there is one group
} else if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
if ( (tokens = slice.call( match[0], 0 )).length > 2 &&
(token = tokens[0]).part === "ID" &&
contextNodeType === 9 && !xml &&
Expr.relative[ tokens[1].part ] ) {
context = Expr.find["ID"]( token.captures[0].replace( rbackslash, "" ), context, xml )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().string.length );
}
findContext = ( (match = rsibling.exec( tokens[0].string )) && !match.index && context.parentNode ) || context;
// Reduce the set if possible
lastToken = "";
for ( i = tokens.length - 1; i >= 0; i-- ) {
token = tokens[i];
type = token.part;
lastToken = token.string + lastToken;
if ( Expr.relative[ type ] ) {
break;
}
if ( Expr.order.test(type) ) {
elements = Expr.find[ type ]( token.captures[0].replace( rbackslash, "" ), findContext, xml );
if ( elements == null ) {
continue;
} else {
selector = selector.slice( 0, selector.length - lastToken.length ) +
lastToken.replace( matchExpr[ type ], "" );
if ( !selector ) {
push.apply( results, slice.call(elements, 0) );
}
break;
}
}
}
}
// Only loop over the given elements once
if ( selector ) {
matcher = compile( selector, context, xml );
dirruns = matcher.dirruns++;
if ( elements == null ) {
elements = Expr.find["TAG"]( "*", (rsibling.test( selector ) && context.parentNode) || context );
}
for ( i = 0; (elem = elements[i]); i++ ) {
cachedruns = matcher.runs++;
if ( matcher(elem) ) {
results.push( elem );
}
}
}
return results;
}
if ( document.querySelectorAll ) {
(function() {
var disconnectedMatch,
oldSelect = select,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
rbuggyQSA = [],
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
// A support test would require too much code (would include document ready)
// just skip matchesSelector for :active
rbuggyMatches = [":active"],
matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector;
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here (do not put tests after this one)
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE9 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<p test=''></p>";
if ( div.querySelectorAll("[test^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here (do not put tests after this one)
div.innerHTML = "<input type='hidden'/>";
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push(":enabled", ":disabled");
}
});
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
select = function( selector, context, results, seed, xml ) {
// Only use querySelectorAll when not filtering,
// when this is not xml,
// and when no QSA bugs apply
if ( !seed && !xml && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
if ( context.nodeType === 9 ) {
try {
push.apply( results, slice.call(context.querySelectorAll( selector ), 0) );
return results;
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var groups, i, len,
old = context.getAttribute("id"),
nid = old || expando,
newContext = rsibling.test( selector ) && context.parentNode || context;
if ( old ) {
nid = nid.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
groups = tokenize(selector, context, xml);
// Trailing space is unnecessary
// There is always a context check
nid = "[id='" + nid + "']";
for ( i = 0, len = groups.length; i < len; i++ ) {
groups[i] = nid + groups[i].selector;
}
try {
push.apply( results, slice.call( newContext.querySelectorAll(
groups.join(",")
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
return oldSelect( selector, context, results, seed, xml );
};
if ( matches ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
try {
matches.call( div, "[test!='']:sizzle" );
rbuggyMatches.push( matchExpr["PSEUDO"].source, matchExpr["POS"].source, "!=" );
} catch ( e ) {}
});
// rbuggyMatches always contains :active, so no need for a length check
rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") );
Sizzle.matchesSelector = function( elem, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyMatches always contains :active, so no need for an existence check
if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && (!rbuggyQSA || !rbuggyQSA.test( expr )) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
}
})();
}
// Deprecated
Expr.setFilters["nth"] = Expr.setFilters["eq"];
// Back-compat
Expr.filters = Expr.pseudos;
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, l, length, n, r, ret,
self = this;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
ret = this.pushStack( "", "find", selector );
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, core_slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rcheckableType = /^(?:checkbox|radio)$/,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "X<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( set, this ), "before", this.selector );
}
},
after: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( this, set ), "after", this.selector );
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
if ( !isDisconnected( this[0] ) ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
}
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = [].concat.apply( [], args );
var results, first, fragment, iNoClone,
i = 0,
value = args[0],
scripts = [],
l = this.length;
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call( this, i, table ? self.html() : undefined );
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
results = jQuery.buildFragment( args, this, scripts );
fragment = results.fragment;
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
// Fragments from the fragment cache must always be cloned and never used in place.
for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) {
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
i === iNoClone ?
fragment :
jQuery.clone( fragment, true, true )
);
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
if ( jQuery.ajax ) {
jQuery.ajax({
url: elem.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.error("no ajax");
}
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
if ( nodeName === "object" ) {
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, context, scripts ) {
var fragment, cacheable, cachehit,
first = args[ 0 ];
// Set context from what may come in as undefined or a jQuery collection or a node
// Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &
// also doubles as fix for #8950 where plain objects caused createDocumentFragment exception
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
// Mark cacheable and look for a hit
cacheable = true;
fragment = jQuery.fragments[ first ];
cachehit = fragment !== undefined;
}
if ( !fragment ) {
fragment = context.createDocumentFragment();
jQuery.clean( args, context, fragment, scripts );
// Update the cache, but only store false
// unless this is a second parsing of the same content
if ( cacheable ) {
jQuery.fragments[ first ] = cachehit && fragment;
}
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
l = insert.length,
parent = this.length === 1 && this[0].parentNode;
if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( ; i < l; i++ ) {
elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
clone;
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags,
safe = context === document && safeFragment,
ret = [];
// Ensure that context is a document
if ( !context || typeof context.createDocumentFragment === "undefined" ) {
context = document;
}
// Use the already-created safe fragment if context permits
for ( i = 0; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Ensure a safe container in which to render the html
safe = safe || createSafeFragment( context );
div = context.createElement("div");
safe.appendChild( div );
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Go to html and back, then peel off extra wrappers
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
depth = wrap[0];
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
hasBody = rtbody.test(elem);
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Take out of fragment container (we need a fresh div each time)
div.parentNode.removeChild( div );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
jQuery.merge( ret, elem );
}
}
// Fix #11356: Clear elements from safeFragment
if ( div ) {
elem = div = safe = null;
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
for ( i = 0; (elem = ret[i]) != null; i++ ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
}
// Append elements to a provided document fragment
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
},
cleanData: function( elems, /* internal */ acceptData ) {
var data, id, elem, type,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
jQuery.deletedIds.push( id );
}
}
}
}
}
});
// Limit scope pollution from any deprecated API
(function() {
var matched, browser;
// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
};
})();
var curCSS, iframe, iframeDoc,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ),
elemdisplay = {},
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
eventsToggle = jQuery.fn.toggle;
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var elem, display,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && elem.style.display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
display = curCSS( elem, "display" );
if ( !values[ index ] && display !== "none" ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state, fn2 ) {
var bool = typeof state === "boolean";
if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) {
return eventsToggle.apply( this, arguments );
}
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, numeric, extra ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( numeric || extra !== undefined ) {
num = parseFloat( val );
return numeric || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
curCSS = function( elem, name ) {
var ret, width, minWidth, maxWidth,
computed = window.getComputedStyle( elem, null ),
style = elem.style;
if ( computed ) {
ret = computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
curCSS = function( elem, name ) {
var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
// we use jQuery.css instead of curCSS here
// because of the reliableMarginRight CSS hook!
val += jQuery.css( elem, extra + cssExpand[ i ], true );
}
// From this point on we use curCSS for maximum performance (relevant in animations)
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
} else {
// at this point, extra isn't content, so add padding
val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
valueIsBorderBox = true,
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
if ( elemdisplay[ nodeName ] ) {
return elemdisplay[ nodeName ];
}
var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ),
display = elem.css("display");
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// Use the already-created iframe if possible
iframe = document.body.appendChild(
iframe || jQuery.extend( document.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
})
);
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write("<!doctype html><html><body>");
iframeDoc.close();
}
elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) );
display = curCSS( elem, "display" );
document.body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
} else {
return getWidthOrHeight( elem, name, extra );
}
}
},
set: function( elem, value, extra ) {
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "marginRight" );
}
});
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
var ret = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rselectTextarea = /^(?:select|textarea)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
var // Document location
ajaxLocation,
// Document location segments
ajaxLocParts,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType, list, placeBefore,
dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ),
i = 0,
length = dataTypes.length;
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var selection,
list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters );
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
// Don't do a request if no elements are being requested
if ( !this.length ) {
return this;
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// Request the remote document
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params,
complete: function( jqXHR, status ) {
if ( callback ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
}
}
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append( responseText.replace( rscript, "" ) )
// Locate the specified elements
.find( selector ) :
// If not, just inject the full result
responseText );
});
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // ifModified key
ifModifiedKey,
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || strAbort;
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ ifModifiedKey ] = modified;
}
modified = jqXHR.getResponseHeader("Etag");
if ( modified ) {
jQuery.etag[ ifModifiedKey ] = modified;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = "" + ( nativeStatusText || statusText );
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.always( tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace );
// Determine if a cross-domain request is in order
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
var conv, conv2, current, tmp,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ],
converters = {},
i = 0;
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for ( ; (current = dataTypes[++i]); ) {
// There's only work to do if current dataType is non-auto
if ( current !== "*" ) {
// Convert response if prev dataType is non-auto and differs from current
if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split(" ");
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.splice( i--, 0, current );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s["throws"] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
var oldCallbacks = [],
rquestion = /\?/,
rjsonp = /(=)\?(?=&|$)|\?\?/,
nonce = jQuery.now();
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
data = s.data,
url = s.url,
hasCallback = s.jsonp !== false,
replaceInUrl = hasCallback && rjsonp.test( url ),
replaceInData = hasCallback && !replaceInUrl && typeof data === "string" &&
!( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") &&
rjsonp.test( data );
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
overwritten = window[ callbackName ];
// Insert callback into url or form data
if ( replaceInUrl ) {
s.url = url.replace( rjsonp, "$1" + callbackName );
} else if ( replaceInData ) {
s.data = data.replace( rjsonp, "$1" + callbackName );
} else if ( hasCallback ) {
s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var xhrCallbacks,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( _ ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback, 0 );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var end, unit, prevScale,
tween = this.createTween( prop, value ),
parts = rfxnum.exec( value ),
target = tween.cur(),
start = +target || 0,
scale = 1;
if ( parts ) {
end = +parts[2];
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" && start ) {
// Iteratively approximate from a nonzero starting point
// Prefer the current property, because this process will be trivial if it uses the same units
// Fallback to end or a simple constant
start = jQuery.css( tween.elem, prop, true ) || end || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
prevScale = scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zeroes from tween.cur()
scale = tween.cur() / target;
// Stop looping if we've hit the mark or scale is unchanged
} while ( scale !== 1 && scale !== prevScale );
}
tween.unit = unit;
tween.start = start;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
}, 0 );
return ( fxNow = jQuery.now() );
}
function createTweens( animation, props ) {
jQuery.each( props, function( prop, value ) {
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( collection[ index ].call( animation, prop, value ) ) {
// we're done with this property
return;
}
}
});
}
function Animation( elem, properties, options ) {
var result,
index = 0,
tweenerIndex = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
percent = 1 - ( remaining / animation.duration || 0 ),
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end, easing ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
createTweens( animation, props );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
anim: animation,
queue: animation.opts.queue,
elem: elem
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
var index, prop, value, length, dataShow, tween, hooks, oldfire,
anim = this,
style = elem.style,
orig = {},
handled = [],
hidden = elem.nodeType && isHidden( elem );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.done(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( index in props ) {
value = props[ index ];
if ( rfxtypes.exec( value ) ) {
delete props[ index ];
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
handled.push( index );
}
}
length = handled.length;
if ( length ) {
dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery.removeData( elem, "fxshow", true );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( index = 0 ; index < length ; index++ ) {
prop = handled[ index ];
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing any value as a 4th parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, false, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ||
// special check for .toggle( handler, handler, ... )
( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations resolve immediately
if ( empty ) {
anim.stop( true );
}
};
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) && !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.interval = 13;
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
var rroot = /^(?:body|html)$/i;
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var box, docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, top, left,
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
if ( (body = doc.body) === elem ) {
return jQuery.offset.bodyOffset( elem );
}
docElem = doc.documentElement;
// Make sure we're not dealing with a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return { top: 0, left: 0 };
}
box = elem.getBoundingClientRect();
win = getWindow( doc );
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
scrollTop = win.pageYOffset || docElem.scrollTop;
scrollLeft = win.pageXOffset || docElem.scrollLeft;
top = box.top + scrollTop - clientTop;
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.body;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, value, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
return jQuery;
})( window ); }));
})(window)
},{}]},{},[2])
; |
test/ModalHeaderSpec.js | HPate-Riptide/react-bootstrap | import React from 'react';
import ReactTestUtils from 'react-addons-test-utils';
import ReactDOM from 'react-dom';
import Modal from '../src/Modal';
describe('Modal.Header', () => {
it('uses "div" by default', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Modal.Header />
);
assert.equal(ReactDOM.findDOMNode(instance).nodeName, 'DIV');
});
it('has "modal-header" class', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Modal.Header />
);
assert.include(ReactDOM.findDOMNode(instance).className, 'modal-header');
});
it('should merge additional classes passed in', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Modal.Header className="custom-class" />
);
const classes = ReactDOM.findDOMNode(instance).className;
assert.include(classes, 'modal-header');
assert.include(classes, 'custom-class');
});
it('should render children', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Modal.Header>
<strong>Content</strong>
</Modal.Header>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong'));
});
it('has closeButton without a containing Modal and renders', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Modal.Header closeButton />
);
assert.isNotNull(ReactDOM.findDOMNode(instance));
});
it('Should trigger onHide when modal is closed', () => {
const onHideSpy = sinon.spy();
const instance = ReactTestUtils.renderIntoDocument(
<Modal.Header closeButton onHide={onHideSpy} />
);
const closeButton = ReactTestUtils.findRenderedDOMComponentWithClass(
instance,
'close',
);
ReactTestUtils.Simulate.click(closeButton);
expect(onHideSpy).to.have.been.called;
});
});
|
submissions/tonyhu/src/views/App.react.js | sensduo/flux-challenge |
import React from 'react';
import JediContainer from '../containers/JediContainer.react.js'
import WorldContainer from '../containers/WorldContainer.react.js'
export default class App extends React.Component {
render() {
return (
<div className="app-container">
<div className="css-root">
<WorldContainer />
<JediContainer />
</div>
</div>
);
}
}
|
components/dashboard/wrapper.js | Yutenko/stories360 | import React from 'react'
import {observer} from 'mobx-react'
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import injectTapEventPlugin from 'react-tap-event-plugin'
import getMuiTheme from 'material-ui/styles/getMuiTheme'
import DashboardStore from '../../stores/dashboardstore'
import {lightBlue400,amber600} from 'material-ui/styles/colors'
import DashboardLogin from './login'
import Dashboard from './dashboard'
injectTapEventPlugin();
const muiTheme = getMuiTheme({
palette: {
primary1Color:amber600,
accent1Color:lightBlue400
}
})
@observer
class DashboardWrapper extends React.Component {
render () {
const store = DashboardStore
return (
<MuiThemeProvider muiTheme={muiTheme}>
<div>
{store.isLoggedIn && <Dashboard />}
{!store.isLoggedIn && <DashboardLogin />}
</div>
</MuiThemeProvider>
)
}
}
export default DashboardWrapper
|
test/integration/AutoComplete/AutoComplete.spec.js | ichiohta/material-ui | /* eslint-env mocha */
import React from 'react';
import {assert} from 'chai';
import {mount} from 'enzyme';
import AutoComplete from 'src/AutoComplete';
import getMuiTheme from 'src/styles/getMuiTheme';
describe('<AutoComplete />', () => {
const muiTheme = getMuiTheme();
const mountWithContext = (node) => mount(node, {context: {muiTheme}});
describe('Popover', () => {
it('should open the Popover when we start typing keys', () => {
const wrapper = mountWithContext(
<AutoComplete id="search" dataSource={['foo', 'bar']} />
);
wrapper.find('input').simulate('change', {target: {value: 'f'}});
assert.strictEqual(wrapper.state().open, true);
});
});
});
|
frontend/node_modules/react-scripts/node_modules/babel-preset-react-app/node_modules/babel-preset-latest/node_modules/babel-preset-es2015/node_modules/babel-plugin-transform-es2015-modules-commonjs/node_modules/babel-template/node_modules/babel-traverse/lib/path/lib/hoister.js | andres81/auth-service | "use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var referenceVisitor = {
ReferencedIdentifier: function ReferencedIdentifier(path, state) {
if (path.isJSXIdentifier() && _babelTypes.react.isCompatTag(path.node.name) && !path.parentPath.isJSXMemberExpression()) {
return;
}
if (path.node.name === "this") {
var scope = path.scope;
do {
if (scope.path.isFunction() && !scope.path.isArrowFunctionExpression()) break;
} while (scope = scope.parent);
if (scope) state.breakOnScopePaths.push(scope.path);
}
var binding = path.scope.getBinding(path.node.name);
if (!binding) return;
if (binding !== state.scope.getBinding(path.node.name)) return;
state.bindings[path.node.name] = binding;
}
};
var PathHoister = function () {
function PathHoister(path, scope) {
(0, _classCallCheck3.default)(this, PathHoister);
this.breakOnScopePaths = [];
this.bindings = {};
this.scopes = [];
this.scope = scope;
this.path = path;
this.attachAfter = false;
}
PathHoister.prototype.isCompatibleScope = function isCompatibleScope(scope) {
for (var key in this.bindings) {
var binding = this.bindings[key];
if (!scope.bindingIdentifierEquals(key, binding.identifier)) {
return false;
}
}
return true;
};
PathHoister.prototype.getCompatibleScopes = function getCompatibleScopes() {
var scope = this.path.scope;
do {
if (this.isCompatibleScope(scope)) {
this.scopes.push(scope);
} else {
break;
}
if (this.breakOnScopePaths.indexOf(scope.path) >= 0) {
break;
}
} while (scope = scope.parent);
};
PathHoister.prototype.getAttachmentPath = function getAttachmentPath() {
var path = this._getAttachmentPath();
if (!path) return;
var targetScope = path.scope;
if (targetScope.path === path) {
targetScope = path.scope.parent;
}
if (targetScope.path.isProgram() || targetScope.path.isFunction()) {
for (var name in this.bindings) {
if (!targetScope.hasOwnBinding(name)) continue;
var binding = this.bindings[name];
if (binding.kind === "param") continue;
if (this.getAttachmentParentForPath(binding.path).key > path.key) {
this.attachAfter = true;
path = binding.path;
for (var _iterator = binding.constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var violationPath = _ref;
if (this.getAttachmentParentForPath(violationPath).key > path.key) {
path = violationPath;
}
}
}
}
}
return path;
};
PathHoister.prototype._getAttachmentPath = function _getAttachmentPath() {
var scopes = this.scopes;
var scope = scopes.pop();
if (!scope) return;
if (scope.path.isFunction()) {
if (this.hasOwnParamBindings(scope)) {
if (this.scope === scope) return;
return scope.path.get("body").get("body")[0];
} else {
return this.getNextScopeAttachmentParent();
}
} else if (scope.path.isProgram()) {
return this.getNextScopeAttachmentParent();
}
};
PathHoister.prototype.getNextScopeAttachmentParent = function getNextScopeAttachmentParent() {
var scope = this.scopes.pop();
if (scope) return this.getAttachmentParentForPath(scope.path);
};
PathHoister.prototype.getAttachmentParentForPath = function getAttachmentParentForPath(path) {
do {
if (!path.parentPath || Array.isArray(path.container) && path.isStatement() || path.isVariableDeclarator() && path.parentPath.node !== null && path.parentPath.node.declarations.length > 1) return path;
} while (path = path.parentPath);
};
PathHoister.prototype.hasOwnParamBindings = function hasOwnParamBindings(scope) {
for (var name in this.bindings) {
if (!scope.hasOwnBinding(name)) continue;
var binding = this.bindings[name];
if (binding.kind === "param" && binding.constant) return true;
}
return false;
};
PathHoister.prototype.run = function run() {
var node = this.path.node;
if (node._hoisted) return;
node._hoisted = true;
this.path.traverse(referenceVisitor, this);
this.getCompatibleScopes();
var attachTo = this.getAttachmentPath();
if (!attachTo) return;
if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return;
var uid = attachTo.scope.generateUidIdentifier("ref");
var declarator = t.variableDeclarator(uid, this.path.node);
var insertFn = this.attachAfter ? "insertAfter" : "insertBefore";
attachTo[insertFn]([attachTo.isVariableDeclarator() ? declarator : t.variableDeclaration("var", [declarator])]);
var parent = this.path.parentPath;
if (parent.isJSXElement() && this.path.container === parent.node.children) {
uid = t.JSXExpressionContainer(uid);
}
this.path.replaceWith(uid);
};
return PathHoister;
}();
exports.default = PathHoister;
module.exports = exports["default"]; |
ajax/libs/milojs/1.4.3/milo.bundle.js | jonobr1/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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';
var _ = require('milo-core').proto;
module.exports = Facet;
/**
* `milo.classes.Facet`
* Base Facet class is an ancestor of [ComponentFacet](../components/c_facet.js.html) class, the main building block in milo.
*
* @param {FacetedObject} owner an instance of FacetedObject subclass that stores the facet on its property with the same name as `name` property of facet
* @param {Object} config optional facet configuration, used in subclasses
*/
function Facet(owner, config) {
this.name = _.firstLowerCase(this.constructor.name);
this.owner = owner;
this.config = config || {};
this.init.apply(this, arguments);
}
/**
* `init` method of subclass will be called by Facet constructor.
*/
_.extendProto(Facet, {
init: function() {}
});
},{"milo-core":84}],2:[function(require,module,exports){
'use strict';
var Facet = require('./facet')
, miloCore = require('milo-core')
, _ = miloCore.proto
, logger = miloCore.util.logger
, check = miloCore.util.check
, Match = check.Match;
module.exports = FacetedObject;
/**
* `milo.classes.FacetedObject`
* Component class is based on an abstract ```FacetedObject``` class. This class can be used in any situation where objects can be represented via collection of facets (a facet is an object of a certain class, it holds its own configuration, data and methods).
* In a way, "facets pattern" is an inversion of "adapter pattern" - while the latter allows finding a class/methods that has specific functionality, faceted object is simply constructed to have these functionalities.
* With this architecture it is possible to create a virtually unlimited number of component classes with a very limited number of building blocks without having any hierarchy of classes - all components inherit directly from Component class.
*
* This constructor should be called by all subclasses constructor (it will happen automatically if a subclass is created with `_.createSubclass`).
*
* @return {FacetedObject}
*/
function FacetedObject() {
// this.facetsConfig and this.facetsClasses were stored on a specific class prototype
// when the class was created by FacetedObject.createFacetedClass
var facetsConfig = this.facetsConfig || {};
var facetsDescriptors = {}
, facets = {};
// FacetedObject class itself is not meant to be instantiated - it has no facets
// It may change, as adding facets is possible to instances
if (this.constructor == FacetedObject)
throw new Error('FacetedObject is an abstract class, can\'t be instantiated');
// instantiate class facets
if (this.facetsClasses)
_.eachKey(this.facetsClasses, instantiateFacet, this, true);
// add facets to the class as properties under their own name
Object.defineProperties(this, facetsDescriptors);
// store all facets on `facets` property so that they can be enumerated
_.defineProperty(this, 'facets', facets);
// call `init`method if it is defined in subclass
if (this.init)
this.init.apply(this, arguments);
// instantiate facet with a given class (FacetClass) and name (facetName)
function instantiateFacet(FacetClass, facetName) {
// get facet configuration
var fctConfig = facetsConfig[facetName];
// instatiate facets
facets[facetName] = new FacetClass(this, fctConfig);
// add facet to property descriptors
facetsDescriptors[facetName] = {
enumerable: true,
value: facets[facetName]
};
}
}
/**
* ####FacetedObject class methods####
*
* - [createFacetedClass](#FacetedObject$$createFacetedClass)
* - [hasFacet](#FacetedObject$$hasFacet)
*/
_.extend(FacetedObject, {
createFacetedClass: FacetedObject$$createFacetedClass,
hasFacet: FacetedObject$$hasFacet,
getFacetConfig: FacetedObject$$getFacetConfig
});
/**
* ####FacetedObject instance methods####
*
* - [addFacet](#FacetedObject$addFacet)
*/
_.extendProto(FacetedObject, {
addFacet: FacetedObject$addFacet
});
/**
* FacetedObject instance method.
* Adds a facet to the instance of FacetedObject subclass.
* Returns an instance of the facet that was created.
*
* @param {Function} FacetClass facet class constructor
* @param {Object} facetConfig optional facet configuration
* @param {String} facetName optional facet name, FacetClass.name will be used if facetName is not passed.
* @param {Boolean} throwOnErrors If set to false, then errors will only be logged to console. True by default.
* @return {Facet}
*/
function FacetedObject$addFacet(FacetClass, facetConfig, facetName, throwOnErrors) {
check(FacetClass, Function);
check(facetName, Match.Optional(String));
// first letter of facet name should be lowercase
facetName = _.firstLowerCase(facetName || FacetClass.name);
// get facets defined in class
var protoFacets = this.constructor.prototype.facetsClasses;
// check that this facetName was not already used in the class
if (protoFacets && protoFacets[facetName])
throw new Error('facet ' + facetName + ' is already part of the class ' + this.constructor.name);
// check that this faceName does not already exist on the faceted object
if (this[facetName]) {
var message = 'facet ' + facetName + ' is already present in object';
if (throwOnErrors === false)
return logger.error('FacetedObject addFacet: ', message);
else
throw new Error(message);
}
// instantiate the facet
var newFacet = this.facets[facetName] = new FacetClass(this, facetConfig);
// add facet to faceted object
_.defineProperty(this, facetName, newFacet, _.ENUM);
return newFacet;
}
/**
* FacetedObject class method
* Returns reference to the facet class if the facet with `facetName` is part of the class, `undefined` otherwise. If subclass is created using _.createSubclass (as it should be) it will also have this method.
*
* @param {Subclass(FacetedObject)} this this in this method refers to FacetedObject (or its subclass) that calls this method
* @param {String} facetName
* @return {Subclass(Facet)|undefined}
*/
function FacetedObject$$hasFacet(facetName) {
// this refers to the FacetedObject class (or subclass), not instance
var protoFacets = this.prototype.facetsClasses;
return protoFacets && protoFacets[facetName];
}
/**
* FacetedObject class method
* Return the configuration of a facet
* @param {String} facetName the facet which config should be retrieved
* @return {Object} the configuration object that was passed to the facet
*/
function FacetedObject$$getFacetConfig(facetName) {
return this.hasFacet(facetName) ? this.prototype.facetsConfig[facetName] : null;
}
/**
* FacetedObject class method
* Class factory that creates classes (constructor functions) from the maps of facets and their configurations.
* Created class will be subclass of `FacetedObject`.
*
* @param {Subclass(FacetedObject)} this this in this method refers to FacetedObject (or its subclass) that calls this method
* @param {String} name class name (will be function name of class constructor function)
* @param {Object[Subclass(Facet)]} facetsClasses map of classes of facets that will constitute the created class
* @param {Object<Object>} facetsConfig map of facets configuration, should have the same keys as the map of classes. Some facets may not have configuration, but the configuration for a facet that is not included in facetsClasses will throw an exception
* @return {Subclass(FacetedObject)}
*/
function FacetedObject$$createFacetedClass(name, facetsClasses, facetsConfig) {
check(name, String);
check(facetsClasses, Match.Optional(Match.ObjectHash(Match.Subclass(Facet, true))));
check(facetsConfig, Match.Optional(Object));
// throw exception if config passed for facet for which there is no class
if (facetsConfig)
_.eachKey(facetsConfig, function(fctConfig, fctName) {
if (! facetsClasses.hasOwnProperty(fctName))
throw new Error('configuration for facet (' + fctName + ') passed that is not in class');
});
// create subclass of the current class (this refers to the class that calls this method)
var FacetedClass = _.createSubclass(this, name, true);
// get facets classes and configurations from parent class
facetsClasses = addInheritedFacets(this, facetsClasses, 'facetsClasses');
facetsConfig = addInheritedFacets(this, facetsConfig, 'facetsConfig');
// store facets classes and configurations of class prototype
_.extendProto(FacetedClass, {
facetsClasses: facetsClasses,
facetsConfig: facetsConfig
});
return FacetedClass;
function addInheritedFacets(superClass, facetsInfo, facetsInfoName) {
var inheritedFacetsInfo = superClass.prototype[facetsInfoName];
if (inheritedFacetsInfo)
return _(inheritedFacetsInfo)
.clone()
.extend(facetsInfo || {})._();
else
return facetsInfo;
}
}
},{"./facet":1,"milo-core":84}],3:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match;
module.exports = ClassRegistry;
/**
* `milo.classes.ClassRegistry` - the registry of classes class.
* Components and Facets register themselves in registries. It allows to avoid requiring them from one module and prevents circular dependencies between modules.
*
* @param {Function} FoundationClass All classes that are registered in the registry should be subclasses of the FoundationClass
* @return {Object}
*/
function ClassRegistry (FoundationClass) {
if (FoundationClass)
this.setClass(FoundationClass);
this.__registeredClasses = {};
}
/**
* ####ClassRegistry instance methods####
*
* - [add](#add)
* - [get](#get)
* - [remove](#remove)
* - [clean](#clean)
* - [setClass](#setClass)
*/
_.extendProto(ClassRegistry, {
add: add,
get: get,
remove: remove,
clean: clean,
setClass: setClass
});
/**
* ClassRegistry instance method that registers a class in the registry.
* The method will throw an exception if a class is registered under the same name as previously registered class.
* The method allows registering the same class under a different name, so class aliases can be created.
*
* @param {Function} aClass class to register in the registry. Should be subclass of `this.FoundationClass`.
* @param {String} name Optional class name. If class name is not specified, it will be taken from constructor function name. Class name should be a valid identifier and cannot be an empty string.
*/
function add(aClass, name) {
name = name || aClass.name;
check(name, Match.IdentifierString, 'class name must be identifier string');
if (this.FoundationClass) {
if (aClass != this.FoundationClass)
check(aClass, Match.Subclass(this.FoundationClass), 'class must be a sub(class) of a foundation class');
} else
throw new Error('foundation class must be set before adding classes to registry');
if (this.__registeredClasses[name])
throw new Error('class "' + name + '" is already registered');
this.__registeredClasses[name] = aClass;
}
/**
* Gets class from registry by name
*
* @param {String} name Class name
* @return {Function}
*/
function get(name) {
check(name, String, 'class name must be string');
return this.__registeredClasses[name];
}
/**
* Remove class from registry by its name.
* If class is not registered, this method will throw an exception.
*
* @param {String|Function} nameOrClass Class name. If class constructor is supplied, its name will be used.
*/
function remove(nameOrClass) {
check(nameOrClass, Match.OneOf(String, Function), 'class or name must be supplied');
var name = typeof nameOrClass == 'string'
? nameOrClass
: nameOrClass.name;
if (! this.__registeredClasses[name])
throw new Error('class is not registered');
delete this.__registeredClasses[name];
}
/**
* Removes all classes from registry.
*/
function clean() {
this.__registeredClasses = {};
}
/**
* Sets `FoundationClass` of the registry. It should be set before any class can be added.
*
* @param {Function} FoundationClass Any class that will be added to the registry should be a subclass of this class. FoundationClass itself can be added to the registry too.
*/
function setClass(FoundationClass) {
check(FoundationClass, Function);
_.defineProperty(this, 'FoundationClass', FoundationClass, _.ENUM);
}
},{"milo-core":84}],4:[function(require,module,exports){
'use strict';
var Attribute = require('./a_class')
, config = require('../config')
, miloCore = require('milo-core')
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match
, componentName = require('../util/component_name');
var ATTRIBUTE_REGEXP= /^([^\:\[\]]*)(?:\[([^\:\[\]]*)\])?\:?([^:]*)$/
, FACETS_SPLIT_REGEXP = /\s*(?:\,|\s)\s*/
, ATTRIBUTE_TEMPLATE = '%compClass%compFacets:%compName';
/**
* `milo.attributes.bind`
* BindAttribute class parses/validates/etc. an attribute that binds DOM elements to milo components.
* Possible attribute values are:
*
* - `:myView` - only component name
* - `View:myView` - class and component name
* - `[Events, Data]:myView` - facets and component name
* - `View[Events]:myView` - class, facet(s) and component name
*
* See [binder](../binder.js.html) for more information.
*/
var BindAttribute = _.createSubclass(Attribute, 'BindAttribute', true);
/**
* ####BindAttribute instance methods####
*
* - [attrName](#attrName)
* - [parse](#parse)
* - [validate](#validate)
* - [render](#render)
*/
_.extendProto(BindAttribute, {
attrName: attrName,
parse: parse,
validate: validate,
render: render
});
/**
* BindAttribute class methods
*
* - [setInfo](#BindAttribute$$setInfo)
*/
_.extend(BindAttribute, {
setInfo: BindAttribute$$setInfo
});
module.exports = BindAttribute;
/**
* BindAttribute instance method that returns attribute name, by default - `'ml-bind'`.
* To configure bind attribute name use:
* ```
* milo.config({ attrs: { bind: 'cc-bind' } }); // will set bind attribute to 'cc-bind'
* ```
*
* @return {String}
*/
function attrName() {
return config.attrs.bind;
}
/**
* BindAttribute instance method that parses bind attribute if it is present on the element.
* It defines properties `compClass`, `compFacets` and `compName` on BindAttribute instance.
* Returns the instance for method chaining.
*
* @return {BindAttribute}
*/
function parse() {
if (! this.node) return;
var value = this.get();
if (value)
var bindTo = value.match(ATTRIBUTE_REGEXP);
if (! bindTo)
throw new Error('invalid bind attribute ' + value);
this.compClass = bindTo[1] || 'Component';
this.compFacets = (bindTo[2] && bindTo[2].split(FACETS_SPLIT_REGEXP)) || undefined;
this.compName = bindTo[3] || componentName();
return this;
}
/**
* BindAttribute instance method that validates bind attribute, throws if it has an invalid value.
* Returns the instance for method chaining.
*
* @return {BindAttribute}
*/
function validate() {
check(this.compName, Match.IdentifierString);
if (! this.compClass)
throw new Error('empty component class name ' + this.compClass);
return this;
}
/**
* BindAttribute instance method that returns the attribute value for given values of properties `compClass`, `compName` and `compFacets`.
* If `this.compName` is not set it will be generated automatically.
*
* @return {String}
*/
function render() {
this.compName = this.compName || componentName();
return ATTRIBUTE_TEMPLATE
.replace('%compClass', this.compClass || '')
.replace('%compFacets', this.compFacets && this.compFacets.length
? '[' + this.compFacets.join(', ') + ']'
: '')
.replace('%compName', this.compName);
}
/**
* BindAttribute class method
* @param {Element} el
* @param {String} componentClass optional class name
* @param {String} componentName optional
* @param {Array<String>} componentFacets optional extra facet to add to the class
*/
function BindAttribute$$setInfo(el, componentClass, componentName, componentFacets) {
var attr = new BindAttribute(el);
_.extend(attr, {
compClass: componentClass,
compName: componentName,
compFacets: componentFacets
});
attr.decorate();
}
},{"../config":42,"../util/component_name":53,"./a_class":5,"milo-core":84}],5:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match;
module.exports = Attribute;
/**
* An absctract class for parsing and validation of element attributes.
* Subclasses should define methods `attrName`, `parse`, `validate` and `render`.
*
* @param {Element} el DOM element where attribute is attached
* @param {String} name Optional name of the attribute, usually supplied by subclass via `attrName` method
*/
function Attribute(el, name) {
this.name = name || this.attrName();
this.el = el;
// attribute node
this.node = el.attributes[this.name];
}
_.extend(Attribute, {
remove: Attribute$$remove
});
/**
* ####Attribute instance methods####
*
* - [get](#Attribute$get)
* - [set](#Attribute$set)
* - [decorate](#Attribute$decorate)
*
* The following instance methods should be defined by subclass
*
* - attrName - should return attribute name
* - parse - should parse attribute value
* - validate - should validate attribute value, throwing exception if it is incorrect
* - render - should return attribute value for a given attribute state (other properties, as defined in subclass)
*/
_.extendProto(Attribute, {
get: Attribute$get,
set: Attribute$set,
remove: Attribute$remove,
decorate: Attribute$decorate,
destroy: Attribute$destroy,
// should be defined in subclass
attrName: toBeImplemented,
parse: toBeImplemented,
validate: toBeImplemented,
render: toBeImplemented
});
function Attribute$$remove(el, deep) {
var name = this.prototype.attrName();
el.removeAttribute(name);
if (deep) {
var selector = '[' + name + ']';
var children = el.querySelectorAll(selector);
_.forEach(children, function(childEl) {
childEl.removeAttribute(name);
});
}
}
function Attribute$remove() {
delete this.node;
}
function Attribute$destroy() {
delete this.el;
delete this.node;
}
/**
* Attribute instance method that returns attribute value as string.
*
* @return {String}
*/
function Attribute$get() {
return this.el.getAttribute(this.name);
}
/**
* Attribute instance method that sets attribute value.
*
* @param {String} value
*/
function Attribute$set(value) {
this.el.setAttribute(this.name, value);
}
/**
* Attribute instance method that decorates element with its rendered value.
* Uses `render` method that should be defiend in subclass.
*/
function Attribute$decorate() {
this.set(this.render());
}
function toBeImplemented() {
throw new Error('calling the method of an absctract class');
}
},{"milo-core":84}],6:[function(require,module,exports){
'use strict';
var Attribute = require('./a_class')
, config = require('../config')
, _ = require('milo-core').proto;
/**
* `milo.attributes.load`
* LoadAttribute class parses/validates/etc. an attribute that loads sub-views into the page.
* Attribute value should be URL of the file to load subview from.
* See [loader](../loader.js.html) for more information.
*/
var LoadAttribute = _.createSubclass(Attribute, 'LoadAttribute', true);
/**
* ####LoadAttribute instance methods####
*
* - [attrName](#attrName)
* - [parse](#parse)
* - [validate](#validate)
* - [render](#render)
*/
_.extendProto(LoadAttribute, {
attrName: attrName,
parse: parse,
validate: validate,
render: render
});
module.exports = LoadAttribute;
/**
* BindAttribute instance method that returns attribute name, by default - `'ml-load'`.
* To configure load attribute name use:
* ```
* milo.config({ attrs: { load: 'cc-load' } }); // will set bind attribute to 'cc-load'
* ```
*
* @return {String}
*/
function attrName() {
return config.attrs.load;
}
/**
* LoadAttribute instance method that parses load attribute if it is present on the element.
* It defines property `loadUrl` on LoadAttribute instance.
* Returns the instance for method chaining.
*
* @return {LoadAttribute}
*/
function parse() {
if (! this.node) return;
this.loadUrl = this.get();
return this;
}
/**
* LoadAttribute instance method that should validate load attribute and throw if it has an invalid value.
* TODO - implement url validation.
* Returns the instance for method chaining.
*
* @return {LoadAttribute}
*/
function validate() {
// TODO url validation
return this;
}
/**
* LoadAttribute instance method - returns URL
*
* @return {String}
*/
function render() {
return this.loadUrl;
}
},{"../config":42,"./a_class":5,"milo-core":84}],7:[function(require,module,exports){
'use strict';
/**
* Subclasses of [Attribute](./a_class.js.html) class
*
* - [BindAttribute](./a_bind.js.html)
* - [LoadAttribute](./a_load.js.html)
*/
var attributes = module.exports = {
bind: require('./a_bind'),
load: require('./a_load')
};
},{"./a_bind":4,"./a_load":6}],8:[function(require,module,exports){
'use strict';
var miloMail = require('./services/mail')
, componentsRegistry = require('./components/c_registry')
, facetsRegistry = require('./components/c_facets/cf_registry')
, Component = componentsRegistry.get('Component')
, ComponentInfo = require('./components/c_info')
, Scope = require('./components/scope')
, BindAttribute = require('./attributes/a_bind')
, miloCore = require('milo-core')
, _ = miloCore.proto
, check = miloCore.util.check
, utilDom = require('./util/dom')
, Match = check.Match;
binder.scan = scan;
binder.create = create;
binder.twoPass = twoPass;
module.exports = binder;
/**
* `milo.binder`
*
* Recursively scans the document tree inside `scopeEl` (document.body by default) looking for __ml-bind__ attribute that should contain the class, additional facets and the name of the component that should be created and bound to the element.
*
* Possible values of __ml-bind__ attribute:
*
* - `:myView` - only component name. An instance of Component class will be created without any facets.
* - `View:myView` - class and component name. An instance of View class will be created.
* - `[Events, Data]:myView` - facets and component name. An instance of Component class will be created with the addition of facets Events and Data.
* - `View[Events, Data]:myView` - class, facet(s) and component name. An instance of View class will be created with the addition of facets Events and Data.
*
* Function returns an instance of [`Scope`](./components/scope.js.html) class containing all components created as a result of scanning DOM.
*
* If the component has [`Container`](./components/c_facets/Container.js) facet, children of this element will be stored in the `scope` object, available as scope property on the Container facet of this component. Names of components within the scope should be unique, but they can be the same as the names of components in outer scope (or some other scope).
*
* @param {Element} scopeEl root element inside which DOM will be scanned and bound
* @param {Scope} rootScope Optional Root scope object where top level components will be saved.
* @param {Boolean} bindRootElement If set to false, then the root element will not be bound. True by default.
* @param {Boolean} throwOnErrors If set to false, then errors will only be logged to console. True by default.
* @return {Scope}
*/
function binder(scopeEl, rootScope, bindRootElement, throwOnErrors) {
return createBinderScope(scopeEl, function(scope, el, attr, throwOnErrors) {
var info = new ComponentInfo(scope, el, attr, throwOnErrors);
return Component.create(info, throwOnErrors);
}, rootScope, bindRootElement, throwOnErrors);
}
// bind in two passes
function twoPass(scopeEl, rootScope, bindRootElement, throwOnErrors) {
var scanScope = binder.scan(scopeEl, rootScope, bindRootElement, throwOnErrors);
return binder.create(scanScope, undefined, throwOnErrors);
}
// scan DOM for BindAttribute
function scan(scopeEl, rootScope, bindRootElement, throwOnErrors) {
return createBinderScope(scopeEl, function(scope, el, attr, throwOnErrors) {
return new ComponentInfo(scope, el, attr, throwOnErrors);
}, rootScope, bindRootElement, throwOnErrors);
}
// create bound components
function create(scanScope, hostObject, throwOnErrors) {
var scope = new Scope(scanScope._rootEl, hostObject)
, addMethod = throwOnErrors === false ? '_safeAdd' : '_add';
scanScope._each(function(compInfo) {
// set correct component's scope
var info = _.clone(compInfo);
info.scope = scope;
// create component
var aComponent = Component.create(info, throwOnErrors);
scope[addMethod](aComponent, aComponent.name);
if (aComponent.container)
aComponent.container.scope = create(compInfo.container.scope, aComponent.container, throwOnErrors);
});
return scope;
}
/**
* `createBinderScope`
* @param {Element} scopeEl scopeEl root element inside which DOM will be scanned and bound (document.body by default).
* @param {Function} scopeObjectFactory See [binder](#milo.binder)
* @param {Scope} rootScope Optional Root scope object where top level components will be saved.
* @param {Boolean} bindRootElement If set to false, then the root element will not be bound. True by default.
* @param {Boolean} throwOnErrors If set to false, then errors will only be logged to console. True by default.
* @return {Scope} [description]
*/
function createBinderScope(scopeEl, scopeObjectFactory, rootScope, bindRootElement, throwOnErrors) {
scopeEl = scopeEl || document.body;
var scope = rootScope || new Scope(scopeEl)
, addMethod = throwOnErrors === false ? '_safeAdd' : '_add';
createScopeForElement(scope, scopeEl, bindRootElement);
return scope;
function createScopeForElement(scope, el, bindRootElement) {
// get element's binding attribute (ml-bind by default)
var attr = new BindAttribute(el);
// if element has bind attribute crate scope object (Component or ComponentInfo)
if (attr.node && bindRootElement !== false) {
var scopedObject = scopeObjectFactory(scope, el, attr, throwOnErrors)
, isContainer = typeof scopedObject != 'undefined' && scopedObject.container;
}
// if there are childNodes add children to new scope if this element has component with Container facet
// otherwise create a new scope
if (el.childNodes && el.childNodes.length) {
if (isContainer) {
var innerScope = new Scope(el);
scopedObject.container.scope = innerScope;
innerScope._hostObject = scopedObject.container;
}
createScopeForChildren(el, isContainer ? innerScope : scope);
}
// if scope wasn't previously created on container facet, create empty scope anyway
if (isContainer && ! scopedObject.container.scope)
scopedObject.container.scope = new Scope(el);
// TODO condition after && is a hack, should not be used!
if (scopedObject) // && ! scope[attr.compName])
scope[addMethod](scopedObject, attr.compName);
// _.defer(postChildrenBoundMessage, el);
postChildrenBoundMessage(el);
return scopedObject;
function postChildrenBoundMessage(el) {
var elComp = Component.getComponent(el);
if (elComp) {
elComp.postMessageSync('childrenbound');
elComp.childrenBound();
}
}
}
function createScopeForChildren(containerEl, scope) {
var children = utilDom.children(containerEl);
_.forEach(children, function(node) {
createScopeForElement(scope, node, true);
});
return scope;
}
}
},{"./attributes/a_bind":4,"./components/c_facets/cf_registry":31,"./components/c_info":32,"./components/c_registry":33,"./components/scope":41,"./services/mail":48,"./util/dom":57,"milo-core":84}],9:[function(require,module,exports){
'use strict';
var coreClasses = require('milo-core').classes;
// <a name="classes"></a>
// milo.classes
// -----------
// This module contains foundation classes and class registries.
var classes = {
Facet: require('./abstract/facet'),
FacetedObject: require('./abstract/faceted_object'),
Scope: require('./components/scope'),
ClassRegistry: require('./abstract/registry'),
Mixin: coreClasses.Mixin,
MessageSource: coreClasses.MessageSource,
MessengerMessageSource: coreClasses.MessengerMessageSource,
MessengerAPI: coreClasses.MessengerAPI,
DOMEventsSource: require('./components/msg_src/dom_events'),
Transaction: require('./command/transaction'),
TransactionHistory: require('./command/transaction_history')
};
module.exports = classes;
},{"./abstract/facet":1,"./abstract/faceted_object":2,"./abstract/registry":3,"./command/transaction":13,"./command/transaction_history":14,"./components/msg_src/dom_events":39,"./components/scope":41,"milo-core":84}],10:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, _ = miloCore.proto
, logger = miloCore.util.logger;
module.exports = ActionsHistory;
/**
* Stores list of commands or transactions
*
* @constructor
* @param {Number} maxLength
*/
function ActionsHistory(maxLength) {
this._maxLength = maxLength || Infinity;
this.actions = [];
this.position = 0;
}
_.extendProto(ActionsHistory, {
store: ActionsHistory$store,
deleteLast: ActionsHistory$deleteLast,
undo: ActionsHistory$undo,
redo: ActionsHistory$redo,
nextUndoAction: ActionsHistory$getLastAction,
nextRedoAction: ActionsHistory$nextRedoAction,
undoAll: ActionsHistory$undoAll,
redoAll: ActionsHistory$redoAll,
undoAllAsync: ActionsHistory$undoAllAsync,
redoAllAsync: ActionsHistory$redoAllAsync,
each: ActionsHistory$each,
eachReverse: ActionsHistory$eachReverse,
getLastAction: ActionsHistory$getLastAction,
getDescription: ActionsHistory$getDescription
});
function ActionsHistory$store(command) {
_truncateToCurrentPosition.call(this);
this.actions.push(command);
if (this.actions.length > this._maxLength) {
var act = this.actions.shift();
act.destroy();
}
this.position = this.actions.length;
return this.position - 1;
}
function ActionsHistory$deleteLast() {
if (!this.actions.length) return;
this.position--;
var act = this.actions.pop();
act.destroy();
}
function _truncateToCurrentPosition() {
for (var i = this.position; i < this.actions.length; i++)
this.actions[i].destroy();
this.actions.length = this.position;
}
function ActionsHistory$undo(cb) {
if (this.position === 0) return; // nothing to undo
var act = this.actions[--this.position];
act.undo(cb);
return act;
}
function ActionsHistory$redo(cb) {
if (this.position == this.actions.length) return; // nothing to redo
var act = this.actions[this.position++];
act.redo(cb);
return act;
}
function ActionsHistory$nextRedoAction() {
return this.actions[this.position];
}
function ActionsHistory$undoAll() {
while (this.position) this.undo();
}
function ActionsHistory$redoAll() {
while (this.position < this.actions.length) this.redo();
}
function ActionsHistory$undoAllAsync(cb) {
if (this.position) {
this.undo();
if (this.position)
_.deferMethod(this, 'undoAllAsync', cb);
else
if (cb) _.defer(cb);
}
}
function ActionsHistory$redoAllAsync(cb) {
if (this.position < this.actions.length) {
this.redo();
if (this.position < this.actions.length)
_.deferMethod(this, 'redoAllAsync', cb);
else
if (cb) _.defer(cb);
}
}
function ActionsHistory$each(funcOrMethod, thisArg) {
var func = typeof funcOrMethod == 'string'
? function(act) { act[funcOrMethod](); }
: funcOrMethod;
this.actions.forEach(func, thisArg || this);
}
function ActionsHistory$eachReverse(funcOrMethod, thisArg) {
this.actions.reverse();
this.each(funcOrMethod, thisArg);
this.actions.reverse();
}
function ActionsHistory$getLastAction() {
return this.position && this.actions[this.position - 1];
}
function ActionsHistory$getDescription() {
var actions = this.actions.map(function(act) {
return act.getDescription();
});
return {
actions: actions,
position: this.position,
length: actions.length
};
}
},{"milo-core":84}],11:[function(require,module,exports){
'use strict';
var ClassRegistry = require('../abstract/registry')
, Command = require('./index');
/**
* `milo.registry.components`
* An instance of [ClassRegistry](../abstract/registry.js.html) class that is used by milo to register and find components.
*/
var commandsRegistry = new ClassRegistry(Command);
// add common ancestor to all components to the registry.
commandsRegistry.add(Command);
module.exports = commandsRegistry;
},{"../abstract/registry":3,"./index":12}],12:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match
, logger = miloCore.util.logger;
var UNDO_COMMAND = '_undoCommand';
module.exports = Command;
/**
* Command class to implement "command pattern" - packaging ll information necessary for delayed method execution
*
* @constructor
* @param {Function} func method name or function to be executed
* @param {List} *arguments parameters to be passed to method or function
*/
function Command(func) { // , ... arguments
this.init.apply(this, arguments);
}
/**
* Command instance methods
*
* - [init](#Command$execute) - initialize command, should be overwritten by subclasses
* - [execute](#Command$execute) - execute command
* - [setUndo](#Command$setUndo) - set undo command for this command
* - [getUndo](#Command$getUndo) - get undo command of this command
* - [setArguments](#Command$setArguments) - set commands arguments
* - [addArguments](#Command$addArguments) - add arguments to command
* - [destroy](#Command$destroy)
*/
_.extendProto(Command, {
init: Command$init,
execute: Command$execute,
setUndo: Command$setUndo,
getUndo: Command$getUndo,
undo: Command$undo,
redo: Command$execute, // same for command, different for transaction
setArguments: Command$setArguments,
addArguments: Command$addArguments,
getArguments: Command$getArguments,
changeArguments: Command$changeArguments,
destroy: Command$destroy,
setComment: Command$setComment,
getDescription: Command$getDescription
});
/**
* Command class methods
*
* - [create](#Command$$create) - commands factory
*/
_.extend(Command, {
create: Command$$create,
createWithUndo: Command$$createWithUndo
});
function Command$init(func) { // , ... arguments
check(func, Match.Optional(Function));
this.func = func || function(){};
this.args = _.slice(arguments, 1);
}
/**
* Execute command making command object available via function property.
*/
function Command$execute(cb) {
var result = this.func.apply(this, this.args);
if (cb) _.defer(cb);
return result;
}
/**
* Set undo command for this command. This command becomes undo command for undo command (so undo command can change this command during its execution).
*
* @param {Command} undoCommand
*/
function Command$setUndo(undoCommand) {
if (this[UNDO_COMMAND])
logger.warn('Command setUndo: undo command is already set');
this[UNDO_COMMAND] = undoCommand;
undoCommand[UNDO_COMMAND] = this;
}
/**
* Returns undo command of a given command
*
* @return {Command}
*/
function Command$getUndo() {
return this[UNDO_COMMAND];
}
/**
* Executes undo command of current command
*/
function Command$undo(cb) {
var undoCmd = this.getUndo();
if (! undoCmd) return logger.error('Command undo called without undo command present');
var result = undoCmd.execute();
if (cb) _.defer(cb);
return result;
}
/**
* Set command's arguments. If arguments were set during command's creation, this method will overwrite arguments and log warning.
*
* @param {List} *arguments
*/
function Command$setArguments() { //, ... arguments
if (this.args && this.args.length)
logger.warn('Command setArguments: command arguments are already set');
this.args = _.toArray(arguments);
}
function Command$getArguments() {
return this.args;
}
function Command$changeArguments() { //, ... arguments
this.args = _.toArray(arguments);
}
/**
* Add (append) arguments to command
*
* @param {List} *arguments arguments list to be appended to command
*/
function Command$addArguments() { //, ... arguments
if (! this.args) this.args = [];
_.appendArray(this.args, arguments);
}
/**
* Commands factory. Likely ot be overridden by subclasses to implement custom logic of command construction
*
* @this {Function} Class of command
* @param {Function} func method name or function to be executed
* @param {List} *arguments parameters to be passed to method or function
* @return {Command}
*/
function Command$$create(func) { // , ... arguments
return _.newApply(this, arguments);
}
function Command$$createWithUndo() {
throw new Error('createWithUndo should be implemented by subsclass');
}
/**
* Destroy current command (to prevent potential memory leaks when commands point to DOM elements)
*/
function Command$destroy() {
delete this.func;
delete this.args;
var undoCmd = this[UNDO_COMMAND];
if (undoCmd) {
delete this[UNDO_COMMAND][UNDO_COMMAND];
delete this[UNDO_COMMAND];
undoCmd.destroy();
}
}
function Command$setComment(comment) {
this.comment = comment;
}
function Command$getDescription() {
return {
func: this.func.name,
comment: this.comment
};
}
},{"milo-core":84}],13:[function(require,module,exports){
'use strict';
var ActionsHistory = require('./actions_history')
, _ = require('milo-core').proto;
module.exports = Transaction;
function Transaction() {
this.commands = new ActionsHistory;
}
_.extendProto(Transaction, {
execute: Transaction$execute,
undo: Transaction$undo,
redo: Transaction$redo,
destroy: Transaction$destroy,
storeCommand: Transaction$storeCommand,
merge: Transaction$merge,
setComment: Transaction$setComment,
getDescription: Transaction$getDescription
});
function Transaction$execute() {
this.commands.each('execute');
}
function Transaction$undo(cb) {
this.commands.undoAllAsync(cb);
}
function Transaction$redo(cb) {
this.commands.redoAllAsync(cb);
}
function Transaction$destroy() {
this.commands.each('destroy');
}
function Transaction$storeCommand(command) {
this.commands.store(command);
}
function Transaction$merge(transaction) {
transaction.commands.each(function(cmd) {
this.commands.store(cmd);
}, this);
if (transaction.comment) this.comment = transaction.comment;
}
function Transaction$setComment(comment) {
this.comment = comment;
}
function Transaction$getDescription() {
var commands = this.commands.getDescription();
return {
commands: commands.actions,
comment: this.comment
};
}
},{"./actions_history":10,"milo-core":84}],14:[function(require,module,exports){
'use strict';
var ActionsHistory = require('./actions_history')
, Transaction = require('./transaction')
, miloCore = require('milo-core')
, logger = miloCore.util.logger
, Messenger = miloCore.Messenger
, _ = miloCore.proto;
module.exports = TransactionHistory;
var SCHEDULED = '_scheduled';
function TransactionHistory(maxLength) {
this.transactions = new ActionsHistory(maxLength);
this.currentBatch = undefined;
this.currentTransaction = undefined;
this[SCHEDULED] = false;
}
_.extendProto(TransactionHistory, {
storeCommand: TransactionHistory$storeCommand,
endTransaction: TransactionHistory$endTransaction,
storeTransaction: TransactionHistory$storeTransaction,
deleteLastTransaction: TransactionHistory$deleteLastTransaction,
undo: TransactionHistory$undo,
redo: TransactionHistory$redo,
inTransaction: TransactionHistory$inTransaction,
getDescription: TransactionHistory$getDescription,
useMessenger: TransactionHistory$useMessenger,
destroy: TransactionHistory$destroy
});
/**
* Stores command in the history.
* @param {Command} command
* @param {Boolean} appendTransaction If `true`, appends to the current or previous transaction if there is no current transaction.
*/
function TransactionHistory$storeCommand(command, appendTransaction) {
if (appendTransaction && !(this.currentTransaction || this.currentBatch)) {
var transaction = this.transactions.getLastAction();
transaction.storeCommand(command);
_postTransactionMessage.call(this, 'appended', transaction);
return transaction;
}
if (! this.currentBatch) this.currentBatch = new Transaction;
this.currentBatch.storeCommand(command);
if (! this[SCHEDULED]) {
this[SCHEDULED] = true;
_.deferMethod(this, _storeTransaction);
}
return this.currentBatch;
}
function TransactionHistory$deleteLastTransaction() {
if (this.currentBatch || this.currentTransaction) {
this.currentBatch = undefined;
this.currentTransaction = undefined;
} else {
this.transactions.deleteLast();
}
}
function _storeTransaction() {
if (this.currentBatch) {
_addBatchToTransaction.call(this);
_.deferMethod(this, _storeTransaction);
} else {
_storeCurrentTransaction.call(this);
this[SCHEDULED] = false;
}
}
function TransactionHistory$endTransaction() {
_addBatchToTransaction.call(this);
_storeCurrentTransaction.call(this);
}
function _addBatchToTransaction() {
if (this.currentBatch) {
if (! this.currentTransaction) this.currentTransaction = new Transaction;
this.currentTransaction.merge(this.currentBatch);
this.currentBatch = undefined;
}
}
function _storeCurrentTransaction() {
if (this.currentTransaction) {
var t = this.currentTransaction;
this.transactions.store(t);
_postTransactionMessage.call(this, 'stored', t);
this.currentTransaction = undefined;
}
}
function TransactionHistory$storeTransaction(transaction) {
this.endTransaction();
this.transactions.store(transaction);
_postTransactionMessage.call(this, 'stored', transaction);
}
function _postTransactionMessage(msg, transaction) {
if (this._messenger)
this._messenger.postMessage(msg, { transaction: transaction });
}
function _postTransactionMessageSync(msg, transaction) {
if (this._messenger)
this._messenger.postMessageSync(msg, { transaction: transaction });
}
function TransactionHistory$undo(cb) {
var t = this.transactions.nextUndoAction();
if (!t) return;
_postTransactionMessageSync.call(this, 'undoing', t);
var self = this;
this.transactions.undo(function() {
_postTransactionMessage.call(self, 'undone', t);
cb && cb();
});
return t;
}
function TransactionHistory$redo(cb) {
var t = this.transactions.nextRedoAction();
if (!t) return;
_postTransactionMessageSync.call(this, 'redoing', t);
var self = this;
this.transactions.redo(function() {
_postTransactionMessage.call(self, 'redone', t);
cb && cb();
});
return t;
}
function TransactionHistory$inTransaction() {
return this[SCHEDULED];
}
function TransactionHistory$getDescription() {
return this.transactions.getDescription();
}
function TransactionHistory$useMessenger() {
this._messenger = new Messenger(this, Messenger.defaultMethods);
return this._messenger
}
function TransactionHistory$destroy() {
if (this._messenger) this._messenger.destroy();
delete this.transactions;
}
},{"./actions_history":10,"./transaction":13,"milo-core":84}],15:[function(require,module,exports){
'use strict';
var FacetedObject = require('../abstract/faceted_object')
, facetsRegistry = require('./c_facets/cf_registry')
, ComponentFacet = facetsRegistry.get('ComponentFacet')
, componentUtils = require('./c_utils')
, miloCore = require('milo-core')
, Messenger = miloCore.Messenger
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match
, config = require('../config')
, miloComponentName = require('../util/component_name')
, logger = miloCore.util.logger
, domUtils = require('../util/dom')
, BindAttribute = require('../attributes/a_bind')
, Scope = require('./scope')
, DOMStorage = require('../util/storage');
var _makeComponentConditionFunc = componentUtils._makeComponentConditionFunc;
/**
* `milo.Component`
* Base Component class. Subclass of [FacetedObject](../abstract/faceted_object.js.html), but none of this class methods should be directly used with component.
* Its constructor passes its parameters, including its [scope](./scope.js.html), DOM element and name to [`init`](#init) method.
* The constructor of Component class rarely needs to be used directly, as [milo.binder](../binder.js.html) creates components when it scans DOM tree.
* [`Component.createComponentClass`](#createComponentClass) should be used to create a subclass of Component class with configured facets.
*
*
* ####Component instance properties####
*
* - el - DOM element that component is attached to. If the second component is attached to the same DOM element, the warning will be logged to console. To get component reference from DOM element use [Component.getComponent](./c_utils.js.html#getComponent) class method. To inspect component via element in browser check `___milo_component` property of element (property name be changed using `milo.config`).
* - scope - parent scope object, an instance of [Scope](./scope.js.html) class. To get parent component use [getScopeParent](#Component$getScopeParent) instance method of component. The actual path to get parent of conponent is `component.scope._hostObject.owner`, where `_hostObject` refers to [Container](c_facets/Container.js.html) facet of parent component and `owner` to the parent itself. The children of component are accessible via the scope of its container facet: `component.container.scope`. The scope hierarchy can be the same or different as the DOM hierarchy - DOM children of the component will be on the same scope as component if it does not have `Container` facet and in the scope of its Container facet if it has it. See [Scope](./scope.js.html).
* - name - the name of component, should be unique for the scope where component belongs. To find component in scope the component's name should be used as property of scope object. See [Scope](./scope.js.html).
* - facets - map of references of all component's facets (facet names are lowercase in this map). All facets can be accessed directly as properties of component, this property can be used to iterate facets (it is used in this way in [allFacets](#Component$allFacets) component's instance method that allows to call method with the same name on all facets).
* - extraFacets - an array of names of facets that are added to component and do not form the part of component's class.
* - _messenger - the reference to component's [messenger](../messenger/index.js.html). Rarely needs to be used directly as all commonly used methods of mesenger are available directly on component.
*
*
* ####Component events####
*
* - 'childrenbound' - synchronously dispatched when children of DOM element which compnent is connected to are connected to components. The event is dispatched when component is created with `milo.binder` (as is almost always the case, as all Component class methods that create/copy components use `milo.binder` internally - component constructor and Component.create methods are not used in framework outside of `milo.binder` and rarely if ever need to be used in aplication).
* - 'addedtoscope' - synchronously dispatched when component is added to scope.
* - 'stateready' - aynchronously dispatched when component (together with its scope children) is created with [Component.createFromState](#Component$$createFromState) (or `createFromDataTransfer`) method. Can be dispatched by application if the component's state is set with some other mechanism. This event is not used in `milo`, it can be used in application in particular subclasses of component.
* - 'getstatestarted' - emitted synchronously just before getState executes so components and facets can clean up their state for serialization.
* - 'getstatecompleted' - emitted asynchronously after getState executes so components and facets can restore their state after serialization.
*
*
* ####Component "lifecycle"####
*
* 1. Component constructor is called. Component's constructor simply calls constructor of [FacetedObject](../abstract/faceted_object.js.html) that is a superclass of Component. Subclasses of Component should not implement their own constructor, they can optionally implement `init` method, but most components do not need to do it.
* 2. constructors and `init` methods of all facets are called in sequence. Same as components, facet do not implement their constructors, they can optionally implement `init` and `start` methods (see below). Inside `init` method there should be only general initialization code without any dependency on component itself (it is not ready yet) and other facets (as there is no specific facets creation order). If facet implements `init` method it MUST call inherited init with `ComponentFacet.prototype.init.apply(this, arguments)`.
* 3. `init` method of component is called. At this point all facets are created but facets still can be not ready as they can have initialization code in `start` method. If component subclass implements `init` method it MUST call inherited method with `<Superclass>.prototype.init.apply(this, arguments)`, where <Superclass> is Component or another superclass the component is a subclass of.
* 4. `check` method of all facets is called. This method adds facets that are not part of the component declaration (being part of the class or explicitely listed in bind attribute) but are required by facets that the compnent already has. Subclasses of [ComponentFacet](./c_facet.js.html) do not need to implement this method.
* 5. `start` method of all facets is called. This method is usually implemented by ComponentFacet subclasses and it can have any initialization code that depends on component or on other facets that are the dependencies of a facet. Inherited `start` method should be called int he same way as written above.
* 6. `start` method of component is called. This component method can be implemented by subclasses if they need to have some initialization code that depends on some facets and requires that these facets are fully inialized. Often such code also depends on component's scope children as well so this code should be inside `'childrenbound'` method. `start` of scope parent is called BEFORE `start` of children.
* 7. 'addedtoscope' event is dispatched when component is added to its parent's scope or to top level scope created by `milo.binder`.
* 8. component's children are created (steps 1-6 above are followed for each child).
* 9. `childrenBound` method is called and 'childrenbound' event is dispatched when all component's children are created and added to their scope (see event description below). `childrenBound` of scope parent is called AFTER `childrenBound` of all children.
* 10. 'stateready' event is dispatched for component and all its children when component is create from state (see event description below).
* 11. at this point component is in the "interactive" state when it and its facets will only respond to messages/events that they subscribed to during initialization.
*
*
* @param {Scope} scope scope to which component will belong. It is usually a top level scope object returned by `milo.binder` or `scope` property of Container facet.
* @param {Element} element DOM element that component is attached to
* @param {String} name component name, should be unique in the scope of component
* @param {ComponentInfo} componentInfo instance of ComponentInfo class that can be used to create a copy of component
* TODO try removing it
* @return {Component}
*/
var Component = _.createSubclass(FacetedObject, 'Component', true);
module.exports = Component;
_registerWithDomStorage('Component');
/**
* ####Component class methods####
*
* - [createComponentClass](#Component$$createComponentClass)
* - [create](#Component$$create)
* - [copy](#Component$$copy)
* - [createOnElement](#Component$$createOnElement)
* - [isComponent](c_utils.js.html#isComponent)
* - [getComponent](c_utils.js.html#getComponent)
* - [getContainingComponent](c_utils.js.html#getContainingComponent)
* - [createFromState](#Component$$createFromState)
* - [createFromDataTransfer](#Component$$createFromDataTransfer)
*/
_.extend(Component, {
createComponentClass: Component$$createComponentClass,
create: Component$$create,
copy: Component$$copy,
createOnElement: Component$$createOnElement,
isComponent: componentUtils.isComponent,
getComponent: componentUtils.getComponent,
getContainingComponent: componentUtils.getContainingComponent,
createFromState: Component$$createFromState,
createFromDataTransfer: Component$$createFromDataTransfer
});
delete Component.createFacetedClass;
/**
* ####Component instance methods####
*
* - [init](#Component$init)
* - [createElement](#Component$createElement)
* - [hasFacet](#Component$hasFacet)
* - [addFacet](#Component$addFacet)
* - [allFacets](#Component$allFacets)
* - [rename](#Component$rename)
* - [remove](#Component$remove)
* - [getState](#Component$getState)
* - [getTransferState](#Component$getTransferState)
* - [setState](#Component$setState)
* - [getScopeParent](#Component$getScopeParent)
* - [getTopScopeParent](#Component$getTopScopeParent)
* - [getScopeParentWithClass](#Component$getScopeParentWithClass)
* - [getTopScopeParentWithClass](#Component$getTopScopeParentWithClass)
* - [walkScopeTree](#Component$walkScopeTree)
* - [broadcast](#Component$broadcast)
* - [destroy](#Component$destroy)
* - [isDestroyed](#Component$isDestroyed)
*
*
* #####[Messenger](../messenger/index.js.html) methods available on component#####
*
* - [on](../messenger/index.js.html#Messenger$on) - single subscribe
* - [off](../messenger/index.js.html#Messenger$off) - single unsubscribe
* - [onMessages](../messenger/index.js.html#Messenger$onMessages) - multiple subscribe
* - [offMessages](../messenger/index.js.html#Messenger$offMessages) - multiple unsubscribe
* - [postMessage](../messenger/index.js.html#Messenger$postMessage) - post message on component
* - [getSubscribers](../messenger/index.js.html#Messenger$getSubscribers) - get subscribers for a given message
*/
_.extendProto(Component, {
init: Component$init,
start: Component$start,
childrenBound: Component$childrenBound,
createElement: Component$createElement,
hasFacet: Component$hasFacet,
addFacet: Component$addFacet,
allFacets: Component$allFacets,
rename: Component$rename,
remove: Component$remove,
insertInto: Component$insertInto,
getState: Component$getState,
getTransferState: Component$getTransferState,
_getState: Component$_getState,
setState: Component$setState,
getScopeParent: Component$getScopeParent,
getTopScopeParent: Component$getTopScopeParent,
getScopeParentWithClass: Component$getScopeParentWithClass,
getTopScopeParentWithClass: Component$getTopScopeParentWithClass,
setScopeParentFromDOM: Component$setScopeParentFromDOM,
walkScopeTree: Component$walkScopeTree,
treePathOf: Component$treePathOf,
getComponentAtTreePath: Component$getComponentAtTreePath,
insertAtTreePath: Component$insertAtTreePath,
broadcast: Component$broadcast,
destroy: Component$destroy,
isDestroyed: Component$isDestroyed
});
/**
* Expose Messenger methods on Component prototype
*/
var MESSENGER_PROPERTY = '_messenger';
Messenger.useWith(Component, MESSENGER_PROPERTY, Messenger.defaultMethods);
var COMPONENT_DATA_TYPE_PREFIX = 'x-application/milo-component';
var COMPONENT_DATA_TYPE_REGEX = /x-application\/milo-component\/([a-z_$][0-9a-z_$]*)(?:\/())/i;
/**
* Component class method
* Creates a subclass of component from the map of configured facets.
* This method wraps and replaces [`createFacetedClass`](../abstract/faceted_object.js.html#createFacetedClass) class method of FacetedObject.
* Unlike createFacetedClass, this method take facet classes from registry by their name, so only map of facets configuration needs to be passed. All facets classes should be subclasses of [ComponentFacet](./c_facet.js.html)
*
* @param {String} name class name
* @param {Object<Object> | Array<String>} facetsConfig map of facets configuration.
* If some facet does not require configuration, `undefined` should be passed as the configuration for the facet.
* If no facet requires configuration, the array of facets names can be passed.
* @return {Subclass<Component>}
*/
function Component$$createComponentClass(name, facetsConfig) {
// convert array of facet names to map of empty facets configurations
if (Array.isArray(facetsConfig)) {
var configMap = {};
facetsConfig.forEach(function(fct) {
var fctName = _.firstLowerCase(fct);
configMap[fctName] = {};
});
facetsConfig = configMap;
}
// construct map of facets classes from facetRegistry
var facetsClasses;
if (typeof facetsConfig == 'object' && _.keys(facetsConfig).length) {
facetsClasses = {};
_.eachKey(facetsConfig, function(fctConfig, fct) {
var fctName = _.firstLowerCase(fct);
var fctClassName = _.firstUpperCase(fct);
facetsClasses[fctName] = facetsRegistry.get(fctClassName);
});
}
// create subclass of Component using method of FacetedObject
var ComponentClass = FacetedObject.createFacetedClass.call(this, name, facetsClasses, facetsConfig);
_registerWithDomStorage(name);
return ComponentClass;
}
function _registerWithDomStorage(className) {
DOMStorage.registerDataType(className, Component_domStorageSerializer, Component_domStorageParser);
}
function Component_domStorageSerializer(component) {
var state = component.getState();
return JSON.stringify(state);
}
function Component_domStorageParser(compStr, compClassName) {
var state = _.jsonParse(compStr);
if (state)
return Component.createFromState(state);
}
/**
* Component class method
* Creates component from [ComponentInfo](./c_info.js.html) (used by [milo.binder](../binder.js.html) and to copy component)
* Component of any registered class (see [componentsRegistry](./c_registry.js.html)) with any additional registered facets (see [facetsRegistry](./c_facets/cf_registry.js.html)) can be created using this method.
*
* @param {ComponentInfo} info
* @param {Boolean} throwOnErrors If set to false, then errors will only be logged to console. True by default.
@ @return {Component}
*/
function Component$$create(info, throwOnErrors) {
var ComponentClass = info.ComponentClass;
if (typeof ComponentClass != 'function') {
var message = 'create: component class should be function, "' + typeof ComponentClass + '" passed';
if (throwOnErrors === false) {
logger.error('Component', message, ';using base Component class instead');
ComponentClass = Component;
} else
throw new Error(message);
}
var aComponent = new ComponentClass(info.scope, info.el, info.name, info);
if (info.extraFacetsClasses)
_.eachKey(info.extraFacetsClasses, function(FacetClass) {
if (! aComponent.hasFacet(FacetClass))
aComponent.addFacet(FacetClass, undefined, undefined, throwOnErrors);
});
return aComponent;
}
/**
* Component class method
* Create a copy of component, including a copy of DOM element. Returns a copy of `component` (of the same class) with new DOM element (not inserted into page).
* Component is added to the same scope as the original component.
*
* @param {Component} component an instance of Component class or subclass
* @param {Boolean} deepCopy optional `true` to make deep copy of DOM element, otherwise only element without children is copied
* @return {Component}
*/
function Component$$copy(component, deepCopy) {
check(component, Component);
check(deepCopy, Match.Optional(Boolean));
if (deepCopy && !component.container)
throw new Error('Cannot deep copy component without container facet');
// copy DOM element, using Dom facet if it is available
var newEl = component.dom
? component.dom.copy(deepCopy)
: component.el.cloneNode(deepCopy);
var ComponentClass = component.constructor;
// create component of the same class on the element
var aComponent = ComponentClass.createOnElement(newEl, undefined, component.scope, component.extraFacets);
var state = component._getState(deepCopy || false);
aComponent.setState(state);
_.deferMethod(aComponent, 'broadcast', 'stateready');
return aComponent;
}
/**
* Component class method
* Creates an instance of component atached to element. All subclasses of component inherit this method.
* Returns the component of the class this method is used with (thecontext of the method call).
*
* @param {Element} el optional element to attach component to. If element is not passed, it will be created
* @param {String} innerHTML optional inner html to insert in element before binding.
* @param {Scope} rootScope optional scope to put component in. If not passed, component will be attached to the scope that contains the element. If such scope does not exist, new scope will be created.
* @param {Array<String>} extraFacets list of extra facet to add to component
* @return {Subclass<Component>}
*/
function Component$$createOnElement(el, innerHTML, rootScope, extraFacets) {
check(innerHTML, Match.Optional(String));
check(rootScope, Match.Optional(Scope));
check(extraFacets, Match.Optional([String]));
// "this" refers to the class of component here, as this is a class method
if (el && innerHTML) el.innerHTML = innerHTML;
el = el || _createComponentElement.call(this, innerHTML);
rootScope = rootScope || _findOrCreateComponentRootScope(el);
var aComponent = _addAttributeAndBindComponent.call(this, el, rootScope, extraFacets);
aComponent.broadcast('stateready');
return aComponent;
}
function _createComponentElement(innerHTML) {
// "this" refers to the class of component here, as this is a class method
var Dom = facetsRegistry.get('Dom')
, domFacetConfig = this.getFacetConfig('dom')
, templateFacetConfig = this.getFacetConfig('template')
, template = templateFacetConfig && templateFacetConfig.template;
var elConfig = {
domConfig: domFacetConfig,
template: template,
content: innerHTML
};
return Dom.createElement(elConfig);
}
function _findOrCreateComponentRootScope(el) {
var parent = Component.getContainingComponent(el, false, 'Container');
return parent ? parent.container.scope : new Scope(el);
}
function _addAttributeAndBindComponent(el, rootScope, extraFacets) {
// add bind attribute to element
var attr = new BindAttribute(el);
// "this" refers to the class of component here, as this is a class method
attr.compClass = this.name;
attr.compFacets = extraFacets;
attr.decorate();
// should be required here to resolve circular dependency
var miloBinder = require('../binder');
miloBinder(el, rootScope);
return rootScope[attr.compName];
}
/**
* Component class method
* Creates component from component state, that includes information about its class, extra facets, facets data and all scope children.
* This is used to save/load, copy/paste and drag/drop component
*
* @param {Object} state state from which component will be created
* @param {Scope} rootScope scope to which component will be added
* @param {Boolean} newUniqueName optional `true` to create component with the name different from the original one. `False` by default.
* @param {Boolean} throwOnErrors If set to false, then errors will only be logged to console. True by default.
* @return {Component} component
*/
function Component$$createFromState(state, rootScope, newUniqueName, throwOnErrors) {
check(state, Match.ObjectIncluding({
compName: Match.Optional(String),
compClass: Match.Optional(String),
extraFacets: Match.Optional([String]),
facetsStates: Match.Optional(Object),
outerHTML: String
}));
var miloBinder = require('../binder');
// create wrapper element optionally renaming component
var wrapEl = _createComponentWrapElement(state, newUniqueName);
// instantiate all components from HTML
var scope = miloBinder(wrapEl, undefined, undefined, throwOnErrors);
// as there should only be one component, call to _any will return it
var component = scope._any();
// set component's scope
if (rootScope) {
component.scope = rootScope;
rootScope._add(component);
}
// restore component state
component.setState(state);
_.deferMethod(component, 'broadcast', 'stateready');
return component;
}
// used by Component$$createFromState
function _createComponentWrapElement(state, newUniqueName) {
var wrapEl = document.createElement('div');
wrapEl.innerHTML = state.outerHTML;
var children = domUtils.children(wrapEl);
if (children.length != 1)
throw new Error('cannot create component: incorrect HTML, elements number: ' + children.length + ' (should be 1)');
var compEl = children[0];
var attr = new BindAttribute(compEl);
attr.compName = newUniqueName ? miloComponentName() : state.compName;
attr.compClass = state.compClass;
attr.compFacets = state.extraFacets;
attr.decorate();
return wrapEl;
}
/**
* Creates a component from a DataTransfer object (if possible)
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer
* @param {DataTransfer} dataTransfer Data transfer
*/
function Component$$createFromDataTransfer(dataTransfer) {
var dataType = _.find(dataTransfer.types, function (type) {
return COMPONENT_DATA_TYPE_REGEX.test(type);
});
if (!dataType) return;
var state = _.jsonParse(dataTransfer.getData(dataType));
if (!state) return;
return Component.createFromState(state, undefined, true);
}
/**
* Component instance method.
* Initializes component. Automatically called by inherited constructor of FacetedObject.
* Subclasses should call inherited init methods:
* ```
* Component.prototype.init.apply(this, arguments)
* ```
*
* @param {Scope} scope scope to which component will belong. It is usually a top level scope object returned by `milo.binder` or `scope` property of Container facet.
* @param {Element} element DOM element that component is attached to
* @param {String} name component name, should be unique in the scope of component
* @param {ComponentInfo} componentInfo instance of ComponentInfo class that can be used to create a copy of component
* TODO try removing it
*/
function Component$init(scope, element, name, componentInfo) {
// create DOM element if it wasn't passed to Constructor
this.el = element || this.createElement();
// store reference to component on DOM element
if (this.el) {
// check that element does not have a component already atached
var elComp = this.el[config.componentRef];
if (elComp)
logger.warn('component ' + name + ' attached to element that already has component ' + elComp.name);
this.el[config.componentRef] = this;
}
_.defineProperties(this, {
componentInfo: componentInfo,
extraFacets: []
}, _.ENUM);
this.name = name;
this.scope = scope;
// create component messenger
var messenger = new Messenger(this);
_.defineProperty(this, MESSENGER_PROPERTY, messenger);
// check all facets dependencies (required facets)
this.allFacets('check');
// start all facets
this.allFacets('start');
// call start method if it's defined in subclass
if (this.start) this.start();
}
/**
* This is a stub to avoid confusion whether the method of superclass should be called in subclasses
* start method of subclass instance is called once all the facets are created, initialized and started (see above)
* start method of scope parent is called BEFORE the same method of the child
*/
function Component$start() {}
/**
* This is a stub to avoid confusion whether the method of superclass should be called in subclasses
* childrenBound method of subclass instance is called once all the scope children are created, initialized, started and bound (see above)
* childrenBound method of scope parent is called AFTER childrenBound method of the child
*/
function Component$childrenBound() {}
/**
* Component instance method.
* Initializes the element which this component is bound to
*
* This method is called when a component is instantiated outside the DOM and
* will generate a new element for the component.
*
* @return {Element}
*/
function Component$createElement() {
if (typeof document == 'undefined')
return;
this.el = this.dom
? this.dom.createElement()
: document.createElement('DIV');
return this.el;
}
/**
* Component instance method
* Returns true if component has facet
*
* @param {Function|String} facetNameOrClass
* @return {Boolean}
*/
function Component$hasFacet(facetNameOrClass) {
var facetName = _.firstLowerCase(typeof facetNameOrClass == 'function'
? facetNameOrClass.name
: facetNameOrClass);
var facet = this[facetName];
if (! facet instanceof ComponentFacet)
logger.warn('expected facet', facetName, 'but this property name is used for something else');
return !! facet;
}
/**
* Component instance method.
* Adds facet with given name or class to the instance of Component (or its subclass).
*
* @param {String|Subclass<Component>} facetNameOrClass name of facet class or the class itself. If name is passed, the class will be retireved from facetsRegistry
* @param {Object} facetConfig optional facet configuration
* @param {String} facetName optional facet name. Allows to add facet under a name different from the class name supplied.
* @param {Boolean} throwOnErrors If set to false, then errors will only be logged to console. True by default.
*/
function Component$addFacet(facetNameOrClass, facetConfig, facetName, throwOnErrors) {
check(facetNameOrClass, Match.OneOf(String, Match.Subclass(ComponentFacet)));
check(facetConfig, Match.Optional(Object));
check(facetName, Match.Optional(String));
var FacetClass;
// if only name passed, retrieve facet class from registry
if (typeof facetNameOrClass == 'string') {
var facetClassName = _.firstUpperCase(facetNameOrClass);
FacetClass = facetsRegistry.get(facetClassName);
} else
FacetClass = facetNameOrClass;
if (!facetName)
facetName = _.firstLowerCase(FacetClass.name);
this.extraFacets.push(facetName);
// add facet using method of FacetedObject
var newFacet = FacetedObject.prototype.addFacet.call(this, FacetClass, facetConfig, facetName, throwOnErrors);
// check depenedencies and start facet
if (newFacet.check) newFacet.check();
if (newFacet.start) newFacet.start();
}
/**
* Component instance method.
* Envoke given method with optional parameters on all facets.
* Returns the map of values returned by all facets. If the facet doesn't have the method it is simply not called and the value in the map will be undefined.
*
* @param {String} method method name to envoke on the facet
* @return {Object}
*/
function Component$allFacets(method) { // ,... arguments
var args = _.slice(arguments, 1);
return _.mapKeys(this.facets, function(facet, fctName) {
if (facet && typeof facet[method] == 'function')
return facet[method].apply(facet, args);
});
}
/**
* Component instance method.
*
* @param {String} [name] optional new name of component,
* @param {Boolean} [renameInScope] optional false to not rename ComponentInfo object in its scope, true by default
*/
function Component$rename(name, renameInScope) {
name = name || miloComponentName();
this.componentInfo.rename(name, false);
Scope.rename(this, name, renameInScope);
}
/**
* Component instance method.
* Removes component from its scope.
*
* @param {Boolean} preserveScopeProperty true not to delete scope property of component
* @param {Boolean} quiet optional true to suppress the warning message if the component is not in scope
*/
function Component$remove(preserveScopeProperty, quiet) {
if (this.scope) {
this.scope._remove(this.name, quiet);
if (! preserveScopeProperty)
delete this.scope;
}
}
/**
* Component instance method.
* Inserts the component into the DOM and attempts to adjust the scope tree accordingly.
* @param {HTMLElement} parentEl The element into which the component should be inserted.
* @param {HTMLElement} referenceEl (optional) The reference element it should be inserted before.
*/
function Component$insertInto(parentEl, referenceEl) {
parentEl.insertBefore(this.el, referenceEl);
this.setScopeParentFromDOM();
}
/**
* Component instance method
* Retrieves all component state, including information about its class, extra facets, facets data and all scope children.
* This information is used to save/load, copy/paste and drag/drop component
* Returns component state
*
* @this {Component} component which state will be saved
* @return {Object}
*/
function Component$getState() {
this.broadcast('getstatestarted', { rootComponent: this }, undefined, true);
var state = this._getState(true);
state.outerHTML = this.el.outerHTML;
_.deferMethod(this, 'broadcast', 'getstatecompleted', { rootComponent: this }, undefined, true);
return state;
}
/**
* Component instance method
* Retrieves all component state, including information about its class, extra facets, facets data and all scope children.
* This information is used to save/load, copy/paste and drag/drop component
* If component has [Transfer](./c_facets/Transfer.js.html) facet on it, this method retrieves state from this facet
* Returns component state
*
* @this {Component} component which state will be saved
* @param {Object} options can be used by subclasses.
* @return {Object}
*/
function Component$getTransferState(options) {
return this.transfer
? this.transfer.getState(options)
: this.getState(options);
}
/**
* Component instance method
* Returns the state of component
* Used by class method `Component.getState` and by [Container](./c_facets/Container.js.html) facet.
*
* @private
* @param {Boolean} deepState false to get shallow state from all facets (true by default)
* @return {Object}
*/
function Component$_getState(deepState){
var facetsStates = this.allFacets('getState', deepState === false ? false : true);
facetsStates = _.filterKeys(facetsStates, function(fctState) {
return !! fctState;
});
return {
compName: this.name,
compClass: this.constructor.name,
extraFacets: this.extraFacets,
facetsStates: facetsStates
};
}
/**
* Component instance method
* Sets the state of component.
* Used by class method `Component.createFromState` and by [Container](./c_facets/Container.js.html) facet.
*
* @private
* @param {Object} state state to set the component
*/
function Component$setState(state) {
if (state.facetsStates)
_.eachKey(state.facetsStates, function(fctState, fctName) {
var facet = this[fctName];
if (facet && typeof facet.setState == 'function')
facet.setState(fctState);
}, this);
}
/**
* Component instance method.
* Returns the scope parent of a component.
* If `conditionOrFacet` parameter is not specified, an immediate parent will be returned, otherwise the closest ancestor with a specified facet or passing condition test.
*
* @param {Function|String} conditionOrFacet optional condition that component should pass (or facet name it should contain)
* @return {Component|undefined}
*/
function Component$getScopeParent(conditionOrFacet) {
return _callGetScopeParent.call(this, _getScopeParent, conditionOrFacet);
}
function _callGetScopeParent(_getScopeParentFunc, conditionOrFacet) {
check(conditionOrFacet, Match.Optional(Match.OneOf(Function, String)));
var conditionFunc = componentUtils._makeComponentConditionFunc(conditionOrFacet);
return _getScopeParentFunc.call(this, conditionFunc);
}
function _getScopeParent(conditionFunc) {
var parent;
try { parent = this.scope._hostObject.owner; } catch(e) {}
// Where there is no parent, this function will return undefined
// The parent component is checked recursively
if (parent) {
if (! conditionFunc || conditionFunc(parent) )
return parent;
else
return _getScopeParent.call(parent, conditionFunc);
}
}
/**
* Component instance method
* Returns scope parent with a given class, with same class if not specified
*
* @param {Function} [ComponentClass] component class that the parent should have, same class by default
* @return {Component}
*/
function Component$getScopeParentWithClass(ComponentClass) {
ComponentClass = ComponentClass || this.constructor;
return _getScopeParent.call(this, function(comp) {
return comp instanceof ComponentClass;
});
}
/**
* Component instance method.
* Returns the topmost scope parent of a component.
* If `conditionOrFacet` parameter is not specified, the topmost scope parent will be returned, otherwise the topmost ancestor with a specified facet or passing condition test.
*
* @param {Function|String} conditionOrFacet optional condition that component should pass (or facet name it should contain)
* @return {Component|undefined}
*/
function Component$getTopScopeParent(conditionOrFacet) {
return _callGetScopeParent.call(this, _getTopScopeParent, conditionOrFacet);
}
function _getTopScopeParent(conditionFunc) {
var topParent
, parent = this;
do {
parent = _getScopeParent.call(parent, conditionFunc);
if (parent)
topParent = parent;
} while (parent);
return topParent;
}
/**
* Component instance method
* Returns scope parent with a given class, with same class if not specified
*
* @param {Function} [ComponentClass] component class that the parent should have, same class by default
* @return {Component}
*/
function Component$getTopScopeParentWithClass(ComponentClass) {
ComponentClass = ComponentClass || this.constructor;
return _getTopScopeParent.call(this, function(comp) {
return comp instanceof ComponentClass;
});
}
/**
* Component instance method
* Finds scope parent of component using DOM tree (unlike getScopeParent that simply goes up the scope tree).
* While getScopeParent is faster it may fail if scope chain is not setup yet (e.g., when component has been just inserted).
* The scope property of component will be changed to point to scope object of container facet of that parent.
* Returned scope parent of the component will be undefined (as well as component's scope property) if no parent in the DOM tree has container facet.
* TODO Method will not bind DOM children correctly if component has no container facet.
*
* @return {Component}
*/
function Component$setScopeParentFromDOM() {
var parentEl = this.el.parentNode;
var parent, foundParent;
while (parentEl && ! foundParent) {
parent = Component.getComponent(parentEl);
foundParent = parent && parent.container;
parentEl = parentEl.parentNode;
}
this.remove(); // remove component from its current scope (if it is defined)
if (foundParent) {
this.rename(undefined, false);
parent.container.scope._add(this);
return parent;
}
}
/**
* Walks component tree, calling provided callback on each component
*
* @param callback
* @param thisArg
*/
function Component$walkScopeTree(callback, thisArg) {
callback.call(thisArg, this);
if (!this.container) return;
this.container.scope._each(function(component) {
component.walkScopeTree(callback, thisArg);
});
}
function Component$treePathOf(component) {
return domUtils.treePathOf(this.el, component.el);
}
function Component$getComponentAtTreePath(treePath, nearest) {
var node = domUtils.getNodeAtTreePath(this.el, treePath, nearest);
return Component.getComponent(node);
}
function Component$insertAtTreePath(treePath, component, nearest) {
var wasInserted = domUtils.insertAtTreePath(this.el, treePath, component.el);
if (wasInserted) component.setScopeParentFromDOM();
return wasInserted;
}
/**
* Broadcast message to component and to all its scope children
*
* @param {String|RegExp} msg message to be sent
* @param {Any} [data] optional message data
* @param {Function} [callback] optional callback
* @param {Boolean} [synchronously] if it should use postMessageSync
*/
function Component$broadcast(msg, data, callback, synchronously) {
var postMethod = synchronously ? 'postMessageSync' : 'postMessage';
this.walkScopeTree(function(component) {
component[postMethod](msg, data, callback);
});
}
/**
* Destroy component: removes component from DOM, removes it from scope, deletes all references to DOM nodes and unsubscribes from all messages both component and all facets
*/
function Component$destroy(opts) {
if (typeof opts == 'boolean') opts = { quiet: opts };
else if (!opts) opts = {};
if (this._destroyed) {
if (!opts.quiet) logger.warn('Component destroy: component is already destroyed');
return;
}
this.remove(false, opts.quiet);
this.allFacets('destroy', opts);
this[MESSENGER_PROPERTY].destroy();
if (this.el) {
domUtils.detachComponent(this.el);
domUtils.removeElement(this.el);
delete this.el;
}
this.componentInfo.destroy();
this._destroyed = true;
}
/**
* Returns true if component was destroyed
*
* @return {Boolean}
*/
function Component$isDestroyed() {
return !!this._destroyed;
}
},{"../abstract/faceted_object":2,"../attributes/a_bind":4,"../binder":8,"../config":42,"../util/component_name":53,"../util/dom":57,"../util/storage":67,"./c_facets/cf_registry":31,"./c_utils":34,"./scope":41,"milo-core":84}],16:[function(require,module,exports){
'use strict';
/**
* `milo.Component.Facet`
*
* The class fot the facet of component. When a component is created, it
* creates all its facets.
*
* See Facets section on information about available facets and on
* how to create new facets classes.
*
* - Component - basic compponent class
* - ComponentFacet - basic
*/
var Facet = require('../abstract/facet')
, miloCore = require('milo-core')
, Messenger = miloCore.Messenger
, componentUtils = require('./c_utils')
, _ = miloCore.proto;
var ComponentFacet = _.createSubclass(Facet, 'ComponentFacet');
module.exports = ComponentFacet;
/**
* postDomParent
*
* If facet has DOM parent facet (see `domParent` method), posts the message to this facet.
*
* @param {String} messageType
* @param {Object} messageData
*/
var postDomParent = _.partial(_postParent, domParent);
/**
* postScopeParent
*
* If facet has scope parent facet (see `scopeParent` method), posts the message to this facet.
*
* @param {String} messageType
* @param {Object} messageData
*/
var postScopeParent = _.partial(_postParent, scopeParent);
_.extendProto(ComponentFacet, {
init: ComponentFacet$init,
start: ComponentFacet$start,
check: ComponentFacet$check,
destroy: ComponentFacet$destroy,
onConfigMessages: ComponentFacet$onConfigMessages,
domParent: domParent,
postDomParent: postDomParent,
scopeParent: scopeParent,
postScopeParent: postScopeParent,
getMessageSource: getMessageSource,
dispatchSourceMessage: dispatchSourceMessage,
_createMessenger: _createMessenger,
_setMessageSource: _setMessageSource,
_createMessageSource: _createMessageSource,
_createMessageSourceWithAPI: _createMessageSourceWithAPI
});
_.extend(ComponentFacet, {
requiresFacet: requiresFacet
});
/**
* Expose Messenger methods on Facet prototype
*/
var MESSENGER_PROPERTY = '_messenger';
Messenger.useWith(ComponentFacet, MESSENGER_PROPERTY, Messenger.defaultMethods);
// initComponentFacet
function ComponentFacet$init() {
this._createMessenger();
}
// some subclasses (e.g. ModelFacet) overrride this method and do not create their own messenger
function _createMessenger(){
_.defineProperty(this, MESSENGER_PROPERTY, new Messenger(this));
}
// startComponentFacet
function ComponentFacet$start() {
if (this.config.messages)
this.onConfigMessages(this.config.messages);
}
function ComponentFacet$onConfigMessages(messageSubscribers) {
var notYetRegisteredMap = _.mapKeys(messageSubscribers, function(subscriber, messages) {
var subscriberType = typeof subscriber;
if (subscriberType == 'function')
return this.on(messages, subscriber);
if (subscriberType == 'object') {
var contextType = typeof subscriber.context;
if (contextType == 'object')
return this.on(messages, subscriber);
if (contextType == 'string') {
if (subscriber.context == this.name || subscriber.context == 'facet')
subscriber = {
subscriber: subscriber.subscriber,
context: this
};
else if (subscriber.context == 'owner')
subscriber = {
subscriber: subscriber.subscriber,
context: this.owner
};
else
throw new Error('unknown subscriber context in configuration: ' + subscriber.context);
return this.on(messages, subscriber);
}
throw new Error('unknown subscriber context type in configuration: ' + contextType);
}
throw new Error('unknown subscriber type in configuration: ' + subscriberType);
}, this);
return notYetRegisteredMap;
}
// checkDependencies and config
function ComponentFacet$check() {
if (this.require) {
this.require.forEach(function(reqFacet) {
if (! this.owner.hasFacet(reqFacet))
this.owner.addFacet(reqFacet);
}, this);
}
if (this.configSchema) {
try {
milo.util.check(this.config, this.configSchema);
} catch(e) {
throw 'Error validating config schema for "' + this.name +'" facet: ' + e;
}
}
}
// destroys facet
function ComponentFacet$destroy() {
if (this[MESSENGER_PROPERTY]) this[MESSENGER_PROPERTY].destroy();
this._destroyed = true;
}
/**
* domParent
*
* @return {ComponentFacet} reference to the facet of the same class of the closest parent DOM element, that has a component with the same facet class attached to it. If such element doesn't exist method will return undefined.
*/
function domParent() {
var parentComponent = componentUtils.getContainingComponent(this.owner.el, false, this.name);
return parentComponent && parentComponent[this.name];
}
/**
* scopeParent
*
* @return {ComponentFacet} reference to the facet of the same class as `this` facet of the closest scope parent (i.e., the component that has the scope of the current component in its container facet).
*/
function scopeParent() {
var parentComponent = this.owner.getScopeParent(this.name);
return parentComponent && parentComponent[this.name];
}
function _postParent(getParentMethod, messageType, messageData) {
var parentFacet = getParentMethod.call(this);
if (parentFacet)
parentFacet.postMessage(messageType, messageData);
}
function _setMessageSource(messageSource) {
this[MESSENGER_PROPERTY]._setMessageSource(messageSource);
}
function getMessageSource() {
return this[MESSENGER_PROPERTY].getMessageSource();
}
function dispatchSourceMessage(message, data) {
return this.getMessageSource().dispatchMessage(message, data);
}
function _createMessageSource(MessageSourceClass, options) {
var messageSource = new MessageSourceClass(this, undefined, undefined, this.owner, options);
this._setMessageSource(messageSource);
_.defineProperty(this, '_messageSource', messageSource);
}
function _createMessageSourceWithAPI(MessageSourceClass, messengerAPIOrClass, options) {
var messageSource = new MessageSourceClass(this, undefined, messengerAPIOrClass, this.owner, options);
this._setMessageSource(messageSource);
_.defineProperty(this, '_messageSource', messageSource);
}
function requiresFacet(facetName) {
// 'this' refers to the Facet Class
var facetRequire = this.prototype.require;
return facetRequire && (facetRequire.indexOf(_.firstUpperCase(facetName)) >= 0
|| facetRequire.indexOf(_.firstLowerCase(facetName)) >= 0);
}
},{"../abstract/facet":1,"./c_utils":34,"milo-core":84}],17:[function(require,module,exports){
'use strict';
var ComponentFacet = require('../c_facet')
, miloBinder = require('../../binder')
, Scope = require('../scope')
, miloCore = require('milo-core')
, _ = miloCore.proto
, logger = miloCore.util.logger
, facetsRegistry = require('./cf_registry')
, domUtils = require('../../util/dom');
/**
* `milo.registry.facets.get('Container')`
* A special component facet that makes component create its own inner scope.
* When [milo.binder](../../binder.js.html) binds DOM tree and creates components, if components are inside component WITH Container facet, they are put on the `scope` of it (component.container.scope - see [Scope](../scope.js.html)), otherwise they are put on the same scope even though they may be deeper in DOM tree.
* It allows creating namespaces avoiding components names conflicts, at the same time creating more shallow components tree than the DOM tree.
* To create components for elements inside the current component use:
* ```
* component.container.binder();
* ```
* See [milo.binder](../../binder.js.html)
*/
var Container = _.createSubclass(ComponentFacet, 'Container');
/**
* ####Container facet instance methods####
*
* - [binder](#Container$binder) - create components from DOM inside the current one
*/
_.extendProto(Container, {
start: Container$start,
path: Container$path,
getState: Container$getState,
setState: Container$setState,
binder: Container$binder,
destroy: Container$destroy,
unwrap: Container$unwrap,
append: Container$append,
insertBefore: Container$insertBefore,
remove: Container$remove
});
facetsRegistry.add(Container);
module.exports = Container;
/**
* Container instance method.
* Scans DOM, creates components and adds to scope children of component element.
*/
function Container$binder() {
return miloBinder(this.owner.el, this.scope, false);
}
/**
* Container instance method.
* Setup empty scope object on start
*/
function Container$start() {
ComponentFacet.prototype.start.apply(this, arguments);
this.scope = new Scope(this.owner.el, this);
}
var allowedNamePattern = /^[A-Za-z][A-Za-z0-9\_\$]*$/;
/**
* Container instance method.
* Safely traverses component scope
* Returns component in scope for a given path
* If path is invalid the method will throw, if there is no component at a given path or some of the components along the path does not have Container facet the method will return undefined,
*
* @param {String} path path of child component in scope, each name should be prefixed with '.', e.g.: '.child.subchild'
* @return {Component}
*/
function Container$path(path) {
path = path.split('.');
var len = path.length;
if (path[0] || len < 2) throwInvalidPath();
var comp = this.owner;
for (var i = 1; i < len; i++) {
var name = path[i];
if (!allowedNamePattern.test(name)) throwInvalidPath();
if (!comp.container) return;
comp = comp.container.scope[name];
if (!comp) return;
}
return comp;
function throwInvalidPath() {
throw new Error('path ' + path + ' is invalid');
}
}
/**
* Container instance method
* Called by `Component.prototype.getState` to get facet's state
* Returns the state of components in the scope
*
* @param {Boolean} deepCopy true by default
* @return {Object}
*/
function Container$getState(deepCopy) {
var state = { scope: {} };
if (deepCopy !== false)
this.scope._each(function(component, compName) {
state.scope[compName] = component._getState();
});
return state;
}
/**
* Container instance method
* Called by `Component.prototype.setState` to set facet's state
* Sets the state of components in the scope
*
* @param {Object} data data to set on facet's model
*/
function Container$setState(state) {
_.eachKey(state.scope, function(compData, compName) {
var component = this.scope[compName];
if (component)
component.setState(compData);
else
logger.warn('component "' + compName + '" does not exist on scope');
}, this);
}
function Container$destroy(opts) {
this.scope._each(function(component) {
if (opts.async) _.deferMethod(component, 'destroy', opts);
else component.destroy(opts);
});
this.scope._detachElement();
ComponentFacet.prototype.destroy.apply(this, arguments);
}
/**
* Container instance method
* Moves all of the contents of the owner into the parent scope
*
* @param {Boolean} renameChildren pass false to not rename scope children (default is true)
* @param {Boolean} destroy If not false, the component will be destroyed at the end (default is true).
*/
function Container$unwrap(renameChildren, destroy) {
domUtils.unwrapElement(this.owner.el);
if (this.scope)
this.scope._each(function (child) {
child.remove();
if (renameChildren !== false) child.rename(undefined, false);
if (this.owner.scope) this.owner.scope._add(child);
}, this);
if (destroy !== false) this.owner.destroy();
}
/**
* Container instance method
* Append component to DOM and to scope
* @param {Component} comp component that will be appended
*/
function Container$append(comp) {
this.scope._add(comp);
this.owner.el.appendChild(comp.el);
}
/**
* Container instance method
* Insert component to DOM and to scope before another component
* @param {Component} comp component that will be inserted
* @param {Component} sibling component before which component will be appended
*/
function Container$insertBefore(comp, sibling) {
this.scope._add(comp);
this.el.insertBefore(comp.el, sibling && sibling.el);
}
function Container$remove(comp) {
this.scope._remove(comp);
this.owner.el.removeChild(comp.el);
}
},{"../../binder":8,"../../util/dom":57,"../c_facet":16,"../scope":41,"./cf_registry":31,"milo-core":84}],18:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match
, modelUtils = miloCore.Model._utils
, createFacetClass = require('../../util/create_facet_class');
/**
* Css Facet facilitates the binding of model values to the css classes being applied to the element owned by a milo
* component.
*
* Facet configuration looks like:
*
* ```
* css: {
* classes: {
* '.someModelProp': 'some-css-class', // Apply css class if the value of '.someModelProp' is truthy
* '.someOtherModelProp': {
* 'value-1': 'some-css-class', // Apply if the value of '.someOtherModelProp' == 'value-1'
* 'value-2: 'some-other-css-class' // etc
* },
* '.anotherModelProp': function getCssClass(modelValue) { return ... } // Apply result of function
* '.oneMoreModelProp': 'my-$-class' // Template value of '.oneMoreModelProp' (By replacing $ character)
* }
* }
* ```
*
* To bind a data source to the facet, use milo binder:
*
* ```
* milo.binder(someDataSource, '->>', myComponent.css);
* ```
*
* Or else, set data directly on the facet like so:
*
* ```
* component.css.set({
* '.someModelProp': 'milo',
* '.someOtherModelProp': 'is-cool'
* });
*/
var CssFacet = module.exports = createFacetClass({
className: 'Css',
methods: {
start: CssFacet$start,
set: CssFacet$set,
del: CssFacet$del,
path: CssFacet$path,
update: CssFacet$update
}
});
// Config data type to update function
var updateHandlers = {
string: updateSimple,
object: updateByObject,
function: updateByFunction
};
function CssFacet$start() {
CssFacet.super.start.apply(this, arguments);
var getClassList = this.config.getClassList
this._classList = (getClassList && getClassList.call(this)) || this.owner.el.classList;
modelUtils.path.wrapMessengerMethods.call(this);
this.onSync('changedata', modelUtils.changeDataHandler); // Listen for changes to data source
this.activeModelPaths = {}; // Key-Value object: Css classes (key) set by what model paths (value)
}
function CssFacet$set(data) {
check(data, Match.OneOf(Object, null, undefined));
if(data) {
var self = this;
_.eachKey(data, function (value, prop) {
var modelPath = prop.charAt(0) !== '.' ? '.' + prop : prop;
self.update(modelPath, value);
});
} else {
this.del();
}
}
function CssFacet$del() {
var classList = this._classList;
_.eachKey(this.activeModelPaths, function(modelPaths, cssClass) {
modelPaths.clear();
classList.remove(cssClass);
});
}
function CssFacet$path(modelPath) {
if (!modelPath) return this; // No model path (or '') means the root object
// Otherwise the modelPath has to exist in the facet configuration
return this.config.classes && this.config.classes[modelPath] ? new Path(this, modelPath) : null;
}
function CssFacet$update(modelPath, value) {
var cssConfig = this.config.classes[modelPath];
if (cssConfig) {
var handler = updateHandlers[typeof cssConfig];
handler.call(this, modelPath, cssConfig, value);
this.postMessageSync('changed', {
modelPath: modelPath,
modelValue: value
});
}
}
function updateSimple(modelPath, cssClass, data) {
var classList = this._classList;
// Remove any css class set via this model path
_.eachKey(this.activeModelPaths, function(modelPaths, cssClass) {
if (modelPaths.has(modelPath)) {
modelPaths.delete(modelPath);
if (modelPaths.size === 0) // Only remove the class if no other model path is applying it
classList.remove(cssClass);
}
});
// Apply new css class (cssClass / data can be null if this is a remove only operation)
if (cssClass && data) {
cssClass = data ? cssClass.replace(/\$/g, data) : cssClass; // Process any template characters ($) in class name
var modelPaths = this.activeModelPaths[cssClass] || (this.activeModelPaths[cssClass] = new Set());
modelPaths.add(modelPath);
classList.add(cssClass);
}
}
function updateByObject(modelPath, cssClasses, value) {
// Apply new css class
var cssClass = cssClasses[value];
updateSimple.call(this, modelPath, cssClass, value);
}
function updateByFunction(modelPath, getCssClassFn, data) {
var cssClass = getCssClassFn.call(this, data);
updateSimple.call(this, modelPath, cssClass, true);
}
// Path class
function Path(cssFacet, modelPath) {
this.cssFacet = cssFacet;
this.modelPath = modelPath;
}
Path.prototype.set = function(value) {
this.cssFacet.update(this.modelPath, value);
};
Path.prototype.del = function() {
this.set(null);
};
},{"../../util/create_facet_class":55,"milo-core":84}],19:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, Mixin = miloCore.classes.Mixin
, ComponentFacet = require('../c_facet')
, facetsRegistry = require('./cf_registry')
, Messenger = miloCore.Messenger
, DOMEventsSource = require('../msg_src/dom_events')
, DataMsgAPI = require('../msg_api/data')
, getElementDataAccess = require('../msg_api/de_data')
, Model = miloCore.Model
, pathUtils = Model._utils.path
, modelUtils = Model._utils.model
, changeDataHandler = Model._utils.changeDataHandler
, getTransactionFlag = changeDataHandler.getTransactionFlag
, setTransactionFlag = changeDataHandler.setTransactionFlag
, postTransactionFinished = changeDataHandler.postTransactionFinished
, _ = miloCore.proto
, logger = miloCore.util.logger;
/**
* `milo.registry.facets.get('Data')`
* Facet to give access to DOM data
*/
var Data = _.createSubclass(ComponentFacet, 'Data');
/**
* Data facet instance methods
*
* - [start](#Data$start) - start Data facet
* - [get](#Data$get) - get DOM data from DOM tree
* - [set](#Data$set) - set DOM data to DOM tree
* - [path](#Data$path) - get reference to Data facet by path
*/
_.extendProto(Data, {
start: Data$start,
getState: Data$getState,
setState: Data$setState,
get: Data$get,
set: Data$set,
del: Data$del,
splice: Data$splice,
len: Data$len,
path: Data$path,
getPath: Data$getPath,
getKey: Data$getKey,
_get: Data$_get,
_set: Data$_set,
_del: Data$_del,
_splice: Data$_splice,
_len: Data$_len,
_setScalarValue: Data$_setScalarValue,
_getScalarValue: Data$_getScalarValue,
_bubbleUpDataChange: Data$_bubbleUpDataChange,
_queueDataChange: Data$_queueDataChange,
_postDataChanges: Data$_postDataChanges,
_prepareMessageSource: _prepareMessageSource
});
facetsRegistry.add(Data);
module.exports = Data;
/**
* ModelPath methods added to Data prototype
*/
['push', 'pop', 'unshift', 'shift'].forEach(function(methodName) {
var method = Model.Path.prototype[methodName];
_.defineProperty(Data.prototype, methodName, method);
});
// these methods will be wrapped to support "*" pattern subscriptions
var proxyDataSourceMethods = {
// value: 'value',
trigger: 'trigger'
};
/**
* Data facet instance method
* Starts Data facet
* Called by component after component is initialized.
*/
function Data$start() {
// change messenger methods to work with "*" subscriptions (like Model class)
pathUtils.wrapMessengerMethods.call(this);
ComponentFacet.prototype.start.apply(this, arguments);
// get/set methods to set data of element
this.elData = getElementDataAccess(this.owner.el);
this._dataChangesQueue = [];
this._prepareMessageSource();
// store facet data path
this._path = '.' + this.owner.name;
// current value
this._value = this.get();
// prepare internal and external messengers
// this._prepareMessengers();
// subscribe to DOM event and accessors' messages
this.onSync('', onOwnDataChange);
// message to mark the end of batch on the current level
this.onSync('datachangesfinished', onDataChangesFinished);
// changes in scope children with Data facet
this.onSync('childdata', onChildData);
// to enable reactive connections
this.onSync('changedata', changeDataHandler);
}
/**
* Data facet instance method
* Create and connect internal and external messengers of Data facet.
* External messenger's methods are proxied on the Data facet and they allows "*" subscriptions.
*/
// function _prepareMessengers() {
// Data facet will post all its changes on internal messenger
// var internalMessenger = new Messenger(this);
// message source to connect internal messenger to external
// var internalMessengerSource = new MessengerMessageSource(this, undefined, new ModelMsgAPI, internalMessenger);
// external messenger to which all model users will subscribe,
// that will allow "*" subscriptions and support "changedata" message api.
// var externalMessenger = new Messenger(this, Messenger.defaultMethods, internalMessengerSource);
// _.defineProperties(this, {
// _messenger: externalMessenger,
// _internalMessenger: internalMessenger
// });
// }
/**
* Data facet instance method
* Initializes DOMEventsSource and connects it to Data facet messenger
*
* @private
*/
function _prepareMessageSource() {
var dataAPI = new DataMsgAPI(this.owner)
, dataEventsSource = new DOMEventsSource(this, proxyDataSourceMethods, dataAPI, this.owner);
this._setMessageSource(dataEventsSource);
_.defineProperty(this, '_dataEventsSource', dataEventsSource);
// make value method of DataMsgAPI available on Data facet
// this is a private method, get() should be used to get data.
Mixin.prototype._createProxyMethod.call(dataAPI, 'value', 'value', this);
}
/**
* Subscriber to data change event
*
* @private
* @param {String} msgType in this instance will be ''
* @param {Object} data data change information
*/
function onOwnDataChange(msgType, data) {
this._bubbleUpDataChange(data);
this._queueDataChange(data);
if (data.path === '') {
var inTransaction = getTransactionFlag(data);
this.postMessage('datachangesfinished', { transaction: inTransaction });
}
}
/**
* Data facet instance method
* Sends data `message` to DOM parent
*
* @private
* @param {Object} msgData data change message
*/
function Data$_bubbleUpDataChange(msgData) {
var parentData = this.scopeParent();
if (parentData) {
var parentMsg = _.clone(msgData);
parentMsg.path = (this._path || ('.' + this.owner.name)) + parentMsg.path;
parentData.postMessage('childdata', parentMsg || msgData);
}
}
/**
* Data facet instance method
* Queues data messages to be dispatched to connector
*
* @private
* @param {Object} change data change description
*/
function Data$_queueDataChange(change) {
this._dataChangesQueue.push(change);
}
/**
* Subscriber to datachangesfinished event.
* Calls the method to post changes batch and bubbles up the message
*
* @param {String} msg
* @param {Object} [data]
*/
function onDataChangesFinished(msg, data) {
this._postDataChanges(data.inTransaction);
var parentData = this.scopeParent();
if (parentData) parentData.postMessage('datachangesfinished', data);
}
/**
* Dispatches all changes collected in the batch
* Used for data propagation - connector subscribes to this message
*
* @private
*/
function Data$_postDataChanges(inTransaction) {
var queue = this._dataChangesQueue.reverse();
this.postMessageSync('datachanges', {
changes: queue,
transaction: inTransaction
});
this._dataChangesQueue = []; // it can't be .length = 0, as the actual array may still be used
}
/**
* Subscriber to data change event in child Data facet
*
* @private
* @param {String} msgType
* @param {Obejct} data data change information
*/
function onChildData(msgType, data) {
this.postMessage(data.path, data);
this._bubbleUpDataChange(data);
this._queueDataChange(data);
}
/**
* Data facet instance method
* Sets data in DOM hierarchy recursively.
* Returns the object with the data actually set (can be different, if components matching some properties are missing).
*
* @param {Object|String|Number} value value to be set. If the value if scalar, it will be set on component's element, if the value is object - on DOM tree inside component
* @return {Object|String|Number}
*/
function Data$set(value) {
var inTransaction = getTransactionFlag(Data$set);
try {
return executeHook.call(this, 'set', arguments);
} catch (e) {
if (e != noHook) throw e;
}
setTransactionFlag(this._set, inTransaction);
var oldValue = this._value
, newValue = this._set(value);
// this message triggers onOwnDataChange, as well as actuall DOM change
// so the parent gets notified
var msg = { path: '', type: 'changed',
newValue: newValue, oldValue: oldValue };
setTransactionFlag(msg, inTransaction);
this.postMessage('', msg);
return newValue;
}
function Data$_set(value) {
var inTransaction = getTransactionFlag(Data$_set);
var valueSet;
if (value !== null && typeof value == 'object') {
if (Array.isArray(value)) {
valueSet = [];
var listFacet = this.owner.list;
if (listFacet){
var listLength = listFacet.count()
, newItemsCount = value.length - listLength;
if (newItemsCount >= 3) {
listFacet._addItems(newItemsCount);
listFacet._updateDataPaths(listLength, listFacet.count());
}
value.forEach(function(childValue, index) {
setChildData.call(this, valueSet, childValue, index, '[$$]');
}, this);
var listCount = listFacet.count()
, removeCount = listCount - value.length;
while (removeCount-- > 0)
listFacet._removeItem(value.length);
} else
logger.warn('Data: setting array data without List facet');
} else {
valueSet = {};
_.eachKey(value, function(childValue, key) {
setChildData.call(this, valueSet, childValue, key, '.$$');
}, this);
}
} else
valueSet = this._setScalarValue(value);
this._value = valueSet;
return valueSet;
function setChildData(valueSet, childValue, key, pathSyntax) {
var childPath = pathSyntax.replace('$$', key);
var childDataFacet = this.path(childPath, typeof childValue != 'undefined');
if (childDataFacet) {
setTransactionFlag(childDataFacet.set, inTransaction);
valueSet[key] = childDataFacet.set(childValue);
}
}
}
/**
* Data facet instance method
* Deletes component from view and scope, only in case it has Item facet on it
*/
function Data$del() {
var inTransaction = getTransactionFlag(Data$del);
try {
var result = executeHook.call(this, 'del');
postTransactionFinished.call(this, inTransaction);
return result;
} catch (e) {
if (e != noHook) throw e;
}
var oldValue = this._value;
setTransactionFlag(this._del, inTransaction);
this._del();
// this message triggers onOwnDataChange, as well as actuall DOM change
// so the parent gets notified
var msg = { path: '', type: 'deleted', oldValue: oldValue };
setTransactionFlag(msg, inTransaction);
this.postMessage('', msg);
}
function Data$_del() {
var inTransaction = getTransactionFlag(Data$_del);
setTransactionFlag(this._set, inTransaction);
this._set();
}
/**
* Data facet instance method
* Sets scalar value to DOM element
*
* @private
* @param {String|Number} value value to set to DOM element
*/
function Data$_setScalarValue(value) {
return this.elData.set(this.owner.el, value);
}
/**
* Data facet instance method
* Get structured data from DOM hierarchy recursively
* Returns DOM data
*
* @param {Boolean} deepGet true by default
* @return {Object}
*/
function Data$get(deepGet) {
try {
return executeHook.call(this, 'get', arguments);
} catch (e) {
if (e != noHook) throw e;
}
return this._get(deepGet);
}
function Data$_get(deepGet) {
if (deepGet === false) // a hack to enable getting shallow state
return;
var comp = this.owner
, scopeData;
if (comp.list) {
scopeData = [];
comp.list.each(function(listItem, index) {
scopeData[index] = listItem.data.get();
});
if (comp.container)
comp.container.scope._each(function(scopeItem, name) {
if (! comp.list.contains(scopeItem) && scopeItem.data)
scopeData[name] = scopeItem.data.get();
});
} else if (comp.container) {
scopeData = {};
comp.container.scope._each(function(scopeItem, name) {
if (scopeItem.data)
scopeData[name] = scopeItem.data.get();
});
} else
scopeData = this._getScalarValue();
this._value = scopeData;
return scopeData;
}
/**
* Data facet instance method
* Gets scalar data from DOM element
*
* @private
*/
function Data$_getScalarValue() {
return this.elData.get(this.owner.el);
}
/**
* Data facet instance method
* Splices List items. Requires List facet to be present on component. Works in the same way as array splice.
* Returns data retrieved from removed items
*
* @param {Integer} spliceIndex index to delete/insert at
* @param {Integer} spliceHowMany number of items to delete
* @param {List} arguments optional items to insert
* @return {Array}
*/
function Data$splice(spliceIndex, spliceHowMany) { //, ... arguments
var inTransaction = getTransactionFlag(Data$splice);
var result;
try {
result = executeHook.call(this, 'splice', arguments);
postTransactionFinished.call(this, inTransaction);
return result;
} catch (e) {
if (e != noHook) throw e;
}
setTransactionFlag(this._splice, inTransaction);
result = this._splice.apply(this, arguments);
if (!result) return;
var msg = { path: '', type: 'splice',
index: result.spliceIndex,
removed: result.removed,
addedCount: result.addedCount,
newValue: this._value };
setTransactionFlag(msg, inTransaction);
this.postMessage('', msg);
return result.removed;
}
var noHook = {};
function executeHook(methodName, args) {
var hook = this.config[methodName];
switch (typeof hook) {
case 'function':
return hook.apply(this.owner, args);
case 'string':
return this.owner[hook].apply(this.owner, args);
default:
throw noHook;
}
}
function Data$_splice(spliceIndex, spliceHowMany) { //, ... arguments
var inTransaction = getTransactionFlag(Data$_splice);
var listFacet = this.owner.list;
if (! listFacet)
return logger.warn('Data: cannot use splice method without List facet');
var removed = [];
var listLength = listFacet.count();
arguments[0] = spliceIndex =
modelUtils.normalizeSpliceIndex(spliceIndex, listLength);
if (spliceHowMany > 0 && listLength > 0) {
for (var i = spliceIndex; i < spliceIndex + spliceHowMany; i++) {
var item = listFacet.item(spliceIndex);
if (item) {
var itemData = item.data.get();
listFacet._removeItem(spliceIndex);
} else
logger.warn('Data: no item for index', i);
removed.push(itemData);
}
listFacet._updateDataPaths(spliceIndex, listFacet.count());
}
var added = [];
var argsLen = arguments.length
, addItems = argsLen > 2
, addedCount = argsLen - 2;
if (addItems) {
listFacet._addItems(addedCount, spliceIndex);
for (var i = 2, j = spliceIndex; i < argsLen; i++, j++) {
item = listFacet.item(j);
if (item) {
setTransactionFlag(item.data.set, inTransaction);
itemData = item.data.set(arguments[i]);
} else
logger.warn('Data: no item for index', j);
added.push(itemData);
}
// change paths of items that were added and items after them
listFacet._updateDataPaths(spliceIndex, listFacet.count());
}
// if (Array.isArray(this._value)) {
// _.prependArray(added, [spliceIndex, spliceHowMany]);
// Array.prototype.splice.apply(this._value, added);
// } else
this._value = this.get();
return {
spliceIndex: spliceIndex,
removed: removed,
addedCount: addItems ? addedCount : 0
};
}
function Data$len() {
try {
return executeHook.call(this, 'len');
} catch (e) {
if (e != noHook) throw e;
}
return this._len();
}
function Data$_len() {
if (this.owner.list) return this.owner.list.count();
else logger.error('Data: len called without list facet');
}
/**
* Data facet instance method
* Returns data facet of a child component (by scopes) corresponding to the path
* @param {String} accessPath data access path
*/
function Data$path(accessPath, createItem) {
// createItem = true; // this hack seems to be no longer needed...
if (! accessPath)
return this;
var parsedPath = pathUtils.parseAccessPath(accessPath);
var currentComponent = this.owner;
for (var i = 0, len = parsedPath.length; i < len; i++) {
var pathNode = parsedPath[i]
, nodeKey = pathUtils.getPathNodeKey(pathNode);
if (pathNode.syntax == 'array' && currentComponent.list) {
var itemComponent = currentComponent.list.item(nodeKey);
if (! itemComponent && createItem !== false) {
itemComponent = currentComponent.list._addItem(nodeKey);
itemComponent.data._path = pathNode.property;
}
currentComponent = itemComponent;
} else if (currentComponent.container)
currentComponent = currentComponent.container.scope[nodeKey];
var currentDataFacet = currentComponent && currentComponent.data;
if (! currentDataFacet)
break;
}
return currentDataFacet;
}
/**
* Data facet instance method
* Returns path to access this data facet from parent (using path method)
*
* @return {String}
*/
function Data$getPath() {
return this._path;
}
/**
* Data facet instance method
* Returns key to access the value related to this data facet on the value related to parent data facet.
* If component has List facet, returns index
*
* @return {String|Integer}
*/
function Data$getKey() {
var path = this._path;
return path[0] == '['
? +path.slice(1, -1) // remove "[" and "]"
: path.slice(1); // remove leading "."
}
/**
* Data facet instance method
* Called by `Component.prototype.getState` to get facet's state
* Returns DOM data
*
* @param {Boolean} deepState, true by default
* @return {Object}
*/
function Data$getState(deepState) {
return { state: this.get(deepState) };
}
/**
* Data facet instance method
* Called by `Component.prototype.setState` to set facet's state
* Simply sets model data
*
* @param {Object} state data to set on facet's model
*/
function Data$setState(state) {
return this.set(state.state);
}
},{"../c_facet":16,"../msg_api/data":36,"../msg_api/de_data":37,"../msg_src/dom_events":39,"./cf_registry":31,"milo-core":84}],20:[function(require,module,exports){
'use strict';
var ComponentFacet = require('../c_facet')
, facetsRegistry = require('./cf_registry')
, miloCore = require('milo-core')
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match
, doT = miloCore.util.doT
, binder = require('../../binder')
, BindAttribute = require('../../attributes/a_bind')
, domUtils = require('../../util/dom')
, config = require('../../config');
/**
* `milo.registry.facets.get('Dom')`
* Facet with component related dom utils
*/
var Dom = _.createSubclass(ComponentFacet, 'Dom');
_.extend(Dom, {
createElement: Dom$$createElement
});
/**
* Facet class method
* Creates an element from a passed configuation object
*
* @param {Object} config with the properties `domConfig`, `content`, `template`
* @return {Element} an html element
*/
function Dom$$createElement(config) {
var domConfig = config.domConfig || {}
, tagName = domConfig.tagName || 'div'
, newEl = document.createElement(tagName)
, content = config.content
, template = config.template;
// TODO it will be called again when/if component is instantiated
// Should be someproperty on element to indicate it's been called?
_applyConfigToElement(newEl, domConfig);
if (typeof content == 'string') {
if (template)
newEl.innerHTML = doT.template(template)({content: content});
else
newEl.innerHTML = content;
}
return newEl;
}
function _applyConfigToElement(el, config) {
var cssClasses = config && config.cls
, configAttributes = config && config.attributes;
if (configAttributes)
_.eachKey(configAttributes, function(attrValue, attrName) {
el.setAttribute(attrName, attrValue);
});
if (cssClasses)
_attachCssClasses(el, 'add', cssClasses);
}
_.extendProto(Dom, {
start: start,
show: show,
hide: hide,
toggle: toggle,
detach: detach,
remove: remove,
append: append,
prepend: prepend,
appendChildren: appendChildren,
prependChildren: prependChildren,
insertAfter: insertAfter,
insertBefore: insertBefore,
appendToScopeParent: appendToScopeParent,
children: Dom$children,
setStyle: setStyle,
setStyles: setStyles,
copy: copy,
createElement: createElement,
addCssClasses: _.partial(_manageCssClasses, 'add'),
removeCssClasses: _.partial(_manageCssClasses, 'remove'),
toggleCssClasses: _.partial(_manageCssClasses, 'toggle'),
find: find,
hasTextBeforeSelection: hasTextBeforeSelection,
hasTextAfterSelection: hasTextAfterSelection,
});
facetsRegistry.add(Dom);
module.exports = Dom;
// start Dom facet
function start() {
ComponentFacet.prototype.start.apply(this, arguments);
var el = this.owner.el;
_applyConfigToElement(el, this.config);
var currentStyle = window.getComputedStyle(el);
this._visible = currentStyle && currentStyle.display != 'none';
}
// show HTML element of component
function show() {
this.toggle(true);
}
// hide HTML element of component
function hide() {
this.toggle(false);
}
// show/hide
function toggle(doShow) {
doShow = typeof doShow == 'undefined'
? ! this._visible
: !! doShow;
this._visible = doShow;
var el = this.owner.el;
el.style.display = doShow ? 'block' : 'none';
return doShow;
}
function _manageCssClasses(methodName, cssClasses, enforce) {
_attachCssClasses(this.owner.el, methodName, cssClasses, enforce);
}
function _attachCssClasses(el, methodName, cssClasses, enforce) {
var classList = el.classList
, doToggle = methodName == 'toggle';
if (Array.isArray(cssClasses))
cssClasses.forEach(callMethod);
else if (typeof cssClasses == 'string')
callMethod(cssClasses);
else
throw new Error('unknown type of CSS classes parameter');
function callMethod(cssCls) {
if (doToggle) {
// Only pass 'enforce' if a value has been provided (The 'toggle' function of the classList will treat undefined === false resulting in only allowing classes to be removed)
if (enforce === undefined) classList[methodName](cssCls)
else classList[methodName](cssCls, enforce);
} else
classList[methodName](cssCls);
}
}
function detach() {
if (this.owner.el)
domUtils.detachComponent(this.owner.el);
}
function setStyle(property, value) {
if (!this.owner.el) {
throw new Error("Cannot call setStyle on owner with no element: " + this.owner.constructor.name);
}
this.owner.el.style[property] = value;
}
function setStyles(properties) {
for (var property in properties)
this.owner.el.style[property] = properties[property];
}
// create a copy of DOM element using facet config if set
function copy(isDeep) {
return this.owner.el && this.owner.el.cloneNode(isDeep);
}
function createElement() {
var newEl = Dom.createElement(this.config);
return newEl;
}
// remove HTML element of component
function remove() {
domUtils.removeElement(this.owner.el);
}
// append inside HTML element of component
function append(el) {
this.owner.el.appendChild(el);
}
// prepend inside HTML element of component
function prepend(el) {
var thisEl = this.owner.el
, firstChild = thisEl.firstChild;
if (firstChild)
thisEl.insertBefore(el, firstChild);
else
thisEl.appendChild(el);
}
// appends children of element inside this component's element
function appendChildren(el) {
while(el.childNodes.length)
this.append(el.childNodes[0]);
}
// prepends children of element inside this component's element
function prependChildren(el) {
while(el.childNodes.length)
this.prepend(el.childNodes[el.childNodes.length - 1]);
}
function insertAfter(el) {
var thisEl = this.owner.el
, parent = thisEl.parentNode;
parent.insertBefore(el, thisEl.nextSibling);
}
function insertBefore(el) {
var thisEl = this.owner.el
, parent = thisEl.parentNode;
parent.insertBefore(el, thisEl);
}
// appends component's element to scope parent. If it was alredy in DOM it will be moved
function appendToScopeParent() {
var parent = this.owner.getScopeParent();
if (parent) parent.el.appendChild(this.owner.el);
}
/**
* Dom facet instance method
* Returns the list of child elements of the component element
*
* @return {Array<Element>}
*/
function Dom$children() {
return domUtils.children(this.owner.el);
}
var findDirections = {
'up': 'previousNode',
'down': 'nextNode'
};
// Finds component passing optional iterator's test
// in the same scope as the current component (this)
// by traversing DOM tree upwards (direction = "up")
// or downwards (direction = "down")
function find(direction, iterator) {
if (! findDirections.hasOwnProperty(direction))
throw new Error('incorrect find direction: ' + direction);
var el = this.owner.el
, scope = this.owner.scope
, treeWalker = document.createTreeWalker(scope._rootEl, NodeFilter.SHOW_ELEMENT);
treeWalker.currentNode = el;
var nextNode = treeWalker[findDirections[direction]]()
, componentsNames = Object.keys(scope)
, found = false;
while (nextNode) {
var attr = new BindAttribute(nextNode);
if (attr.node) {
attr.parse().validate();
if (scope.hasOwnProperty(attr.compName)) {
var component = scope[attr.compName];
if (! iterator || iterator(component)) {
found = true;
break;
}
}
}
treeWalker.currentNode = nextNode;
nextNode = treeWalker[findDirections[direction]]();
}
if (found) return component;
}
// returns true if the element has text before selection
function hasTextBeforeSelection() {
var selection = window.getSelection();
if (! selection.isCollapsed) return true;
var text = selection.focusNode && selection.focusNode.textContent;
var startPos = text && text.charAt(0) == ' ' ? 1 : 0;
if (selection.anchorOffset != startPos) return true;
// walk up the DOM tree to check if there are text nodes before cursor
var treeWalker = document.createTreeWalker(this.owner.el, NodeFilter.SHOW_TEXT);
treeWalker.currentNode = selection.anchorNode;
var prevNode = treeWalker.previousNode();
var isText = prevNode ? prevNode.nodeValue.trim() !== '' : false;
return isText;
}
function hasTextAfterSelection() {
var selection = window.getSelection();
if (! selection.isCollapsed) return true;
var text = selection.focusNode && selection.focusNode.textContent;
var startPos = text && text.charAt(text.length-1) == ' ' ? selection.anchorNode.length-1 : selection.anchorNode.length;
if (selection.anchorOffset < startPos) return true;
// walk up the DOM tree to check if there are text nodes after cursor
var treeWalker = document.createTreeWalker(this.owner.el, NodeFilter.SHOW_TEXT);
treeWalker.currentNode = selection.anchorNode;
var nextNode = treeWalker.nextNode();
//To capture when treewalker gives us an empty text node (unknown reason)
var isText = nextNode ? !nextNode.nodeValue.trim() == '' : false;
return isText;
}
},{"../../attributes/a_bind":4,"../../binder":8,"../../config":42,"../../util/dom":57,"../c_facet":16,"./cf_registry":31,"milo-core":84}],21:[function(require,module,exports){
'use strict';
// <a name="components-facets-drag"></a>
// ###drag facet
var ComponentFacet = require('../c_facet')
, facetsRegistry = require('./cf_registry')
, DOMEventsSource = require('../msg_src/dom_events')
, Component = require('../c_class')
, DragDrop = require('../../util/dragdrop')
, miloCore = require('milo-core')
, _ = miloCore.proto
, logger = miloCore.util.logger;
/**
* `milo.registry.facets.get('Drag')`
* Facet for components that can be dragged
* Drag facet supports the following configuration parameters:
*
* - meta: object with properties
* - params: object of key-value pairs that will be passed in metadata data type (can also be function or method name that returns this object). See config.dragDrop.dataTypes.componentMetaTemplate
* - data: data that will be stored in the above meta data type (or function)
* - allowedEffects: string (or function) as specified here: https://developer.mozilla.org/en-US/docs/DragDrop/Drag_Operations#dragstart
* - dragImage:
* - url: path to image to display when dragging, instead of the owner element
* - x: x offset for the image
* - y: y offset for the image
* - dragCls: CSS class to apply to the component being dragged
* - dataTypes: map of additional data types the component will supply to data transfer object, key is data type, value is a function that returns it, component will be passed as the context to this function
*
* If function is specified in any parameter it will be called with the component as the context
*/
var Drag = _.createSubclass(ComponentFacet, 'Drag');
_.extendProto(Drag, {
init: Drag$init,
start: Drag$start,
setHandle: Drag$setHandle
});
facetsRegistry.add(Drag);
module.exports = Drag;
function Drag$init() {
ComponentFacet.prototype.init.apply(this, arguments);
this._createMessageSourceWithAPI(DOMEventsSource);
this._dragData = {};
var dataTypeInfo = this.config._dataTypeInfo || '';
this._dataTypeInfo = typeof dataTypeInfo == 'function'
? dataTypeInfo
: function() { return dataTypeInfo; };
}
/**
* Drag facet instance method
* Sets the drag handle element of component. This element has to be dragged for the component to be dragged.
*
* @param {Element} handleEl
*/
function Drag$setHandle(handleEl) {
if (! this.owner.el.contains(handleEl))
return logger.warn('drag handle should be inside element to be dragged');
this._dragHandle = handleEl;
}
function Drag$start() {
ComponentFacet.prototype.start.apply(this, arguments);
_addDragAttribute.call(this);
_createDragImage.call(this);
_toggleDragCls.call(this, false);
this.onMessages({
'mousedown': onMouseDown,
'mouseenter mouseleave mousemove': onMouseMovement,
'dragstart': onDragStart,
'drag': onDragging,
'dragend': onDragEnd
});
this.owner.onMessages({
'getstatestarted': _removeDragAttribute,
'getstatecompleted': _addDragAttribute
});
}
/**
* Adds draggable attribute to component's element
*
* @private
*/
function _addDragAttribute() {
if (this.el) this.el.setAttribute('draggable', true);
}
function _removeDragAttribute() {
if (this.el) this.el.removeAttribute('draggable');
}
function _createDragImage() {
var dragImage = this.config.dragImage;
if (dragImage) {
this._dragElement = new Image();
this._dragElement.src = dragImage.url;
}
}
function onMouseDown(eventType, event) {
this.__mouseDownTarget = event.target;
if (targetInDragHandle.call(this)) {
window.getSelection().empty();
event.stopPropagation();
}
}
function onMouseMovement(eventType, event) {
var shouldBeDraggable = targetInDragHandle.call(this);
this.owner.el.setAttribute('draggable', shouldBeDraggable);
if (document.body.getAttribute('data-dragEnableEvent') != 'false')
event.stopPropagation();
}
function onDragStart(eventType, event) {
event.stopPropagation();
if (this.config.off || ! targetInDragHandle.call(this)) {
event.preventDefault();
return;
}
var dragImage = this.config.dragImage;
if (dragImage)
event.dataTransfer.setDragImage(this._dragElement, dragImage.x || 0, dragImage.y || 0);
var owner = this.owner;
var dt = new DragDrop(event);
this._dragData = dt.setComponentState(owner);
setMeta.call(this);
setAdditionalDataTypes.call(this);
_setAllowedEffects.call(this, dt);
_toggleDragCls.call(this, true);
DragDrop.service.postMessageSync('dragdropstarted', {
eventType: 'dragstart',
dragDrop: dt,
dragFacet: this
});
function setMeta() {
var params = getMetaData.call(this, 'params')
, data = getMetaData.call(this, 'data');
this._dragMetaDataType = dt.setComponentMeta(owner, params, data);
this._dragMetaData = data;
}
function getMetaData(property) {
try { var func = this.config.meta[property]; } catch(e) {}
if (typeof func == 'string') func = owner[func];
return _.result(func, owner);
}
function setAdditionalDataTypes() {
if (this.config.dataTypes) {
this._dataTypesData = _.mapKeys(this.config.dataTypes, function (getDataFunc, dataType) {
if (typeof getDataFunc == 'string') getDataFunc = owner[getDataFunc];
var data = getDataFunc.call(this.owner, dataType);
if (typeof data == 'object') data = JSON.stringify(data);
if (data) dt.setData(dataType, data);
return data;
}, this);
}
}
}
function onDragging(eventType, event) {
if (_dragIsDisabled.call(this, event)) return;
var dt = new DragDrop(event);
dt.setComponentState(this.owner, this._dragData);
dt.setData(this._dragMetaDataType, this._dragMetaData);
if (this._dataTypesData) {
_.eachKey(this._dataTypesData, function(data, dataType) {
if (data) dt.setData(dataType, data);
});
}
_setAllowedEffects.call(this, dt);
}
function onDragEnd(eventType, event) {
if (_dragIsDisabled.call(this, event)) return;
event.stopPropagation();
_toggleDragCls.call(this, false);
var dt = new DragDrop(event);
DragDrop.service.postMessageSync('completedragdrop', {
eventType: 'dragend',
dragDrop: dt,
dragFacet: this
});
}
function _toggleDragCls(showHide) {
if (this.config.dragCls)
this.owner.el.classList.toggle(this.config.dragCls, showHide);
}
function _setAllowedEffects(DragDrop) {
var effects = _.result(this.config.allowedEffects, this.owner);
DragDrop.setAllowedEffects(effects);
}
function targetInDragHandle() {
return ! this._dragHandle || this._dragHandle.contains(this.__mouseDownTarget);
}
function _dragIsDisabled(event) {
if (this.config.off) {
event.preventDefault();
return true;
}
return false;
}
},{"../../util/dragdrop":60,"../c_class":15,"../c_facet":16,"../msg_src/dom_events":39,"./cf_registry":31,"milo-core":84}],22:[function(require,module,exports){
'use strict';
// <a name="components-facets-drop"></a>
// ###drop facet
var ComponentFacet = require('../c_facet')
, facetsRegistry = require('./cf_registry')
, DOMEventsSource = require('../msg_src/dom_events')
, DropMsgAPI = require('../msg_api/drop')
, DragDrop = require('../../util/dragdrop')
, _ = require('milo-core').proto;
/**
* `milo.registry.facets.get('Drop')`
* Facet for components that can accept drops
* Drop facet supports the following configuration parameters:
*
* - allow - an object that will define allowed data types during drag (`dragenter` and `dragover` events) with these properties:
* - components: `true` by default (all components will be accepted)
* OR string with allowed component class
* OR list of allowed components classes (strings)
* OR map with allowed classes in keys and `true`/test functions in values
* OR test function that will be passed object defined below
* OR `false` to NOT accept components
* - dataTypes: `false` by default (no other data types will be accepted)
* OR string with allowed data type
* OR list of additional data types that a drop target would accept
* OR test function that will be passed DragDrop object
* OR `true` to accept all data types
* - checkParent: `false` by default
* OR `true` will call parent component drop allow to check if parent component will accept the component
* If test functions are used, they should return boolean. Each test function can also set drop effect as defined here:
* https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer#dropEffect.28.29
* Setting drop effect that is not allowed by dragged object will prevent drop.
* Test functions for components will be passed the owner of Drop facet as context, the object with the following possible properties as the first parameter:
* compClass - name of component class as stored in registry
* compName - name of component (all lowercase)
* params - parameters as encoded in dataType, passed to `milo.util.dragDrop.setComponentMeta` by Drag facet
* metaDataType - data type of the data that has compClass, compName and params encoded
*
* ... and DragDrop instance as the second parameter
*
* Test function for other data types will be passed the owner of Drop facet as context and DragDrop instance as the first parameter
*
* ####Events####
*
* In addition to configuring allowed components and data types, components classes should subscribe to events.
* At the very least, they should subscribe to `drop` event.
*
* Drop facet emits dragin/dragout messages that are emitted whenever actual component element is entered or left
* (which is different from dragenter and dragleave messages that are emitted whenever any child element is entered or left, as long as event bubbles up)
* If child component has drop facet attached, dragout will be emitted on the current component when the child is entered.
*
* You can see the demonstration of when messages are emitted [here](http://jsbin.com/buqov/6)
*
*/
var Drop = _.createSubclass(ComponentFacet, 'Drop');
_.extendProto(Drop, {
init: Drop$init,
start: Drop$start
// _reattach: _reattachEventsOnElementChange
});
facetsRegistry.add(Drop);
module.exports = Drop;
function Drop$init() {
ComponentFacet.prototype.init.apply(this, arguments);
this._createMessageSourceWithAPI(DOMEventsSource, new DropMsgAPI);
}
function Drop$start() {
ComponentFacet.prototype.start.apply(this, arguments);
this.owner.el.classList.add('cc-module-relative');
this.onMessages({
'dragenter dragover': onDragging,
'drop': onDrop,
'dragenter dragover dragleave drop dragin dragout': postToService
});
}
function onDragging(eventType, event) {
var dt = new DragDrop(event);
event.stopPropagation();
event.preventDefault();
if (! _handleDropDependency.call(this, dt))
dt.setDropEffect('none');
}
function onDrop(eventType, event) {
event.stopPropagation();
var dt = new DragDrop(event);
DragDrop.service.postMessageSync('dragdropcompleted', {
eventType: 'drop',
dragDrop: dt,
dropFacet: this,
component: this.owner
});
}
function postToService(eventType, event) {
DragDrop.service.postMessageSync(eventType, {
event: event,
dropFacet: this,
component: this.owner
});
}
var _handleDropDependency = _.throttle(_handleDropDependencyNothrottle, 50);
function _handleDropDependencyNothrottle(dt, originalDropComponent) {
var allow = this.config.allow
, parentAllowed = true;
originalDropComponent = originalDropComponent || this.owner;
if (allow && allow.checkParent) {
var parent = this.owner.getScopeParent('Drop');
if (parent)
parentAllowed = _handleDropDependencyNothrottle.call(parent.drop, dt, originalDropComponent);
}
return parentAllowed && _isDropAllowed.call(this, dt, originalDropComponent);
}
/**
* Checks if drop is allowed based on facet configuration (see above)
*
* @param {DragDrop} dt
* @return {Boolean}
*/
function _isDropAllowed(dt, originalDropComponent) {
var allow = this.config.allow;
if (dt.isComponent()) {
var allowComps = allow && allow.components
, meta = dt.getComponentMeta();
switch (typeof allowComps) {
case 'undefined':
return true;
case 'boolean':
return allowComps;
// component class
case 'string':
return meta && meta.compClass == allowComps;
// test function
case 'function':
return allowComps.call(this.owner, meta, dt, originalDropComponent);
case 'object':
if (Array.isArray(allowComps))
// list of allowed classes
return allowComps.indexOf(meta && meta.compClass) >= 0;
else {
// map of class: boolean|test function
var test = allowComps[meta && meta.compClass];
return !! _.result(test, this.owner, meta, dt);
}
break;
default:
throw new Error('Incorrect allowed components in config');
}
} else {
var dataTypes = allow && allow.dataTypes;
switch (typeof dataTypes) {
case 'undefined':
return false;
case 'string':
return dt.types.indexOf(dataTypes) >= 0;
}
}
// TODO test for other data types
}
},{"../../util/dragdrop":60,"../c_facet":16,"../msg_api/drop":38,"../msg_src/dom_events":39,"./cf_registry":31,"milo-core":84}],23:[function(require,module,exports){
'use strict';
var ComponentFacet = require('../c_facet')
, facetsRegistry = require('./cf_registry')
, miloCore = require('milo-core')
, Messenger = miloCore.Messenger
, DOMEventsSource = require('../msg_src/dom_events')
, _ = miloCore.proto;
/**
* `milo.registry.facets.get('Events')`
* Component facet that manages subscriptions to DOM events using [Messenger](../../messenger/index.js.html) with [DOMEventsSource](../msg_src/dom_events.js.html).
* All public methods of Messenger and `trigger` method of [DOMEventsSource](../msg_src/dom_events.js.html) are proxied directly to this facet.
* For example, to subscribe to `click` event use:
* ```
* component.frame.on('click', function() {
* // ...
* });
* ```
* See [Messenger](../../messenger/index.js.html)
*/
var Events = _.createSubclass(ComponentFacet, 'Events');
/**
* ####Events facet instance methods####
*
* - [init](#Events$init) - called by constructor automatically
*/
_.extendProto(Events, {
init: Events$init
// _reattach: _reattachEventsOnElementChange
});
facetsRegistry.add(Events);
module.exports = Events;
/**
* Expose DOMEventsSource trigger method on Events prototype
*/
var MSG_SOURCE_KEY = '_domEventsSource';
DOMEventsSource.useWith(Events, MSG_SOURCE_KEY, ['trigger']);
/**
* Events facet instance method
* Initialzes facet, connects DOMEventsSource to facet's messenger
*/
function Events$init() {
ComponentFacet.prototype.init.apply(this, arguments);
var domEventsSource = new DOMEventsSource(this, undefined, undefined, this.owner);
this._setMessageSource(domEventsSource);
_.defineProperty(this, MSG_SOURCE_KEY, domEventsSource);
}
},{"../c_facet":16,"../msg_src/dom_events":39,"./cf_registry":31,"milo-core":84}],24:[function(require,module,exports){
'use strict';
var ComponentFacet = require('../c_facet')
, facetsRegistry = require('./cf_registry')
, miloCore = require('milo-core')
, Messenger = miloCore.Messenger
, FrameMessageSource = require('../msg_src/frame')
, domEventsConstructors = require('../../services/de_constrs')
, _ = miloCore.proto;
/**
* `milo.registry.facets.get('Frame')`
* Component facet that simplifies sending window messages to iframe and subscribing to messages on inner window of iframe.
* All public methods of Messenger and `trigger` method of [FrameMessageSource](../msg_src/frame.js.html) are proxied directly to this facet.
* For example, to send custom message to iframe window use:
* ```
* iframeComponent.frame.trigger('mymessage', myData);
* ```
* To subscribe to this messages inside frame use (with milo - see [milo.mail](../../mail/index.js.html)):
* ```
* milo.mail.on('message:mymessage', function(msgType, msgData) {
* // data is inside of window message data
* // msgType == 'message:mymessage'
* var myData = msgData.data;
* // ... app logic here
* });
* ```
* or without milo:
* ```
* window.attachEventListener('message', function(message) {
* var msgType = message.type; // e.g., 'mymessage'
* var myData = message.data;
* // ... message routing and code here
* });
* ```
* Milo does routing based on sent message type automatically.
* See [Messenger](../../messenger/index.js.html) and [milo.mail](../../mail/index.js.html).
*/
var Frame = _.createSubclass(ComponentFacet, 'Frame');
/**
* Calls passed function when frame DOM becomes ready. If already ready calls immediately
*/
var Frame$whenReady = _makeWhenReadyFunc(Frame$isReady, 'domready');
/**
* Calls passed function when frame milo becomes ready. If already ready calls immediately
*/
var Frame$whenMiloReady = _makeWhenReadyFunc(Frame$isMiloReady, 'message:miloready');
/**
* ####Events facet instance methods####
*
* - [init](#Frame$init) - called by constructor automatically
*/
_.extendProto(Frame, {
init: Frame$init,
start: Frame$start,
destroy: Frame$destroy,
getWindow: Frame$getWindow,
isReady: Frame$isReady,
whenReady: Frame$whenReady,
isMiloReady: Frame$isMiloReady,
whenMiloReady: Frame$whenMiloReady,
milo: Frame$milo
// _reattach: _reattachEventsOnElementChange
});
facetsRegistry.add(Frame);
module.exports = Frame;
/**
* Expose FrameMessageSource trigger method on Events prototype
*/
var MSG_SOURCE_KEY = '_messageSource';
FrameMessageSource.useWith(Frame, MSG_SOURCE_KEY, ['trigger']);
/**
* Frame facet instance method
* Initialzes facet, connects FrameMessageSource to facet's messenger
*/
function Frame$init() {
ComponentFacet.prototype.init.apply(this, arguments);
var messageSource = new FrameMessageSource(this, undefined, undefined, this.owner);
this._setMessageSource(messageSource);
_.defineProperty(this, MSG_SOURCE_KEY, messageSource);
}
/**
* Frame facet instance method
* Emits frameloaded event when ready.
*/
function Frame$start() {
ComponentFacet.prototype.start.apply(this, arguments);
var self = this;
milo(postDomReady);
function postDomReady(event) {
self.postMessage('domready', event);
}
}
function Frame$destroy() {
ComponentFacet.prototype.destroy.apply(this, arguments);
}
/**
* Frame facet instance method
* Retrieves the internal window of the frame
*
* @param {Window}
*/
function Frame$getWindow() {
return this.owner.el.contentWindow;
}
/**
* Frame facet instance method
* Returns document.readyState if frame doument state is 'interactive' or 'complete', false otherwise
*
* @return {String|Boolean}
*/
function Frame$isReady() {
var readyState = this.getWindow().document.readyState;
return readyState != 'loading' ? readyState : false;
}
/**
* Frame facet instance method
* Returns true if milo is loaded and has finished initializing inside the frame
*
* @return {Boolean}
*/
function Frame$isMiloReady() {
var frameMilo = this.getWindow().milo;
return this.isReady() && frameMilo && frameMilo.milo_version;
}
/**
* Gives access to milo in the frame (assuming it is loaded there)
* Calls function when both milo and DOM are ready if function is passed.
* Returns the reference to milo inside the frame if the window is already available.
*
* @param {Function} func function to be called when milo and DOM are ready in the frame
* @return {Function} reference to milo in the frame
*/
function Frame$milo(func) {
if (typeof func == 'function') {
var self = this;
this.whenMiloReady(function() {
self.getWindow().milo(func);
});
}
var win = this.getWindow();
return win && win.milo;
}
function _makeWhenReadyFunc(isReadyFunc, event) {
return function Frame_whenReadyFunc(func) { // , arguments
var self = this
, args = _.slice(arguments, 1);
if (isReadyFunc.call(this))
callFunc();
else
this.on(event, callFunc);
function callFunc() {
func.apply(self, args);
}
};
}
},{"../../services/de_constrs":46,"../c_facet":16,"../msg_src/frame":40,"./cf_registry":31,"milo-core":84}],25:[function(require,module,exports){
'use strict';
var ComponentFacet = require('../c_facet')
, facetsRegistry = require('./cf_registry')
, miloCore = require('milo-core')
, Model = miloCore.Model
, _ = miloCore.proto
, miloMail = require('../../services/mail');
var ItemFacet = _.createSubclass(ComponentFacet, 'Item');
_.extendProto(ItemFacet, {
getState: ItemFacet$getState,
setState: ItemFacet$setState,
getIndex: ItemFacet$getIndex,
setIndex: ItemFacet$setIndex,
removeItem: ItemFacet$removeItem,
extractItem: ItemFacet$extractItem,
isSample: ItemFacet$isSample,
require: ['Container', 'Dom', 'Data']
});
facetsRegistry.add(ItemFacet);
module.exports = ItemFacet;
function ItemFacet$getState() {
return { state: {
index: this.getIndex()
}};
}
function ItemFacet$setState(state) {
this.setIndex(state.state.index);
}
/**
* Facet instance method
* Returns the index of the owner component in it's parent list component
* @return {Integer} The index
*/
function ItemFacet$getIndex() {
return this.index;
}
/**
* Facet instance method
* Sets the index of this component
* @param {Integer} index The index to be set
*/
function ItemFacet$setIndex(index) {
this.index = index;
}
/**
* ItemFacet instance method
* Removes component from the list, component gets destroyed
*/
function ItemFacet$removeItem() {
// this.list and this.index are set by the list when the item is added
this.list.removeItem(this.index);
}
/**
* ItemFacet instance method
* Removes component from the list, component is NOT destroyed
*/
function ItemFacet$extractItem() {
this.list.extractItem(this.index);
}
/**
* Returns true if the component is a sample for the containing list, false if not
* @return {Boolean}
*/
function ItemFacet$isSample() {
return this.list.itemSample == this.owner;
}
},{"../../services/mail":48,"../c_facet":16,"./cf_registry":31,"milo-core":84}],26:[function(require,module,exports){
'use strict';
var ComponentFacet = require('../c_facet')
, Component = require('../c_class')
, facetsRegistry = require('./cf_registry')
, miloCore = require('milo-core')
, _ = miloCore.proto
, miloMail = require('../../services/mail')
, miloBinder = require('../../binder')
, logger = miloCore.util.logger
, doT = miloCore.util.doT
, check = miloCore.util.check
, Match = check.Match
, domUtils = require('../../util/dom')
, componentName = require('../../util/component_name')
, miloConfig = require('../../config');
var LIST_SAMPLE_CSS_CLASS = 'ml-list-item-sample';
/**
* `milo.registry.facets.get('List')`
* Facet enabling list functionality
*/
var List = _.createSubclass(ComponentFacet, 'List');
_.extendProto(List, {
init: List$init,
start: List$start,
destroy: List$destroy,
require: ['Container', 'Dom', 'Data'],
_itemPreviousComponent: _itemPreviousComponent,
item: List$item,
count: List$count,
contains: List$contains,
addItem: List$addItem,
addItems: List$addItems,
replaceItem: List$replaceItem,
moveItem: List$moveItem,
removeItem: List$removeItem,
extractItem: List$extractItem,
each: List$each,
map: List$map,
_setItem: List$_setItem,
_removeItem: List$_removeItem,
_addItem: List$_addItem,
_addItems: List$_addItems,
_createCacheTemplate: List$_createCacheTemplate,
_updateDataPaths: List$_updateDataPaths
});
facetsRegistry.add(List);
module.exports = List;
/**
* Facet instance method
* Initialized List facet instance and sets up item properties.
*/
function List$init() {
ComponentFacet.prototype.init.apply(this, arguments);
var self = this;
_.defineProperties(this, {
_listItems: [],
_listItemsHash: {}
});
_.defineProperty(this, 'itemSample', null, _.WRIT);
}
/**
* Facet instance method
* Starts the List facet instance, finds child with Item facet.
*/
function List$start() {
ComponentFacet.prototype.start.apply(this, arguments);
// Fired by __binder__ when all children of component are bound
this.owner.on('childrenbound', onChildrenBound);
}
function onChildrenBound() {
// get items already in the list
var children = this.dom.children()
, items = this.list._listItems
, itemsHash = this.list._listItemsHash;
if (children) children.forEach(function(childEl) {
var comp = Component.getComponent(childEl);
if (comp && comp.item) {
items.push(comp);
itemsHash[comp.name] = comp;
comp.item.list = this.list;
}
}, this);
if (items.length) {
var foundItem = items[0];
items.splice(0, 1);
delete itemsHash[foundItem.name];
items.forEach(function(item, index) {
item.item.setIndex(index);
});
}
// Component must have one child with an Item facet
if (! foundItem) throw new Error('No child component has Item facet');
this.list.itemSample = foundItem;
// After keeping a reference to the item sample, it must be hidden and removed from scope. The item sample will
// remain in the DOM and as such is marked with a CSS class allowing other code to ignore this element if required.
foundItem.dom.hide();
foundItem.remove(true);
foundItem.dom.addCssClasses(LIST_SAMPLE_CSS_CLASS);
// remove references to components from sample item
foundItem.walkScopeTree(function(comp) {
delete comp.el[miloConfig.componentRef];
});
this.list._createCacheTemplate();
}
function List$_createCacheTemplate() {
if (!this.itemSample) return false;
var itemSample = this.itemSample;
// create item template to insert many items at once
var itemElCopy = itemSample.el.cloneNode(true);
itemElCopy.classList.remove(LIST_SAMPLE_CSS_CLASS);
var attr = itemSample.componentInfo.attr;
var attrCopy = _.clone(attr);
attr.compName = '{{= it.componentName() }}';
attr.el = itemElCopy;
attr.decorate();
var itemsTemplateStr =
'{{ var i = it.count; while(i--) { }}'
+ itemElCopy.outerHTML
+ '{{ } }}';
this.itemsTemplate = doT.compile(itemsTemplateStr);
}
/**
* Facet instance method
* Retrieve a particular child item by index
* @param {Integer} index The index of the child item to get.
* @return {Component} The component found
*/
function List$item(index) {
return this._listItems[index];
}
/**
* Facet instance method
* Gets the total number of child items
* @return {Integer} The total
*/
function List$count() {
return this._listItems.length;
}
function List$_setItem(index, component) {
this._listItems.splice(index, 0, component);
this._listItemsHash[component.name] = component;
component.item.list = this;
component.item.setIndex(+index);
}
/**
* Facet instance method
* Returns true if a particular child item exists in the list
* @param {Component} component The component to look for.
* @return {Boolean}
*/
function List$contains(component) {
return this._listItemsHash[component.name] == component;
}
/**
* Facet instance method
* Adds a new child component at a particular index and returns the new component.
* This method uses data facet, so notification will be emitted on data facet.
* @param {Integer} index The index to add at
* @return {Component} The newly created component
*/
function List$addItem(index, itemData) {
index = isNaN(+index) ? this.count() : +index;
this.owner.data.splice(index, 0, itemData || {});
return this.item(index);
}
/**
* Facet instance method
* Adds a new child component at a particular index and returns the new component
* @param {Integer} index The index to add at
* @return {Component} The newly created component
*/
function List$_addItem(index) {
if (this.item(index))
throw Error('attempt to create item with ID of existing item');
// Copy component
var component = Component.copy(this.itemSample, true);
var prevComponent = this._itemPreviousComponent(index);
if (!prevComponent.el.parentNode)
return logger.warn('list item sample was removed from DOM, probably caused by wrong data. Reset list data with array');
// Add it to the DOM
prevComponent.dom.insertAfter(component.el);
// Add to list items
this._setItem(index, component);
// Show the list item component
component.el.style.display = '';
component.el.classList.remove(LIST_SAMPLE_CSS_CLASS);
_updateItemsIndexes.call(this, index + 1);
return component;
}
function _updateItemsIndexes(fromIndex, toIndex) {
fromIndex = fromIndex || 0;
toIndex = toIndex || this.count();
for (var i = fromIndex; i < toIndex; i++) {
var component = this._listItems[i];
if (component)
component.item.setIndex(i);
else
logger.warn('List: no item at position', i);
}
}
function List$addItems(count, index) { // ,... items data
var itemsData = _.slice(arguments, 2);
if (itemsData.length < count)
itemsData.concat(_.repeat(count - itemsData.length, {}));
var spliceArgs = [index, 0].concat(itemsData);
var dataFacet = this.owner.data;
dataFacet.splice.apply(dataFacet, spliceArgs);
}
/**
* List facet instance method
* Adds a given number of items using template rendering rather than adding elements one by one
*
* @param {Integer} count number of items to add
* @param {Integer} [index] optional index of item after which to add
*/
function List$_addItems(count, index) {
check(count, Match.Integer);
if (count < 0)
throw new Error('can\'t add negative number of items');
if (count === 0) return;
var itemsHTML = this.itemsTemplate({
componentName: componentName,
count: count
});
var wrapEl = document.createElement(this.owner.el.tagName);
wrapEl.innerHTML = itemsHTML;
miloBinder(wrapEl, this.owner.container.scope);
var children = domUtils.children(wrapEl);
if (count != children.length)
logger.error('number of items added is different from requested');
if (children && children.length) {
var listLength = this.count();
var spliceIndex = index < 0
? 0
: typeof index == 'undefined' || index > listLength
? listLength
: index;
var prevComponent = spliceIndex === 0
? this.itemSample
: this._listItems[spliceIndex - 1];
var frag = document.createDocumentFragment()
, newComponents = [];
children.forEach(function(el, i) {
var component = Component.getComponent(el);
if (! component)
return logger.error('List: element in new items is not a component');
newComponents.push(component);
this._setItem(spliceIndex++, component);
frag.appendChild(el);
el.style.display = '';
}, this);
_updateItemsIndexes.call(this, spliceIndex);
if (!prevComponent.el.parentNode)
return logger.warn('list item sample was removed from DOM, probably caused by wrong data. Reset list data with array');
// Add it to the DOM
prevComponent.dom.insertAfter(frag);
_.deferMethod(newComponents, 'forEach', function(comp) {
comp.broadcast('stateready');
});
}
}
/**
* List facet instance method
* @param {Integer} index The index of the item to remove
* @return {Array[Object]} The spliced data
*/
function List$removeItem(index) {
return this.owner.data.splice(index, 1);
}
/**
* List facet instance method
* @param {Integer} index The index of the item to extract
* @return {Component} The extracted item
*/
function List$extractItem(index) {
var itemComp = this._removeItem(index, false);
this._updateDataPaths(index, this.count());
return itemComp;
}
/**
* List facet instance method
* Removes item, returns the removed item that is destroyed by default.
*
* @param {Number} index item index
* @param {Boolean} doDestroyItem optional false to prevent item destruction, true by default
* @return {Component}
*/
function List$_removeItem(index, doDestroyItem) {
var comp = this.item(index);
if (! comp)
return logger.warn('attempt to remove list item with id that does not exist');
this._listItems[index] = undefined;
delete this._listItemsHash[comp.name];
if (doDestroyItem !== false) comp.destroy();
else {
comp.remove();
comp.dom.remove();
}
this._listItems.splice(index, 1);
_updateItemsIndexes.call(this, index);
return comp;
}
function List$replaceItem(index, newItem){
var oldItem = this.item(index);
oldItem.dom.insertAfter(newItem.el);
this._removeItem(index);
this._setItem(index, newItem);
}
function List$moveItem(fromIndex, toIndex) {
var componentToMove = this.extractItem(fromIndex);
var toComponent = this.item(toIndex);
componentToMove.insertInto(this.owner.el, toComponent.el);
this._setItem(toIndex, componentToMove);
_updateItemsIndexes.call(this, 0);
}
// Returns the previous item component given an index
function _itemPreviousComponent(index) {
while (index >= 0 && ! this._listItems[index])
index--;
return index >= 0
? this._listItems[index]
: this.itemSample;
}
// toIndex is not included
// no range checking is made
function List$_updateDataPaths(fromIndex, toIndex) {
for (var i = fromIndex; i < toIndex; i++) {
var item = this.item(i);
if (item)
item.data._path = '[' + i + ']';
else
logger.warn('Data: no item for index', i);
}
}
/**
* Facet instance method
* Similar to forEach method of Array, iterates each of the child items.
* @param {Function} callback An iterator function to be called on each child item.
* @param {Any} [thisArg] Context to set `this`.
*/
function List$each(callback, thisArg) {
this._listItems.forEach(function(item, index) {
if (item) callback.apply(this, arguments); // passes item, index to callback
else logger.warn('List$each: item', index, 'is undefined');
}, thisArg || this);
}
function List$map(callback, thisArg) {
return this._listItems.map(function(item, index) {
if (item) return callback.apply(this, arguments); // passes item, index to callback
else logger.warn('List$map: item', index, 'is undefined');
}, thisArg || this);
}
/**
* Facet instance method
* Destroys the list
*/
function List$destroy() {
if (this.itemSample) this.itemSample.destroy(true);
ComponentFacet.prototype.destroy.apply(this, arguments);
}
},{"../../binder":8,"../../config":42,"../../services/mail":48,"../../util/component_name":53,"../../util/dom":57,"../c_class":15,"../c_facet":16,"./cf_registry":31,"milo-core":84}],27:[function(require,module,exports){
'use strict';
var ComponentFacet = require('../c_facet')
, facetsRegistry = require('./cf_registry')
, miloCore = require('milo-core')
, Model = miloCore.Model
, Mixin = miloCore.classes.Mixin
, _ = miloCore.proto;
// generic drag handler, should be overridden
var ModelFacet = _.createSubclass(ComponentFacet, 'Model');
_.extendProto(ModelFacet, {
init: ModelFacet$init,
getState: ModelFacet$getState,
setState: ModelFacet$setState,
_createMessenger: ModelFacet$_createMessenger,
destroy: ModelFacet$destroy
});
facetsRegistry.add(ModelFacet);
module.exports = ModelFacet;
/**
* Expose Model class methods on ModelFacet
*/
Model.useWith(ModelFacet, 'm');
function ModelFacet$init() {
this.m = new Model(this.config.data, this);
ComponentFacet.prototype.init.apply(this, arguments);
// this.m.proxyMethods(this); // Creates model's methods directly on facet
}
/**
* ModelFacet instance method
* Called by `Component.prototype.getState` to get facet's state
* Simply returns model data
*
* @return {Object}
*/
function ModelFacet$getState() {
var modelValue = this.m.get();
if (typeof modelValue == 'object')
modelValue = _.deepClone(modelValue);
return { state: modelValue };
}
/**
* ModelFacet instance method
* Called by `Component.prototype.setState` to set facet's state
* Simply sets model data
*
* @param {Object} state data to set on facet's model
*/
function ModelFacet$setState(state) {
return this.m.set(state.state);
}
function ModelFacet$_createMessenger() { // Called by inherited init
this._messenger = this.m._messenger;
}
function ModelFacet$destroy() {
this.m.destroy();
ComponentFacet.prototype.destroy.apply(this, arguments);
}
},{"../c_facet":16,"./cf_registry":31,"milo-core":84}],28:[function(require,module,exports){
'use strict';
var ComponentFacet = require('../c_facet')
, facetsRegistry = require('./cf_registry')
, miloCore = require('milo-core')
, Model = miloCore.Model
, _ = miloCore.proto;
// generic drag handler, should be overridden
var Options = _.createSubclass(ComponentFacet, 'Options');
_.extendProto(Options, {
init: Options$init,
destroy: Options$destroy,
_createMessenger: Options$_createMessenger
});
facetsRegistry.add(Options);
module.exports = Options;
function Options$init() {
this.m = new Model(this.config.options, this);
ComponentFacet.prototype.init.apply(this, arguments);
this.m.proxyMethods(this); // Creates model's methods directly on facet
}
function Options$_createMessenger() { // Called by inherited init
this._messenger = this.m._messenger;
}
function Options$destroy() {
this.m.destroy();
ComponentFacet.prototype.destroy.apply(this, arguments);
}
},{"../c_facet":16,"./cf_registry":31,"milo-core":84}],29:[function(require,module,exports){
'use strict';
// <a name="components-facets-template"></a>
// ###template facet
// simplifies rendering of component element from template.
// Any templating enging can be used that supports template compilation
// (or you can mock this compilation easily by creating closure storing
// template string in case your engine doesn't support compilation).
// By default milo uses [doT](), the most versatile, conscise and at the
// same time the fastest templating engine.
// If you use milo in browser, it is the part of milo bundle and available
// as global variable `doT`.
var ComponentFacet = require('../c_facet')
, facetsRegistry = require('./cf_registry')
, miloCore = require('milo-core')
, _ = miloCore.proto
, check = miloCore.util.check
, logger = miloCore.util.logger
, Match = check.Match
, binder = require('../../binder')
, config = require('../../config');
// data model connection facet
var Template = _.createSubclass(ComponentFacet, 'Template');
_.extendProto(Template, {
init: Template$init,
start: Template$start,
set: Template$set,
getCompiled: Template$getCompiled,
render: Template$render,
binder: Template$binder
// _reattach: _reattachEventsOnElementChange
});
facetsRegistry.add(Template);
module.exports = Template;
function Template$init() {
ComponentFacet.prototype.init.apply(this, arguments);
// templates are interpolated with default (doT) or configured engine (this.config.compile)
// unless this.config.interpolate is false
var compile = this.config.interpolate === false
? undefined
: this.config.compile || config.template.compile;
this.set(this.config.template || '', compile, this.config.compileOptions);
}
function Template$start() {
ComponentFacet.prototype.start.apply(this, arguments);
if (this.config.autoRender) {
this.render();
if (this.config.autoBinder)
this.binder();
}
}
function Template$getCompiled() {
return this._template;
}
function Template$set(templateStr, compile, compileOptions) {
check(templateStr, Match.OneOf(String, Function));
check(compile, Match.Optional(Function));
if (typeof templateStr == 'function')
this._template = templateStr;
else {
this._templateStr = templateStr;
if (compile)
this._compile = compile;
else
compile = this._compile;
if (compile)
this._template = compile(templateStr, compileOptions);
}
return this;
}
function Template$render(data) { // we need data only if use templating engine
this.owner.el.innerHTML = this._template
? this._template(data)
: this._templateStr;
return this;
}
function Template$binder() {
if (this.owner.container)
return this.owner.container.binder();
else
logger.error('TemplateFacet: Binder called without container facet.');
}
},{"../../binder":8,"../../config":42,"../c_facet":16,"./cf_registry":31,"milo-core":84}],30:[function(require,module,exports){
'use strict';
var ComponentFacet = require('../c_facet')
, facetsRegistry = require('./cf_registry');
/**
* Transfer facet is designed for components to be able to represent other components
* If a [Component](../c_class.js.html) has Transfer facet, when `Component.getState` is called for this componet it returns previously saved data, possibly from another component.
* For example, a list of documents can use this facet so that each item in the list can store actual document component on it.
*/
var Transfer = _.createSubclass(ComponentFacet, 'Transfer');
_.extendProto(Transfer, {
init: Transfer$init,
getState: Transfer$getState,
setState: Transfer$setState,
setActiveState: Transfer$setActiveState,
setStateWithKey: Transfer$setStateWithKey,
getStateWithKey: Transfer$getStateWithKey,
getComponentMeta: Transfer$getComponentMeta
});
facetsRegistry.add(Transfer);
module.exports = Transfer;
function Transfer$init() {
ComponentFacet.prototype.init.apply(this, arguments);
this._activeState = '';
this._defaultKey = '';
this._state = {};
}
/**
* Transfer facet instance method
* Returns transfer state for component. Can be obtained from another component by using `Component.getState`
*
* @return {Object}
*/
function Transfer$getState() {
return this._state[this._activeState] || this._state[this._defaultKey];
}
/**
* Transfer facet instance method
* Sets transfer state for component. Can be obtained from another component by using `Component.getState`
*
* @param {Object} state
*/
function Transfer$setState(state) {
this._state[''] = state;
this.setActiveState('');
}
/**
* Transfer facet instance method
* Sets the active state (used by getState)
* @param {String} key state key
*/
function Transfer$setActiveState(key) {
this._activeState = key;
}
/**
* Transfer facet instance method
* Sets transfer state for component without default key. Can be obtained from another component by using `Component.getState`
* When the active state is set to the expected key
* @param {String} key state key
* @param {Object} state state object
* @param {Boolean} [isDefaultKey] (Optional)
*/
function Transfer$setStateWithKey(key, state, isDefaultKey) {
if (!key) throw new Error('Transfer$setStateWithKey: no key');
if (isDefaultKey)
this._defaultKey = key;
else
this._defaultKey = this._defaultKey || key;
this._state[key] = state;
this.setActiveState(key);
}
function Transfer$getStateWithKey(key) {
return typeof key == 'string' && this._state[key];
}
function Transfer$getComponentMeta() {
var state = this.getState();
return {
compName: state && state.compName,
compClass: state && state.compClass
};
}
},{"../c_facet":16,"./cf_registry":31}],31:[function(require,module,exports){
'use strict';
var ClassRegistry = require('../../abstract/registry')
, ComponentFacet = require('../c_facet');
/**
* `milo.registry.facets`
* Component facets registry. An instance of [ClassRegistry](../../abstract/registry.js.html) class that is used by milo to register and find facets.
*/
var facetsRegistry = new ClassRegistry(ComponentFacet);
// Adds common ancestor to all facets of components to the registry.
facetsRegistry.add(ComponentFacet);
module.exports = facetsRegistry;
},{"../../abstract/registry":3,"../c_facet":16}],32:[function(require,module,exports){
'use strict';
var componentsRegistry = require('./c_registry')
, facetsRegistry = require('./c_facets/cf_registry')
, componentName = require('../util/component_name')
, Scope = require('./scope')
, miloCore = require('milo-core')
, logger = miloCore.util.logger
, _ = miloCore.proto;
module.exports = ComponentInfo;
/**
* Simple class to hold information allowing to create/copy component using [`Component.create`](./c_class.js.html#create) and [`Component.copy`](./c_class.js.html#copy).
*
* @constructor
* @param {Scope} scope scope object the component belogs to, usually either top level scope that will be returned by [milo.binder](../binder.js.html) or `scope` property of [Container](./c_facets/Container.js.html) facet of containing component
* @param {Element} el DOM element the component is attached to
* @param {BindAttribute} attr BindAttribute instance that the component was created with
* @param {Boolean} throwOnErrors If set to false, then errors will only be logged to console. True by default.
* @return {ComponentInfo}
*/
function ComponentInfo(scope, el, attr, throwOnErrors) {
attr.parse().validate();
this.scope = scope;
this.el = el;
this.attr = attr;
this.name = attr.compName;
this.ComponentClass = getComponentClass(attr, throwOnErrors);
this.extraFacetsClasses = getComponentExtraFacets(this.ComponentClass, attr, throwOnErrors);
if (this.ComponentClass
&& hasContainerFacet(this.ComponentClass, this.extraFacetsClasses)) {
this.container = {};
}
}
/**
* ####ComponentInfo instance methods####
*
* - [destroy](#ComponentInfo$destroy)
* - [rename](#ComponentInfo$rename)
*/
_.extendProto(ComponentInfo, {
destroy: ComponentInfo$destroy,
rename: ComponentInfo$rename
});
/**
* ComponentInfo instance method
* Destroys ComponentInfo by removing the references to DOM element
*/
function ComponentInfo$destroy() {
delete this.el;
this.attr.destroy();
}
/**
* ComponentInfo instance method
* Renames ComponentInfo object
*
* @param {String} [name] optional new component name, generated from timestamp by default
* @param {Boolean} [renameInScope] optional false to not rename ComponentInfo object in its scope, true by default
*/
function ComponentInfo$rename(name, renameInScope) {
name = name || componentName();
Scope.rename(this, name, renameInScope);
this.attr.compName = name;
this.attr.decorate();
}
function getComponentClass(attr, throwOnErrors) {
var ComponentClass = componentsRegistry.get(attr.compClass);
if (! ComponentClass)
reportBinderError(throwOnErrors, 'class ' + attr.compClass + ' is not registered');
return ComponentClass;
}
function getComponentExtraFacets(ComponentClass, attr, throwOnErrors) {
var facets = attr.compFacets
, extraFacetsClasses = {};
if (Array.isArray(facets))
facets.forEach(function(fctName) {
fctName = _.firstUpperCase(fctName);
if (ComponentClass.hasFacet(fctName))
reportBinderError(throwOnErrors, 'class ' + ComponentClass.name
+ ' already has facet ' + fctName);
if (extraFacetsClasses[fctName])
reportBinderError(throwOnErrors, 'component ' + attr.compName
+ ' already has facet ' + fctName);
var FacetClass = facetsRegistry.get(fctName);
extraFacetsClasses[fctName] = FacetClass;
});
return extraFacetsClasses;
}
function reportBinderError(throwOnErrors, message) {
if (throwOnErrors === false)
logger.error('ComponentInfo binder error:', message);
else
throw new Error(message);
}
function hasContainerFacet(ComponentClass, extraFacetsClasses) {
return (ComponentClass.hasFacet('container')
|| 'Container' in extraFacetsClasses
|| _.someKey(extraFacetsClasses, facetRequiresContainer)
|| classHasFacetThatRequiresContainer());
function classHasFacetThatRequiresContainer() {
return (ComponentClass.prototype.facetsClasses
&& _.someKey(ComponentClass.prototype.facetsClasses, facetRequiresContainer));
}
function facetRequiresContainer(FacetClass) {
return FacetClass.requiresFacet('container');
}
}
},{"../util/component_name":53,"./c_facets/cf_registry":31,"./c_registry":33,"./scope":41,"milo-core":84}],33:[function(require,module,exports){
'use strict';
var ClassRegistry = require('../abstract/registry')
, Component = require('./c_class');
/**
* `milo.registry.components`
* An instance of [ClassRegistry](../abstract/registry.js.html) class that is used by milo to register and find components.
*/
var componentsRegistry = new ClassRegistry(Component);
// add common ancestor to all components to the registry.
componentsRegistry.add(Component);
module.exports = componentsRegistry;
},{"../abstract/registry":3,"./c_class":15}],34:[function(require,module,exports){
'use strict';
var config = require('../config')
, miloCore = require('milo-core')
, check = miloCore.util.check
, Match = check.Match
, _ = miloCore.proto;
var componentUtils = module.exports = {
isComponent: isComponent,
getComponent: getComponent,
getContainingComponent: getContainingComponent,
_makeComponentConditionFunc: _makeComponentConditionFunc
};
/**
* isComponent
*
* Checks if element has a component attached to it by
* checking the presence of property difined in milo.config
*
* @param {Element} el DOM element
* @return {Boolean} true, if it has milo component attached to it
*/
function isComponent(el) {
return el.hasOwnProperty(config.componentRef);
}
/**
* getComponent
*
* @param {Element} el DOM element
* @return {Component} component attached to element
*/
function getComponent(el) {
return el && el[config.componentRef];
}
/**
* Returns the closest component which contains the specified element,
* optionally, only component that passes `condition` test or contains specified facet
*
* Unless `returnCurrent` parameter is false, the function will return
* the current component of the element (true by default).
*
* @param {Node} node DOM Element or text Node
* @param {Boolean} returnCurrent optional boolean value indicating whether the component of the element can be returned. True by default, should be false to return only ancestors.
* @param {Function|String} conditionOrFacet optional condition that component should pass (or facet name it should contain)
* @return {Component}
*/
function getContainingComponent(node, returnCurrent, conditionOrFacet) {
// check(node, Node); - can't check tiype here as it is most likely coming from another frame
check(returnCurrent, Match.Optional(Boolean));
check(conditionOrFacet, Match.Optional(Match.OneOf(Function, String)));
var conditionFunc = _makeComponentConditionFunc(conditionOrFacet);
return _getContainingComponent(node, returnCurrent, conditionFunc);
}
function _makeComponentConditionFunc(conditionOrFacet) {
if (typeof conditionOrFacet == 'function')
return conditionOrFacet;
else if (typeof conditionOrFacet == 'string') {
var facetName = _.firstLowerCase(conditionOrFacet);
return function (comp) {
return comp.hasFacet(facetName);
};
}
}
function _getContainingComponent(el, returnCurrent, conditionFunc) {
// Where the current element is a component it should be returned
// if returnCurrent is true or undefined
if (returnCurrent !== false) {
var comp = getComponent(el);
if (comp && (! conditionFunc || conditionFunc(comp)))
return comp;
}
// Where there is no parent element, this function will return undefined
// The parent element is checked recursively
if (el.parentNode)
return _getContainingComponent(el.parentNode, true, conditionFunc);
}
},{"../config":42,"milo-core":84}],35:[function(require,module,exports){
'use strict';
var Component = require('../c_class')
, componentsRegistry = require('../c_registry');
var View = Component.createComponentClass('View', ['container']);
componentsRegistry.add(View);
module.exports = View;
},{"../c_class":15,"../c_registry":33}],36:[function(require,module,exports){
'use strict';
var getElementDataAccess = require('./de_data')
, miloCore = require('milo-core')
, MessengerAPI = miloCore.classes.MessengerAPI
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match;
// class to handle subscribtions to changes in DOM for UI (maybe also content editable) elements
/**
* A class
*/
var DataMsgAPI = _.createSubclass(MessengerAPI, 'DataMsgAPI', true);
_.extendProto(DataMsgAPI, {
// implementing MessageSource interface
init: DataMsgAPI$init,
translateToSourceMessage: translateToSourceMessage,
filterSourceMessage: filterSourceMessage,
createInternalData: createInternalData,
// class specific methods
value: DataMsgAPI$value
});
module.exports = DataMsgAPI;
function DataMsgAPI$init(component) {
MessengerAPI.prototype.init.apply(this, arguments);
this.component = component;
this.elData = getElementDataAccess(component.el);
}
// getDomElementDataValue
function DataMsgAPI$value() { // value method
var componentGetter = this.component.data.config.get;
var newValue = typeof componentGetter == 'function'
? componentGetter.call(this.component)
: this.elData.get(this.component.el);
this.component.data._value = newValue;
return newValue;
}
// TODO: this function should return relevant DOM event dependent on element tag
// Can also implement beforedatachanged event to allow preventing the change
// translateToDomEvent
function translateToSourceMessage(message) {
var componentEvent = this.component.data.config.event;
var event = componentEvent || this.elData.event(this.component.el);
if (message === '' && event)
return event; // this.tagEvent;
}
// filterDataMessage
function filterSourceMessage(sourceMessage, message, data) {
return data.newValue != data.oldValue;
}
function createInternalData(sourceMessage, message, data) {
var oldValue = this.component.data._value
, newValue = this.value();
var internalData = {
path: '',
type: 'changed',
oldValue: oldValue,
newValue: newValue
};
return internalData;
}
},{"./de_data":37,"milo-core":84}],37:[function(require,module,exports){
'use strict';
var _ = require('milo-core').proto;
/**
* Returns data access methods and events for given DOM element.
* Used by [Data](../c_facets/Data.js.html) facet and by [DataMsgAPI](./data.js.html)
*
* @param {Element} el
* @return {Object}
*/
var getElementDataAccess = function(el) {
var tagName = el.tagName.toLowerCase()
, elData = domElementsDataAccess[tagName];
return elData || domElementsDataAccess.byDefault;
};
module.exports = getElementDataAccess;
/**
* Data access methods and events for DOM elements.
*/
var domElementsDataAccess = {
byDefault: {
property: 'innerHTML',
},
'div': {
property: 'innerHTML', // hack, should be innerHTML? to make work with Editable facet
// event: 'input'
},
'span': {
property: 'innerHTML',
event: 'input'
},
'p': {
property: 'innerHTML',
event: 'input'
},
'input': {
property: inputDataProperty,
event: inputChangeEvent
},
'textarea': {
property: 'value',
event: 'input'
},
'select': {
property: 'value',
event: 'change'
},
'img': {
property: 'src'
},
'caption': {
property: 'innerHTML',
event: 'input'
},
'thead': {
property: 'innerHTML',
event: 'input'
},
'tbody': {
property: 'innerHTML',
event: 'input'
},
'tfoot': {
property: 'innerHTML',
event: 'input'
}
};
// convert strings to functions and create getset methods
_.eachKey(domElementsDataAccess, function(tagInfo) {
var property = tagInfo.property
, event = tagInfo.event;
if (typeof property != 'function')
tagInfo.property = function() { return property; };
var propFunc = tagInfo.property;
if (typeof event != 'function')
tagInfo.event = function() { return event; };
if (! tagInfo.get)
tagInfo.get = function(el) { return el[propFunc(el)]; };
if (! tagInfo.set)
tagInfo.set = function(el, value) {
return (el[propFunc(el)] = typeof value == 'undefined' ? '' : value);
};
});
/**
* Types of input elements
*/
var inputElementTypes = {
byDefault: {
property: 'value',
event: 'input'
},
'checkbox': {
property: 'checked',
event: 'change'
},
'radio': {
property: 'checked',
event: 'change'
},
'text': {
property: 'value',
event: 'input'
}
};
/**
* Return property of input element to get/set its data
*
* @param {Element} el
* @return {String}
*/
function inputDataProperty(el) {
var inputType = inputElementTypes[el.type];
return inputType
? inputType.property
: inputElementTypes.byDefault.property;
}
/**
* Returns DOM event type to listen to to react to input element change
*
* @param {Element} el
* @return {String}
*/
function inputChangeEvent(el) {
var inputType = inputElementTypes[el.type];
return inputType
? inputType.event
: inputElementTypes.byDefault.event;
}
},{"milo-core":84}],38:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, MessengerAPI = miloCore.classes.MessengerAPI
, _ = miloCore.proto;
var DropMsgAPI = _.createSubclass(MessengerAPI, 'DropMsgAPI', true);
_.extendProto(DropMsgAPI, {
// implementing MessageSource interface
translateToSourceMessage: translateToSourceMessage,
filterSourceMessage: filterSourceMessage,
});
module.exports = DropMsgAPI;
var dropEventsMap = {
'dragin': 'dragenter',
'dragout': 'dragleave'
};
function translateToSourceMessage(message) {
return dropEventsMap.hasOwnProperty(message)
? dropEventsMap[message]
: message;
}
function resetFilterVars() {
delete this._currentTarget;
delete this._inside;
}
function filterSourceMessage(sourceMessage, message, data) { // data is DOM event object
var ok = true;
if (sourceMessage == 'dragenter' && message == 'dragin') {
this._currentTarget = data.target;
ok = !this._inside;
this._inside = true;
} else if (sourceMessage == 'dragleave' && message == 'dragout') {
ok = this._currentTarget == data.target;
if (ok) resetFilterVars.call(this);
} else if (sourceMessage == 'drop') resetFilterVars.call(this);
return ok;
}
},{"milo-core":84}],39:[function(require,module,exports){
'use strict';
var DOMEmitterSource = require('../../services/dom_source')
, miloCore = require('milo-core')
, MessageSource = miloCore.classes.MessageSource
, Component = require('../c_class')
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match;
var DOMEventsSource = _.createSubclass(DOMEmitterSource, 'DOMEventsSource', true);
_.extendProto(DOMEventsSource, {
init: init,
destroy: DOMEventsSource$destroy,
emitter: emitter
});
module.exports = DOMEventsSource;
var useCapturePattern = /__capture$/
, useCapturePostfix = '__capture';
// init DOM event source
function init(hostObject, proxyMethods, messengerAPIOrClass, component) {
check(component, Component);
this.component = component;
MessageSource.prototype.init.apply(this, arguments);
}
function DOMEventsSource$destroy() {
MessageSource.prototype.destroy.apply(this, arguments);
delete this.component;
}
// get DOM element of component
function emitter() {
return this.component.el;
}
},{"../../services/dom_source":47,"../c_class":15,"milo-core":84}],40:[function(require,module,exports){
'use strict';
// ###component iframe source
var Component = require('../c_class')
, miloCore = require('milo-core')
, MessageSource = miloCore.classes.MessageSource
, _ = miloCore.proto
, check = miloCore.util.check
, logger = miloCore.util.logger
, Match = check.Match;
var FrameMessageSource = _.createSubclass(MessageSource, 'FrameMessageSource', true);
_.extendProto(FrameMessageSource, {
// implementing MessageSource interface
init: init,
addSourceSubscriber: addSourceSubscriber,
removeSourceSubscriber: removeSourceSubscriber,
trigger: trigger,
//class specific methods
frameWindow: frameWindow,
handleEvent: handleEvent // event dispatcher - as defined by Event DOM API
});
module.exports = FrameMessageSource;
function init(hostObject, proxyMethods, messengerAPIOrClass, component) {
check(component, Component);
this.component = component;
if (component.el.tagName.toLowerCase() != 'iframe')
throw new Error('component for FrameMessageSource can only be attached to iframe element');
MessageSource.prototype.init.apply(this, arguments);
}
function frameWindow() {
return this.component.el.contentWindow;
}
// addIFrameMessageListener
function addSourceSubscriber(sourceMessage) {
var win = this.frameWindow();
if (win) win.addEventListener('message', this, false);
else logger.warn('FrameMessageSource: frame window is undefined');
}
// removeIFrameMessageListener
function removeSourceSubscriber(sourceMessage) {
var win = this.frameWindow();
if (win) win.removeEventListener('message', this, false);
else logger.warn('FrameMessageSource: frame window is undefined');
}
function trigger(msgType, data) {
data = data || {};
data.type = msgType;
this.frameWindow().postMessage(data, '*');
}
// TODO maybe refactor to FrameMsgAPI?
function handleEvent(event) {
this.dispatchMessage(event.data.type, event);
}
},{"../c_class":15,"milo-core":84}],41:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, _ = miloCore.proto
, componentName = require('../util/component_name')
, check = miloCore.util.check
, Match = check.Match
, logger = miloCore.util.logger;
/**
* Scope class.
* @param {Element} rootEl the root element of this scope
* @param {Object} hostObject the host
* @return {Scope}
*/
function Scope(rootEl, hostObject) {
_.defineProperties(this, {
_rootEl: rootEl,
_hostObject: hostObject
}, _.WRIT); // writable
}
_.extendProto(Scope, {
_add: Scope$_add,
_safeAdd: Scope$_safeAdd,
_copy: Scope$_copy,
_each: Scope$_each,
_move: Scope$_move,
_merge: Scope$_merge,
_length: Scope$_length,
_any: Scope$_any,
_remove: Scope$_remove,
_clean: Scope$_clean,
_detachElement: Scope$_detachElement,
_has: Scope$_has,
_filter: Scope$_filter
});
_.extend(Scope, {
rename: Scope$$rename
});
module.exports = Scope;
var allowedNamePattern = /^[A-Za-z][A-Za-z0-9\_\$]*$/;
/**
* Scope instance method.
* Adds object to the scope, throwing if name is not unique
* @param {Component|ComponentInfo} object component or component info to add to the scope
* @param {String} name the name of the component to add
*/
function Scope$_add(object, name) {
if (typeof name == 'string')
object.name = name;
else
name = object.name;
if (this.hasOwnProperty(name))
throw new Error('duplicate object name: ' + name);
checkName(name);
__add.call(this, object, name);
}
/**
* Scope instance method
* Adds object to scope renaming it if name is not unique
* @param {Component|ComponentInfo} object component or component info to add to the scope
* @param {String} name the name of the component to add
*/
function Scope$_safeAdd(object, name) {
if (typeof name == 'string')
object.name = name;
else
name = object.name;
var shouldRename = this.hasOwnProperty(name);
if (shouldRename)
logger.error('Scope: duplicate object name: ' + name);
else {
shouldRename = ! allowedNamePattern.test(name);
if (shouldRename)
logger.error('Scope: name should start from letter, this name is not allowed: ' + name);
}
if (shouldRename) {
name = componentName();
object.name = name;
}
__add.call(this, object, name);
}
function __add(object, name) {
this[name] = object;
object.scope = this;
if (typeof object.postMessage === 'function')
object.postMessage('addedtoscope');
}
/**
* Instance method.
* copies all objects from one scope to another,
* throwing if some object is not unique
* @param {Scope} aScope the scope to copy
*/
function Scope$_copy(aScope) {
check(aScope, Scope);
aScope._each(Scope$_add, this);
}
/**
* Instance method.
* Moves a component from this scope to another scope.
* @param {Component} component the component to be moved
* @param {Scope} otherScope the scope to copy the component to
*/
function Scope$_move(component, otherScope) {
otherScope._add(component);
this._remove(component.name);
component.scope = otherScope;
}
/**
* Instance method.
* Merges one scope into this scope
* @param {Scope} scope the scope to absorb
*/
function Scope$_merge(scope) {
scope._each(function (comp) {
this._add(comp, comp.name);
scope._remove(comp.name);
}, this);
}
/**
* Instance method.
* Enumerates each component in the scope
* @param {Function} callback the function to execute for each component
* @param {Object} thisArg the context
*/
function Scope$_each(callback, thisArg) {
_.eachKey(this, callback, thisArg || this, true); // enumerates enumerable properties only
}
/**
* Instance method.
* Returns a filtered list of components based on a callback
* @param {Function} callback the function to execute for each component
* @param {Object} thisArg the context
* @return {Array}
*/
function Scope$_filter(callback, thisArg) {
return _.filterKeys(this, callback, thisArg || this, true);
}
/**
* Checks the validity of a name.
* @param {Function} callback the function to execute for each component
*/
function checkName(name) {
if (! allowedNamePattern.test(name))
throw new Error('name should start from letter, this name is not allowed: ' + name);
}
/**
* Instance method.
* Returns the number of objects in the scope
* @return {Number}
*/
function Scope$_length() {
return Object.keys(this).length;
}
/**
* Instance method.
* Returns a component from the scope. It may look like it returns the first component
* but in reality given that scopes are hashes, there is no such thing.
* @return {Component}
*/
function Scope$_any() {
var key = Object.keys(this)[0];
return key && this[key];
}
/**
* Instance method.
* Removes a component from the scope by it's name.
* @param {String} name the name of the component to remove
* @param {Boolean} quiet optional true to suppress the warning message if the component is not in scope
*/
function Scope$_remove(name, quiet) {
if (! (name in this)) {
if (!quiet) logger.warn('removing object that is not in scope');
return;
}
var object = this[name];
delete this[name];
if (typeof object.postMessage === 'function')
object.postMessage('removedfromscope');
}
/**
* Instance method.
* Removes all components from the scope.
*/
function Scope$_clean() {
this._each(function(object, name) {
delete this[name].scope;
delete this[name];
}, this);
}
function Scope$_detachElement() {
this._rootEl = null;
}
/**
* Checks if scope has object by object name
* @param {Object} object
* @return {Boolean}
*/
function Scope$_has(object) {
return this.hasOwnProperty(object.name);
}
/**
* Change object name, renaming it in scope unless renameInScope is false
* @param {Object} obj
* @param {String} name new name
* @param {Boolean} renameInScope true by default
*/
function Scope$$rename(obj, name, renameInScope) {
if (obj.scope && renameInScope !== false) {
obj.scope._remove(obj.name);
obj.scope._add(obj, name);
} else
obj.name = name;
}
},{"../util/component_name":53,"milo-core":84}],42:[function(require,module,exports){
'use strict';
// <a name="config"></a>
// milo.config
// -----------
// It is the function that allows to change milo configurations and also
// access them on config's properties.
// ```javascript
// milo.config({
// attrs: {
// bind: 'ml-bind',
// load: 'ml-load'
// }
// });
// ```
var miloCore = require('milo-core')
, _ = miloCore.proto
, doT = miloCore.util.doT;
var config = module.exports = miloCore.config;
config({
attrs: {
bind: 'ml-bind',
load: 'ml-load'
},
componentRef: '___milo_component',
componentPrefix: 'milo_',
template: {
compile: doT.compile
},
domStorage: {
typeSuffix: ':___milo_data_type',
prefixSeparator: '/',
root: '',
messageKey: '___milo_message/',
messageTimestamp: '___milo_timestamp',
quotaExceeded: {
throwError: true,
message: false
}
},
dragDrop: {
dataTypes: {
component: 'x-application/milo/component',
componentMetaTemplate: 'x-application/milo/component-meta/%class/%name/%params',
componentMetaRegex: /^x\-application\/milo\/component\-meta\/([a-z0-9]+)\/([a-z0-9]+)\/([a-z0-9]*)$/,
}
},
request: {
jsonpTimeout: 60000,
jsonpCallbackPrefix: '___milo_callback_',
optionsKey: '___milo_options',
completedKey: '___milo_completed',
defaults: {
timeout: 60000
}
},
websocket: {
rpc: {
timeout: 15000,
responsePrefix: 'response_'
}
},
deprecationWarning: 'once'
});
},{"milo-core":84}],43:[function(require,module,exports){
'use strict';
var miloMail = require('./services/mail')
, request = require('./util/request')
, miloCore = require('milo-core')
, logger = miloCore.util.logger
, _ = miloCore.proto
, utilDom = require('./util/dom')
, config = require('./config')
, LoadAttribute = require('./attributes/a_load');
module.exports = loader;
/**
* `milo.loader`
*
* Recursively scans the document tree inside `rootEl` (document.body by default) looking for __ml-load__ @attribute.
* One level load is executed. No additional loader get called on inside __ml-load__ attributes.
*
* Possible usages:
* - milo.loader([myRootEl,][myRemoveAttribute,]myCallback)
*
* @param {Element} rootEl Root element inside which DOM will be scanned (document.body by default).
* @param {Boolean} removeAttribute If set to true, then the __ml-load__ attribute will be removed once loader has been executed (False by default).
* @param {Function} callback Callback to call after all elements get loaded (Required).
*/
function loader(rootEl, removeAttribute, callback) {
milo(function() {
_loader(rootEl, removeAttribute, callback);
});
}
function _loader(rootEl, removeAttribute, callback) {
if (typeof rootEl == 'function') {
callback = rootEl;
rootEl = undefined;
removeAttribute = false;
}
if (typeof removeAttribute == 'function') {
callback = removeAttribute;
removeAttribute = false;
}
rootEl = rootEl || document.body;
miloMail.postMessage('loader', { state: 'started' });
_loadViewsInElement(rootEl, removeAttribute, function(views) {
miloMail.postMessage('loader', {
state: 'finished',
views: views
});
callback(views);
});
}
function _loadViewsInElement(rootEl, removeAttribute, callback) {
var loadElements = rootEl.getAttribute(config.attrs.load)
? [rootEl]
: rootEl.querySelectorAll('[' + config.attrs.load + ']');
var views = {}
, totalCount = loadElements.length
, loadedCount = 0;
_.forEach(loadElements, function (el) {
loadView(el, removeAttribute, function(err) {
views[el.id] = err || el;
loadedCount++;
if (loadedCount == totalCount)
callback(views);
});
});
}
function loadView(el, removeAttribute, callback) {
if (utilDom.children(el).length)
throw new Error('can\'t load html into element that is not empty');
var attr = new LoadAttribute(el);
attr.parse().validate();
request.get(attr.loadUrl, function(err, html) {
if (err) {
err.message = err.message || 'can\'t load file ' + attr.loadUrl;
// logger.error(err.message);
callback(err);
return;
}
el.innerHTML = html;
if (removeAttribute) LoadAttribute.remove(el);
callback(null);
});
}
},{"./attributes/a_load":6,"./config":42,"./services/mail":48,"./util/dom":57,"./util/request":65,"milo-core":84}],44:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, _ = miloCore.proto;
// register included facets
require('./use_facets');
require('./components/classes/View');
/**
* `milo`
*
* A minimalist browser framework that binds DOM elements to JS components and components to models.
*
* `milo` is available as global object in the browser.
* At the moment it is not possiible to require it with browserify to have it bundled with the app because of the way [brfs](https://github.com/substack/brfs) browserify plugin is implemented.
* It is possible though to require `milo` with node to use universal parts of the framework (abstract classes, Messenger, Model, etc.):
* ```
* var milo = require('milojs');
* ```
*
* `milo` itself is a function that in the browser can be used to delay execution until DOM is ready.
*/
function milo(func) {
milo.util.domReady(func);
}
/**
* ####Milo packages####
*
* - [loader](./loader.js.html) - loading subviews into page
* - [binder](./binder.js.html) - components instantiation and binding of DOM elements to them
* - [minder](./minder.js.html) - data reactivity, one or two way, shallow or deep, as you like it
* - [mail](./mail/index.js.html) - applicaiton level messenger, also connects to messages from other windows dispatched with `window.postMessage`.
* - [config](./config.js.html) - milo configuration
* - [util](./util/index.js.html) - logger, request, dom, check, error, etc.
* - [classes](./classes.js.html) - abstract and base classes
* - [attributes](./attributes/index.js.html) - classes that wrap DOM elements attributes recognized by milo
* - [ComponentFacet](./components/c_facet.js.html) - base class of Component facet
* - [Component](./components/c_class.js.html) - base Component class
* - [Messenger](./messenger/index.js.html) - generic Messenger used in most other milo classes, can be mixed into app classes too.
* - [Model](./model/index.js.html) - Model class that emits messages on changes to any depth without timer based watching
* - [registry](./registry.js.html) - registries of fasets and components classes
*/
_.extend(milo, {
Messenger: miloCore.Messenger,
Model: miloCore.Model,
minder: miloCore.minder,
loader: require('./loader'),
binder: require('./binder'),
mail: require('./services/mail'),
window: require('./services/window'),
config: require('./config'),
util: require('./util'),
classes: require('./classes'),
attributes: require('./attributes'),
ComponentFacet: require('./components/c_facet'),
Component: require('./components/c_class'),
Command: require('./command'),
registry: require('./registry'),
milo_version: require('../package.json').version,
createComponentClass: require('./util/create_component_class'),
createFacetClass: require('./util/create_facet_class'),
destroy: destroy
});
// export for node/browserify
if (typeof module == 'object' && module.exports)
module.exports = milo;
// global milo for browser
if (typeof window == 'object') {
window.milo = milo;
milo.mail.trigger('miloready');
}
function destroy() {
miloCore.destroy();
milo.mail.destroy();
milo.window.destroy();
milo.util.destroy();
}
},{"../package.json":118,"./attributes":7,"./binder":8,"./classes":9,"./command":12,"./components/c_class":15,"./components/c_facet":16,"./components/classes/View":35,"./config":42,"./loader":43,"./registry":45,"./services/mail":48,"./services/window":51,"./use_facets":52,"./util":63,"./util/create_component_class":54,"./util/create_facet_class":55,"milo-core":84}],45:[function(require,module,exports){
'use strict';
/**
* Registries of facets and of components
*
* - [facets](./components/c_facets/cf_registry.js.html)
* - [components](./components/c_registry.js.html)
*/
var registry = module.exports = {
facets: require('./components/c_facets/cf_registry'),
components: require('./components/c_registry'),
commands: require('./command/cmd_registry')
};
},{"./command/cmd_registry":11,"./components/c_facets/cf_registry":31,"./components/c_registry":33}],46:[function(require,module,exports){
'use strict';
// <a name="components-dom-constructors"></a>
// ###dom events constructors
var _ = require('milo-core').proto;
// https://developer.mozilla.org/en-US/docs/Web/Reference/Events
var eventTypes = {
ClipboardEvent: ['copy', 'cut', 'paste', 'beforecopy', 'beforecut', 'beforepaste'],
Event: ['input', 'readystatechange'],
FocusEvent: ['focus', 'blur', 'focusin', 'focusout'],
KeyboardEvent: ['keydown', 'keypress', 'keyup'],
MouseEvent: ['click', 'contextmenu', 'dblclick', 'mousedown', 'mouseup',
'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover',
'show' /* context menu */],
TouchEvent: ['touchstart', 'touchend', 'touchmove', 'touchenter', 'touchleave', 'touchcancel'],
};
// mock window and event constructors for testing
if (typeof window != 'undefined')
var global = window;
else {
global = {};
_.eachKey(eventTypes, function(eTypes, eventConstructorName) {
var eventConstructor = _.makeFunction(eventConstructorName, 'type', 'properties',
'this.type = type; _.extend(this, properties);');
global[eventConstructorName] = eventConstructor;
});
}
var domEventsConstructors = {};
_.eachKey(eventTypes, function(eTypes, eventConstructorName) {
eTypes.forEach(function(type) {
if (Object.hasOwnProperty(domEventsConstructors, type))
throw new Error('duplicate event type ' + type);
domEventsConstructors[type] = global[eventConstructorName];
});
});
module.exports = domEventsConstructors;
},{"milo-core":84}],47:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, MessageSource = miloCore.classes.MessageSource
, Component = require('../components/c_class')
, domEventsConstructors = require('./de_constrs') // TODO merge with DOMEventSource ??
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match;
var DOMEmitterSource = _.createSubclass(MessageSource, 'DOMEmitterSource', true);
_.extendProto(DOMEmitterSource, {
// implementing MessageSource interface
init: init,
destroy: DOMEmitterSource$destroy,
addSourceSubscriber: _.partial(sourceSubscriberMethod, 'addEventListener'),
removeSourceSubscriber: _.partial(sourceSubscriberMethod, 'removeEventListener'),
postMessage: DOMEmitterSource$postMessage,
trigger: trigger,
// class specific methods
emitter: emitter,
handleEvent: handleEvent, // event dispatcher - as defined by Event DOM API
});
module.exports = DOMEmitterSource;
var useCapturePattern = /__capture$/
, useCapturePostfix = '__capture';
// init DOM event source
function init(hostObject, proxyMethods, messengerAPIOrClass, eventEmitter) {
this.eventEmitter = eventEmitter;
MessageSource.prototype.init.apply(this, arguments);
}
function DOMEmitterSource$destroy() {
MessageSource.prototype.destroy.apply(this, arguments);
delete this.eventEmitter;
}
// get DOM element of component
function emitter() {
return this.eventEmitter;
}
function sourceSubscriberMethod(method, eventType) {
if (! (eventType && typeof eventType == 'string')) return;
var capture = useCapturePattern.test(eventType);
if (capture) eventType = eventType.replace(useCapturePattern, '');
this.emitter()[method](eventType, this, capture);
}
// event dispatcher - as defined by Event DOM API
function handleEvent(event) {
var isCapturePhase;
if (typeof window != 'undefined')
isCapturePhase = event.eventPhase == window.Event.CAPTURING_PHASE;
var msg = event.type + (isCapturePhase ? useCapturePostfix : '');
this.dispatchMessage(msg, event);
}
function DOMEmitterSource$postMessage(message, data) {
this.messenger.postMessageSync(message, data);
}
function trigger(eventType, properties) {
check(eventType, String);
check(properties, Match.Optional(Object));
eventType = eventType.replace(useCapturePattern, '');
var EventConstructor = domEventsConstructors[eventType];
if (typeof EventConstructor != 'function')
throw new Error('unsupported event type');
// check if it is correct
if (typeof properties != 'undefined')
properties.type = eventType;
var domEvent = new EventConstructor(eventType, properties);
var notCancelled = this.emitter().dispatchEvent(domEvent);
return notCancelled;
}
},{"../components/c_class":15,"./de_constrs":46,"milo-core":84}],48:[function(require,module,exports){
'use strict';
/**
* `milo.mail`
* It is an application level messenger that is an instance of Messenger class.
*
* At the moment, in addition to application messages that you define, you can subscribe to __domready__ message that is guaranteed to fire once,
* even if DOM was ready at the time of the subscription.
*
* Messaging between frames is available via milo.mail. See [Frame facet](../components/c_facets/Frame.js.html).
*
* See [Messenger](../messenger/index.js.html).
*
**/
var miloCore = require('milo-core')
, Messenger = miloCore.Messenger
, MailMsgAPI = require('./mail_api')
, MailMessageSource = require('./mail_source')
, _ = miloCore.proto;
var miloMail = new Messenger;
var mailMsgSource = new MailMessageSource(miloMail, { trigger: 'trigger' }, new MailMsgAPI);
miloMail._setMessageSource(mailMsgSource);
module.exports = miloMail;
},{"./mail_api":49,"./mail_source":50,"milo-core":84}],49:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, MessengerAPI = miloCore.classes.MessengerAPI
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match;
var MailMsgAPI = _.createSubclass(MessengerAPI, 'MailMsgAPI', true);
_.extendProto(MailMsgAPI, {
translateToSourceMessage: translateToSourceMessage,
filterSourceMessage: filterSourceMessage
});
module.exports = MailMsgAPI;
// TODO: this function should return relevant DOM event dependent on element tag
// Can also implement beforedatachanged event to allow preventing the change
// translateToDomEvent
var windowMessageRegExp = /^message\:/
, windowMessagePrefix = 'message:';
function translateToSourceMessage(message) {
if (message == 'domready')
return 'readystatechange';
else if (windowMessageRegExp.test(message))
return 'message';
}
// filterDataMessage
function filterSourceMessage(sourceMessage, msgType, msgData) {
if (sourceMessage == 'readystatechange') {
//return document.readyState == 'interactive';
// return false;
// _.defineProperty(this, '_domReadyFired', true, _.WRIT);
return true;
} else if (sourceMessage == 'message')
return windowMessagePrefix + msgData.data.type == msgType;
}
},{"milo-core":84}],50:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, MessageSource = miloCore.classes.MessageSource
, domEventsConstructors = require('../de_constrs')
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match;
var MailMessageSource = _.createSubclass(MessageSource, 'MailMessageSource', true);
_.extendProto(MailMessageSource, {
// implementing MessageSource interface
addSourceSubscriber: addSourceSubscriber,
removeSourceSubscriber: removeSourceSubscriber,
trigger: trigger,
// class specific methods
_windowSubscriberMethod: _windowSubscriberMethod,
handleEvent: handleEvent, // event dispatcher - as defined by Event DOM API
});
module.exports = MailMessageSource;
function addSourceSubscriber(sourceMessage) {
if (isReadyStateChange(sourceMessage)) {
if (document.readyState == 'loading')
document.addEventListener('readystatechange', this, false);
else {
var EventConstructor = domEventsConstructors.readystatechange;
var domEvent = new EventConstructor('readystatechange', { target: document });
this.dispatchMessage('readystatechange', domEvent);
}
} else
this._windowSubscriberMethod('addEventListener', sourceMessage);
}
function removeSourceSubscriber(sourceMessage) {
if (isReadyStateChange(sourceMessage))
document.removeEventListener('readystatechange', this, false);
else
this._windowSubscriberMethod('removeEventListener', sourceMessage);
}
function isReadyStateChange(sourceMessage) {
return sourceMessage == 'readystatechange' && typeof document == 'object';
}
function isWindowMessage(sourceMessage) {
return sourceMessage == 'message' && typeof window == 'object';
}
function _windowSubscriberMethod(method, sourceMessage) {
if (isWindowMessage(sourceMessage))
window[method]('message', this, false);
}
// event dispatcher - as defined by Event DOM API
function handleEvent(event) {
this.dispatchMessage(event.type, event);
}
function trigger(msgType, data) {
data = data || {};
data.type = 'message:' + msgType;
if (typeof window == 'object')
window.postMessage(data, '*');
}
},{"../de_constrs":46,"milo-core":84}],51:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, Messenger = miloCore.Messenger
, DOMEmitterSource = require('./dom_source')
, _ = miloCore.proto;
var windowService = new Messenger;
var domEmitterSource = new DOMEmitterSource(windowService, { trigger: 'trigger' }, undefined, window);
windowService._setMessageSource(domEmitterSource);
module.exports = windowService;
_.extend(windowService, {
isTop: windowService_isTop
});
function windowService_isTop() {
return window.top == window.self || window.__karma__;
}
},{"./dom_source":47,"milo-core":84}],52:[function(require,module,exports){
'use strict';
require('./components/c_facets/Css');
require('./components/c_facets/Dom');
require('./components/c_facets/Data');
require('./components/c_facets/Frame');
require('./components/c_facets/Events');
require('./components/c_facets/Options');
require('./components/c_facets/Template');
require('./components/c_facets/Container');
require('./components/c_facets/ModelFacet');
require('./components/c_facets/Drag');
require('./components/c_facets/Drop');
require('./components/c_facets/List');
require('./components/c_facets/Item');
require('./components/c_facets/Transfer');
},{"./components/c_facets/Container":17,"./components/c_facets/Css":18,"./components/c_facets/Data":19,"./components/c_facets/Dom":20,"./components/c_facets/Drag":21,"./components/c_facets/Drop":22,"./components/c_facets/Events":23,"./components/c_facets/Frame":24,"./components/c_facets/Item":25,"./components/c_facets/List":26,"./components/c_facets/ModelFacet":27,"./components/c_facets/Options":28,"./components/c_facets/Template":29,"./components/c_facets/Transfer":30}],53:[function(require,module,exports){
'use strict';
var uniqueId = require('./unique_id')
, config = require('../config')
, prefix = config.componentPrefix;
module.exports = componentName;
function componentName() {
return prefix + uniqueId();
}
},{"../config":42,"./unique_id":70}],54:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match
, componentRegistry = require('../components/c_registry');
module.exports = createComponentClass;
/**
* Utility function which creates and registers new milo component. The component created will have
* a reference to the super class used in its creation (Accessible using <ComponentClass>.super).
*
* @param {string} config.className - The name of the new component
* @param {string} ['Component'] config.superClassName - The name of an existing component to be used as the new component's super class
* @param {object=} config.facets - Facet configuration (Hash of facet name {string} to config {object})
* @param {object=} config.methods - Methods of the new component (Hash of function name {string} to function {function})
* @param {object=} config.staticMethods - Static methods of the new component (Hash of function name {string} to function {function})
*/
function createComponentClass(config) {
check(config, {
superClassName: Match.Optional(String),
className: String,
facets: Match.Optional(Object),
methods: Match.Optional(Match.ObjectHash(Function)),
staticMethods: Match.Optional(Match.ObjectHash(Function)),
});
var SuperClass = componentRegistry.get(config.superClassName || 'Component');
var ComponentClass = SuperClass.createComponentClass(config.className, config.facets);
if (config.methods) _.extendProto(ComponentClass, config.methods);
if (config.staticMethods) {
if (config.staticMethods.super !== undefined) throw '\'super\' is a reserved keyword';
_.extend(ComponentClass, config.staticMethods);
}
ComponentClass.super = SuperClass.prototype;
componentRegistry.add(ComponentClass);
return ComponentClass;
}
},{"../components/c_registry":33,"milo-core":84}],55:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match
, FacetBaseClass = require('../components/c_facet')
, facetRegistry = require('../components/c_facets/cf_registry');
module.exports = createFacetClass;
function createFacetClass(config) {
check(config, {
className: String,
superClassName: Match.Optional(String),
require: Match.Optional(Array),
methods: Match.Optional(Match.ObjectHash(Function)),
configSchema: Match.Optional(Object)
});
var SuperClass = config.superClassName ? facetRegistry.get(config.superClassName) : FacetBaseClass;
var FacetClass = _.createSubclass(SuperClass, config.className);
if (config.methods) _.extendProto(FacetClass, config.methods);
if (config.require) _.extendProto(FacetClass, { require: config.require });
if (config.configSchema) _.extendProto(FacetClass, { configSchema: config.configSchema });
FacetClass.super = SuperClass.prototype;
facetRegistry.add(FacetClass);
return FacetClass;
}
},{"../components/c_facet":16,"../components/c_facets/cf_registry":31,"milo-core":84}],56:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, _ = miloCore.proto
, logger = miloCore.util.logger
, config = require('../config');
module.exports = function deprecate(fn, message) {
var warned;
switch (typeof fn) {
case 'object':
return _.mapKeys(fn, function(f) { return deprecate(f, message); });
case 'function':
for (var prop in fn)
deprecated[prop] = deprecate(fn[prop], message);
return deprecated;
default:
return fn;
}
function deprecated() {
if (config.deprecationWarning
&& (!warned || config.deprecationWarning == 'always')) {
logger.error(message || 'Function ' + fn.name + ' is DEPRECATED');
warned = true;
}
return fn.apply(this, arguments);
}
};
},{"../config":42,"milo-core":84}],57:[function(require,module,exports){
'use strict';
var config = require('../config')
, miloCore = require('milo-core')
, _ = miloCore.proto
, logger = miloCore.util.logger;
var domUtils = {
children: children,
filterNodeListByType: filterNodeListByType,
containingElement: containingElement,
selectElementContents: selectElementContents,
selectElementText: selectElementText,
getElementOffset: getElementOffset,
setCaretPosition: setCaretPosition,
getSelectionDirection: getSelectionDirection,
setSelection: setSelection,
clearSelection: clearSelection,
removeElement: removeElement,
unwrapElement: unwrapElement,
wrapInElement: wrapInElement,
detachComponent: detachComponent,
firstTextNode: firstTextNode,
lastTextNode: lastTextNode,
trimNodeRight: trimNodeRight,
trimNodeLeft: trimNodeLeft,
stripHtml: stripHtml,
htmlEntities: htmlEntities,
walkTree: walkTree,
createTreeWalker: createTreeWalker,
treePathOf: treePathOf,
getNodeAtTreePath: getNodeAtTreePath,
insertAtTreePath: insertAtTreePath,
isTreePathBefore: isTreePathBefore,
getNodeWindow: getNodeWindow,
getComponentsFromRange: getComponentsFromRange,
deleteRangeWithComponents: deleteRangeWithComponents,
forEachNodesInRange: forEachNodesInRange,
areRangesEqual: areRangesEqual,
xpathSelector: xpathSelector,
xpathSelectorAll: xpathSelectorAll,
addDebugPoint: addDebugPoint
};
module.exports = domUtils;
/**
* Returns the list of element children of DOM element
*
* @param {Element} el element to return the children of (only DOM elements)
* @return {Array<Element>}
*/
function children(el) {
return filterNodeListByType(el.childNodes, Node.ELEMENT_NODE);
}
/**
* Filters the list of nodes by type
*
* @param {NodeList} nodeList the list of nodes, for example childNodes property of DOM element
* @param {Integer} nodeType an integer constant [defined by DOM API](https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeType), e.g. `Node.ELEMENT_NODE` or `Node.TEXT_NODE`
* @return {Array<Node>}
*/
function filterNodeListByType(nodeList, nodeType) {
return _.filter(nodeList, function (node) {
return node.nodeType == nodeType;
});
}
/**
* Find nearest parent element for node.
* If node is an element, it will be returned.
*
* @param {Node} node
* @return {Element|null}
*/
function containingElement(node) {
while (node) {
if (node.nodeType == Node.ELEMENT_NODE)
return node;
node = node.parentNode;
}
return null;
}
/**
* Selects inner contents of DOM element
*
* @param {Element} el DOM element
*/
function selectElementContents(el) {
var doc = el.ownerDocument;
if (! doc) return logger.error('selectElementContents: element has no document');
var range = doc.createRange();
range.selectNodeContents(el);
var win = getNodeWindow(el)
, sel = win.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
/**
* Selects text inside element
* @param {Element} el
*/
function selectElementText(el) {
var fromNode = firstTextNode(el)
, toNode = lastTextNode(el);
if (fromNode && toNode)
setSelection(fromNode, 0, toNode, toNode.textContent.length);
}
/**
* Sets the caret position to the position in the node
*
* @param {Node} node DOM node
* @param {Number} pos caret position
*/
function setCaretPosition(node, pos) {
var doc = node.ownerDocument;
if (! doc) return logger.error('setCaretPosition: element has no document');
var range = doc.createRange();
range.setStart(node, pos);
var win = getNodeWindow(node)
, sel = win.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
/**
* get the direction of a selection
*
* 1 forward, -1 backward, 0 no direction, undefined one of the node is detached or in a different frame
*
* @param {sel} a selection object
* @return {Integer} can be -1, 0, 1 or undefined
*/
function getSelectionDirection(sel){
return _getDirection(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset);
}
function _getDirection(fromNode, startOffset, toNode, endOffset){
var docPosition = fromNode.compareDocumentPosition(toNode);
if (docPosition & Node.DOCUMENT_POSITION_FOLLOWING){
return 1;
}
else if (docPosition & Node.DOCUMENT_POSITION_PRECEDING){
return -1;
}
else if (fromNode == toNode){
if (startOffset < endOffset){
return 1;
}
else if (startOffset > endOffset){
return -1;
}
else {
return 0;
}
}
}
/**
* Selects a range in a document
*
* @param {Node} fromNode DOM node to start selection in
* @param {Number} startOffset
* @param {Node} toNode DOM node to end selection in
* @param {Number} endOffset
*/
function setSelection(fromNode, startOffset, toNode, endOffset) {
var doc = fromNode.ownerDocument;
if (! doc) return logger('setCaretPosition: element has no document');
var backward = _getDirection(fromNode, startOffset, toNode, endOffset) == -1;
var range = doc.createRange();
var container, originalContentEditable;
// does not work in non contentEditable items
var win = getNodeWindow(fromNode)
, sel = win.getSelection();
if (backward){
range.setStart(toNode, endOffset);
range.setEnd(fromNode, startOffset);
range.collapse(false);
}
else {
range.setStart(fromNode, startOffset);
range.setEnd(toNode, endOffset);
}
container = range.commonAncestorContainer == Node.ELEMENT_NODE ?
range.commonAncestorContainer :
range.commonAncestorContainer.parentElement;
if (!container.isContentEditable){
originalContentEditable = container.contentEditable; // false or inherit
container.contentEditable = "true";
}
sel.removeAllRanges();
sel.addRange(range);
if (backward){
sel.extend(toNode, endOffset);
}
if (originalContentEditable){
// restoring contentEditable
container.contentEditable = originalContentEditable;
}
}
/**
* Clears selection in a given window
* @param {Window} win
*/
function clearSelection(win) {
win = win || window;
var sel = win.getSelection();
sel.removeAllRanges();
}
/**
* Calculates an element's total top and left offset from the document edge.
*
* @param {Element} el the element for which position needs to be returned
* @param {includeBorder} if is to include the border width
* @return {Object} vector object with properties topOffset and leftOffset
*/
function getElementOffset(el, includeBorder) {
var yPos, xPos;
yPos = el.offsetTop;
xPos = el.offsetLeft;
el = el.offsetParent;
while (el) {
yPos += el.offsetTop + getBorder(el, 'Height', includeBorder);
xPos += el.offsetLeft + getBorder(el, 'Width', includeBorder);
el = el.offsetParent;
}
return { topOffset: yPos, leftOffset: xPos };
}
function getBorder(el, type, includeBorder) {
if (includeBorder) {
var side = (type == 'Height') ? 'top' : 'left',
styles = window.getComputedStyle(el),
sideValue = parseInt(styles.getPropertyValue('border-' + side + '-width'), 10);
if (sideValue) return sideValue;
}
return 0;
}
/**
* Removes element from the document
*
* @param {Element} el the element to be removed
*/
function removeElement(el) {
var parent = el.parentNode;
if (parent){
parent.removeChild(el);
parent.normalize();
}
}
/**
* Returns the first child text node of an element
*
* @param {Element|Node} node the node to be searched, if the node is text node we return the node.
* @return {TextNode}
*/
function firstTextNode(node) {
if (node.nodeType == Node.TEXT_NODE) return node;
var treeWalker = createTreeWalker(node, NodeFilter.SHOW_TEXT);
return treeWalker.firstChild();
}
/**
* Returns the last child text node of an element
*
* @param {Element|Node} node the node to be searched, if the node is text node we return the node.
* @return {TextNode}
*/
function lastTextNode(node) {
if (node.nodeType == Node.TEXT_NODE) return node;
var treeWalker = createTreeWalker(node, NodeFilter.SHOW_TEXT);
return treeWalker.lastChild();
}
/**
* Removes element from the document putting its children in its place
*
* @param {Element} el the element to be "unwrapped"
*/
function unwrapElement(el) {
var parent = el.parentNode;
if (parent) {
var frag = document.createDocumentFragment();
// must be copied to avoid iterating a mutating list of childNodes
var children = _.slice(el.childNodes);
children.forEach(frag.appendChild, frag);
parent.replaceChild(frag, el);
parent.normalize();
}
}
/**
* Wraps an element in another element
*
* @param {Element} wrapIntoEl
* @param {Element} el
*/
function wrapInElement(wrapIntoEl, el) {
var parent = el.parentNode;
if (parent) {
parent.insertBefore(wrapIntoEl, el);
wrapIntoEl.appendChild(el);
}
}
/**
* Trims a text node of trailing spaces, and returns true if a trim was performed.
*
* @param {TextNode} node
* @return {Boolean}
*/
function trimNodeRight(node) {
return _trimNode(node, 'trimRight');
}
/**
* Trims a text node of leading spaces, and returns true if a trim was performed.
*
* @param {TextNode} node
* @return {Boolean}
*/
function trimNodeLeft(node) {
return _trimNode(node, 'trimLeft');
}
function _trimNode(node, methodName) {
var len = node.length;
node.textContent = node.textContent[methodName]();
return len !== node.length;
}
/**
* Removes the reference to component from element
*
* @param {Element} el
*/
function detachComponent(el) {
delete el[config.componentRef];
}
/**
* Retrieves the content of a html string
* @param {String} str Any string
* @return {String} returns the string cleaned of any html content.
*/
function stripHtml(str) {
var div = document.createElement('DIV');
div.innerHTML = str;
return div.textContent || '';
}
/**
* Convenience wrapper for native TreeWalker that automatically walks the tree and calls an iterator function.
* This will not iterate the root element.
* @param {HTMLElement} root The containing root element to be walked. Will not be iterated.
* @param {NodeFiler} filter A NodeFilter constant, see https://developer.mozilla.org/en/docs/Web/API/TreeWalker
* @param {Function} iterator A function to be called on each node. Returning 'false' will break.
* @param {Object} context An optional context to passed, defaults to root.
*/
function walkTree(root, filter, iterator, context) {
var tw = document.createTreeWalker(root, filter);
while(tw.nextNode()) {
var result = iterator.call(context || root, tw.currentNode);
if (result === false) break;
}
}
/**
* Returns array of child indexes of element path inside root element in DOM tree using breadth first tree traversal.
* Returns undefined if the element is not inside root element, 0 if the root element itself is passed.
*
* @param {Element} rootEl element to search
* @param {Element} el element to find the index of
* @return {Array<Number>}
*/
function treePathOf(rootEl, el) {
if (! (rootEl && rootEl.contains(el))) return;
var treePath = []
, node = rootEl;
while (node != el) {
var nodeIndex = _.findIndex(node.childNodes, containsEl);
treePath.push(nodeIndex);
node = node.childNodes[nodeIndex];
}
return treePath;
function containsEl(child) {
return child.contains(el);
}
}
/**
* Returns element at given tree path
*
* @param {Element} rootEl
* @param {Array<Number>} treePath
* @param {Boolean} nearest return nearest possible node if exact node does not exist
* @return {Node}
*/
function getNodeAtTreePath(rootEl, treePath, nearest) {
if (!treePath) return;
var len = treePath.length;
if (len === 0) return rootEl;
var node = rootEl;
for (var i = 0; i < len; i++) {
var children = node.childNodes;
if (! children) {
if (! nearest) node = undefined;
break;
}
var childIndex = treePath[i]
, child = children[childIndex];
if (! child) {
node = nearest
? children[children.length - 1]
: undefined;
break;
}
node = child;
}
return node;
}
/**
* Inserts an element inside root at a given path in tree (that has the same meaning as the index returned by `treePathOf` function). If element is already in the root's tree, it will be removed first and then moved to the passed treeIndex
* Insertion at index 0 is not possible and will return undefined as it would mean replacing the root element.
*
* @param {Element} rootEl element into which to insert
* @param {Number} treeIndex index in DOM tree inside root element (see treePathOf)
* @param {Element} el element to be inserted
* @return {Boolean} true if was successfully inserted
*/
function insertAtTreePath(rootEl, treePath, el, nearest) {
var toNormalize = el.nodeType == Node.TEXT_NODE;
if (rootEl.contains(el))
removeElement(el); // can't use removeChild as rootEl here is not an immediate parent
if (treePath.length === 0) return;
var parent = getNodeAtTreePath(rootEl, treePath.slice(0, -1), nearest)
, children = parent.childNodes;
if (! children) {
if (nearest) {
parent = parent.parentNode;
children = parent.childNodes;
} else return;
}
var childIndex = treePath[treePath.length - 1]
, child = children[childIndex];
if (child) {
parent.insertBefore(el, child);
if (toNormalize) parent.normalize();
return true;
} else if (children.length === 0 && (childIndex === 0 || nearest)) {
parent.appendChild(el);
if (toNormalize) parent.normalize();
return true;
} else {
child = children[childIndex - 1];
if (child || nearest) {
parent.appendChild(el);
if (toNormalize) parent.normalize();
return true;
}
}
}
/**
* Returns `true` if the first tree path points to a node which is before the other in the document order.
* @param {Array} path1 A treepath array
* @param {Array} path2 A treepath array
* @return {Boolean}
*/
function isTreePathBefore(path1, path2) {
var i = 0
, isBefore;
if (!Array.isArray(path1) && Array.isArray(path2))
return logger.error('isTreePathBefore: One or both paths are not valid treepath arrays.');
for (i; i < path1.length; i++) {
if (path1[i] < path2[i]) {
isBefore = true;
break;
} else if (path1[i] > path2[i]) {
isBefore = false;
break;
}
}
if (typeof isBefore == 'undefined')
if (path1.length < path2.length)
logger.warn('isTreePathBefore: One node is inside another');
return isBefore || false;
}
/**
* Converts non latin characters to HTML entity codes.
* @param {String} str the string to convert
* @return {String} the string with html entities
*/
function htmlEntities(str) {
return str.replace(/[\u00A0-\u99999<>\&]/gim, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
}
function createTreeWalker(el, whatToShow) {
whatToShow = whatToShow || (NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
return document.createTreeWalker(el, whatToShow);
}
/**
* Returns the reference to the window the node is in
*
* @param {Node} node
* @return {Window}
*/
function getNodeWindow(node) {
var doc = node.ownerDocument;
return doc && (doc.defaultView || doc.parentWindow);
}
/**
* do something for each nodes contained in a range
*
* @param {range} a range
* @param {cb} a function taking a node as argument
*/
function forEachNodesInRange(range, cb){
var rangeContainer = range.commonAncestorContainer
, doc = rangeContainer.ownerDocument;
function isNodeInsideRange(node){
var nodeRange = document.createRange();
var isInside = false;
nodeRange.selectNode(node);
if (nodeRange.compareBoundaryPoints(window.Range.START_TO_START, range) != -1
&& nodeRange.compareBoundaryPoints(window.Range.END_TO_END, range) != 1){
isInside = true;
}
return isInside;
}
var treeWalker = doc.createTreeWalker(rangeContainer,
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT);
var currentNode;
while (currentNode = treeWalker.nextNode()){ // should be assignment
if (isNodeInsideRange(currentNode)){
cb(currentNode);
}
}
}
/**
* get all components contained in a range
*
* @param {range} a DOM range.
*/
function getComponentsFromRange(range) {
var win = getNodeWindow(range.startContainer)
, Component = win.milo.Component;
var components = [];
forEachNodesInRange(range, function (node){
if (node.nodeType != Node.TEXT_NODE) {
var comp = Component.getComponent(node);
if (comp)
components.push(comp);
}
});
return components;
}
/**
* delete a range
*
* @param {range} delete a DOM range and all the components inside
*/
function deleteRangeWithComponents(range) {
var components = getComponentsFromRange(range);
components.forEach(function(comp) {
comp.destroy(true);
});
range.deleteContents();
}
/**
* check if two ranges are equivalent
*
* @param {range} range1
* @param {range} range2
* @return {Boolean} are the two ranges equivalent
*/
function areRangesEqual(range1, range2){
return range1.compareBoundaryPoints(window.Range.START_TO_START, range2) === 0 && range1.compareBoundaryPoints(window.Range.END_TO_END, range2) === 0;
}
/**
* Return the first node that matches xpath expression
* @param {String} xpath xpath expression, e.g. '//a[contains(text(), "Click here")]' or '/html/body//h1'
* @param {Node} context optional context node to search inside, document by default
* @return {Node}
*/
function xpathSelector(xpath, context) {
if (!document.evaluate) return logger.error('document.evaluate is not supported');
context = context || document;
var result = document.evaluate(xpath, context, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
return result && result.singleNodeValue;
}
/**
* Return array of nodes that match xpath expression
* @param {String} xpath xpath expression, e.g. '//a[contains(text(), "Click here")]' or '/html/body//h1'
* @param {Node} context optional context node to search inside, document by default
* @return {Array<Node>}
*/
function xpathSelectorAll(xpath, context) {
if (!document.evaluate) return logger.error('document.evaluate is not supported');
context = context || document;
var result = document.evaluate(xpath, context, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var nodes = [], i = 0, node;
while (node = result.snapshotItem(i)) nodes[i++] = node;
return nodes;
}
/**
* Adds a single pixel div to the body at a given x and y position. Useful for debugging position specific code.
* @param {Number} x
* @param {Number} y
*/
function addDebugPoint(x, y) {
var dbEl = document.createElement('div');
dbEl.setAttribute('style', 'width: 1px; height: 1px; position:fixed; left:'+x+'px; top:'+y+'px; background-color:red; z-index: 100');
setTimeout(function() {document.body.appendChild(dbEl);}, 200);
}
},{"../config":42,"milo-core":84}],58:[function(require,module,exports){
'use strict';
var _ = require('milo-core').proto;
module.exports = DOMListeners;
function DOMListeners() {
this.listeners = [];
}
_.extendProto(DOMListeners, {
add: DOMListeners$add,
remove: DOMListeners$remove,
removeAll: DOMListeners$removeAll
});
function DOMListeners$add(target, eventType, handler) {
this.listeners.push({
target: target,
eventType: eventType,
handler: handler
});
target.addEventListener(eventType, handler);
}
function DOMListeners$remove(target, eventType, handler) {
var listener = {
target: target,
eventType: eventType,
handler: handler
};
var idx = _.findIndex(this.listeners, _.partial(_.isEqual, listener));
if (idx > -1) {
this.listeners.splice(idx, 1);
_removeListener(listener);
}
}
function DOMListeners$removeAll() {
this.listeners.forEach(_removeListener);
this.listeners = [];
}
function _removeListener(l) {
l.target.removeEventListener(l.eventType, l.handler);
}
},{"milo-core":84}],59:[function(require,module,exports){
'use strict';
var _ = require('milo-core').proto;
module.exports = domReady;
var domReadyFuncs = []
, domReadySubscribed = false;
function domReady(func) { // , arguments
var self = this
, args = _.slice(arguments, 1);
if (isReady.call(this))
callFunc();
else {
if (!domReadySubscribed) {
document.addEventListener('readystatechange', onDomReady);
domReadySubscribed = true;
}
domReadyFuncs.push(callFunc); // closure is added, so every time different function will be called
}
function callFunc() {
func.apply(self, args);
}
}
function onDomReady() {
document.removeEventListener('readystatechange', onDomReady);
domReadyFuncs.forEach(function(func) { func(); });
}
_.extend(domReady, {
isReady: isReady
});
function isReady() {
var readyState = document.readyState;
return readyState == 'loading' ? false : readyState;
}
},{"milo-core":84}],60:[function(require,module,exports){
'use strict';
var Component = require('../components/c_class')
, miloCore = require('milo-core')
, Messenger = miloCore.Messenger
, dragDropConfig = require('../config').dragDrop
, componentMetaRegex = dragDropConfig.dataTypes.componentMetaRegex
, _ = miloCore.proto
, base32 = require('base32');
module.exports = DragDrop;
/**
* Wrapper for event.dataTransfer of drag-drop HTML API
*
* @constructor
* @param {event} DOM event
* @return {DragDrop}
*/
function DragDrop(event) {
this.event = event;
this.dataTransfer = event.dataTransfer;
this.types = event.dataTransfer.types;
}
/**
* Usage:
* var testDT = new DragDrop(event);
* testDT.setComponentMeta(newComponent, {test: 'test', test2: 'test2'});
* testDT.getComponentMeta();
*/
_.extend(DragDrop, {
componentDataType: DragDrop$$componentDataType,
getDropPositionY: DragDrop$$getDropPositionY
});
_.extendProto(DragDrop, {
isComponent: DragDrop$isComponent,
getComponentState: DragDrop$getComponentState,
setComponentState: DragDrop$setComponentState,
getComponentMeta: DragDrop$getComponentMeta,
setComponentMeta: DragDrop$setComponentMeta,
getAllowedEffects: DragDrop$getAllowedEffects,
setAllowedEffects: DragDrop$setAllowedEffects,
getDropEffect: DragDrop$getDropEffect,
setDropEffect: DragDrop$setDropEffect,
isEffectAllowed: DragDrop$isEffectAllowed,
getData: DragDrop$getData,
setData: DragDrop$setData,
clearData: DragDrop$clearData
});
function DragDrop$$componentDataType() {
return dragDropConfig.dataTypes.component;
}
function DragDrop$$getDropPositionY(event, el) {
var dP = getDropPosition(event, el);
var isBelow = dP.clientY > dP.targetTop + dP.targetHeight / 2;
return isBelow ? 'below' : 'above';
}
function getDropPosition(event, el) {
try {
var clientRect = el.getBoundingClientRect();
var targetWidth = clientRect.width;
var targetHeight = clientRect.height;
var targetTop = clientRect.top;
var targetLeft = clientRect.left;
} catch(e){}
return {
clientX: event.clientX,
clientY: event.clientY,
targetWidth: targetWidth,
targetHeight: targetHeight,
targetTop: targetTop,
targetLeft: targetLeft
};
}
function DragDrop$isComponent() {
return _.indexOf(this.types, DragDrop.componentDataType()) >= 0;
}
function DragDrop$getComponentState() {
var dataType = DragDrop.componentDataType()
, stateStr = this.dataTransfer.getData(dataType)
, state = _.jsonParse(stateStr);
return state;
}
function DragDrop$setComponentState(component, stateStr){
if (! stateStr) {
var state = component.getTransferState({ requestedBy: 'drag' });
stateStr = JSON.stringify(state);
}
var dataType = DragDrop.componentDataType();
stateStr && this.dataTransfer.setData(dataType, stateStr);
this.dataTransfer.setData('text/html', component.el.outerHTML);
return stateStr;
}
function DragDrop$setComponentMeta(component, params, data) {
var meta = _componentMeta(component);
var paramsStr = JSON.stringify(params || {});
var dataType = dragDropConfig.dataTypes.componentMetaTemplate
.replace('%class', _encode(meta.compClass || ''))
.replace('%name', _encode(meta.compName || ''))
.replace('%params', _encode(paramsStr || ''));
if (data && typeof data == 'object') data = JSON.stringify(data);
this.dataTransfer.setData(dataType, data || '');
return dataType;
}
function _encode(str) {
return base32.encode(str).toLowerCase();
}
function _componentMeta(component) {
return component.transfer
? component.transfer.getComponentMeta()
: {
compClass: component.constructor.name,
compName: component.name
};
}
function DragDrop$getComponentMeta() {
var match;
var metaDataType = _.find(this.types, function (dType) {
match = dType.match(componentMetaRegex);
return !!match;
});
if (!metaDataType) return;
for (var i=1; i<4; i++)
match[i] = base32.decode(match[i]);
return {
compClass: match[1],
compName: match[2],
params: JSON.parse(match[3]),
metaDataType: metaDataType,
metaData: _.jsonParse(this.dataTransfer.getData(metaDataType)) || this.dataTransfer.getData(metaDataType)
};
}
// as defined here: https://developer.mozilla.org/en-US/docs/DragDrop/Drag_Operations#dragstart
function DragDrop$getAllowedEffects() {
return this.dataTransfer.effectAllowed;
}
function DragDrop$setAllowedEffects(effects) {
this.dataTransfer.effectAllowed = effects;
}
function DragDrop$getDropEffect() {
return this.dataTransfer.dropEffect;
}
function DragDrop$setDropEffect(effect) {
this.dataTransfer.dropEffect = effect;
}
function DragDrop$isEffectAllowed(effect) {
var allowedEffects = this.getAllowedEffects()
, isCopy = effect == 'copy'
, isMove = effect == 'move'
, isLink = effect == 'link'
, isAllowed = isCopy || isLink || isMove;
switch (allowedEffects) {
case 'copy':
case 'move':
case 'link':
return allowedEffects == effect;
case 'copyLink':
return isCopy || isLink;
case 'copyMove':
return isCopy || isMove;
case 'linkMove':
return isLink || isMove;
case 'all':
case 'uninitialized':
return isAllowed;
case 'none':
return false;
}
}
function DragDrop$getData(dataType) {
return this.dataTransfer.getData(dataType);
}
function DragDrop$setData(dataType, dataStr) {
this.dataTransfer.setData(dataType, dataStr);
}
function DragDrop$clearData(dataType) {
this.dataTransfer.clearData(dataType);
}
/**
* Drag drop service compensating for the lack of communication from drop target to drag source in DOM API
*/
var dragDropService = new Messenger;
var _currentDragDrop, _currentDragFacet;
_.extend(DragDrop, {
service: dragDropService,
destroy: DragDrop_destroy
});
dragDropService.onMessages({
// data is DragDropDataTransfer instance
// fired by Drag facet on "dragstart" event
'dragdropstarted': onDragDropStarted,
// data is object with at least dropEffect property
// fired by Drop facet on "drop" event
'dragdropcompleted': onDragDropCompleted,
// fired by Drag facet on "dragend" event to complete drag
// if drop happended in another window or if it was cancelled
'completedragdrop': onCompleteDragDrop
});
_.extend(dragDropService, {
getCurrentDragDrop: getCurrentDragDrop,
getCurrentDragSource: getCurrentDragSource
});
function onDragDropStarted(msg, data) {
_currentDragDrop = data.dragDrop;
_currentDragFacet = data.dragFacet;
}
function onDragDropCompleted(msg, data) {
_currentDragFacet && _currentDragFacet.postMessageSync('dragdropcompleted', data);
_currentDragDrop = undefined;
_currentDragFacet = undefined;
}
function onCompleteDragDrop(msg, data) {
if (_currentDragDrop)
dragDropService.postMessageSync('dragdropcompleted', data);
}
function getCurrentDragDrop() {
return _currentDragDrop;
}
function getCurrentDragSource() {
return _currentDragFacet && _currentDragFacet.owner;
}
function DragDrop_destroy() {
dragDropService.offAll();
}
},{"../components/c_class":15,"../config":42,"base32":74,"milo-core":84}],61:[function(require,module,exports){
// <a name="utils-error"></a>
// milo.utils.error
// -----------
'use strict';
var _ = require('milo-core').proto;
// module exports error classes for all names defined in this array
var errorClassNames = ['AbstractClass', 'Mixin', 'Messenger', 'Component',
'Attribute', 'Binder', 'Loader', 'MailMessageSource', 'Facet',
'Scope', 'Model', 'DomFacet', 'EditableFacet',
'List', 'Connector', 'Registry', 'FrameMessageSource',
'Drop', 'Angular', 'StorageMessageSource'];
var error = {
toBeImplemented: error$toBeImplemented,
createClass: error$createClass
};
errorClassNames.forEach(function(name) {
error[name] = error$createClass(name + 'Error');
});
module.exports = error;
function error$createClass(errorClassName) {
var ErrorClass = _.makeFunction(errorClassName, 'message',
'this.name = "' + errorClassName + '"; \
this.message = message || "There was an error";');
_.makeSubclass(ErrorClass, Error);
return ErrorClass;
}
function error$toBeImplemented() {
throw new error.AbstractClass('calling the method of an absctract class');
}
},{"milo-core":84}],62:[function(require,module,exports){
'use strict';
var Component = require('../components/c_class')
, BindAttribute = require('../attributes/a_bind')
, binder = require('../binder')
, domUtils = require('./dom')
, miloCore = require('milo-core')
, logger = miloCore.util.logger
, check = miloCore.util.check
, _ = miloCore.proto;
var createRangePaths = _createNodesAndPathsFunc(domUtils.treePathOf);
var createRangeNodes = _createNodesAndPathsFunc(domUtils.getNodeAtTreePath);
var fragmentUtils = module.exports = {
getState: fragment_getState,
getStateAsync: fragment_getStateAsync,
expandRangeToSiblings: expandRangeToSiblings,
getRangeSiblings: getRangeSiblings,
createRangeFromSiblings: createRangeFromSiblings,
createRangeFromNodes: createRangeFromSiblings, // alias
createRangePaths: createRangePaths,
createRangeNodes: createRangeNodes
};
/**
* Creates an object with the state of wrapped range with components, including partially selected. The range will be cloned and wrapped in component with container facet before getting its state.
* This function will log error and return undefined if range has no common ancestor that has component with container facet
*
* @param {Range} range DOM Range instance
* @param {Boolean} renameChildren optional parameter, `true` to rename fragment child components
* @param {String} wrapperClassName optional parameter to wrap in a custom component class
* @return {Object}
*/
function fragment_getState(range, renameChildren, wrapperClassName) {
var rangeContainer = _getRangeContainer(range);
if (! rangeContainer) {
logger.error('fragment.getState: range has no common container');
return;
}
var frag = range.cloneContents()
, wrapper = _wrapFragmentInContainer(frag, wrapperClassName);
_transferStates(rangeContainer, wrapper);
if (renameChildren) _renameChildren(wrapper);
var wrapperState = wrapper.getState();
_.deferMethod(wrapper, 'destroy');
return wrapperState;
}
/**
* Creates an object with the state of wrapped range with components, including partially selected. The range will be cloned and wrapped in component with container facet before getting its state.
* This function will return result and any error via callback.
*
* @param {Range} range DOM Range instance
* @param {Boolean} renameChildren optional parameter, `true` to rename fragment child components
* @param {Function} callback always the last parameter, optional parameters can be dropped; result is passed via callback with any error as first parameter
*/
function fragment_getStateAsync(range, renameChildren, callback) {
try {
var rangeContainer = _getRangeContainer(range);
if (! rangeContainer) {
callback(new Error('fragment.getState: range has no common container'));
return; // do NOT connect return to previous callback, getState should return undefined
}
if (typeof renameChildren == 'function') {
callback = renameChildren;
renameChildren = false;
}
var frag = range.cloneContents()
, wrapper = _wrapFragmentInContainer(frag);
_transferStates(rangeContainer, wrapper);
_.defer(function() {
wrapper.broadcast('stateready');
_.defer(function() {
if (renameChildren) _renameChildren(wrapper);
var wrapperState = wrapper.getState();
wrapper.destroy();
callback(null, wrapperState);
});
});
} catch (err) {
callback(err);
}
}
function _wrapFragmentInContainer(frag, wrapperClassName) {
var wrapEl = document.createElement('div')
, attr = new BindAttribute(wrapEl);
_.extend(attr, {
compClass: wrapperClassName || 'Component',
compFacets: wrapperClassName ? [] : ['container'],
compName: 'wrapper'
});
attr.decorate();
wrapEl.appendChild(frag);
var scope = binder(wrapEl);
return scope.wrapper;
}
function _getRangeContainer(range) {
var el = domUtils.containingElement(range.commonAncestorContainer);
return Component.getContainingComponent(el, true, 'container');
}
function _transferStates(fromComp, toComp) {
var fromScope = fromComp.container.scope;
toComp.container.scope._each(function(toChildComp, name) {
var fromChildComp = fromScope[name];
if (! fromChildComp) return logger.error('fragment.getState: conponent', name, 'not found in range');
var state = fromChildComp._getState(true);
toChildComp.setState(state);
});
}
function _renameChildren(comp) {
comp.container.scope._each(function(child) {
child.rename();
});
}
function expandRangeToSiblings(range) {
var siblings = getRangeSiblings(range);
range = createRangeFromSiblings(siblings);
return range;
}
function createRangeFromSiblings(nodes) {
var range = document.createRange();
if (nodes.siblings) {
range.setStartBefore(nodes.start);
range.setEndAfter(nodes.end);
} else
range.selectNode(nodes.start);
return range;
}
function getRangeSiblings(range) {
var containerNode = range.commonAncestorContainer
, startNode = range.startContainer
, endNode = range.endContainer;
if (startNode == endNode) {
if (startNode != containerNode) logger.error('deleteSelectionCommand logical error: start==end, but container is different');
return { siblings: false, start: startNode };
}
if (startNode == containerNode || endNode == containerNode)
return { siblings: false, start: containerNode };
var startSibling = _findContainingChild(containerNode, startNode);
var endSibling = _findContainingChild(containerNode, endNode);
if (startSibling && endSibling) {
if (startSibling == endSibling) {
logger.error('deleteSelectionCommand logical error: same siblings');
return { siblings: false, start: startSibling };
} else
return { siblings: true, start: startSibling, end: endSibling };
}
}
function _findContainingChild(containerNode, selNode) {
return _.find(containerNode.childNodes, function(node) {
return node.contains(selNode);
});
}
function _createNodesAndPathsFunc(func) {
return function(rootEl, fromObj) {
var toObj = {
siblings: fromObj.siblings,
start: func(rootEl, fromObj.start)
};
if (toObj.siblings)
toObj.end = func(rootEl, fromObj.end);
return toObj;
};
}
},{"../attributes/a_bind":4,"../binder":8,"../components/c_class":15,"./dom":57,"milo-core":84}],63:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, deprecate = require('./deprecate');
/**
* `milo.util`
*/
var util = {
logger: miloCore.util.logger,
request: require('./request'),
websocket: require('./websocket'),
check: miloCore.util.check,
error: deprecate(require('./error'), 'milo.util.error is DEPRECATED and will be REMOVED soon!'),
count: deprecate(require('./unique_id'), 'milo.util.count is DEPRECATED! Use milo.util.uniqueId instead'),
uniqueId: require('./unique_id'),
componentName: require('./component_name'),
dom: require('./dom'),
domListeners: require('./dom_listeners'),
selection: require('./selection'),
fragment: require('./fragment'),
jsonParse: deprecate(require('./json_parse'), 'milo.util.jsonParse is DEPRECATED! Use _.jsonParse instead'),
storage: require('./storage'),
domReady: require('./domready'),
dragDrop: require('./dragdrop'),
deprecate: deprecate,
doT: miloCore.util.doT,
destroy: util_destroy
};
module.exports = util;
function util_destroy() {
util.request.destroy();
util.dragDrop.destroy();
}
},{"./component_name":53,"./deprecate":56,"./dom":57,"./dom_listeners":58,"./domready":59,"./dragdrop":60,"./error":61,"./fragment":62,"./json_parse":64,"./request":65,"./selection":66,"./storage":67,"./unique_id":70,"./websocket":71,"milo-core":84}],64:[function(require,module,exports){
'use strict';
module.exports = jsonParse;
/**
* `milo.util.jsonParse`
* Safe JSON.parse, returns undefined if JSON.parse throws an exception
*
* @param {String} str - JSON string representation of object
* @return {Object|undefined}
*/
function jsonParse(str) {
try {
return JSON.parse(str);
} catch (e) {}
}
},{}],65:[function(require,module,exports){
'use strict';
// milo.utils.request
// -----------
// Convenience functions wrapping XMLHTTPRequest functionality.
// ```
// var request = milo.utils.request
// , opts: { method: 'GET' };
// request(url, opts, function(err, data) {
// logger.debug(data);
// });
// request.get(url, function(err, data) {
// logger.debug(data);
// });
// ```
// Only generic request and get, json, post convenience methods are currently implemented.
var miloCore = require('milo-core')
, _ = miloCore.proto
, uniqueId = require('./unique_id')
, config = require('../config')
, logger = miloCore.util.logger
, Messenger = miloCore.Messenger;
module.exports = request;
var _pendingRequests = [];
var promiseThen = createPromiseOverride('then');
var promiseCatch = createPromiseOverride('catch');
/**
* Creates a function which is used to override standard promise behaviour and allow promise instances
* created to maintain a reference to the request object no matter if .then() or .catch() is called.
*/
function createPromiseOverride(functionName) {
return function() {
var promise = Promise.prototype[functionName].apply(this, arguments);
keepRequestObject(promise, this._request);
return promise;
};
}
function request(url, opts, callback) {
opts.url = url;
opts.contentType = opts.contentType || 'application/json;charset=UTF-8';
if (_messenger) request.postMessageSync('request', { options: opts });
var req = new XMLHttpRequest();
req.open(opts.method, opts.url, (opts.sync ? false : true));
req.setRequestHeader('Content-Type', opts.contentType);
setRequestHeaders(req, opts.headers);
if (!opts.sync) req.timeout = opts.timeout || config.request.defaults.timeout;
req.onloadend = req.ontimeout = req.onabort = onReady;
var xPromise = _createXPromise(req);
req.send(JSON.stringify(opts.data));
req[config.request.optionsKey] = opts;
if (opts.trackCompletion !== false) _pendingRequests.push(req);
return xPromise.promise;
function onReady(e) {
_onReady(req, callback, xPromise, e.type);
}
}
function _createXPromise(request) {
var resolvePromise, rejectPromise;
var promise = new Promise(function(resolve, reject) {
resolvePromise = resolve;
rejectPromise = reject;
});
keepRequestObject(promise, request);
promise.catch(_.noop); // Sometimes errors are handled within callbacks, so uncaught promise error message should be suppressed.
return {
promise: promise,
resolve: resolvePromise,
reject: rejectPromise
};
}
// Ensures that the promise (and any promises created when calling .then/.catch) has a reference to the original request object
function keepRequestObject(promise, request) {
promise._request = request;
promise.then = promiseThen;
promise.catch = promiseCatch;
return promise;
}
function setRequestHeaders(req, headers) {
if (headers)
_.eachKey(headers, function(value, key) {
req.setRequestHeader(key, value);
});
}
function _onReady(req, callback, xPromise, eventType) {
if (req.readyState != 4) return;
if (req[config.request.completedKey]) return;
_.spliceItem(_pendingRequests, req);
var error;
try {
if ( req.status >= 200 && req.status < 400 ) {
try {
postMessage('success');
callback && callback(null, req.responseText, req);
} catch(e) { error = e; }
xPromise.resolve(req.responseText);
}
else {
var errorReason = req.status || eventType;
try {
postMessage('error');
postMessage('error' + errorReason);
callback && callback(errorReason, req.responseText, req);
} catch(e) { error = e; }
xPromise.reject({ reason: errorReason, response: req.responseText });
}
} catch(e) {
error = error || e;
} finally {
req[config.request.completedKey] = true;
}
// not removing subscription creates memory leak, deleting property would not remove subscription
req.onloadend = req.ontimeout = req.onabort = undefined;
if (!_pendingRequests.length)
postMessage('requestscompleted');
if (error) {
var errObj = new Error('Exception: ' + error);
logger.error(error.stack);
throw errObj;
}
function postMessage(msg) {
if (_messenger) request.postMessage(msg,
{ status: status, response: req.responseText });
}
}
_.extend(request, {
get: request$get,
post: request$post,
put: request$put,
delete: request$delete,
json: request$json,
jsonp: request$jsonp,
file: request$file,
useMessenger: request$useMessenger,
destroy: request$destroy,
whenRequestsCompleted: whenRequestsCompleted
});
var _messenger;
function request$useMessenger() {
_messenger = new Messenger(request, ['on', 'once', 'onSync', 'off', 'onMessages', 'offMessages', 'postMessage', 'postMessageSync']);
}
function request$get(url, callback) {
return request(url, { method: 'GET' }, callback);
}
function request$post(url, data, callback) {
return request(url, { method: 'POST', data: data }, callback);
}
function request$put(url, data, callback) {
return request(url, { method: 'PUT', data: data }, callback);
}
function request$delete(url, data, callback) {
return request(url, { method: 'DELETE', data: data }, callback);
}
function request$json(url, callback) {
var promise = request(url, { method: 'GET' });
var jsonPromise = promise.then(JSON.parse);
if (callback)
jsonPromise
.then(function(data) {
callback(null, data);
}, function(errData) {
callback(errData.reason, errData.response);
});
return jsonPromise;
}
var jsonpOptions = { method: 'GET', jsonp: true };
function request$jsonp(url, callback) {
var script = document.createElement('script'),
xPromise = _createXPromise(script),
head = window.document.head,
uniqueCallback = config.request.jsonpCallbackPrefix + uniqueId();
var opts = _.extend({ url: url }, jsonpOptions);
if (_messenger) request.postMessageSync('request', { options: opts });
if (! _.isEqual(_.omitKeys(opts, 'url'), jsonpOptions))
logger.warn('Ignored not allowed request options change in JSONP request - only URL can be changed');
var timeout = setTimeout(function() {
var err = new Error('No JSONP response or no callback in response');
_onResult(err);
}, config.request.jsonpTimeout);
window[uniqueCallback] = _.partial(_onResult, null);
_pendingRequests.push(window[uniqueCallback]);
script.type = 'text/javascript';
script.src = opts.url + (opts.url.indexOf('?') == -1 ? '?' : '&') + 'callback=' + uniqueCallback;
head.appendChild(script);
return xPromise.promise;
function _onResult(err, result) {
_.spliceItem(_pendingRequests, window[uniqueCallback]);
var error;
try {
postMessage(err ? 'error' : 'success', err, result);
if (err) {
logger.error('No JSONP response or timeout');
postMessage('errorjsonptimeout', err);
}
callback && callback(err, result);
}
catch(e) { error = e; }
if (err) xPromise.reject(err);
else xPromise.resolve(result);
cleanUp();
if (!_pendingRequests.length)
postMessage('requestscompleted');
if (error) throw error;
}
function cleanUp() {
clearTimeout(timeout);
head.removeChild(script);
delete window[uniqueCallback];
}
function postMessage(msg, status, result) {
if (_messenger) request.postMessage(msg,
{ status: status, response: result });
}
}
function request$file(opts, fileData, callback, progress) {
if (typeof opts == 'string')
opts = { method: 'POST', url: opts };
opts.method = opts.method || 'POST';
opts.file = true;
if (_messenger) request.postMessageSync('request', { options: opts });
var req = new XMLHttpRequest();
if (progress) req.upload.onprogress = progress;
req.open(opts.method, opts.url, true);
setRequestHeaders(req, opts.headers);
req.timeout = opts.timeout || config.request.defaults.timeout;
req.onloadend = req.ontimeout = req.onabort = onReady;
var xPromise = _createXPromise(req);
if (opts.binary)
req.send(fileData);
else {
var formData = new FormData();
formData.append('file', fileData);
req.send(formData);
}
req[config.request.optionsKey] = opts;
if (opts.trackCompletion !== false) _pendingRequests.push(req);
return xPromise.promise;
function onReady(e) {
if (progress) req.upload.onprogress = undefined;
_onReady(req, callback, xPromise, e.type);
}
}
function request$destroy() {
if (_messenger) _messenger.destroy();
request._destroyed = true;
}
function whenRequestsCompleted(callback, timeout) {
callback = _.once(callback);
if (timeout)
_.delay(callback, timeout, 'timeout');
if (_pendingRequests.length)
_messenger.once('requestscompleted', callback);
else
_.defer(callback);
}
},{"../config":42,"./unique_id":70,"milo-core":84}],66:[function(require,module,exports){
'use strict';
var domUtils = require('../dom')
, containingElement = domUtils.containingElement
, setCaretPosition = domUtils.setCaretPosition
, getComponentsFromRange = domUtils.getComponentsFromRange
, deleteRangeWithComponents = domUtils.deleteRangeWithComponents
, miloCore = require('milo-core')
, logger = miloCore.util.logger
, Component = require('../../components/c_class')
, _ = miloCore.proto;
module.exports = TextSelection;
/**
* Text selection class.
* Serves as a helper to manage current selection
* The object cannot be reused, if the selection changes some of its properties may contain information related to previous selection
*
* @param {Window} win window in which text selection is processed
*/
function TextSelection(win) {
if (! this instanceof TextSelection)
return new TextSelection(win);
this.window = win || window;
this.init();
}
/**
* TextSelection instance method
* Returns selection start element
*
* @return {Element|null}
*/
var TextSelection$startElement =
_.partial(_getElement, '_startElement', 'startContainer');
/**
* TextSelection instance method
* Returns selection end element
*
* @return {Element|null}
*/
var TextSelection$endElement =
_.partial(_getElement, '_endElement', 'endContainer');
/**
* TextSelection instance method
* Returns selection end element
*
* @return {Element|null}
*/
var TextSelection$containingElement =
_.partial(_getElement, '_containingElement', 'commonAncestorContainer');
/**
* TextSelection instance method
* Returns selection start Component
*
* @return {Component}
*/
var TextSelection$startComponent =
_.partial(_getComponent, '_startComponent', 'startElement');
/**
* TextSelection instance method
* Returns selection end Component
*
* @return {Component}
*/
var TextSelection$endComponent =
_.partial(_getComponent, '_endComponent', 'endElement');
/**
* TextSelection instance method
* Returns selection end Component
*
* @return {Component}
*/
var TextSelection$containingComponent =
_.partial(_getComponent, '_containingComponent', 'containingElement');
_.extendProto(TextSelection, {
init: TextSelection$init,
text: TextSelection$text,
textNodes: TextSelection$textNodes,
clear: TextSelection$clear,
startElement: TextSelection$startElement,
endElement: TextSelection$endElement,
containingElement: TextSelection$containingElement,
startComponent: TextSelection$startComponent,
endComponent: TextSelection$endComponent,
containingComponent: TextSelection$containingComponent,
containedComponents: TextSelection$containedComponents,
eachContainedComponent: TextSelection$eachContainedComponent,
del: TextSelection$del,
_getPostDeleteSelectionPoint: _getPostDeleteSelectionPoint,
_selectAfterDelete: _selectAfterDelete,
getRange: TextSelection$getRange,
getState: TextSelection$getState,
getNormalizedRange: TextSelection$$getNormalizedRange,
getDirection: TextSelection$$getDirection
});
_.extend(TextSelection, {
createFromRange: TextSelection$$createFromRange,
createFromState: TextSelection$$createFromState,
createStateObject: TextSelection$$createStateObject
});
/**
* TextSelection instance method
* Initializes TextSelection from the current selection
*/
function TextSelection$init() {
this.selection = this.window.getSelection();
if (this.selection.rangeCount)
this.range = this.selection.getRangeAt(0);
this.isCollapsed = this.selection.isCollapsed;
}
/**
* TextSelection instance method
* Retrieves and returns selection text
*
* @return {String}
*/
function TextSelection$text() {
if (! this.range) return undefined;
if (! this._text)
this._text = this.range.toString();
return this._text;
}
/**
* TextSelection instance method
* Retrieves and returns selection text nodes
*
* @return {Array<Node>}
*/
function TextSelection$textNodes() {
if (! this.range) return undefined;
if (! this._textNodes)
this._textNodes = _getTextNodes.call(this);
return this._textNodes;
}
function TextSelection$clear() {
this.selection.removeAllRanges();
}
/**
* Retrieves text and text nodes from selection saving them on properties of object
*
* @private
* @param {TextSelection} this
*/
function _getTextNodes() {
// list of selected text nodes
var textNodes = [];
if (this.isCollapsed)
return textNodes;
// create TreeWalker to traverse the tree to select all text nodes
var selStart = this.range.startContainer
, selEnd = this.range.endContainer
, rangeContainer = this.range.commonAncestorContainer;
var treeWalker = this.window.document.createTreeWalker(rangeContainer, NodeFilter.SHOW_TEXT);
var node = treeWalker.currentNode = selStart;
// traverse DOM tree to collect all selected text nodes
while (node && (! inEnd || selEnd.contains(node))) {
textNodes.push(node);
var inEnd = inEnd || selEnd.contains(node);
node = treeWalker.nextNode();
}
return textNodes;
}
/**
* Retrieves and returns start/end element from selection saving them on properties of object
*
* @private
* @param {TextSelection} this
* @return {Element|null}
*/
function _getElement(thisPropName, rangePropName) {
if (! this.range) return undefined;
if (typeof this[thisPropName] == 'undefined')
this[thisPropName] = containingElement(this.range[rangePropName]);
return this[thisPropName];
}
/**
* Retrieves and returns start/end component from selection saving them on properties of object
*
* @private
* @param {TextSelection} this
* @return {Component}
*/
function _getComponent(thisPropName, elMethodName) {
if (! this.range) return undefined;
if (typeof this[thisPropName] == 'undefined')
this[thisPropName] = Component.getContainingComponent(this[elMethodName]());
return this[thisPropName];
}
function TextSelection$containedComponents() {
if (this._containedComponents)
return this._containedComponents;
var components = this._containedComponents = [];
if (this.isCollapsed || ! this.range) return components;
return getComponentsFromRange(this.range);
}
function TextSelection$eachContainedComponent(callback, thisArg) {
if (this.isCollapsed || ! this.range) return;
var components = this.containedComponents();
components.forEach(callback, thisArg);
}
/**
* TextSelection instance method
* Deletes the current selection and all components in it
*
* @param {Boolean} selectEndContainer set to true if the end container should be selected after deletion
*/
function TextSelection$del(selectEndContainer) {
if (this.isCollapsed || ! this.range) return;
var selPoint = this._getPostDeleteSelectionPoint(selectEndContainer);
deleteRangeWithComponents(this.range);
this._selectAfterDelete(selPoint);
selPoint.node.parentNode.normalize();
}
function _getPostDeleteSelectionPoint(selectEndContainer) {
var selNode = this.range.startContainer;
var selOffset = this.range.startOffset;
if (selectEndContainer && this.range.startContainer != this.range.endContainer) {
selNode = this.range.endContainer;
selOffset = 0;
}
return { node: selNode, offset: selOffset };
}
function _selectAfterDelete(selPoint) {
var selNode = selPoint.node
, selOffset = selPoint.offset;
if (!selNode) return;
if (selNode.nodeType == Node.TEXT_NODE)
selNode.textContent = selNode.textContent.trimRight();
if (!selNode.nodeValue)
selNode.nodeValue = '\u00A0'; //non-breaking space, \u200B for zero width space;
var position = selOffset > selNode.length ? selNode.length : selOffset;
setCaretPosition(selNode, position);
}
/**
* Returns selection range
*
* @return {Range}
*/
function TextSelection$getRange() {
return this.range;
}
/**
* Stores selection window, nodes and offsets in object
*/
function TextSelection$getState(rootEl) {
var r = this.range;
var doc = rootEl.ownerDocument
, win = doc.defaultView || doc.parentWindow;
if (!r) return { window: win };
return TextSelection.createStateObject(rootEl, r.startContainer, r.startOffset, r.endContainer, r.endOffset);
}
function TextSelection$$createStateObject(rootEl, startContainer, startOffset, endContainer, endOffset) {
endContainer = endContainer || startContainer;
endOffset = endOffset || startOffset;
var doc = rootEl.ownerDocument
, win = doc.defaultView || doc.parentWindow;
return {
window: win,
rootEl: rootEl,
start: _getSelectionPointState(rootEl, startContainer, startOffset),
end: _getSelectionPointState(rootEl, endContainer, endOffset)
};
}
function _getSelectionPointState(rootEl, node, offset) {
var treePath = domUtils.treePathOf(rootEl, node);
if (! treePath) logger.error('Selection point is outside of root element');
return {
treePath: treePath,
offset: offset
};
}
/**
* Restores actual selection to the stored range
*/
function TextSelection$$createFromState(state) {
var domUtils = state.window.milo.util.dom;
if (state.rootEl && state.start && state.end) {
var startNode = _selectionNodeFromState(state.rootEl, state.start)
, endNode = _selectionNodeFromState(state.rootEl, state.end);
try {
domUtils.setSelection(startNode, state.start.offset, endNode, state.end.offset);
return new TextSelection(state.window);
} catch(e) {
logger.error('Text selection: can\'t create selection', e, e.message);
}
} else {
domUtils.clearSelection(state.window);
return new TextSelection(state.window);
}
}
function _selectionNodeFromState(rootEl, pointState) {
var node = domUtils.getNodeAtTreePath(rootEl, pointState.treePath);
if (! node) logger.error('TextSelection createFromState: no node at treePath');
return node;
}
/**
* Creates selection from passed range
*
* @param {Range} range
* @param {Boolean} backward
*
* @return {TextSelection}
*/
function TextSelection$$createFromRange(range, backward) {
var win = range.startContainer.ownerDocument.defaultView
, sel = win.getSelection()
, endRange;
sel.removeAllRanges();
if (backward){
endRange = range.cloneRange();
endRange.collapse(false);
sel.addRange(endRange);
sel.extend(range.startContainer, range.startOffset);
}
else {
sel.addRange(range);
}
return new TextSelection(win);
}
/**
* Returns a normalized copy of the range
* If you triple click an item, the end of the range is positioned at the beginning of the NEXT node.
* this function returns a range with the end positioned at the end of the last textnode contained
* inside a component with the "editable" facet
*
* @return {range}
*/
function TextSelection$$getNormalizedRange(){
var doc = this.range.commonAncestorContainer.ownerDocument
, tw, previousNode
, newRange = this.range.cloneRange();
if (newRange.endContainer.nodeType !== Node.TEXT_NODE) {
tw = doc.createTreeWalker(doc.body, NodeFilter.SHOW_TEXT);
tw.currentNode = newRange.endContainer;
previousNode = tw.previousNode();
newRange.setEnd(previousNode, previousNode.length);
}
return newRange;
}
/**
* get the direction of a selection
*
* 1 forward, -1 backward, 0 no direction, undefined one of the node is detached or in a different frame
*
* @return {Integer} can be -1, 0, 1 or undefined
*/
function TextSelection$$getDirection(){
return domUtils.getSelectionDirection(this.selection);
}
},{"../../components/c_class":15,"../dom":57,"milo-core":84}],67:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, Messenger = miloCore.Messenger
, StorageMessageSource = require('./msg_src')
, config = require('../../config')
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match;
require('./model');
module.exports = DOMStorage;
// shared keys stored by all instances, include key prefixes
var _storedKeys = {
true: {}, // session storage
false: {} // local storage
};
/**
* DOMStorage class to simplify storage and retrieval of multiple items with types preservation to DOM storage (localStorage and sessionStorage).
* Types will be stored in the key created from value keys with appended `milo.config.domStorage.typeSuffix`
*
* @param {String} keyPrefix prefix that will be added to all keys followed by `milo.config.domStorage.prefixSeparator` ("/" by default).
* @param {Boolean} sessionOnly true to use sessionStorage. localStorage will be used by default.
* @param {Window} win window to work in
*/
function DOMStorage(keyPrefix, sessionOnly, win) {
if (typeof window == 'undefined') return;
win = win || window;
keyPrefix = config.domStorage.root +
(keyPrefix
? keyPrefix + config.domStorage.prefixSeparator
: '');
_.defineProperties(this, {
keyPrefix: keyPrefix,
sessionOnly: !! sessionOnly,
window: win,
_storage: sessionOnly ? win.sessionStorage : win.localStorage,
_typeSuffix: config.domStorage.typeSuffix,
_keys: {}
}, _.WRIT);
}
_.extendProto(DOMStorage, {
get: DOMStorage$get,
set: DOMStorage$set,
remove: DOMStorage$remove,
hasItem: DOMStorage$hasItem,
getItem: DOMStorage$getItem,
setItem: DOMStorage$setItem,
removeItem: DOMStorage$removeItem,
_storageKey: DOMStorage$_storageKey,
_domStorageKey: DOMStorage$_domStorageKey,
getAllKeys: DOMStorage$getAllKeys,
getAllItems: DOMStorage$getAllItems,
createMessenger: DOMStorage$createMessenger,
destroy: DOMStorage$destroy
});
/**
* Expose Mesenger and MessageSource methods on DOMStorage
*/
Messenger.useWith(DOMStorage, '_messenger', Messenger.defaultMethods);
StorageMessageSource.useWith(DOMStorage, '_messageSource', ['trigger']);
var _sessionStorage = new DOMStorage('', true)
, _localStorage = new DOMStorage('', false);
var _domStorage = {
true: _sessionStorage,
false: _localStorage
};
_.extend(DOMStorage, {
registerDataType: DOMStorage$$registerDataType,
local: _localStorage,
session: _sessionStorage,
storage: _domStorage,
_storedKeys: _storedKeys // exposed for testing
});
/**
* Sets data to DOM storage. `this.keyPrefix` is prepended to keys.
*
* @param {Object} data single object can be passed in which case keys will be used as keys in local storage.
* @param {List} arguments alternatively just the list of arguments can be passed where arguments can be sequentially used as keys and values.
*/
function DOMStorage$set(data) { // or arguments
if (typeof data == 'object')
_.eachKey(data, function(value, key) {
this.setItem(key, value);
}, this);
else {
var argsLen = arguments.length;
if (argsLen % 2)
throw new Error('DOMStorage: set should have even number of arguments or object');
for (var i = 0; i < argsLen; i++) {
var key = arguments[i]
, value = arguments[++i];
this.setItem(key, value);
}
}
}
/**
* Gets data from DOM storage. `this.keyPrefix` is prepended to passed keys, but returned object will have keys without root keys.
*
* @param {List} arguments keys can be passed as strings or arrays of strings
* @returns {Object}
*/
function DOMStorage$get() { // , ... arguments
var data = {};
_.deepForEach(arguments, function(key) {
data[key] = this.getItem(key);
}, this);
return data;
}
/**
* Removes keys from DOM storage. `this.keyPrefix` is prepended to passed keys.
*
* @param {List} arguments keys can be passed as strings or arrays of strings
*/
function DOMStorage$remove() { //, ... arguments
_.deepForEach(arguments, function(key) {
this.removeItem(key);
}, this);
}
/**
* Check for presence of single item in DOM storage. `this.keyPrefix` is prepended to passed key.
*
* @param {String} key
* @return {Boolean}
*/
function DOMStorage$hasItem(key) {
var pKey = this._storageKey(key);
return this._storage.getItem(pKey) != null;
}
/**
* Gets single item from DOM storage prepending `this.keyPrefix` to passed key.
* Reads type of the originally stored value from `key + this._typeSuffix` and converts data to the original type.
*
* @param {String} key
* @return {Any}
*/
function DOMStorage$getItem(key) {
var pKey = this._storageKey(key);
var dataType = _getKeyDataType.call(this, pKey);
var valueStr = this._storage.getItem(pKey);
var value = _parseData(valueStr, dataType);
return value;
}
/**
* Sets single item to DOM storage prepending `this.keyPrefix` to passed key.
* Stores type of the stored value to `key + this._typeSuffix`.
*
* @param {String} key
* @return {Any}
*/
function DOMStorage$setItem(key, value) {
var pKey = this._storageKey(key);
var dataType = _setKeyDataType.call(this, pKey, value);
var valueStr = _serializeData(value, dataType);
try {
this._storage.setItem(pKey, valueStr);
} catch(e) {
if (e.name == 'QuotaExceededError') {
var cfg = config.domStorage.quotaExceeded;
if (cfg.message)
milo.mail.postMessage('quotaexceedederror', value);
if (cfg.throwError)
throw e;
} else
throw e;
}
this._keys[key] = true;
_domStorage[this.sessionOnly]._keys[pKey] = true;
}
/**
* Removes single item from DOM storage prepending `this.keyPrefix` to passed key.
* Type of the stored value (in `key + this._typeSuffix` key) is also removed.
*
* @param {String} key
* @return {Any}
*/
function DOMStorage$removeItem(key) {
var pKey = this._storageKey(key);
this._storage.removeItem(pKey);
_removeKeyDataType.call(this, pKey);
delete this._keys[key];
delete _domStorage[this.sessionOnly]._keys[pKey];
}
/**
* Returns the array of all keys stored by this instance of DOMStorage
*
* @return {Array}
*/
function DOMStorage$getAllKeys() {
var storedKeys = Object.keys(this._keys);
var keysInStorage = storedKeys.filter(function(key) {
if (this.hasItem(key)) return true;
else delete this._keys[key];
}, this);
return keysInStorage;
}
/**
* Returns the map with all keys and values (deserialized) stored using this instance of DOMStorage
*
* @return {Object}
*/
function DOMStorage$getAllItems() {
return this.get(this.getAllKeys());
}
/**
* Returns prefixed key for DOM storage for given unprefixed key.
*
* @param {String} key
* @return {String}
*/
function DOMStorage$_storageKey(key) {
return this.keyPrefix + key;
}
/**
* Returns unprefixed key to be used with this instance of DOMStorage fir given actual key in storage
* If key has different prefix from the keyPrefix returns undefined
*
* @param {String} storageKey actual key in local/session storage
* @return {String}
*/
function DOMStorage$_domStorageKey(storageKey) {
if (storageKey.indexOf(this._typeSuffix) >= 0) return;
return _.unPrefix(storageKey, this.keyPrefix);
}
/**
* Gets originally stored data type for given (prefixed) `key`.
*
* @param {String} pKey prefixed key of stored value
* @return {String}
*/
function _getKeyDataType(pKey) {
pKey = _dataTypeKey.call(this, pKey);
return this._storage.getItem(pKey);
}
/**
* Stores data type for given (prefixed) `key` and `value`.
* Returns data type for `value`.
*
* @param {String} pKey prefixed key of stored value
* @param {Any} value
* @return {String}
*/
function _setKeyDataType(pKey, value) {
var dataType = _getValueType(value);
pKey = _dataTypeKey.call(this, pKey);
this._storage.setItem(pKey, dataType);
return dataType;
}
/**
* Removes stored data type for given (prefixed) `key`.
*
* @param {String} pKey prefixed key of stored value
*/
function _removeKeyDataType(pKey) {
pKey = _dataTypeKey.call(this, pKey);
this._storage.removeItem(pKey);
}
/**
* Returns the key to store data type for given (prefixed) `key`.
*
* @param {String} pKey prefixed key of stored value
* @return {String}
*/
function _dataTypeKey(pKey) {
return pKey + this._typeSuffix;
}
/**
* Returns type of value as string. Class name returned for objects ('null' for null).
* @param {Any} value
* @return {String}
*/
function _getValueType(value) {
var valueType = typeof value
, className = value && value.constructor.name
, dataType = valuesDataTypes[className];
return dataType || (
valueType != 'object'
? valueType
: value == null
? 'null'
: value.constructor.name);
}
var valuesDataTypes = {
// can be registered with `registerDataType`
};
/**
* Serializes value to be stored in DOM storage.
*
* @param {Any} value value to be serialized
* @param {String} valueType optional data type to define serializer, _getValueType is used if not passed.
* @return {String}
*/
function _serializeData(value, valueType) {
valueType = valueType || _getValueType(value);
var serializer = dataSerializers[valueType];
return serializer
? serializer(value, valueType)
: value && value.toString == Object.prototype.toString
? JSON.stringify(value)
: '' + value;
}
var dataSerializers = {
'Array': JSON.stringify
};
/**
* Parses string retrieved from DOM storage.
*
* @param {String} valueStr
* @param {String} valueType data type that defines parser. Original sring will be returned if parser is not defined.
* @return {Any}
*/
function _parseData(valueStr, valueType) {
var parser = dataParsers[valueType];
return parser
? parser(valueStr, valueType)
: valueStr;
}
var dataParsers = {
Object: _.jsonParse,
Array: _.jsonParse,
Date: function(valStr) { return new Date(valStr); },
boolean: function(valStr) { return valStr == 'true'; },
number: Number,
function: _.toFunction,
RegExp: _.toRegExp
};
/**
* Registers data type to be saved in DOM storage. Class name can be used or result of `typeof` operator for non-objects to override default conversions.
*
* @param {String} valueType class (constructor) name or the string returned by typeof.
* @param {Function} serializer optional serializer for this type
* @param {Function} parser optional parser for this type
* @param {String} [storeAsDataType] optional name of stored data type if different from valueType
*/
function DOMStorage$$registerDataType(valueType, serializer, parser, storeAsDataType) {
if (serializer) dataSerializers[valueType] = serializer;
if (parser) dataParsers[valueType] = parser;
valuesDataTypes[valueType] = storeAsDataType || valueType;
}
function DOMStorage$createMessenger() {
var storageMessageSource = new StorageMessageSource(this);
var messenger = new Messenger(this, undefined, storageMessageSource);
_.defineProperties(this, {
_messenger: messenger,
_messageSource: storageMessageSource
}, _.WRIT);
}
function DOMStorage$destroy() {
this._storage = undefined;
this.window = undefined;
if (this._messenger) this._messenger.destroy();
this._destroyed = true;
}
},{"../../config":42,"./model":68,"./msg_src":69,"milo-core":84}],68:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, Model = miloCore.Model
, _ = miloCore.proto;
Model.registerWithDOMStorage = Model$$registerWithDOMStorage;
function Model$$registerWithDOMStorage() {
var DOMStorage = require('./index');
DOMStorage.registerDataType('Model', Model_domStorageSerializer, Model_domStorageParser);
DOMStorage.registerDataType('ModelPath', Model_domStorageSerializer, Model_domStorageParser, 'Model');
}
function Model_domStorageSerializer(value) {
var data = value.get();
return JSON.stringify(data);
}
function Model_domStorageParser(valueStr) {
var data = _.jsonParse(valueStr);
return new Model(data);
}
},{"./index":67,"milo-core":84}],69:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, MessageSource = miloCore.classes.MessageSource
, _ = miloCore.proto
, config = require('../../config')
, uniqueId = require('../../util/unique_id');
var StorageMessageSource = _.createSubclass(MessageSource, 'StorageMessageSource', true);
_.extendProto(StorageMessageSource, {
// implementing MessageSource interface
init: init,
addSourceSubscriber: StorageMessageSource$addSourceSubscriber,
removeSourceSubscriber: StorageMessageSource$removeSourceSubscriber,
postMessage: StorageMessageSource$postMessage,
trigger: StorageMessageSource$trigger,
//class specific methods
handleEvent: handleEvent // event dispatcher - as defined by Event DOM API
});
module.exports = StorageMessageSource;
function init(hostObject, proxyMethods, messengerAPIOrClass) {
if (hostObject.constructor.name != 'DOMStorage')
throw new Error('hostObject should be an instance of DOMStorage');
this.storage = hostObject;
this.messageKey = config.domStorage.messageKey;
this.window = hostObject.window;
MessageSource.prototype.init.apply(this, arguments);
}
function StorageMessageSource$addSourceSubscriber(sourceMessage) {
this.window.addEventListener('storage', this, false);
}
function StorageMessageSource$removeSourceSubscriber(sourceMessage) {
this.window.removeEventListener('storage', this, false);
}
function StorageMessageSource$postMessage(message, data) {
this.messenger.postMessageSync(message, data);
}
function StorageMessageSource$trigger(msgType, data) {
var key = this.messageKey + msgType;
data = data || {};
data[config.domStorage.messageTimestamp] = uniqueId();
_.deferMethod(this.storage, 'setItem', key, data);
}
function handleEvent(event) {
if (event.storageArea != this.storage._storage) return;
var key = this.storage._domStorageKey(event.key); if (! key) return;
var msgType = _.unPrefix(key, this.messageKey); if (! msgType) return;
var data = this.storage.getItem(key); if (! data) return;
this.dispatchMessage(msgType, data);
}
},{"../../config":42,"../../util/unique_id":70,"milo-core":84}],70:[function(require,module,exports){
'use strict';
var timestamp = Date.now()
, count = ''
, uniqueID = '' + timestamp;
function uniqueCount() {
var newTimestamp = Date.now();
uniqueID = '' + newTimestamp;
if (timestamp == newTimestamp) {
count = count === '' ? 0 : count + 1;
uniqueID += '_' + count;
} else {
timestamp = newTimestamp;
count = '';
}
return uniqueID;
}
uniqueCount.get = function() {
return uniqueID;
};
module.exports = uniqueCount;
},{}],71:[function(require,module,exports){
'use strict';
/**
* `milo.util.websocket`
**/
var Messenger = require('milo-core').Messenger
, WSMessageSource = require('./msg_src')
, WSMsgAPI = require('./msg_api');
function websocket() {
var wsMessenger = new Messenger;
var wsMsgSource = new WSMessageSource(wsMessenger, { send: 'trigger', connect: 'connect' }, new WSMsgAPI);
wsMessenger._setMessageSource(wsMsgSource);
return wsMessenger;
}
module.exports = websocket;
},{"./msg_api":72,"./msg_src":73,"milo-core":84}],72:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, MessengerAPI = miloCore.classes.MessengerAPI
, _ = miloCore.proto
, check = miloCore.util.check
, Match = check.Match;
var WSMsgAPI = _.createSubclass(MessengerAPI, 'WSMsgAPI', true);
_.extendProto(WSMsgAPI, {
translateToSourceMessage: translateToSourceMessage,
filterSourceMessage: filterSourceMessage,
createInternalData: createInternalData
});
module.exports = WSMsgAPI;
var SOCKET_MESSAGES = ['open', 'close', 'error', 'message'];
function translateToSourceMessage(message) {
return SOCKET_MESSAGES.indexOf(message) >= 0
? message
: 'message';
}
function filterSourceMessage(sourceMessage, message, msgData) {
if (SOCKET_MESSAGES.indexOf(message) >= 0) return true; // internal message is one of external messages
if (sourceMessage == 'message') {
var msgType = msgData && msgData.type;
return msgType == message; // type equals internal message
}
}
function createInternalData(sourceMessage, message, event) {
var internalData = sourceMessage == 'message'
? _.jsonParse(event.data) || event.data
: event;
return internalData;
}
},{"milo-core":84}],73:[function(require,module,exports){
'use strict';
var miloCore = require('milo-core')
, MessageSource = miloCore.classes.MessageSource
, _ = miloCore.proto
, logger = miloCore.util.logger
, uniqueId = require('../../util/unique_id')
, config = require('../../config')
, check = miloCore.util.check
, Match = check.Match;
var WSMessageSource = _.createSubclass(MessageSource, 'WSMessageSource', true);
_.extendProto(WSMessageSource, {
// implementing MessageSource interface
addSourceSubscriber: addSourceSubscriber,
removeSourceSubscriber: removeSourceSubscriber,
// class specific methods
handleEvent: WSMessageSource$handleEvent,
connect: WSMessageSource$connect,
trigger: WSMessageSource$trigger
});
module.exports = WSMessageSource;
function WSMessageSource$connect(options) {
this._options = options = options || {};
var host = options.host || window.location.host.replace(/:.*/, '')
, port = options.port || '8080';
var self = this;
if (this._ws) {
// TODO should unsubscribe differently
this._ws.onopen = this.ws.onmessage = this.ws.onclose = this.ws.onerror = undefined;
this._ws.close();
}
this._ws = new WebSocket('ws://' + host + ':' + port);
// TODO reconnect
}
function addSourceSubscriber (sourceMessage) {
_wsSubscriberMethod.call(this, 'addEventListener', sourceMessage);
}
function removeSourceSubscriber (sourceMessage) {
_wsSubscriberMethod.call(this, 'removeEventListener', sourceMessage);
}
function _wsSubscriberMethod (method, sourceMessage) {
if (!this._ws) return logger.error('websocket is not created');
this._ws[method](sourceMessage, this);
}
// event dispatcher - as defined by Event DOM API
function WSMessageSource$handleEvent (event) {
this.dispatchMessage(event.type, event);
}
function WSMessageSource$trigger (msg, data, callback) {
if (!this._ws) return logger.error('websocket is not created');
data = data || {};
data.type = msg;
var self = this;
if (callback) {
data.callbackCorrId = uniqueId();
var interval = _.delay(onTimeout, config.websocket.rpc.timeout);
toggleRpcSubscription('once', data.callbackCorrId);
}
this._ws.send(JSON.stringify(data));
function onTimeout() {
toggleRpcSubscription('off', data.callbackCorrId);
callback(new Error('websocket rpc: timeout'));
}
function onResponse(msg, msgData) {
clearInterval(interval);
if (typeof msgData == 'object') {
var err = msgData.error ? new Error(msgData.error) : null;
callback(err, msgData.data);
} else
callback(new Error('websocket rpc: invalid response data'), msgData);
}
function toggleRpcSubscription(onOff, corrId) {
self.messenger[onOff](config.websocket.rpc.responsePrefix + corrId, onResponse);
}
}
},{"../../config":42,"../../util/unique_id":70,"milo-core":84}],74:[function(require,module,exports){
;(function(){
// This would be the place to edit if you want a different
// Base32 implementation
var alphabet = '0123456789abcdefghjkmnpqrtuvwxyz'
var alias = { o:0, i:1, l:1, s:5 }
/**
* Build a lookup table and memoize it
*
* Return an object that maps a character to its
* byte value.
*/
var lookup = function() {
var table = {}
// Invert 'alphabet'
for (var i = 0; i < alphabet.length; i++) {
table[alphabet[i]] = i
}
// Splice in 'alias'
for (var key in alias) {
if (!alias.hasOwnProperty(key)) continue
table[key] = table['' + alias[key]]
}
lookup = function() { return table }
return table
}
/**
* A streaming encoder
*
* var encoder = new base32.Encoder()
* var output1 = encoder.update(input1)
* var output2 = encoder.update(input2)
* var lastoutput = encode.update(lastinput, true)
*/
function Encoder() {
var skip = 0 // how many bits we will skip from the first byte
var bits = 0 // 5 high bits, carry from one byte to the next
this.output = ''
// Read one byte of input
// Should not really be used except by "update"
this.readByte = function(byte) {
// coerce the byte to an int
if (typeof byte == 'string') byte = byte.charCodeAt(0)
if (skip < 0) { // we have a carry from the previous byte
bits |= (byte >> (-skip))
} else { // no carry
bits = (byte << skip) & 248
}
if (skip > 3) {
// not enough data to produce a character, get us another one
skip -= 8
return 1
}
if (skip < 4) {
// produce a character
this.output += alphabet[bits >> 3]
skip += 5
}
return 0
}
// Flush any remaining bits left in the stream
this.finish = function(check) {
var output = this.output + (skip < 0 ? alphabet[bits >> 3] : '') + (check ? '$' : '')
this.output = ''
return output
}
}
/**
* Process additional input
*
* input: string of bytes to convert
* flush: boolean, should we flush any trailing bits left
* in the stream
* returns: a string of characters representing 'input' in base32
*/
Encoder.prototype.update = function(input, flush) {
for (var i = 0; i < input.length; ) {
i += this.readByte(input[i])
}
// consume all output
var output = this.output
this.output = ''
if (flush) {
output += this.finish()
}
return output
}
// Functions analogously to Encoder
function Decoder() {
var skip = 0 // how many bits we have from the previous character
var byte = 0 // current byte we're producing
this.output = ''
// Consume a character from the stream, store
// the output in this.output. As before, better
// to use update().
this.readChar = function(char) {
if (typeof char != 'string'){
if (typeof char == 'number') {
char = String.fromCharCode(char)
}
}
char = char.toLowerCase()
var val = lookup()[char]
if (typeof val == 'undefined') {
// character does not exist in our lookup table
return // skip silently. An alternative would be:
// throw Error('Could not find character "' + char + '" in lookup table.')
}
val <<= 3 // move to the high bits
byte |= val >>> skip
skip += 5
if (skip >= 8) {
// we have enough to preduce output
this.output += String.fromCharCode(byte)
skip -= 8
if (skip > 0) byte = (val << (5 - skip)) & 255
else byte = 0
}
}
this.finish = function(check) {
var output = this.output + (skip < 0 ? alphabet[bits >> 3] : '') + (check ? '$' : '')
this.output = ''
return output
}
}
Decoder.prototype.update = function(input, flush) {
for (var i = 0; i < input.length; i++) {
this.readChar(input[i])
}
var output = this.output
this.output = ''
if (flush) {
output += this.finish()
}
return output
}
/** Convenience functions
*
* These are the ones to use if you just have a string and
* want to convert it without dealing with streams and whatnot.
*/
// String of data goes in, Base32-encoded string comes out.
function encode(input) {
var encoder = new Encoder()
var output = encoder.update(input, true)
return output
}
// Base32-encoded string goes in, decoded data comes out.
function decode(input) {
var decoder = new Decoder()
var output = decoder.update(input, true)
return output
}
var base32 = {
Decoder: Decoder,
Encoder: Encoder,
encode: encode,
decode: decode
}
if (typeof window !== 'undefined') {
// we're in a browser - OMG!
window.base32 = base32
}
if (typeof module !== 'undefined' && module.exports) {
// nodejs/browserify
module.exports = base32
}
})();
},{}],75:[function(require,module,exports){
// not implemented
// The reason for having an empty file and not throwing is to allow
// untraditional implementation of this module.
},{}],76:[function(require,module,exports){
'use strict';
var _ = require('protojs')
, check = require('../util/check')
, Match = check.Match
, config = require('../config');
module.exports = Mixin;
/**
* `milo.classes.Mixin` - an abstract Mixin class.
* Can be subclassed using:
* ```
* var MyMixin = _.createSubclass(milo.classes.Mixin, 'MyMixin');
* ```
*
* Mixin pattern is also used, but Mixin in milo is implemented as a separate object that is stored on the property of the host object and can create proxy methods on the host object if required.
* Classes [Messenger](../messenger/index.js.html) and [MessageSource](../messenger/m_source.js.html) are subclasses of Mixin abstract class. `this` in proxy methods refers to Mixin instance, the reference to the host object is `this._hostObject`.
*
* @param {Object} hostObject Optional object where a Mixin instance will be stored on. It is used to proxy methods and also to find the reference when it is needed for host object implementation.
* @param {Object} proxyMethods Optional map of proxy method names as keys and Mixin methods names as values, so proxied methods can be renamed to avoid name-space conflicts if two different Mixin instances with the same method names are put on the object
* @param {List} arguments all constructor arguments will be passed to init method of Mixin subclass together with hostObject and proxyMethods
* @return {Mixin}
*/
function Mixin(hostObject, proxyMethods) { // , other args - passed to init method
check(hostObject, Match.Optional(Match.OneOf(Object, Function)));
// store hostObject
_.defineProperty(this, '_hostObject', hostObject);
// proxy methods to hostObject
if (proxyMethods)
this._createProxyMethods(proxyMethods);
// calling init if it is defined in the class
if (this.init)
this.init.apply(this, arguments);
}
/**
* ####Mixin instance methods####
* These methods are called by constructor, they are not to be called from subclasses.
*
* - [_createProxyMethod](#_createProxyMethod)
* - [_createProxyMethods](#_createProxyMethods)
*/
_.extendProto(Mixin, {
_createProxyMethod: _createProxyMethod, // deprecated, should not be used
_createProxyMethods: _createProxyMethods // deprecated, should not be used
});
/**
* ####Mixin class methods####
* These method should be called in host class declaration.
*
* - [useWith](#Mixin$$useWith)
*/
_.extend(Mixin, {
useWith: Mixin$$useWith
});
/**
* Creates a proxied method of Mixin subclass on host object.
*
* @param {String} mixinMethodName name of method in Mixin subclass
* @param {String} proxyMethodName name of created proxy method on host object
* @param {Object} hostObject Optional reference to the host object; if not specified the host object passed to constructor wil be used. It allows to use the same instance of Mixin on two host objects.
*/
function _createProxyMethod(proxyMethodName, mixinMethodName, hostObject) {
hostObject = hostObject || this._hostObject;
// Mixin class does not allow shadowing methods that exist on the host object
if (hostObject[proxyMethodName])
throw new Error('method ' + proxyMethodName +
' already defined in host object');
var method = this[mixinMethodName]
check(method, Function);
// Bind proxied Mixin's method to Mixin instance
var boundMethod = method.bind(this);
_.defineProperty(hostObject, proxyMethodName, boundMethod, _.WRIT);
}
/**
* Creates proxied methods of Mixin subclass on host object.
*
* @param {Hash[String]|Array[String]} proxyMethods map of names of methods, key - proxy method name, value - mixin method name. Can be array.
* @param {Object} hostObject an optional reference to the host object; if not specified the host object passed to constructor wil be used. It allows to use the same instance of Mixin on two host objects.
*/
function _createProxyMethods(proxyMethods, hostObject) {
check(proxyMethods, Match.Optional(Match.OneOf([String], Match.ObjectHash(String))));
// creating and binding proxy methods on the host object
if (Array.isArray(proxyMethods))
proxyMethods.forEach(function(methodName) {
// method called this way to allow using _createProxyMethods with objects
// that are not inheriting from Mixin
_createProxyMethod.call(this, methodName, methodName, hostObject);
}, this);
else
_.eachKey(proxyMethods, function(mixinMethodName, proxyMethodName) {
// method called this way to allow using _createProxyMethods with objects
// that are not inheriting from Mixin
_createProxyMethod.call(this, proxyMethodName, mixinMethodName, hostObject);
}, this);
}
/**
* Sets mixin instance property name on the host class
* Can be called only once
*
* @private
* @param {Function} this Mixin subclass (not instance)
* @param {Function} hostClass
* @param {String} instanceKey
*/
function Mixin_setInstanceKey(hostClass, method, instanceKey) {
check(hostClass, Function);
check(instanceKey, Match.IdentifierString);
var prop = config.mixin.instancePropertiesMap
, instanceKeys = hostClass[prop] = hostClass[prop] || {};
if (instanceKeys[method.name])
throw new Error('Mixin: instance property for method with name '
+ method.name + ' is already set');
instanceKeys[method.name] = instanceKey;
}
/**
* Adds method of Mixin subclass to host class prototype.
*
* @private
* @param {Function} this Mixin subclass (not instance)
* @param {String} mixinMethodName name of method in Mixin subclass
* @param {String} hostMethodName (optional) name of created proxy method on host object, same if not specified
* @param {Object} hostObject object class, must be specified as the last parameter (2nd or 3rd)
*/
function Mixin_addMethod(hostClass, instanceKey, mixinMethodName, hostMethodName) {
var method = this.prototype[mixinMethodName];
check(method, Function);
var wrappedMethod = _wrapMixinMethod.call(this, method);
_.defineProperty(hostClass.prototype, hostMethodName, wrappedMethod, _.WRIT);
Mixin_setInstanceKey(hostClass, method, instanceKey)
}
/**
* Returns method that will be exposed on the host class prototype
*
* @private
* @param {Function} this Mixin subclass (not instance)
* @return {Function}
*/
function _wrapMixinMethod(method) {
return function() { // ,... arguments
var mixinInstance = _getMixinInstance.call(this, method.name);
return method.apply(mixinInstance, arguments);
}
}
/**
* Returns the reference to the instance of mixin subclass.
* This method is used when methods are exposed on the host class prototype (using addMehtods) rather than on host instance.
* Subclasses should not use this methods - whenever subclass method is exposed on the prototype it will be wrapped to set correct context for the subclass method.
*
* @private
* @return {Object}
*/
function _getMixinInstance(methodName) {
if (this instanceof Mixin) return this;
var instanceKeys = this.constructor[config.mixin.instancePropertiesMap]
, mixinProp = instanceKeys[methodName]
, mixin = this[mixinProp];
if (!mixin) throw new Error('Mixin ' + mixinProp + ' does not exist');
return mixin;
}
/**
* Adds methods of Mixin subclass to host class prototype.
*
* @param {Function} this Mixin subclass (not instance)
* @param {Object} hostClass host object class; must be specified.
* @param {String} instanceKey the name of the property the host class instance will store mixin instance on
* @param {Hash[String]|Array[String]} mixinMethods map of names of methods, key - host method name, value - mixin method name. Can be array.
*/
function Mixin$$useWith(hostClass, instanceKey, mixinMethods) {
check(mixinMethods, Match.Optional(Match.OneOf([String], Match.ObjectHash(String))));
if (Array.isArray(mixinMethods))
mixinMethods.forEach(function(methodName) {
Mixin_addMethod.call(this, hostClass, instanceKey, methodName, methodName);
}, this);
else
_.eachKey(mixinMethods, function(mixinMethodName, hostMethodName) {
Mixin_addMethod.call(this, hostClass, instanceKey, mixinMethodName, hostMethodName);
}, this);
}
},{"../config":78,"../util/check":95,"protojs":117}],77:[function(require,module,exports){
'use strict';
// <a name="classes"></a>
// milo.classes
// -----------
// This module contains foundation classes
var classes = {
Mixin: require('./abstract/mixin'),
MessageSource: require('./messenger/m_source'),
MessengerMessageSource: require('./messenger/msngr_source'),
MessengerAPI: require('./messenger/m_api'),
MessengerRegexpAPI: require('./messenger/m_api_rx')
};
module.exports = classes;
},{"./abstract/mixin":76,"./messenger/m_api":80,"./messenger/m_api_rx":81,"./messenger/m_source":82,"./messenger/msngr_source":83}],78:[function(require,module,exports){
'use strict';
var _ = require('protojs');
module.exports = config;
function config(options) {
_.deepExtend(config, options);
}
config({
mixin: {
instancePropertiesMap: '___mixin_instances'
},
check: false,
debug: false
});
},{"protojs":117}],79:[function(require,module,exports){
'use strict';
var Mixin = require('../abstract/mixin')
, MessageSource = require('./m_source')
, _ = require('protojs')
, check = require('../util/check')
, Match = check.Match;
// in browser code can be replaced with milo.util.zeroTimeout using useSetTimeout method
var _setTimeout = setTimeout;
/**
* `milo.Messenger`
* A generic Messenger class that is used for all kinds of messaging in milo. It is subclassed from [Mixin](../abstract/mixin.js.html) and it proxies its methods to the host object for convenience.
* All facets and components have messenger attached to them. Messenger class interoperates with [MessageSource](./m_source.js.html) class that connects the messenger to some external source of messages (e.g., DOM events) and [MessengerAPI](./m_api.js.html) class that allows to define higher level messages than messages that exist on the source.
* Messenger class is used internally in milo and can be used together with any objects/classes in the application.
* milo also defines a global messenger [milo.mail](../mail/index.js.html) that dispatches `domready` event and can be used for any application wide messaging.
* To initialize your app after DOM is ready use:
* ```
* milo.mail.on('domready', function() {
* // application starts
* });
* ```
* or the following shorter form of the same:
* ```
* milo(function() {
* // application starts
* });
* ```
*/
var Messenger = _.createSubclass(Mixin, 'Messenger');
var messagesSplitRegExp = Messenger.messagesSplitRegExp = /\s*(?:\,|\s)\s*/;
/**
* ####Messenger instance methods####
*
* - [init](#init)
* - [on](#Messenger$on) (alias - onMessage, deprecated)
* - [off](#Messenger$off) (alias - offMessage, deprecated)
* - [onMessages](#onMessages)
* - [offMessages](#offMessages)
* - [once](#once)
* - [onceSync](#onceSync)
* - [postMessage](#postMessage)
* - [getSubscribers](#getSubscribers)
*
* "Private" methods
*
* - [_chooseSubscribersHash](#_chooseSubscribersHash)
* - [_registerSubscriber](#_registerSubscriber)
* - [_removeSubscriber](#_removeSubscriber)
* - [_removeAllSubscribers](#_removeAllSubscribers)
* - [_callPatternSubscribers](#_callPatternSubscribers)
* - [_callSubscribers](#_callSubscribers)
* - [_setMessageSource](#_setMessageSource)
* - [getMessageSource](#getMessageSource)
*/
_.extendProto(Messenger, {
init: init, // called by Mixin (superclass)
destroy: Messenger$destroy,
on: Messenger$on,
once: Messenger$once,
onceSync: Messenger$onceSync,
onSync: Messenger$onSync,
onAsync: Messenger$onAsync,
onMessage: Messenger$on, // deprecated
off: Messenger$off,
offMessage: Messenger$off, // deprecated
onMessages: onMessages,
offMessages: offMessages,
offAll: Messenger$offAll,
postMessage: postMessage,
postMessageSync: postMessageSync,
getSubscribers: getSubscribers,
getMessageSource: getMessageSource,
_chooseSubscribersHash: _chooseSubscribersHash,
_registerSubscriber: _registerSubscriber,
_removeSubscriber: _removeSubscriber,
_removeAllSubscribers: _removeAllSubscribers,
_callPatternSubscribers: _callPatternSubscribers,
_callSubscribers: _callSubscribers,
_callSubscriber: _callSubscriber,
_setMessageSource: _setMessageSource
});
/**
* A default map of proxy methods used by ComponentFacet and Component classes to pass to Messenger when it is instantiated.
* This map is for convenience only, it is NOT used internally by Messenger, a host class should pass it for methods to be proxied this way.
*/
Messenger.defaultMethods = {
on: 'on',
onSync: 'onSync',
once: 'once',
onceSync: 'onceSync',
off: 'off',
onMessages: 'onMessages',
offMessages: 'offMessages',
postMessage: 'postMessage',
postMessageSync: 'postMessageSync',
getSubscribers: 'getSubscribers'
};
/**
* Messenger class (static) methods
* - [useSetTimeout](#useSetTimeout)
*/
Messenger.useSetTimeout = useSetTimeout;
module.exports = Messenger;
Messenger.subscriptions = [];
/**
* Messenger instance method
* Initializes Messenger. Method is called by Mixin class constructor.
* See [on](#Messenger$on) method, [Messenger](#Messenger) class above and [MessageSource](./m_source.js.html) class.
*
* @param {Object} hostObject Optional object that stores the messenger on one of its properties. It is used to proxy methods of messenger and also as a context for subscribers when they are called by the Messenger. See `on` method.
* @param {Object} proxyMethods Optional map of method names; key - proxy method name, value - messenger's method name.
* @param {MessageSource} messageSource Optional messageSource linked to the messenger. If messageSource is supplied, the reference to the messenger will stored on its 'messenger' property
*/
function init(hostObject, proxyMethods, messageSource) {
// hostObject and proxyMethods are used in Mixin and checked there
if (messageSource)
this._setMessageSource(messageSource);
_initializeSubscribers.call(this);
}
function _initializeSubscribers() {
_.defineProperties(this, {
_messageSubscribers: {},
_patternMessageSubscribers: {},
}, _.CONF);
}
/**
* Destroys messenger. Maybe needs to unsubscribe all subscribers
*/
function Messenger$destroy() {
this.offAll();
var messageSource = this.getMessageSource();
if (messageSource)
messageSource.destroy();
}
/**
* Messenger instance method.
* Registers a subscriber function for a certain message(s).
* This method returns `true` if the subscription was successful. It can be unsuccessful if the passed subscriber has already been subscribed to this message type - double subscription never happens and it is safe to subscribe again - no error or warning is thrown or logged.
* Subscriber is passed two parameters: `message` (string) and `data` (object). Data object is supplied when message is dispatched, Messenger itself adds nothing to it. For example, [events facet](../components/c_facets/Events.js.html) sends actual DOM event when it posts message.
* Usage:
* ```
* // subscribes onMouseUpDown to two DOM events on component via events facet.
* myComp.events.on('mousedown mouseup', onMouseUpDown);
* function onMouseUpDown(eventType, event) {
* // ...
* }
*
* myComp.data.on(/.+/, function(msg, data) {
* logger.debug(msg, data);
* }); // subscribes anonymous function to all non-empty messages on data facet
* // it will not be possible to unsubscribe anonymous subscriber separately,
* // but myComp.data.off(/.+/) will unsubscribe it
* ```
* If messenger has [MessageSource](./m_source.js.html) attached to it, MessageSource will be notified when the first subscriber for a given message is added, so it can subscribe to the source.
* [Components](../components/c_class.js.html) and [facets](../components/c_facet.js.html) change this method name to `on` when they proxy it.
* See [postMessage](#postMessage).
*
* @param {String|Array[String]|RegExp} messages Message types that should envoke the subscriber.
* If string is passed, it can be a sigle message or multiple message types separated by whitespace with optional commas.
* If an array of strings is passed, each string is a message type to subscribe for.
* If a RegExp is passed, the subscriber will be envoked when the message dispatched on the messenger matches the pattern (or IS the RegExp with identical pattern).
* Pattern subscriber does NOT cause any subscription to MessageSource, it only captures messages that are already subscribed to with precise message types.
* @param {Function|Object} subscriber Message subscriber - a function that will be called when the message is dispatched on the messenger (usually via proxied postMessage method of host object).
* If hostObject was supplied to Messenger constructor, hostObject will be the context (the value of this) for the subscriber envocation.
* Subscriber can also be an object with properties `subscriber` (function) and `context` ("this" value when subscriber is called)
* @return {Boolean}
*/
function Messenger$on(messages, subscriber) {
return _Messenger_onWithOptions.call(this, messages, subscriber);
}
function Messenger$once(messages, subscriber) {
return _Messenger_onWithOptions.call(this, messages, subscriber, { dispatchTimes: 1 });
}
function Messenger$onceSync(messages, subscriber) {
return _Messenger_onWithOptions.call(this, messages, subscriber, { dispatchTimes: 1, sync: true });
}
function Messenger$onSync(messages, subscriber) {
return _Messenger_onWithOptions.call(this, messages, subscriber, { sync: true });
}
function Messenger$onAsync(messages, subscriber) {
return _Messenger_onWithOptions.call(this, messages, subscriber, { sync: false });
}
function _Messenger_onWithOptions(messages, subscriber, options) {
check(messages, Match.OneOf(String, [String], RegExp));
check(subscriber, Match.OneOf(Function, {
subscriber: Function,
context: Match.Any,
options: Match.Optional(Object),
}));
if (typeof subscriber == 'function') {
subscriber = {
subscriber: subscriber,
context: this._hostObject,
};
}
if (options) {
subscriber.options = subscriber.options || {};
_.extend(subscriber.options, options);
}
return _Messenger_on.call(this, messages, subscriber);
}
function _Messenger_on(messages, subscriber) {
_.defineProperty(subscriber, '__messages', messages);
return _eachMessage.call(this, '_registerSubscriber', messages, subscriber);
}
function _eachMessage(methodName, messages, subscriber) {
if (typeof messages == 'string')
messages = messages.split(messagesSplitRegExp);
var subscribersHash = this._chooseSubscribersHash(messages);
if (messages instanceof RegExp)
return this[methodName](subscribersHash, messages, subscriber);
else {
var changed = false;
messages.forEach(function(message) {
var subscriptionChanged = this[methodName](subscribersHash, message, subscriber);
changed = changed || subscriptionChanged;
}, this);
return changed;
}
}
/**
* "Private" Messenger instance method
* It is called by [on](#Messenger$on) to register subscriber for one message type.
* Returns `true` if this subscriber is not yet registered for this type of message.
* If messenger has [MessageSource](./m_source.js.html) attached to it, MessageSource will be notified when the first subscriber for a given message is added.
*
* @private
* @param {Object} subscribersHash The map of subscribers determined by [on](#Messenger$on) based on Message type, can be `this._patternMessageSubscribers` or `this._messageSubscribers`
* @param {String} message Message type
* @param {Function|Object} subscriber Subscriber function to be added or object with properties `subscriber` (function) and `context` (value of "this" when subscriber is called)
* @return {Boolean}
*/
function _registerSubscriber(subscribersHash, message, subscriber) {
if (! (subscribersHash[message] && subscribersHash[message].length)) {
subscribersHash[message] = [];
if (message instanceof RegExp)
subscribersHash[message].pattern = message;
if (this._messageSource)
this._messageSource.onSubscriberAdded(message);
var noSubscribers = true;
}
var msgSubscribers = subscribersHash[message];
var notYetRegistered = noSubscribers || _indexOfSubscriber.call(this, msgSubscribers, subscriber) == -1;
if (notYetRegistered)
msgSubscribers.push(subscriber);
return notYetRegistered;
}
/**
* Finds subscriber index in the list
*
* @param {Array[Function|Object]} list list of subscribers
* @param {Function|Object} subscriber subscriber function or object with properties `subscriber` (function) and `context` ("this" object)
*/
function _indexOfSubscriber(list, subscriber) {
var self = this;
return _.findIndex(list, function(subscr){
return subscriber.subscriber == subscr.subscriber
&& subscriber.context == subscr.context
});
}
/**
* Messenger instance method.
* Subscribes to multiple messages passed as map together with subscribers.
* Usage:
* ```
* myComp.events.onMessages({
* 'mousedown': onMouseDown,
* 'mouseup': onMouseUp
* });
* function onMouseDown(eventType, event) {}
* function onMouseUp(eventType, event) {}
* ```
* Returns map with the same keys (message types) and boolean values indicating whether particular subscriber was added.
* It is NOT possible to add pattern subscriber using this method, as although you can use RegExp as the key, JavaScript will automatically convert it to string.
*
* @param {Object[Function]} messageSubscribers Map of message subscribers to be added
* @return {Object[Boolean]}
*/
function onMessages(messageSubscribers) {
check(messageSubscribers, Match.ObjectHash(Match.OneOf(Function, { subscriber: Function, context: Match.Any })));
var notYetRegisteredMap = _.mapKeys(messageSubscribers, function(subscriber, messages) {
return this.on(messages, subscriber);
}, this);
return notYetRegisteredMap;
}
/**
* Messenger instance method.
* Removes a subscriber for message(s). Removes all subscribers for the message if subscriber isn't passed.
* This method returns `true` if the subscriber was registered. No error or warning is thrown or logged if you remove subscriber that was not registered.
* [Components](../components/c_class.js.html) and [facets](../components/c_facet.js.html) change this method name to `off` when they proxy it.
* Usage:
* ```
* // unsubscribes onMouseUpDown from two DOM events.
* myComp.events.off('mousedown mouseup', onMouseUpDown);
* ```
* If messenger has [MessageSource](./m_source.js.html) attached to it, MessageSource will be notified when the last subscriber for a given message is removed and there is no more subscribers for this message.
*
* @param {String|Array[String]|RegExp} messages Message types that a subscriber should be removed for.
* If string is passed, it can be a sigle message or multiple message types separated by whitespace with optional commas.
* If an array of strings is passed, each string is a message type to remove a subscriber for.
* If a RegExp is passed, the pattern subscriber will be removed.
* RegExp subscriber does NOT cause any subscription to MessageSource, it only captures messages that are already subscribed to with precise message types.
* @param {Function} subscriber Message subscriber - Optional function that will be removed from the list of subscribers for the message(s). If subscriber is not supplied, all subscribers will be removed from this message(s).
* @return {Boolean}
*/
function Messenger$off(messages, subscriber) {
check(messages, Match.OneOf(String, [String], RegExp));
check(subscriber, Match.Optional(Match.OneOf(Function, {
subscriber: Function,
context: Match.Any,
options: Match.Optional(Object),
// __messages: Match.Optional(Match.OneOf(String, [String], RegExp))
})));
return _Messenger_off.call(this, messages, subscriber);
}
function _Messenger_off(messages, subscriber) {
return _eachMessage.call(this, '_removeSubscriber', messages, subscriber);
}
/**
* "Private" Messenger instance method
* It is called by [off](#Messenger$off) to remove subscriber for one message type.
* Returns `true` if this subscriber was registered for this type of message.
* If messenger has [MessageSource](./m_source.js.html) attached to it, MessageSource will be notified when the last subscriber for a given message is removed and there is no more subscribers for this message.
*
* @private
* @param {Object} subscribersHash The map of subscribers determined by [off](#Messenger$off) based on message type, can be `this._patternMessageSubscribers` or `this._messageSubscribers`
* @param {String} message Message type
* @param {Function} subscriber Subscriber function to be removed
* @return {Boolean}
*/
function _removeSubscriber(subscribersHash, message, subscriber) {
var msgSubscribers = subscribersHash[message];
if (! msgSubscribers || ! msgSubscribers.length)
return false; // nothing removed
if (subscriber) {
if (typeof subscriber == 'function')
subscriber = { subscriber: subscriber, context: this._hostObject };
var subscriberIndex = _indexOfSubscriber.call(this, msgSubscribers, subscriber);
if (subscriberIndex == -1)
return false; // nothing removed
msgSubscribers.splice(subscriberIndex, 1);
if (! msgSubscribers.length)
this._removeAllSubscribers(subscribersHash, message);
} else
this._removeAllSubscribers(subscribersHash, message);
return true; // subscriber(s) removed
}
/**
* "Private" Messenger instance method
* It is called by [_removeSubscriber](#_removeSubscriber) to remove all subscribers for one message type.
* If messenger has [MessageSource](./m_source.js.html) attached to it, MessageSource will be notified that all message subscribers were removed so it can unsubscribe from the source.
*
* @private
* @param {Object} subscribersHash The map of subscribers determined by [off](#Messenger$off) based on message type, can be `this._patternMessageSubscribers` or `this._messageSubscribers`
* @param {String} message Message type
*/
function _removeAllSubscribers(subscribersHash, message) {
delete subscribersHash[message];
if (this._messageSource && typeof message == 'string')
this._messageSource.onSubscriberRemoved(message);
}
/**
* Messenger instance method.
* Unsubscribes from multiple messages passed as map together with subscribers.
* Returns map with the same keys (message types) and boolean values indicating whether particular subscriber was removed.
* If a subscriber for one of the messages is not supplied, all subscribers for this message will be removed.
* Usage:
* ```
* myComp.events.offMessages({
* 'mousedown': onMouseDown,
* 'mouseup': onMouseUp,
* 'click': undefined // all subscribers to this message will be removed
* });
* ```
* It is NOT possible to remove pattern subscriber(s) using this method, as although you can use RegExp as the key, JavaScript will automatically convert it to string.
*
* @param {Object[Function]} messageSubscribers Map of message subscribers to be removed
* @return {Object[Boolean]}
*/
function offMessages(messageSubscribers) {
check(messageSubscribers, Match.ObjectHash(Match.Optional(Match.OneOf(Function, { subscriber: Function, context: Match.Any }))));
var subscriberRemovedMap = _.mapKeys(messageSubscribers, function(subscriber, messages) {
return this.off(messages, subscriber);
}, this);
return subscriberRemovedMap;
}
/**
* Unsubscribes all subscribers
*/
function Messenger$offAll() {
_offAllSubscribers.call(this, this._patternMessageSubscribers);
_offAllSubscribers.call(this, this._messageSubscribers);
}
function _offAllSubscribers(subscribersHash) {
_.eachKey(subscribersHash, function(subscribers, message) {
this._removeAllSubscribers(subscribersHash, message);
}, this);
}
// TODO - send event to messageSource
/**
* Messenger instance method.
* Dispatches the message calling all subscribers registered for this message and, if the message is a string, calling all pattern subscribers when message matches the pattern.
* Each subscriber is passed the same parameters that are passed to theis method.
* The context of the subscriber envocation is set to the host object (`this._hostObject`) that was passed to the messenger constructor.
* Subscribers are called in the next tick ("asynchronously") apart from those that were subscribed with `onSync` (or that have `options.sync == true`).
*
* @param {String|RegExp} message message to be dispatched
* If the message is a string, the subscribers registered with exactly this message will be called and also pattern subscribers registered with the pattern that matches the dispatched message.
* If the message is RegExp, only the subscribers registered with exactly this pattern will be called.
* @param {Any} data data that will be passed to the subscriber as the second parameter. Messenger does not modify this data in any way.
* @param {Function} callback optional callback to pass to subscriber
* @param {Boolean} _synchronous if true passed, subscribers will be envoked synchronously apart from those that have `options.sync == false`. This parameter should not be used, instead postMessageSync should be used.
*/
function postMessage(message, data, callback, _synchronous) {
check(message, Match.OneOf(String, RegExp));
check(callback, Match.Optional(Function));
var subscribersHash = this._chooseSubscribersHash(message);
var msgSubscribers = subscribersHash[message];
this._callSubscribers(message, data, callback, msgSubscribers, _synchronous);
if (typeof message == 'string')
this._callPatternSubscribers(message, data, callback, msgSubscribers, _synchronous);
}
/**
* Same as postMessage apart from envoking subscribers synchronously, apart from those subscribed with `onAsync` (or with `options.sync == false`).
*
* @param {String|RegExp} message
* @param {Any} data
* @param {Function} callback
*/
function postMessageSync(message, data, callback) {
this.postMessage(message, data, callback, true);
}
/**
* "Private" Messenger instance method
* Envokes pattern subscribers with the pattern that matches the message.
* The method is called by [postMessage](#postMessage) - see more information there.
*
* @private
* @param {String} message message to be dispatched. Pattern subscribers registered with the pattern that matches the dispatched message will be called.
* @param {Any} data data that will be passed to the subscriber as the second parameter. Messenger does not modify this data in any way.
* @param {Function} callback optional callback to pass to subscriber
* @param {Array[Function|Object]} calledMsgSubscribers array of subscribers already called, they won't be called again if they are among pattern subscribers.
*/
function _callPatternSubscribers(message, data, callback, calledMsgSubscribers, _synchronous) {
_.eachKey(this._patternMessageSubscribers,
function(patternSubscribers) {
var pattern = patternSubscribers.pattern;
if (pattern.test(message)) {
if (calledMsgSubscribers) {
var patternSubscribers = patternSubscribers.filter(function(subscriber) {
var index = _indexOfSubscriber.call(this, calledMsgSubscribers, subscriber);
return index == -1;
});
}
this._callSubscribers(message, data, callback, patternSubscribers, _synchronous);
}
}
, this);
}
/**
* "Private" Messenger instance method
* Envokes subscribers from the passed list.
* The method is called by [postMessage](#postMessage) and [_callPatternSubscribers](#_callPatternSubscribers).
*
* @private
* @param {String} message message to be dispatched, passed to subscribers as the first parameter.
* @param {Any} data data that will be passed to the subscriber as the second parameter. Messenger does not modify this data in any way.
* @param {Array[Function|Object]} msgSubscribers the array of message subscribers to be called. Each subscriber is called with the host object (see Messenger constructor) as the context.
* @param {Function} callback optional callback to pass to subscriber
*/
function _callSubscribers(message, data, callback, msgSubscribers, _synchronous) {
if (msgSubscribers && msgSubscribers.length) {
// cloning is necessary as some of the subscribers
// can be unsubscribed during the dispatch
// so this array would change in the process
msgSubscribers = msgSubscribers.slice();
msgSubscribers.forEach(function(subscriber) {
this._callSubscriber(subscriber, message, data, callback, _synchronous);
}, this);
}
}
function _callSubscriber(subscriber, message, data, callback, _synchronous) {
var syncSubscriber = subscriber.options && subscriber.options.sync
, synchro = (_synchronous && syncSubscriber !== false)
|| syncSubscriber;
var dispatchTimes = subscriber.options && subscriber.options.dispatchTimes;
if (dispatchTimes) {
if (dispatchTimes <= 1) {
var messages = subscriber.__messages;
this.off(messages, subscriber);
} else if (dispatchTimes > 1)
subscriber.options.dispatchTimes--;
}
if (synchro)
subscriber.subscriber.call(subscriber.context, message, data, callback);
else
_setTimeout(function() { subscriber.subscriber.call(subscriber.context, message, data, callback); }, 0);
}
/**
* Replace setTimeout with another function (e.g. setImmediate in node or milo.util.zeroTimeout in browser)
*
* @param {Function} setTimeoutFunc function to use to delay execution
*/
function useSetTimeout(setTimeoutFunc) {
_setTimeout = setTimeoutFunc;
}
/**
* Messenger instance method.
* Returns the array of subscribers that would be called if the message were dispatched.
* If `includePatternSubscribers === false`, pattern subscribers with matching patters will not be included (by default they are included).
* If there are no subscribers to the message, `undefined` will be returned, not an empty array, so it is safe to use the result in boolean tests.
*
* @param {String|RegExp} message Message to get subscribers for.
* If the message is RegExp, only pattern subscribers registered with exactly this pattern will be returned.
* If the message is String, subscribers registered with the string messages and pattern subscribers registered with matching pattern will be returned (unless the second parameter is false).
* @param {Boolean} includePatternSubscribers Optional false to prevent inclusion of patter subscribers, by default they are included.
* @return {Array|undefined}
*/
function getSubscribers(message, includePatternSubscribers) {
check(message, Match.OneOf(String, RegExp));
var subscribersHash = this._chooseSubscribersHash(message);
var msgSubscribers = subscribersHash[message]
? [].concat(subscribersHash[message])
: [];
// pattern subscribers are incuded by default
if (includePatternSubscribers !== false && typeof message == 'string') {
_.eachKey(this._patternMessageSubscribers,
function(patternSubscribers) {
var pattern = patternSubscribers.pattern;
if (patternSubscribers && patternSubscribers.length
&& pattern.test(message))
_.appendArray(msgSubscribers, patternSubscribers);
}
);
}
// return undefined if there are no subscribers
return msgSubscribers.length
? msgSubscribers
: undefined;
}
/**
* "Private" Messenger instance method
* Returns the map of subscribers for a given message type.
*
* @private
* @param {String|RegExp} message Message to choose the map of subscribers for
* @return {Object[Function]}
*/
function _chooseSubscribersHash(message) {
return message instanceof RegExp
? this._patternMessageSubscribers
: this._messageSubscribers;
}
/**
* Messenger instance method
* Sets [MessageSource](./m_source.js.html) for the messenger also setting the reference to the messenger in the MessageSource.
* MessageSource can be passed to message constructor; this method allows to set it at a later time. For example, the subclasses of [ComponentFacet](../components/c_facet.js.html) use this method to set different MessageSource'es in the messenger that is created by ComponentFacet.
* Currently the method is implemented in such way that it can be called only once - MessageSource cannot be changed after this method is called.
*
* @param {MessageSource} messageSource an instance of MessageSource class to attach to this messenger (and to have this messenger attached to it too)
*/
function _setMessageSource(messageSource) {
check(messageSource, MessageSource);
_.defineProperty(this, '_messageSource', messageSource);
messageSource.messenger = this;
}
/**
* Messenger instance method
* Returns messenger MessageSource
*
* @return {MessageSource}
*/
function getMessageSource() {
return this._messageSource
}
},{"../abstract/mixin":76,"../util/check":95,"./m_source":82,"protojs":117}],80:[function(require,module,exports){
'use strict';
var _ = require('protojs');
module.exports = MessengerAPI;
/**
* `milo.classes.MessengerAPI`
* Base class, subclasses of which can supplement the functionality of [MessageSource](./m_source.js.html) by implementing three methods:
*
* - `translateToSourceMessage` to translate source messages (recieved from external source via `MessageSOurce`) to internal messages (that are dispatched on Messenger), allowing to make internal messages more detailed than source messages. For example, [Data facet](../components/c_facets/Data.js.html) uses [DataMsgAPI](../components/msg_api/data.js.html) to define several internal messages related to the change of state in contenteditable DOM element.
* - `createInternalData` to modify message data received from source to some more meaningful or more detailed message data that will be dispatched on Messenger. For example, [Data facet](../components/c_facets/Data.js.html) uses [DataMsgAPI](../components/msg_api/data.js.html) (subclass of MessengerAPI) to translate DOM messages to data change messages.
* - `filterSourceMessage` to enable/disable message dispatch based on some conditions in data.
*
* If `MessageSource` constructor is not passed an instance of some subclass of `MessengerAPI`, it automatically creates an instance of MessengerAPI that defines all 3 of those methods in a trivial way. See these methods below for their signatures.
*
* @constructor
* @this {MessengerAPI}
* @return {MessengerAPI}
*/
function MessengerAPI() {
if (this.init)
this.init.apply(this, arguments);
}
/**
* ####MessengerAPI instance methods####
*
* - [init](#init) - initializes MessengerAPI
* - [addInternalMessage](#addInternalMessage) - adds internal message
* - [removeInternalMessage](#removeInternalMessage) - removes internal message
* - [getInternalMessages](#getInternalMessages) - returns the list of internal messages for given source message
*
* These methods should be redefined by subclass:
*
* - [translateToSourceMessage](#translateToSourceMessage) - converts internal message type to source (external) message type
* - [createInternalData](#createInternalData) - converts source message data received via MessageSource to internal message data
* - [filterSourceMessage](#filterSourceMessage) - filters source message based on the data of the message and the corresponding internal message that is about to be sent on Messenger
*/
_.extendProto(MessengerAPI, {
init: init,
destroy: MessengerAPI$destroy,
addInternalMessage: addInternalMessage,
removeInternalMessage: removeInternalMessage,
getInternalMessages: getInternalMessages,
// should be redefined by subclass
translateToSourceMessage: translateToSourceMessage,
createInternalData: createInternalData,
filterSourceMessage: filterSourceMessage
});
/**
* MessengerAPI instance method
* Called by MessengerAPI constructor. Subclasses that re-implement `init` method should call this method using: `MessengerAPI.prototype.init.apply(this, arguments)`
*/
function init() {
_.defineProperty(this, '_internalMessages', {});
}
/**
* Destroys messenger API
*/
function MessengerAPI$destroy() {
}
/**
* MessengerAPI instance method
* Translates internal `message` to source message, adds internal `message` to the list, making sure the same `message` wasn't passed before (it would indicate Messenger error).
* Returns source message if it is used first time (so that `MessageSource` subcribes to this source message) or `undefined`.
*
* @param {String} message internal message to be translated and added
* @return {String|undefined}
*/
function addInternalMessage(message) {
var internalMsgs
, sourceMessage = this.translateToSourceMessage(message);
if (typeof sourceMessage == 'undefined') return;
if (this._internalMessages.hasOwnProperty(sourceMessage)) {
internalMsgs = this._internalMessages[sourceMessage];
if (internalMsgs.indexOf(message) == -1)
internalMsgs.push(message);
else
require('../util/logger').warn('Duplicate addInternalMessage call for internal message ' + message);
} else {
internalMsgs = this._internalMessages[sourceMessage] = [];
internalMsgs.push(message);
return sourceMessage;
}
}
/**
* MessengerAPI instance method
* Removes internal `message` from the list connected to corresponding source message (`translateToSourceMessage` is used for translation).
* Returns source message, if the last internal message was removed (so that `MessageSource` can unsubscribe from this source message), or `undefined`.
*
* @param {String} message internal message to be translated and removed
* @return {String|undefined}
*/
function removeInternalMessage(message) {
var sourceMessage = this.translateToSourceMessage(message);
if (typeof sourceMessage == 'undefined') return;
var internalMsgs = this._internalMessages[sourceMessage];
if (internalMsgs && internalMsgs.length) {
var messageIndex = internalMsgs.indexOf(message);
if (messageIndex >= 0) {
internalMsgs.splice(messageIndex, 1);
if (internalMsgs.length == 0) {
delete this._internalMessages[sourceMessage];
return sourceMessage;
}
} else
unexpectedNotificationWarning();
} else
unexpectedNotificationWarning();
function unexpectedNotificationWarning() {
require('../util/logger').warn('notification received: un-subscribe from internal message ' + message
+ ' without previous subscription notification');
}
}
/**
* MessengerAPI instance method
* Returns the array of internal messages that were translated to given `sourceMessage`.
* This method is used by `MessageSource` to dispatch source message on the `Mesenger`.
*
* @param {String} sourceMessage source message
* @return {Array[String]}
*/
function getInternalMessages(sourceMessage) {
return this._internalMessages[sourceMessage];
}
/**
* MessengerAPI instance method
* Subclasses should re-implement this method to define the rule for translation of internal `message` to source message. This class simply returns the same `message`.
*
* @param {String} message internal message to be translated
* @return {String}
*/
function translateToSourceMessage(message) {
return message
}
/**
* MessengerAPI instance method
* Subclasses should re-implement this method to define the rule for translation of source message data to internal message data. This class simply returns the same `sourceData`.
* This method is used in [dispatchMessage](./m_source.js.html#dispatchMessage) method of `MessageSource`.
*
* @param {String} sourceMessage source message, can be used in translation rule
* @param {String} message internal message, can be used in translation rule
* @param {Object} sourceData data received from source that has to be translated to data that will be sent to internal Messenger subscriber
* @return {Object}
*/
function createInternalData(sourceMessage, message, sourceData) {
return sourceData;
}
/**
* MessengerAPI instance method
* Subclasses should re-implement this method to define the dispatch filter for internal messages. This method should return `true` to allow and `false` to prevent internal message dispatch. This class always returns `true`.
* This method is used in [dispatchMessage](./m_source.js.html#dispatchMessage) method of `MessageSource`.
*
* @param {String} sourceMessage source message, can be used in filter rule
* @param {String} message internal message, can be used in filter rule
* @param {Object} internalData data translated by `createInternalData` method from source data, can be used in filter rule
* @return {Boolean}
*/
function filterSourceMessage(sourceMessage, message, internalData) {
return true;
}
},{"../util/logger":97,"protojs":117}],81:[function(require,module,exports){
'use strict';
var MessengerAPI = require('./m_api')
, _ = require('protojs');
/**
* A generic subsclass of [MessengerAPI](./m_api.js.html) that supports pattern subscriptions to source.
* Can be useful if the source is another Messenger.
*/
var MessengerRegexpAPI = _.createSubclass(MessengerAPI, 'MessengerRegexpAPI');
module.exports = MessengerRegexpAPI;
_.extendProto(MessengerRegexpAPI, {
init: init,
addInternalMessage: addInternalMessage,
removeInternalMessage: removeInternalMessage,
getInternalMessages: getInternalMessages
});
/**
* MessengerRegexpAPI instance method
* Called by MessengerRegexpAPI constructor.
*/
function init() {
MessengerAPI.prototype.init.apply(this, arguments);
_.defineProperties(this, {
_patternInternalMessages: {}
});
this._catchAllSubscribed = false;
}
/**
* MessengerRegexpAPI instance method
* Augments MessengerAPI method by storing regexp
*
* @param {String} message internal message to be translated and added
* @return {String|RegExp|undefined}
*/
function addInternalMessage(message) {
var sourceMessage = MessengerAPI.prototype.addInternalMessage.apply(this, arguments);
// store regexp itself if sourceMessage is regexp
if (sourceMessage && sourceMessage instanceof RegExp) {
this._internalMessages[sourceMessage].pattern = sourceMessage;
this._patternInternalMessages[sourceMessage] = this._internalMessages[sourceMessage];
if (this._catchAllSubscribed) return;
this._catchAllSubscribed = true;
return /.*/;
}
return sourceMessage;
}
/**
* MessengerRegexpAPI instance method
* Augments MessengerAPI method by removing regexp subscirption
*
* @param {String} message internal message to be translated and added
* @return {String|RegExp|undefined}
*/
function removeInternalMessage(message) {
var sourceMessage = MessengerAPI.prototype.removeInternalMessage.apply(this, arguments);
if (sourceMessage && sourceMessage instanceof RegExp) {
delete this._patternInternalMessages[sourceMessage];
var noPatternInternalMessages = ! Object.keys(this._patternInternalMessages).length;
if (noPatternInternalMessages) {
this._catchAllSubscribed = false;
return /.*/;
}
}
return sourceMessage;
}
/**
* MessengerAPI instance method
* Augments MessengerAPI method by returning messages subscribed with regexp
* This method is used by `MessageSource` to dispatch source message on the `Mesenger`.
*
* @param {String|RegExp} sourceMessage source message
* @return {Array[String]}
*/
function getInternalMessages(sourceMessage) {
var internalMessages = MessengerAPI.prototype.getInternalMessages.apply(this, arguments);
// add internal messages for regexp source subscriptions
if (typeof sourceMessage == 'string') {
internalMessages = internalMessages || [];
var internalMessagesHash = _.object(internalMessages, true);
_.eachKey(this._patternInternalMessages, function(patternMessages) {
var sourcePattern = patternMessages.pattern;
if (sourcePattern.test(sourceMessage))
patternMessages.forEach(function(message) {
if (internalMessagesHash[message]) return;
internalMessages.push(message);
internalMessagesHash[message] = true;
});
});
}
return internalMessages;
}
},{"./m_api":80,"protojs":117}],82:[function(require,module,exports){
'use strict';
var Mixin = require('../abstract/mixin')
, MessengerAPI = require('./m_api')
, _ = require('protojs')
, check = require('../util/check')
, Match = check.Match;
/**
* `milo.classes.MessageSource`
* An abstract class (subclass of [Mixin](../abstract/mixin.js.html)) for connecting [Messenger](./index.js.html) to external sources of messages (like DOM events) and defining higher level messages.
* An instance of MessageSource can either be passed to Messenger constructor or later using `_setMessageSource` method of Messenger. Once set, MessageSource of Messenger cannot be changed.
*/
var MessageSource = _.createSubclass(Mixin, 'MessageSource', true);
module.exports = MessageSource;
/**
* ####MessageSource instance methods####
*
* - [init](#init) - initializes messageSource - called by Mixin superclass
* - [setMessenger](#setMessenger) - connects Messenger to MessageSource, is called from `init` or `_setMessageSource` methods of [Messenger](./index.js.html).
* - [onSubscriberAdded](#onSubscriberAdded) - called by Messenger to notify when the first subscriber for an internal message was added, so MessageSource can subscribe to source
* - [onSubscriberRemoved](#onSubscriberRemoved) - called by Messenger to notify when the last subscriber for an internal message was removed, so MessageSource can unsubscribe from source
* - [dispatchMessage](#dispatchMessage) - dispatches source message. MessageSource subclass should implement mechanism when on actual source message this method is called.
*
* Methods below should be implemented in subclass:
*
* - [trigger](#trigger) - triggers messages on the source (an optional method)
* - [addSourceSubscriber](#addSourceSubscriber) - adds listener/subscriber to external message
* - [removeSourceSubscriber](#removeSourceSubscriber) - removes listener/subscriber from external message
*/
_.extendProto(MessageSource, {
init: init,
destroy: MessageSource$destroy,
setMessenger: setMessenger,
onSubscriberAdded: onSubscriberAdded,
onSubscriberRemoved: onSubscriberRemoved,
dispatchMessage: dispatchMessage,
postMessage: postMessage,
_prepareMessengerAPI: _prepareMessengerAPI,
// Methods below must be implemented in subclass
trigger: toBeImplemented,
addSourceSubscriber: toBeImplemented,
removeSourceSubscriber: toBeImplemented
});
/**
* MessageSource instance method.
* Called by Mixin constructor.
* MessageSource constructor should be passed the same parameters as this method signature.
* If an instance of [MessengerAPI](./m_api.js.html) is passed as the third parameter, it extends MessageSource functionality to allow it to define new messages, to filter messages based on their data and to change message data. See [MessengerAPI](./m_api.js.html).
*
* @param {Object} hostObject Optional object that stores the MessageSource on one of its properties. It is used to proxy methods of MessageSource.
* @param {Object[String]} proxyMethods Optional map of method names; key - proxy method name, value - MessageSource's method name.
* @param {MessengerAPI} messengerAPI Optional instance of MessengerAPI.
*/
function init(hostObject, proxyMethods, messengerAPI) {
this._prepareMessengerAPI(messengerAPI);
}
/**
* Destroys message source
*/
function MessageSource$destroy() {
if (this.messengerAPI)
this.messengerAPI.destroy();
}
/**
* MessageSource instance method.
* Sets reference to Messenger instance.
*
* @param {Messenger} messenger reference to Messenger instance linked to this MessageSource
*/
function setMessenger(messenger) {
_.defineProperty(this, 'messenger', messenger);
}
/**
* MessageSource instance method.
* Prepares [MessengerAPI](./m_api.js.html) passed to constructor by proxying its methods to itself or if MessengerAPI wasn't passed defines two methods to avoid checking their availability every time the message is dispatched.
*
* @private
* @param {MessengerAPI} messengerAPI Optional instance of MessengerAPI
*/
function _prepareMessengerAPI(messengerAPI) {
check(messengerAPI, Match.Optional(MessengerAPI));
if (! messengerAPI)
messengerAPI = new MessengerAPI;
_.defineProperty(this, 'messengerAPI', messengerAPI);
}
/**
* MessageSource instance method.
* Subscribes to external source using `addSourceSubscriber` method that should be implemented in subclass.
* This method is called by [Messenger](./index.js.html) when the first subscriber to the `message` is added.
* Delegates to supplied or default [MessengerAPI](./m_api.js.html) for translation of `message` to `sourceMessage`. `MessageAPI.prototype.addInternalMessage` will return undefined if this `sourceMessage` was already subscribed to to prevent duplicate subscription.
*
* @param {String} message internal Messenger message that has to be subscribed to at the external source of messages.
*/
function onSubscriberAdded(message) {
var newSourceMessage = this.messengerAPI.addInternalMessage(message);
if (typeof newSourceMessage != 'undefined')
this.addSourceSubscriber(newSourceMessage);
}
/**
* MessageSource instance method.
* Unsubscribes from external source using `removeSourceSubscriber` method that should be implemented in subclass.
* This method is called by [Messenger](./index.js.html) when the last subscriber to the `message` is removed.
* Delegates to supplied or default [MessengerAPI](./m_api.js.html) for translation of `message` to `sourceMessage`. `MessageAPI.prototype.removeInternalMessage` will return undefined if this `sourceMessage` was not yet subscribed to to prevent unsubscription without previous subscription.
*
* @param {String} message internal Messenger message that has to be unsubscribed from at the external source of messages.
*/
function onSubscriberRemoved(message) {
var removedSourceMessage = this.messengerAPI.removeInternalMessage(message);
if (typeof removedSourceMessage != 'undefined')
this.removeSourceSubscriber(removedSourceMessage);
}
/**
* MessageSource instance method.
* Dispatches sourceMessage to Messenger.
* Mechanism that calls this method when the source message is received should be implemented by subclass (see [DOMEventsSource](../components/msg_src/dom_events.js.html) for example).
* Delegates to supplied or default [MessengerAPI](./m_api.js.html) to create internal message data (`createInternalData`) and to filter the message based on its data and/or message (`filterSourceMessage`).
* Base MessengerAPI class implements these two methods in a trivial way (`createInternalData` simply returns external data, `filterSourceMessage` returns `true`), they are meant to be implemented by subclass.
*
* @param {String} sourceMessage source message received from external source
* @param {Object} sourceData data received from external source
*/
function dispatchMessage(sourceMessage, sourceData) {
var api = this.messengerAPI
, internalMessages = api.getInternalMessages(sourceMessage);
if (internalMessages)
internalMessages.forEach(function (message) {
var internalData = api.createInternalData(sourceMessage, message, sourceData);
var shouldDispatch = api.filterSourceMessage(sourceMessage, message, internalData);
if (shouldDispatch)
this.postMessage(message, internalData);
}, this);
}
/**
* Posts message on the messenger. This method is separated so specific message sources can make message dispatch synchronous by using `postMessageSync`
*
* @param {String} message
* @param {Object} data
*/
function postMessage(message, data) {
this.messenger.postMessage(message, data);
}
function toBeImplemented() {
throw new Error('calling the method of an absctract class');
}
},{"../abstract/mixin":76,"../util/check":95,"./m_api":80,"protojs":117}],83:[function(require,module,exports){
'use strict';
var MessageSource = require('./m_source')
, _ = require('protojs')
, check = require('../util/check');
/**
* Subclass of MessageSource that allows to connect Messenger to another Messenger using it as external source.
*/
var MessengerMessageSource = _.createSubclass(MessageSource, 'MessengerMessageSource');
module.exports = MessengerMessageSource;
/**
* ####MessengerMessageSource instance methods####
*/
_.extendProto(MessengerMessageSource, {
init: init,
addSourceSubscriber: addSourceSubscriber,
removeSourceSubscriber: removeSourceSubscriber,
postMessage: MessengerMessageSource$postMessage
});
/**
* Initializes MessengerMessageSource
* Defines one parameter in addition to [MessageSource](./m_source.js.html) parameters
*
* @param {Messenger} sourceMessenger messenger this message source connects to
*/
function init(hostObject, proxyMethods, messengerAPI, sourceMessenger) {
MessageSource.prototype.init.apply(this, arguments);
this.sourceMessenger = sourceMessenger;
}
/**
* Subscribes to source message. See [MessageSource](./m_source.js.html) docs.
*
* @param {String|Regex} sourceMessage source message to subscribe to
*/
function addSourceSubscriber(sourceMessage) {
this.sourceMessenger.onSync(sourceMessage, { context: this, subscriber: this.dispatchMessage });
}
/**
* Unsubscribes from source message. See [MessageSource](./m_source.js.html) docs.
*
* @param {String|Regex} sourceMessage source message to unsubscribe from
*/
function removeSourceSubscriber(sourceMessage) {
this.sourceMessenger.off(sourceMessage, { context: this, subscriber: this.dispatchMessage });
}
/**
* Overrides defalut message source to dispatch messages synchronously
*
* @param {String} message
* @param {Object} data
*/
function MessengerMessageSource$postMessage(message, data) {
this.messenger.postMessageSync(message, data);
}
},{"../util/check":95,"./m_source":82,"protojs":117}],84:[function(require,module,exports){
'use strict';
var _ = require('protojs');
/**
* ####Milo packages####
*
* - [minder](./minder.js.html) - data reactivity, one or two way, shallow or deep, as you like it
* - [config](./config.js.html) - milo configuration
* - [util](./util/index.js.html) - logger, request, dom, check, error, etc.
* - [classes](./classes.js.html) - abstract and base classes
* - [Messenger](./messenger/index.js.html) - generic Messenger used in most other milo classes, can be mixed into app classes too.
* - [Model](./model/index.js.html) - Model class that emits messages on changes to any depth without timer based watching
*/
var milo = {
minder: require('./minder'),
config: require('./config'),
util: require('./util'),
classes: require('./classes'),
Messenger: require('./messenger'),
Model: require('./model'),
destroy: destroy,
proto: _
};
// export for node/browserify
if (typeof module == 'object' && module.exports)
module.exports = milo;
// global milo for browser
if (typeof window == 'object')
window.milo = milo;
function destroy() {
milo.minder.destroy();
}
},{"./classes":77,"./config":78,"./messenger":79,"./minder":85,"./model":88,"./util":96,"protojs":117}],85:[function(require,module,exports){
'use strict';
var Connector = require('./model/connector')
, Messenger = require('./messenger')
, _ = require('protojs')
, logger = require('./util/logger');
module.exports = minder;
/**
* This function creates one or many Connector objects that
* create live reactive connection between objects implementing
* dataSource interface:
* Objects should emit messages when any part of their data changes,
* methods `on` and `off` should be implemented to subscribe/unsubscribe
* to change notification messages, methods `set` and `get` should be implemented to get/set data
* on path objects, pointing to particular parts of the object, method `path`
* should return path object for a given path string (see path utils for path string syntax).
* Both Model and Data facet are such data sources, they can be linked by Connector object.
*
* @param {Object} ds1 the first data source. Instead of the first data source an array can be passed with arrays of Connection objects parameters in each array element.
* @param {String} mode the connection mode that defines the direction and the depth of connection. Possible values are '->', '<<-', '<<<->>>', etc.
* @param {Object} ds2 the second data source
* @param {Object} options not implemented yet
*/
function minder(ds1, mode, ds2, options) {
if (Array.isArray(ds1)) {
var connDescriptions = ds1;
var connectors = connDescriptions.map(function(descr) {
return new Connector(descr[0], descr[1], descr[2], descr[3]);
});
connectors.forEach(_addConnector);
return connectors;
} else {
var cnct = new Connector(ds1, mode, ds2, options);
_addConnector(cnct);
return cnct;
}
}
/**
* messenger of minder where it emits events related to all connectors
* @type {Messenger}
*/
var _messenger = new Messenger(minder, Messenger.defaultMethods);
var _connectors = []
, _receivedMessages = []
, _isPropagating = false;
_.extend(minder, {
getConnectors: minder_getConnectors,
getExpandedConnections: minder_getExpandedConnections,
isPropagating: minder_isPropagating,
whenPropagationCompleted: minder_whenPropagationCompleted,
destroyConnector: minder_destroyConnector,
destroy: minder_destroy
});
function _addConnector(cnct) {
cnct.___minder_id = _connectors.push(cnct) - 1;
cnct.on(/.*/, onConnectorMessage);
minder.postMessage('added', { connector: cnct });
minder.postMessage('turnedon', { connector: cnct });
}
function onConnectorMessage(msg, data) {
var data = data ? _.clone(data) : {};
_.extend(data, {
id: this.___minder_id,
connector: this
});
minder.postMessage(msg, data);
if (! _receivedMessages.length && ! _isPropagating) {
_.defer(_idleCheck);
_isPropagating = true;
}
_receivedMessages.push({ msg: msg, data: data });
}
function _idleCheck() {
if (_receivedMessages.length) {
_receivedMessages.length = 0;
_.defer(_idleCheck);
minder.postMessage('propagationticked');
} else {
_isPropagating = false;
minder.postMessage('propagationcompleted');
}
}
function minder_isPropagating() {
return _isPropagating;
}
function minder_whenPropagationCompleted(callback) {
if (_isPropagating)
minder.once('propagationcompleted', executeCallback);
else
_.defer(executeCallback);
function executeCallback() {
if (_isPropagating)
minder.once('propagationcompleted', executeCallback);
else
callback();
}
}
function minder_getConnectors(onOff) {
if (typeof onOff == 'undefined')
return _connectors;
return _connectors.filter(function(cnct) {
return cnct.isOn === onOff;
});
}
function minder_destroyConnector(cnct) {
cnct.destroy();
var index = _connectors.indexOf(cnct);
if (index >= 0)
delete _connectors[index];
else
logger.warn('minder: connector destroyed that is not registered in minder');
}
function minder_getExpandedConnections(onOff, searchStr) {
var connectors = minder.getConnectors(onOff);
var connections = connectors.map(function(cnct) {
var connection = {
leftSource: _getExpandedSource(cnct.ds1),
rightSource: _getExpandedSource(cnct.ds2),
mode: cnct.mode,
isOn: cnct.isOn
};
if (cnct.options)
connection.options = cnct.options;
return connection;
});
if (searchStr)
connections = connections.filter(function(cnctn) {
return _sourceMatchesString(cnctn.leftSource, searchStr)
|| _sourceMatchesString(cnctn.rightSource, searchStr);
});
return connections;
}
function _getExpandedSource(ds) {
var source = [];
if (typeof ds == 'function') {
if (ds._model && ds._accessPath) {
source.unshift(ds._accessPath);
ds = ds._model;
}
source.unshift(ds);
ds = ds._hostObject;
}
if (typeof ds == 'object') {
source.unshift(ds);
if (ds.owner)
source.unshift(ds.owner);
}
return source;
}
function _sourceMatchesString(source, matchStr) {
return source.some(function(srcNode) {
var className = srcNode.constructor && srcNode.constructor.name;
return _stringMatch(className, matchStr)
|| _stringMatch(srcNode.name, matchStr)
|| _stringMatch(srcNode, matchStr);
});
}
function _stringMatch(str, substr) {
return str && typeof str == 'string' && str.indexOf(substr) >= 0;
}
function minder_destroy() {
_connectors.forEach(function(cnct) {
destroyDS(cnct.ds1);
destroyDS(cnct.ds2);
cnct.destroy();
});
_messenger.destroy();
minder._destroyed = true;
function destroyDS(ds) {
if (ds && !ds._destroyed) ds.destroy();
}
}
},{"./messenger":79,"./model/connector":87,"./util/logger":97,"protojs":117}],86:[function(require,module,exports){
'use strict';
var logger = require('../util/logger')
, config = require('../config')
, pathUtils = require('./path_utils')
, _ = require('protojs');
/**
* Utility function to process "changedata" messages emitted by Connector object.
*/
module.exports = changeDataHandler;
_.extend(changeDataHandler, {
setTransactionFlag: setTransactionFlag,
getTransactionFlag: getTransactionFlag,
passTransactionFlag: passTransactionFlag,
postTransactionFinished: postTransactionFinished
});
/**
* Change data uses hidden property on accessor methods to pass flag that the accessor is executed as a part of change transaction.
* Accessor methods are supposed to store this flag in a local variable and to clear it (because another accessor can be executed in or out of transaction) using `getTransactionFlag`
*
* @private
* @param {Function} func accessor method reference
* @param {Boolean} flag a flag to be set
*/
function setTransactionFlag(func, flag) {
_.defineProperty(func, '__inChangeTransaction', flag, _.CONF | _.WRIT);
}
/**
* Retrieves and clears transaction flag from accessor method
*
* @private
* @param {Function} func accessor method reference
* @return {Boolean}
*/
function getTransactionFlag(func) {
var inTransaction = func.__inChangeTransaction;
delete func.__inChangeTransaction;
return inTransaction;
}
function passTransactionFlag(fromFunc, toFunc) {
var inTransaction = getTransactionFlag(fromFunc);
setTransactionFlag(toFunc, inTransaction);
return inTransaction;
}
/**
* Posts message on this to indicate the end of transaction unless `inChangeTransaction` is `true`.
*/
function postTransactionFinished() {
this.postMessageSync('datachanges', { transaction: false, changes: [] });
}
/**
* subscriber to "changedata" event emitted by [Connector](./connector.js.html) object to enable reactive connections
* Used by Data facet, Model and ModelPath. Can be used by any object that implements get/set/del/splice api and sets data deeply to the whole tree.
* Object should call `changeDataHandler.initialize.call(this)` in its constructor.
* TODO: optimize messages list to avoid setting duplicate values down the tree
*
* @param {String} msg should be "changedata" here
* @param {Object} data batch of data change desciption objects
* @param {Function} callback callback to call before and after the data is processed
*/
function changeDataHandler(message, data, callback) {
processChanges.call(this, data.changes, callback);
}
// map of message types to methods
var CHANGE_TYPE_TO_METHOD_MAP = {
'added': 'set',
'changed': 'set',
'deleted': 'del',
'removed': 'del'
};
/**
* Processes queued "changedata" messages.
* Posts "changestarted" and "changecompleted" messages and calls callback
*
* @param {[Function]} callback optional callback that is called with `(null, false)` parameters before change processing starts and `(null, true)` after it's finished.
*/
function processChanges(transaction, callback) {
notify.call(this, callback, false);
processTransaction.call(this,
prepareTransaction(
validateTransaction(transaction)));
notify.call(this, callback, true);
}
function notify(callback, changeFinished) {
callback && callback(null, changeFinished);
this.postMessage(changeFinished ? 'changecompleted' : 'changestarted');
}
/**
* Checks that all messages from the transaction come from the same source.
* Hack: reverses the transaction if it comes from the Data facet
* Returns the reference to the transaction (for chaining)
*
* @param {Array} transaction transaction of data changes
* @return {Array}
*/
function validateTransaction(transaction) {
var source = transaction[0].source
, sameSource = true;
if (transaction.length > 1) {
for (var i = 1, len = transaction.length; i < len; i++)
if (transaction[i].source != source) {
logger.error('changedata: changes from different sources in the same transaction, sources:', transaction[i].source.name, source.name);
sameSource = false;
source = transaction[i].source;
}
}
return transaction;
}
function prepareTransaction(transaction) {
var todo = []
, pathsToSplice = []
, pathsToChange = []
, hadSplice
, exitLoop = {};
try { transaction.forEach(checkChange); }
catch (e) { if (e != exitLoop) throw e; }
return todo;
function checkChange(data) {
(data.type == 'splice' ? checkSplice : checkMethod)(data);
}
function checkSplice(data) {
var parsedPath = pathUtils.parseAccessPath(data.path);
var parentPathChanged = pathsToChange.some(function(parentPath) {
if (parsedPath.length < parentPath.length) return;
return _pathIsParentOf(parentPath, parsedPath);
});
if (parentPathChanged) return;
todo.push(data);
if (! config.debug) throw exitLoop;
pathsToSplice.push(parsedPath);
hadSplice = true;
}
function checkMethod(data) {
var parsedPath = pathUtils.parseAccessPath(data.path);
var parentPathSpliced = pathsToSplice && pathsToSplice.some(function(parentPath) {
if (parsedPath.length <= parentPath.length
|| parsedPath[parentPath.length].syntax != 'array') return;
return _pathIsParentOf(parentPath, parsedPath);
});
if (parentPathSpliced) return;
if (hadSplice) logger.error('changedata: child change is executed after splice; probably data source did not emit message with data.type=="finished"');
var parentPathChanged = pathsToChange.some(function(parentPath) {
if (parsedPath.length <= parentPath.length) return;
return _pathIsParentOf(parentPath, parsedPath);
});
if (parentPathChanged) return;
pathsToChange.push(parsedPath);
todo.push(data);
}
function _pathIsParentOf(parentPath, childPath) {
return parentPath.every(function(pathNode, index) {
return pathNode.property == childPath[index].property;
});
}
}
function processTransaction(transaction) {
transaction.forEach(processChange, this);
postTransactionFinished.call(this, false);
function processChange(data) {
var modelPath = this.path(data.path, data.type != 'removed' && data.type != 'deleted');
if (! modelPath) return;
(data.type == 'splice' ? executeSplice : executeMethod)(modelPath, data);
}
}
function executeSplice(modelPath, data) {
var index = data.index
, howMany = data.removed.length
, spliceArgs = [index, howMany];
spliceArgs = spliceArgs.concat(data.newValue.slice(index, index + data.addedCount));
setTransactionFlag(modelPath.splice, true);
modelPath.splice.apply(modelPath, spliceArgs);
}
function executeMethod(modelPath, data) {
var methodName = CHANGE_TYPE_TO_METHOD_MAP[data.type];
if (methodName) {
setTransactionFlag(modelPath[methodName], true);
modelPath[methodName](data.newValue);
} else
logger.error('unknown data change type');
}
},{"../config":78,"../util/logger":97,"./path_utils":93,"protojs":117}],87:[function(require,module,exports){
'use strict';
var Messenger = require('../messenger')
, pathUtils = require('./path_utils')
, _ = require('protojs')
, logger = require('../util/logger');
module.exports = Connector;
var modePattern = /^(\<*)\-+(\>*)$/;
/**
* Connector
* Class that creates connector object for data connection between
* two data-sources
* Data-sources should implement the following API:
* get() - get value from datasource or its path
* set(value) - set value to datasource or to its path
* on(path, subscriber) - subscription to data changes with "*" support
* off(path, subscriber)
* path(accessPath) - to return the object that gives reference to some part of datasource
* and complies with that api too.
*
* ####Events####
*
* - 'turnedon' - connector was turned on
* - 'turnedoff' - connector was turned off
* - 'changestarted' - change on connected datasource is started
* - 'changecompleted' - change on connected datasource is completed
* - 'destroyed' - connector was destroyed
*
* @param {Object} ds1 the first data source.
* @param {String} mode the connection mode that defines the direction and the depth of connection. Possible values are '->', '<<-', '<<<->>>', etc.
* @param {Object} ds2 the second data source
* @param {Object} options optional object with properties dataTranslation, pathTranslation, noPathTranslation, dataValidation
* @return {Connector} when called with `new`, creates a Connector object.
*/
function Connector(ds1, mode, ds2, options) {
setupMode.call(this, mode);
_.extend(this, {
ds1: ds1,
ds2: ds2,
isOn: false,
_changesQueue1: [],
_changesQueue2: [],
_messenger: new Messenger(this, Messenger.defaultMethods)
});
if (options) {
this.options = options;
var pathTranslation = options.pathTranslation;
if (pathTranslation) {
pathTranslation = _.clone(pathTranslation);
var patternTranslation = getPatternTranslations(pathTranslation);
_.extend(this, {
pathTranslation1: reverseTranslationRules(pathTranslation),
pathTranslation2: pathTranslation,
patternTranslation1: reversePatternTranslationRules(patternTranslation),
patternTranslation2: patternTranslation
});
}
var dataTranslation = options.dataTranslation;
if (dataTranslation) {
if (!pathTranslation && !options.noPathTranslation)
logger.warn('dataTranslation without pathTranslation: translations won\'t be applied when properties are changed via a higher level object');
_.extend(this, {
dataTranslation1: dataTranslation['<-'],
dataTranslation2: dataTranslation['->']
});
}
var dataValidation = options.dataValidation;
if (dataValidation) {
_.extend(this, {
dataValidation1: dataValidation['<-'],
dataValidation2: dataValidation['->']
});
}
}
this.turnOn();
}
function setupMode(mode){
var parsedMode = mode.match(modePattern);
if (! parsedMode)
modeParseError();
var depth1 = parsedMode[1].length
, depth2 = parsedMode[2].length;
if (depth1 && depth2 && depth1 != depth2)
modeParseError();
if (! depth1 && ! depth2)
modeParseError();
_.extend(this, {
mode: mode,
depth1: depth1,
depth2: depth2,
});
function modeParseError() {
throw new Error('invalid Connector mode: ' + mode);
}
}
_.extendProto(Connector, {
turnOn: Connector$turnOn,
turnOff: Connector$turnOff,
destroy: Connector$destroy,
changeMode: Connector$changeMode,
deferChangeMode: Connector$deferChangeMode
});
/**
* Function change the mode of the connection
*
* @param @param {String} mode the connection mode that defines the direction and the depth of connection. Possible values are '->', '<<-', '<<<->>>', etc.
* @return {Object[String]}
*/
function Connector$changeMode(mode) {
this.turnOff();
setupMode.call(this, mode);
this.turnOn();
return this;
}
/**
* Function change the mode of the connection
*
* @param @param {String} mode the connection mode that defines the direction and the depth of connection. Possible values are '->', '<<-', '<<<->>>', etc.
* @return {Object[String]}
*/
function Connector$deferChangeMode(mode) {
_.deferMethod(this, 'changeMode', mode);
return this;
}
/**
* Function that reverses translation rules for paths of connected odata sources
*
* @param {Object[String]} rules map of paths defining the translation rules
* @return {Object[String]}
*/
function reverseTranslationRules(rules) {
var reverseRules = {};
_.eachKey(rules, function(path2_value, path1_key) {
reverseRules[path2_value] = path1_key;
});
return reverseRules;
}
function getPatternTranslations(pathTranslation) {
var patternTranslation = [];
_.eachKey(pathTranslation, function(path2_value, path1_key) {
var starIndex1 = path1_key.indexOf('*')
, starIndex2 = path2_value.indexOf('*');
if (starIndex1 >= 0 && starIndex2 >= 0) { // pattern translation
if (path1_key.slice(starIndex1) != path2_value.slice(starIndex2))
_throwInvalidTranslation(path1_key, path2_value);
delete pathTranslation[path1_key];
patternTranslation.push({
fromPattern: pathUtils.createRegexPath(path1_key),
fromStaticPath: _getStaticPath(path1_key, starIndex1),
toPattern: pathUtils.createRegexPath(path2_value),
toStaticPath: _getStaticPath(path2_value, starIndex2)
});
} else if (starIndex1 >= 0 || starIndex2 >= 0) // pattern only on one side of translation
_throwInvalidTranslation(path1_key, path2_value);
});
return patternTranslation;
function _throwInvalidTranslation(path1, path2) {
throw new Error('Invalid pattern translation: ' + path1 + ', ' + path2);
}
function _getStaticPath(path, starIndex) {
return path.replace(/[\.\[]?\*.*$/, '');
}
}
function reversePatternTranslationRules(patternTranslation) {
return patternTranslation.map(function(pt) {
return {
fromPattern: pt.toPattern,
fromStaticPath: pt.toStaticPath,
toPattern: pt.fromPattern,
toStaticPath: pt.fromStaticPath
};
});
}
/**
* turnOn
* Method of Connector that enables connection (if it was previously disabled)
*/
function Connector$turnOn() {
if (this.isOn)
return logger.warn('data sources are already connected');
var subscriptionPath = this._subscriptionPath =
new Array(this.depth1 || this.depth2).join('*');
var subscriptionPattern = pathUtils.createRegexPath(subscriptionPath);
var self = this;
if (this.depth1)
this._link1 = linkDataSource('_link2', this.ds2, this.ds1, this._changesQueue1, this.pathTranslation1, this.patternTranslation1, this.dataTranslation1, this.dataValidation1);
if (this.depth2)
this._link2 = linkDataSource('_link1', this.ds1, this.ds2, this._changesQueue2, this.pathTranslation2, this.patternTranslation2, this.dataTranslation2, this.dataValidation2);
this.isOn = true;
this.postMessage('turnedon');
function linkDataSource(reverseLink, fromDS, toDS, changesQueue, pathTranslation, patternTranslation, dataTranslation, dataValidation) {
fromDS.onSync('datachanges', onData);
return onData;
function onData(message, batch) {
var sendData = {
changes: [],
transaction: batch.transaction
}
batch.changes.forEach(function(change) {
var sourcePath = change.path
, targetPath = translatePath(sourcePath);
if (typeof targetPath == 'undefined') return;
var change = _.clone(change);
_.extend(change, {
source: fromDS,
path: targetPath
});
translateData(sourcePath, change);
validateData(sourcePath, change);
});
if (! changesQueue.length)
_.defer(postChangeData);
changesQueue.push(sendData);
function translatePath(sourcePath) {
if (pathTranslation) {
var translatedPath = pathTranslation[sourcePath];
if (translatedPath) return translatedPath;
if (!patternTranslation.length) return;
var pt = _.find(patternTranslation, function(pTranslation) {
return pTranslation.fromPattern.test(sourcePath);
});
if (!pt) return;
var translatedPath = sourcePath.replace(pt.fromStaticPath, pt.toStaticPath);
} else if (! ((subscriptionPattern instanceof RegExp
&& subscriptionPattern.test(sourcePath))
|| subscriptionPattern == sourcePath)) return;
return translatedPath || sourcePath;
}
function translateData(sourcePath, change) {
if (dataTranslation) {
var translate = dataTranslation[sourcePath];
if (translate && typeof translate == 'function') {
change.oldValue = translate(change.oldValue);
change.newValue = translate(change.newValue);
}
}
}
function validateData(sourcePath, change) {
propagateData(change);
if (dataValidation) {
var validators = dataValidation[sourcePath]
, passedCount = 0
, alreadyFailed = false;
if (validators)
validators.forEach(callValidator);
}
function callValidator(validator) {
validator(change.newValue, function(err, response) {
response.path = sourcePath;
if (! alreadyFailed && (err || response.valid) && ++passedCount == validators.length) {
fromDS.postMessage('validated', response);
} else if (! response.valid) {
alreadyFailed = true;
fromDS.postMessage('validated', response);
}
});
}
}
function propagateData(change) {
sendData.changes.push(change);
}
function postChangeData() {
// prevent endless loop of updates for 2-way connection
if (self[reverseLink]) var callback = subscriptionSwitch;
var transactions = mergeTransactions(changesQueue);
changesQueue.length = 0;
transactions.forEach(function(transaction) {
// send data change instruction as message
toDS.postMessageSync('changedata', { changes: transaction }, callback);
});
}
function subscriptionSwitch(err, changeFinished) {
if (err) return;
var onOff = changeFinished ? 'onSync' : 'off';
toDS[onOff]('datachanges', self[reverseLink]);
var message = changeFinished ? 'changecompleted' : 'changestarted';
self.postMessage(message, { source: fromDS, target: toDS });
}
function mergeTransactions(batches) {
var transactions = []
, currentTransaction;
batches.forEach(function(batch) {
if (! batch.transaction) currentTransaction = undefined;
if (! batch.changes.length) return;
if (batch.transaction) {
if (currentTransaction)
_.appendArray(currentTransaction, batch.changes);
else {
currentTransaction = _.clone(batch.changes);
transactions.push(currentTransaction);
}
} else
transactions.push(batch.changes);
});
return transactions;
}
}
}
}
/**
* turnOff
* Method of Connector that disables connection (if it was previously enabled)
*/
function Connector$turnOff() {
if (! this.isOn)
return logger.warn('data sources are already disconnected');
var self = this;
unlinkDataSource(this.ds1, '_link2', this.pathTranslation2);
unlinkDataSource(this.ds2, '_link1', this.pathTranslation1);
this.isOn = false;
this.postMessage('turnedoff');
function unlinkDataSource(fromDS, linkName, pathTranslation) {
if (self[linkName]) {
fromDS.off('datachanges', self[linkName]);
delete self[linkName];
}
}
}
/**
* Destroys connector object by turning it off and removing references to connected sources
*/
function Connector$destroy() {
this.turnOff();
this.postMessage('destroyed');
this._messenger.destroy();
delete this.ds1;
delete this.ds2;
this._destroyed = true;
}
},{"../messenger":79,"../util/logger":97,"./path_utils":93,"protojs":117}],88:[function(require,module,exports){
'use strict';
var ModelPath = require('./m_path')
, synthesize = require('./synthesize')
, pathUtils = require('./path_utils')
, modelUtils = require('./model_utils')
, changeDataHandler = require('./change_data')
, Messenger = require('../messenger')
, MessengerMessageSource = require('../messenger/msngr_source')
, ModelMsgAPI = require('./m_msg_api')
, Mixin = require('../abstract/mixin')
, _ = require('protojs')
, check = require('../util/check')
, Match = check.Match
, logger = require('../util/logger');
module.exports = Model;
/**
* `milo.Model`
* Model class instantiates objects that allow deep data access with __safe getters__ that return undefined (rather than throwing exception) when properties/items of unexisting objects/arrays are requested and __safe setters__ that create object trees when properties/items of unexisting objects/arrays are set and also post messages to allow subscription on changes and enable data reactivity.
* Reactivity is implememnted via [Connector](./connector.js.html) that can be instantiated either directly or with more convenient interface of [milo.minder](../minder.js.html). At the moment model can be connected to [Data facet](../components/c_facets/Data.js.html) or to another model or [ModelPath](./m_path.js.html).
* Model constructor returns objects that are functions at the same time; when called they return ModelPath objects that allow get/set access to any point in model data. See [ModelData](#ModelData) below.
*
* You can subscribe to model changes with `on` method by passing model access path in place of message, pattern or string with any number of stars to subscribe to a certain depth in model (e.g., `'***'` to subscribe to three levels).
*
* @constructor
* @param {Object|Array} data optional initial array data. If it is planned to connect model to view it is usually better to instantiate an empty Model (`var m = new Model`), connect it to [Component](../components/c_class.js.html)'s [Data facet](../components/c_facets/Data.js.html) (e.g., `milo.minder(m, '<<->>', c.data);`) and then set the model with `m.set(data)` - the view will be automatically updated.
* @param {Object} hostObject optional object that hosts model on one of its properties. Can be used when model itself is the context of the message subscriber and you need to travers to this object (although it is possible to set any context). Can also be used to proxy model's methods to the host like [Model facet](../components/c_facets/ModelFacet.js.html) is doing.
* @param {Object} options pass { reactive: false } to use model without messaging when it is not needed - it makes it much faster
* @return {Model}
*/
function Model(data, hostObject, options) {
// `model` will be returned by constructor instead of `this`. `model`
// (`modelPath` function) should return a ModelPath object with "synthesized" methods
// to get/set model properties, to subscribe to property changes, etc.
// Additional arguments of modelPath can be used in the path using interpolation - see ModelPath below.
var model = function modelPath(accessPath) { // , ... arguments that will be interpolated
return Model$path.apply(model, arguments);
};
model.__proto__ = Model.prototype;
model._hostObject = hostObject;
model._options = options || {};
if (model._options.reactive !== false) {
model._prepareMessengers();
// subscribe to "changedata" message to enable reactive connections
model.onSync('changedata', changeDataHandler);
}
if (data) model._data = data;
return model;
}
Model.prototype.__proto__ = Model.__proto__;
/**
* ####Model instance methods####
*
* - [path](#path) - returns ModelPath object that allows access to any point in Model
* - [get](#Model$get) - get model data
* - set - set model data, synthesized
* - splice - splice model data (as array or pseudo-array), synthesized
* - [len](./m_path.js.html#ModelPath$len) - returns length of array (or pseudo-array) in model in safe way, 0 if no length is set
* - [push](./m_path.js.html#ModelPath$push) - add items to the end of array (or pseudo-array) in model
* - [pop](./m_path.js.html#ModelPath$pop) - remove item from the end of array (or pseudo-array) in model
* - [unshift](./m_path.js.html#ModelPath$unshift) - add items to the beginning of array (or pseudo-array) in model
* - [shift](./m_path.js.html#ModelPath$shift) - remove item from the beginning of array (or pseudo-array) in model
* - [proxyMessenger](#proxyMessenger) - proxy model's Messenger methods to host object
* - [proxyMethods](#proxyMethods) - proxy model methods to host object
*/
_.extendProto(Model, {
path: Model$path,
get: Model$get,
proxyMessenger: proxyMessenger, // deprecated, should not be used
proxyMethods: proxyMethods,
_prepareMessengers: _prepareMessengers,
_getHostObject: _getHostObject,
destroy: Model$destroy
});
// set, del, splice are added to model
_.extendProto(Model, synthesize.modelMethods);
/**
* - Path: ModelPath class as `milo.Model.Path`
*/
_.extend(Model, {
Path: ModelPath,
useWith: Model$$useWith,
_utils: {
path: pathUtils,
model: modelUtils,
changeDataHandler: changeDataHandler
}
});
/**
* Expose Messenger methods on Facet prototype
*/
var MESSENGER_PROPERTY = '_messenger';
Messenger.useWith(Model, MESSENGER_PROPERTY, Messenger.defaultMethods);
/**
* ModelPath methods added to Model prototype
*/
['len', 'push', 'pop', 'unshift', 'shift'].forEach(function(methodName) {
var method = ModelPath.prototype[methodName];
_.defineProperty(Model.prototype, methodName, method);
});
/**
* Model instance method.
* Get model data.
*
* @return {Any}
*/
function Model$get() {
return this._data;
}
/**
* Model instance method.
* Returns ModelPath object that implements the same API as model but allows access to any point inside model as defined by `accessPath`.
* See [ModelPath](./m_path.js.html) class for more information.
*
* @param {String} accessPath string that defines path to access model.
* Path string consists of parts to define either property access (`".name"` to access property name) or array item access (`"[1]"` to access item with index 1).
* Access path can contain as many parts as necessary (e.g. `".list[0].name"` to access property `name` in the first element of array stored in property `list`.
* @param {List} arguments additional arguments of this method can be used to create interpolated paths.
* E.g. `m.path("[$1].$2", id, prop)` returns ModelPath to access property with name `prop` in array item with index `id`. Although this ModelPath object will work exactly as `m("[" + id + "]." + prop)`, the interpolated is much more efficient as ModelPath with interpolation will not synthesize new getters and setters, while ModelPath with computed access path will synthesize new getters and setters for each pair of values of `id` and `prop`.
* @return {ModelPath}
*/
function Model$path(accessPath) { // , ... arguments that will be interpolated
if (! accessPath) return this;
// "null" is context to pass to ModelPath, first parameter of bind
// "this" (model) is added in front of all arguments
_.splice(arguments, 0, 0, null, this);
// calling ModelPath constructor with new and the list of arguments: this (model), accessPath, ...
return new (Function.prototype.bind.apply(ModelPath, arguments));
}
/**
* Model instance method.
* Proxy model's Messenger methods to host object.
*
* @param {Object} modelHostObject optional host object. If not passed, hostObject passed to Model constructor will be used.
*/
function proxyMessenger(modelHostObject) {
modelHostObject = modelHostObject || this._hostObject;
Mixin.prototype._createProxyMethods.call(this[MESSENGER_PROPERTY], Messenger.defaultMethods, modelHostObject);
}
var modelMethodsToProxy = ['path', 'get', 'set', 'del', 'splice', 'len', 'push', 'pop', 'unshift', 'shift'];
/**
* Expose model methods on
* See same method in Mixin class for parameters meaning
*
* @param {Function} hostClass
* @param {[type]} instanceKey
* @param {[type]} mixinMethods optional
*/
function Model$$useWith(hostClass, instanceKey, mixinMethods) {
mixinMethods = mixinMethods || modelMethodsToProxy;
Mixin.useWith.call(Model, hostClass, instanceKey, mixinMethods);
}
/**
* Model instance method.
* Proxy model methods to host object.
*
* @param {Object} modelHostObject optional host object. If not passed, hostObject passed to Model constructor will be used.
*/
function proxyMethods(modelHostObject) {
modelHostObject = modelHostObject || this._hostObject;
Mixin.prototype._createProxyMethods.call(this, modelMethodsToProxy, modelHostObject);
}
/**
* Model instance method.
* Create and connect internal and external model's messengers.
* External messenger's methods are proxied on the model and they allows "*" subscriptions.
*/
function _prepareMessengers() {
// model will post all its changes on internal messenger
var internalMessenger = new Messenger(this, undefined, undefined);
// message source to connect internal messenger to external
var internalMessengerSource = new MessengerMessageSource(this, undefined, new ModelMsgAPI, internalMessenger);
// external messenger to which all model users will subscribe,
// that will allow "*" subscriptions and support "changedata" message api.
var externalMessenger = new Messenger(this, undefined, internalMessengerSource);
_.defineProperty(this, MESSENGER_PROPERTY, externalMessenger);
_.defineProperty(this, '_internalMessenger', internalMessenger);
}
function _getHostObject() {
return this._hostObject;
}
function Model$destroy() {
this[MESSENGER_PROPERTY].destroy();
this._internalMessenger.destroy();
this._destroyed = true;
}
},{"../abstract/mixin":76,"../messenger":79,"../messenger/msngr_source":83,"../util/check":95,"../util/logger":97,"./change_data":86,"./m_msg_api":89,"./m_path":90,"./model_utils":91,"./path_utils":93,"./synthesize":94,"protojs":117}],89:[function(require,module,exports){
'use strict';
var MessengerRegexpAPI = require('../messenger/m_api_rx')
, pathUtils = require('./path_utils')
, _ = require('protojs');
/**
* Subclass of MessengerRegexpAPI that is used to translate messages of external messenger of Model to internal messenger of Model.
*/
var ModelMsgAPI = _.createSubclass(MessengerRegexpAPI, 'ModelMsgAPI');
module.exports = ModelMsgAPI;
/**
* ####ModelMsgAPI instance methods####
*
* - [translateToSourceMessage](#translateToSourceMessage) - translates subscription paths with "*"s to regex, leaving other strings untouched
*/
_.extendProto(ModelMsgAPI, {
translateToSourceMessage: translateToSourceMessage,
});
/**
* ModelMsgAPI instance method
* Translates subscription paths with "*"s to regex, leaving other strings untouched.
*
* @param {String} accessPath relative access path to be translated
* @return {RegExp|String}
*/
function translateToSourceMessage(accessPath) {
if (accessPath instanceof RegExp) return accessPath;
return pathUtils.createRegexPath(accessPath);
}
},{"../messenger/m_api_rx":81,"./path_utils":93,"protojs":117}],90:[function(require,module,exports){
'use strict';
var synthesize = require('./synthesize')
, pathUtils = require('./path_utils')
, changeDataHandler = require('./change_data')
, Messenger = require('../messenger')
, ModelPathMsgAPI = require('./path_msg_api')
, MessengerMessageSource = require('../messenger/msngr_source')
, _ = require('protojs')
, check = require('../util/check')
, Match = check.Match;
module.exports = ModelPath;
/**
* `milo.Model.Path`
* ModelPath object that allows access to any point inside [Model](./index.js.html) as defined by `accessPath`
*
* @constructor
* @param {Model} model Model instance that ModelPath gives access to.
* @param {String} accessPath string that defines path to access model.
* Path string consists of parts to define either property access (`".name"` to access property name) or array item access (`"[1]"` to access item with index 1).
* Access path can contain as many parts as necessary (e.g. `".list[0].name"` to access property `name` in the first element of array stored in property `list`.
* @param {List} arguments additional arguments of this method can be used to create interpolated paths.
* E.g. `m.path("[$1].$2", id, prop)` returns ModelPath to access property with name `prop` in array item with index `id`. Although this ModelPath object will work exactly as `m("[" + id + "]." + prop)`, the interpolated is much more efficient as ModelPath with interpolation will not synthesize new getters and setters, while ModelPath with computed access path will synthesize new getters and setters for each pair of values of `id` and `prop`.
* @return {ModelPath}
*/
function ModelPath(model, path) { // ,... - additional arguments for interpolation
// check(model, Model);
check(path, String);
// `modelPath` will be returned by constructor instead of `this`. `modelPath`
// (`modelPath_path` function) should also return a ModelPath object with "synthesized" methods
// to get/set model properties, to subscribe to property changes, etc.
// Additional arguments of modelPath can be used in the path using interpolation - see ModelPath below.
var modelPath = function modelPath_path(accessPath) { // , ... arguments that will be interpolated
return ModelPath$path.apply(modelPath, arguments);
};
modelPath.__proto__ = ModelPath.prototype;
_.defineProperties(modelPath, {
_model: model,
_path: path,
_args: _.slice(arguments, 1), // path will be the first element of this array
_options: model._options
});
// parse access path
var parsedPath = pathUtils.parseAccessPath(path);
// compute access path string
_.defineProperty(modelPath, '_accessPath', interpolateAccessPath(parsedPath, modelPath._args));
if (modelPath._options.reactive !== false) {
// messenger fails on "*" subscriptions
modelPath._prepareMessenger();
// subscribe to "changedata" message to enable reactive connections
modelPath.onSync('changedata', changeDataHandler);
}
// compiling getter and setter
var methods = synthesize(path, parsedPath);
// adding methods to model path
_.defineProperties(modelPath, methods);
Object.freeze(modelPath);
return modelPath;
}
ModelPath.prototype.__proto__ = ModelPath.__proto__;
/**
* Interpolates path elements to compute real path
*
* @param {Array} parsedPath parsed path - array of path nodes
* @param {Array} args path interpolation arguments, args[0] is path itself
* @return {String}
*/
function interpolateAccessPath(parsedPath, args) {
return parsedPath.reduce(function(accessPathStr, currNode, index) {
var interpolate = currNode.interpolate;
return accessPathStr +
(interpolate
? (currNode.syntax == 'array'
? '[' + args[interpolate] + ']'
: '.' + args[interpolate])
: currNode.property);
}, '');
}
/**
* ####ModelPath instance methods####
*
* - [path](#ModelPath$path) - gives access to path inside ModelPath
* - get - synthesized
* - set - synthesized
* - splice - splice model data (as array or pseudo-array), synthesized
* - [len](#ModelPath$len) - returns length of array (or pseudo-array) in safe way, 0 if no length is set
* - [push](#ModelPath$push) - add items to the end of array (or pseudo-array) in ModelPath
* - [pop](#ModelPath$pop) - remove item from the end of array (or pseudo-array) in ModelPath
* - [unshift](#ModelPath$unshift) - add items to the beginning of array (or pseudo-array) in ModelPath
* - [shift](#ModelPath$shift) - remove item from the beginning of array (or pseudo-array) in ModelPath
*/
_.extendProto(ModelPath, {
path: ModelPath$path,
len: ModelPath$len,
push: ModelPath$push,
pop: ModelPath$pop,
unshift: ModelPath$unshift,
shift: ModelPath$shift,
_prepareMessenger: _prepareMessenger,
_getDefinition: _getDefinition,
destroy: ModelPath$destroy
});
_.extend(ModelPath, {
_createFromDefinition: _createFromDefinition
})
/**
* Expose Messenger methods on Facet prototype
*/
var MESSENGER_PROPERTY = '_messenger';
Messenger.useWith(ModelPath, MESSENGER_PROPERTY, Messenger.defaultMethods);
/**
* ModelPath instance method
* Gives access to path inside ModelPath. Method works similarly to [path method](#Model$path) of model, using relative paths.
*
* @param {String} accessPath string that defines path to access model.
* Path string consists of parts to define either property access (`".name"` to access property name) or array item access (`"[1]"` to access item with index 1).
* Access path can contain as many parts as necessary (e.g. `".list[0].name"` to access property `name` in the first element of array stored in property `list`.
* @param {List} arguments additional arguments of this method can be used to create interpolated paths.
* E.g. `m.path("[$1].$2", id, prop)` returns ModelPath to access property with name `prop` in array item with index `id`. Although this ModelPath object will work exactly as `m("[" + id + "]." + prop)`, the interpolated is much more efficient as ModelPath with interpolation will not synthesize new getters and setters, while ModelPath with computed access path will synthesize new getters and setters for each pair of values of `id` and `prop`.
* @return {ModelPath}
*/
function ModelPath$path(accessPath) { // , ... arguments that will be interpolated
if (! accessPath) return this;
var thisPathArgsCount = this._args.length - 1;
if (thisPathArgsCount > 0) {// this path has interpolated arguments too
accessPath = accessPath.replace(/\$[1-9][0-9]*/g, function(str) {
return '$' + (+str.slice(1) + thisPathArgsCount);
});
}
var newPath = this._path + accessPath;
// this._model is added in front of all arguments as the first parameter
// of ModelPath constructor
var args = [this._model, newPath]
.concat(this._args.slice(1)) // remove old path from _args, as it is 1 based
.concat(_.slice(arguments, 1)); // add new interpolation arguments
// calling ModelPath constructor with new and the list of arguments: this (model), accessPath, ...
return _.newApply(ModelPath, args);
}
/**
* ModelPath and Model instance method
* Returns length property and sets it to 0 if it wasn't set.
*
* @return {Any}
*/
function ModelPath$len() {
return this.path('.length').get() || 0;
}
/**
* ModelPath and Model instance method
* Adds items to the end of array (or pseudo-array). Returns new length.
*
* @param {List} arguments list of items that will be added to array (pseudo array)
* @return {Integer}
*/
function ModelPath$push() { // arguments
var length = this.len();
var newLength = length + arguments.length;
_.splice(arguments, 0, 0, length, 0);
this.splice.apply(this, arguments);
return newLength;
}
/**
* ModelPath and Model instance method
* Removes item from the end of array (or pseudo-array). Returns this item.
*
* @return {Any}
*/
function ModelPath$pop() {
return this.splice(this.len() - 1, 1)[0];
}
/**
* ModelPath and Model instance method
* Inserts items to the beginning of the array. Returns new length.
*
* @param {List} arguments items to be inserted in the beginning of array
* @return {Integer}
*/
function ModelPath$unshift() { // arguments
var length = this.len();
length += arguments.length;
_.splice(arguments, 0, 0, 0, 0);
this.splice.apply(this, arguments);
return length;
}
/**
* ModelPath and Model instance method
* Removes the item from the beginning of array (or pseudo-array). Returns this item.
*
* @return {Any}
*/
function ModelPath$shift() { // arguments
return this.splice(0, 1)[0];
}
/**
* ModelPath instance method
* Initializes ModelPath mesenger with Model's messenger as its source ([MessengerMessageSource](../messenger/msngr_source.js.html)) and [ModelPathMsgAPI](./path_msg_api.js.html) as [MessengerAPI](../messenger/m_api.js.html)
*/
function _prepareMessenger() {
var mPathAPI = new ModelPathMsgAPI(this._accessPath);
// create MessengerMessageSource connected to Model's messenger
var modelMessageSource = new MessengerMessageSource(this, undefined, mPathAPI, this._model);
// create messenger with model passed as hostObject (default message dispatch context)
// and without proxying methods (we don't want to proxy them to Model)
var mPathMessenger = new Messenger(this, undefined, modelMessageSource);
// store messenger on ModelPath instance
_.defineProperty(this, MESSENGER_PROPERTY, mPathMessenger);
}
/**
* Returns the object allowing to recreate model path
*
* @return {Object}
*/
function _getDefinition() {
return {
model: this._model,
path: this._path,
args: this._args
};
}
/**
* Class method
* Creates modelPath object from definition created by _getDefinition
*
* @param {Object} definition
* @return {ModelPath}
*/
function _createFromDefinition(definition) {
check(definition, {
model: Function, // Model
path: String,
args: Array
});
var m = definition.model;
return m.apply(m, definition.args);
}
function ModelPath$destroy() {
this[MESSENGER_PROPERTY].destroy();
}
},{"../messenger":79,"../messenger/msngr_source":83,"../util/check":95,"./change_data":86,"./path_msg_api":92,"./path_utils":93,"./synthesize":94,"protojs":117}],91:[function(require,module,exports){
'use strict';
var modelUtils = {
normalizeSpliceIndex: normalizeSpliceIndex
};
module.exports = modelUtils;
function normalizeSpliceIndex(spliceIndex, length) {
return spliceIndex > length
? length
: spliceIndex >= 0
? spliceIndex
: spliceIndex + length > 0
? spliceIndex + length
: 0;
}
},{}],92:[function(require,module,exports){
'use strict';
var MessengerAPI = require('../messenger/m_api')
, pathUtils = require('./path_utils')
, logger = require('../util/logger')
, _ = require('protojs');
/**
* Subclass of MessengerAPI that is used to translate messages of Messenger on ModelPath to Messenger on Model.
*/
var ModelPathMsgAPI = _.createSubclass(MessengerAPI, 'ModelPathMsgAPI');
module.exports = ModelPathMsgAPI;
/**
* ####ModelPathMsgAPI instance methods####
*
* - [init](#init) - initializes ModelPathMsgAPI
* - [translateToSourceMessage](#translateToSourceMessage) - translates relative access paths of ModelPath to full path of Model
* - [createInternalData](#createInternalData) - changes path in message on model to relative path and adds `fullPath` property to message data
*/
_.extendProto(ModelPathMsgAPI, {
init: init,
translateToSourceMessage: translateToSourceMessage,
createInternalData: createInternalData,
});
/**
* ModelPathMsgAPI instance method
* Called by MessengerAPI constructor.
*
* @param {String} rootPath root path of model path
*/
function init(rootPath) {
MessengerAPI.prototype.init.apply(this, arguments);
this.rootPath = rootPath;
}
/**
* ModelPathMsgAPI instance method
* Translates relative access paths of ModelPath to full path of Model.
*
* @param {String} accessPath relative access path to be translated
* @return {String}
*/
function translateToSourceMessage(message) {
// TODO should prepend RegExes
// TODO should not prepend changedata too???
if (message instanceof RegExp)
return message;
if (message == 'datachanges')
return message;
return this.rootPath + message;
}
/**
* ModelPathMsgAPI instance method
* Changes path in message on model to relative path and adds `fullPath` property to message data.
*
* @param {String} sourceMessage full access path on Model
* @param {String} message relative access path on ModelPath
* @param {Object} sourceData data received from Model, will be translated as described to be dispatched to ModelPath
* @return {Object}
*/
function createInternalData(sourceMessage, message, sourceData) {
// TODO return on changedata too???
if (message == 'datachanges') {
var internalChanges = sourceData.changes
.map(truncateChangePath, this)
.filter(function(change) { return change; });
var internalData = {
changes: internalChanges,
transaction: sourceData.transaction
};
return internalData
}
var internalData = truncateChangePath.call(this, sourceData);
return internalData;
}
function truncateChangePath(change) {
var fullPath = change.path
, path = _.unPrefix(fullPath, this.rootPath);
if (typeof path == 'string') {
var change = _.clone(change);
change.fullPath = fullPath;
change.path = path;
return change;
}
}
},{"../messenger/m_api":80,"../util/logger":97,"./path_utils":93,"protojs":117}],93:[function(require,module,exports){
'use strict';
// <a name="model-path"></a>
// ### model path utils
var check = require('../util/check')
, Match = check.Match
, _ = require('protojs');
var pathUtils = {
parseAccessPath: parseAccessPath,
createRegexPath: createRegexPath,
getPathNodeKey: getPathNodeKey,
wrapMessengerMethods: wrapMessengerMethods
};
module.exports = pathUtils;
var propertyPathSyntax = '\\.[A-Za-z_-][A-Za-z0-9_-]*'
, arrayPathSyntax = '\\[[0-9]+\\]'
, interpolationSyntax = '\\$[1-9][0-9]*'
, propertyInterpolateSyntax = '\\.' + interpolationSyntax
, arrayInterpolateSyntax = '\\[' + interpolationSyntax + '\\]'
, propertyStarSyntax = '\\.\\*'
, arrayStarSyntax = '\\[\\*\\]'
, starSyntax = '\\*'
, pathParseSyntax = [
propertyPathSyntax,
arrayPathSyntax,
propertyInterpolateSyntax,
arrayInterpolateSyntax
].join('|')
, pathParsePattern = new RegExp(pathParseSyntax, 'g')
, patternPathParseSyntax = [
pathParseSyntax,
propertyStarSyntax,
arrayStarSyntax,
starSyntax
].join('|')
, patternPathParsePattern = new RegExp(patternPathParseSyntax, 'g')
//, targetPathParsePattern = /\.[A-Za-z][A-Za-z0-9_]*|\[[0-9]+\]|\.\$[1-9][0-9]*|\[\$[1-9][0-9]*\]|\$[1-9][0-9]/g
, pathNodeTypes = {
'.': { syntax: 'object', empty: '{}' },
'[': { syntax: 'array', empty: '[]'},
'*': { syntax: 'match', empty: '{}'},
};
function parseAccessPath(path, nodeParsePattern) {
nodeParsePattern = nodeParsePattern || pathParsePattern;
var parsedPath = [];
if (! path)
return parsedPath;
var unparsed = path.replace(nodeParsePattern, function(nodeStr) {
var pathNode = { property: nodeStr };
_.extend(pathNode, pathNodeTypes[nodeStr[0]]);
if (nodeStr[1] == '$')
pathNode.interpolate = getPathNodeKey(pathNode, true);
parsedPath.push(pathNode);
return '';
});
if (unparsed)
throw new Error('incorrect model path: ' + path);
return parsedPath;
}
var nodeRegex = {
'.*': propertyPathSyntax,
'[*]': arrayPathSyntax
};
nodeRegex['*'] = nodeRegex['.*'] + '|' + nodeRegex['[*]'];
function createRegexPath(path) {
check(path, Match.OneOf(String, RegExp));
if (path instanceof RegExp || path.indexOf('*') == -1)
return path;
var parsedPath = pathUtils.parseAccessPath(path, patternPathParsePattern)
, regexStr = '^'
// , regexStrEnd = ''
, patternsStarted = false;
parsedPath.forEach(function(pathNode) {
var prop = pathNode.property
, regex = nodeRegex[prop];
if (regex) {
// regexStr += '(' + regex;
// regexStrEnd += '|)';
regexStr += '(' + regex + '|)';
// regexStrEnd += '|)';
patternsStarted = true;
} else {
// if (patternsStarted)
// throw new Error('"*" path segment cannot be in the middle of the path: ' + path);
regexStr += prop.replace(/(\.|\[|\])/g, '\\$1'); // add slash in front of symbols that have special meaning in regex
}
});
regexStr += /* regexStrEnd + */ '$';
try {
return new RegExp(regexStr);
} catch (e) {
throw new Error('can\'t construct regex for path pattern: ' + path);
}
}
function getPathNodeKey(pathNode, interpolated) {
var prop = pathNode.property
, startIndex = interpolated ? 2 : 1;
return pathNode.syntax == 'array'
? prop.slice(startIndex, prop.length - 1)
: prop.slice(startIndex);
}
// TODO allow for multiple messages in a string
function wrapMessengerMethods(methodsNames) {
methodsNames = methodsNames || ['on', 'off'];
var wrappedMethods = _.mapToObject(methodsNames, function(methodName) {
var origMethod = this[methodName];
// replacing message subsribe/unsubscribe/etc. to convert "*" message patterns to regexps
return function(path, subscriber) {
var regexPath = createRegexPath(path);
origMethod.call(this, regexPath, subscriber);
};
}, this);
_.defineProperties(this, wrappedMethods);
}
},{"../util/check":95,"protojs":117}],94:[function(require,module,exports){
'use strict';
var pathUtils = require('../path_utils')
, modelUtils = require('../model_utils')
, logger = require('../../util/logger')
, fs = require('fs')
, doT = require('dot')
, _ = require('protojs')
, changeDataHandler = require('../change_data')
, getTransactionFlag = changeDataHandler.getTransactionFlag
, postTransactionFinished = changeDataHandler.postTransactionFinished;
/**
* Templates to synthesize model getters and setters
*/
var templates = {
get: "'use strict';\n/* Only use this style of comments, not \"//\" */\n\nmethod = function get() {\n var m = {{# def.modelAccessPrefix }};\n return m {{~ it.parsedPath :pathNode }}\n {{? pathNode.interpolate}}\n && (m = m[this._args[ {{= pathNode.interpolate }} ]])\n {{??}}\n && (m = m{{= pathNode.property }})\n {{?}} {{~}};\n};\n",
set: "'use strict';\n/* Only use this style of comments, not \"//\" */\n\n{{# def.include_defines }}\n{{# def.include_create_tree }}\n\n\n/**\n * Template that synthesizes setter for Model and for ModelPath\n */\nmethod = function set(value) {\n {{# def.initVars:'set' }}\n\n {{# def.createTree:'set' }}\n\n {{\n currNode = nextNode;\n currProp = currNode && currNode.property;\n }}\n\n {{ /* assign value to the last property */ }}\n {{? currProp }}\n wasDef = {{# def.wasDefined}};\n {{# def.changeAccessPath }}\n\n var old = m{{# def.currProp }};\n\n {{ /* clone value to prevent same reference in linked models */ }}\n m{{# def.currProp }} = cloneTree(value);\n {{?}}\n\n {{ /* add message related to the last property change */ }}\n if (this._options.reactive !== false) {\n if (! wasDef)\n {{# def.addMsg }} accessPath, type: 'added',\n newValue: value });\n else if (old != value)\n {{# def.addMsg }} accessPath, type: 'changed',\n oldValue: old, newValue: value });\n\n {{ /* add message related to changes in (sub)properties inside removed and assigned value */ }}\n if (! wasDef || old != value)\n addTreeChangesMessages(messages, messagesHash,\n accessPath, old, value); /* defined in the function that synthesizes ModelPath setter */\n\n {{ /* post all stored messages */ }}\n {{# def.postMessages }}\n }\n};\n",
del: "'use strict';\n/* Only use this style of comments, not \"//\" */\n\n{{# def.include_defines }}\n{{# def.include_traverse_tree }}\n\nmethod = function del() {\n {{# def.initVars:'del' }}\n\n {{? it.parsedPath.length }}\n {{# def.traverseTree }}\n\n {{\n var currNode = it.parsedPath[count];\n var currProp = currNode.property; \n }}\n\n if (! treeDoesNotExist && m && m.hasOwnProperty && {{# def.wasDefined}}) {\n var old = m{{# def.currProp }};\n delete m{{# def.currProp }};\n {{# def.changeAccessPath }}\n var didDelete = true;\n }\n {{??}}\n if (typeof m != 'undefined') {\n var old = m;\n {{# def.modelAccessPrefix }} = undefined;\n var didDelete = true;\n }\n {{?}}\n\n if (didDelete && this._options.reactive !== false) {\n {{# def.addMsg }} accessPath, type: 'deleted', oldValue: old });\n\n addTreeChangesMessages(messages, messagesHash,\n accessPath, old, undefined); /* defined in the function that synthesizes ModelPath setter */\n\n {{ /* post all stored messages */ }}\n {{# def.postMessages }}\n }\n};\n",
splice: "'use strict';\n/* Only use this style of comments, not \"//\" */\n\n{{# def.include_defines }}\n{{# def.include_create_tree }}\n{{# def.include_traverse_tree }}\n\nmethod = function splice(spliceIndex, spliceHowMany) { /* ,... - extra arguments to splice into array */\n {{# def.initVars:'splice' }}\n\n var argsLen = arguments.length;\n var addItems = argsLen > 2;\n\n if (addItems) {\n {{ /* only create model tree if items are inserted in array */ }}\n\n {{ /* if model is undefined it will be set to an empty array */ }} \n var value = [];\n {{# def.createTree:'splice' }}\n\n {{? nextNode }}\n {{\n var currNode = nextNode;\n var currProp = currNode.property;\n var emptyProp = '[]';\n }}\n\n {{# def.createTreeStep }}\n {{?}}\n\n } else if (spliceHowMany > 0) {\n {{ /* if items are not inserted, only traverse model tree if items are deleted from array */ }}\n {{? it.parsedPath.length }}\n {{# def.traverseTree }}\n\n {{\n var currNode = it.parsedPath[count];\n var currProp = currNode.property; \n }}\n\n {{ /* extra brace closes 'else' in def.traverseTreeStep */ }}\n {{# def.traverseTreeStep }} }\n {{?}}\n }\n\n {{ /* splice items */ }}\n if (addItems || (! treeDoesNotExist && m\n && m.length > spliceIndex ) ) {\n var oldLength = m.length = m.length || 0;\n\n arguments[0] = spliceIndex = normalizeSpliceIndex(spliceIndex, m.length);\n\n {{ /* clone added arguments to prevent same references in linked models */ }}\n if (addItems)\n for (var i = 2; i < argsLen; i++)\n arguments[i] = cloneTree(arguments[i]);\n\n {{ /* actual splice call */ }}\n var removed = Array.prototype.splice.apply(m, arguments);\n\n if (this._options.reactive !== false) {\n {{# def.addMsg }} accessPath, type: 'splice',\n index: spliceIndex, removed: removed, addedCount: addItems ? argsLen - 2 : 0,\n newValue: m });\n\n if (removed && removed.length)\n removed.forEach(function(item, index) {\n var itemPath = accessPath + '[' + (spliceIndex + index) + ']';\n {{# def.addMsg }} itemPath, type: 'removed', oldValue: item });\n\n if (valueIsTree(item))\n addMessages(messages, messagesHash, itemPath, item, 'removed', 'oldValue');\n });\n\n if (addItems)\n for (var i = 2; i < argsLen; i++) {\n var item = arguments[i];\n var itemPath = accessPath + '[' + (spliceIndex + i - 2) + ']';\n {{# def.addMsg }} itemPath, type: 'added', newValue: item });\n\n if (valueIsTree(item))\n addMessages(messages, messagesHash, itemPath, item, 'added', 'newValue');\n }\n\n {{ /* post all stored messages */ }}\n {{# def.postMessages }}\n }\n }\n\n return removed || [];\n}\n"
};
var include_defines = "'use strict';\n/* Only use this style of comments, not \"//\" */\n\n/**\n * Inserts initialization code\n */\n {{## def.initVars:method:\n var m = {{# def.modelAccessPrefix }};\n var messages = [], messagesHash = {};\n var accessPath = '';\n var treeDoesNotExist;\n /* hack to prevent sending finished events to allow for propagation of batches without splitting them */\n var inChangeTransaction = getTransactionFlag( {{= method }} );\n #}}\n\n/**\n * Inserts the beginning of function call to add message to list\n */\n{{## def.addMsg: addChangeMessage(messages, messagesHash, { path: #}}\n\n/**\n * Inserts current property/index for both normal and interpolated properties/indexes\n */\n{{## def.currProp:{{? currNode.interpolate }}[this._args[ {{= currNode.interpolate }} ]]{{??}}{{= currProp }}{{?}} #}}\n\n/**\n * Inserts condition to test whether normal/interpolated property/index exists\n */\n{{## def.wasDefined: m.hasOwnProperty(\n {{? currNode.interpolate }}\n this._args[ {{= currNode.interpolate }} ]\n {{??}}\n '{{= it.getPathNodeKey(currNode) }}'\n {{?}}\n) #}}\n\n\n/**\n * Inserts code to update access path for current property\n * Because of the possibility of interpolated properties, it can't be calculated in template, it can only be calculated during accessor call.\n */\n{{## def.changeAccessPath:\n accessPath += {{? currNode.interpolate }}\n {{? currNode.syntax == 'array' }}\n '[' + this._args[ {{= currNode.interpolate }} ] + ']';\n {{??}}\n '.' + this._args[ {{= currNode.interpolate }} ];\n {{?}}\n {{??}}\n '{{= currProp }}';\n {{?}}\n#}}\n\n\n/**\n * Inserts code to post stored messages\n */\n{{## def.postMessages:\n if (messages.length) {\n {{# def.modelPostBatchCode }}('datachanges', {\n changes: messages,\n transaction: inChangeTransaction\n });\n\n messages.forEach(function(msg) {\n {{# def.modelPostMessageCode }}(msg.path, msg);\n }, this);\n }\n#}}\n"
, include_create_tree = "'use strict';\n/* Only use this style of comments, not \"//\" */\n\n/**\n * Inserts code to create model tree as neccessary for `set` and `splice` accessors and to add messages to send list if the tree changes.\n */\n{{## def.createTree:method:\n var wasDef = true;\n var old = m;\n\n {{ var emptyProp = it.parsedPath[0] && it.parsedPath[0].empty; }}\n {{? emptyProp }}\n {{ /* create top level model if it was not previously defined */ }}\n if (! m) {\n m = {{# def.modelAccessPrefix }} = {{= emptyProp }};\n wasDef = false;\n\n if (this._options.reactive !== false) {\n {{# def.addMsg }} '', type: 'added',\n newValue: m });\n }\n }\n {{??}}\n {{? method == 'splice' }}\n if (! m) {\n {{?}}\n m = {{# def.modelAccessPrefix }} = cloneTree(value);\n wasDef = typeof old != 'undefined';\n {{? method == 'splice' }}\n }\n {{?}} \n {{?}}\n\n\n {{ /* create model tree if it doesn't exist */ }}\n {{ var modelDataProperty = '';\n var nextNode = it.parsedPath[0];\n var count = it.parsedPath.length - 1;\n\n for (var i = 0; i < count; i++) {\n var currNode = nextNode;\n var currProp = currNode.property;\n nextNode = it.parsedPath[i + 1];\n var emptyProp = nextNode && nextNode.empty;\n }}\n\n {{# def.createTreeStep }}\n\n {{ } /* for loop */ }}\n#}}\n\n\n/**\n * Inserts code to create one step in the model tree\n */\n{{## def.createTreeStep:\n {{# def.changeAccessPath }}\n\n if (! {{# def.wasDefined }}) { \n {{ /* property does not exist */ }}\n m = m{{# def.currProp }} = {{= emptyProp }};\n\n if (this._options.reactive !== false) {\n {{# def.addMsg }} accessPath, type: 'added', \n newValue: m });\n }\n\n } else if (typeof m{{# def.currProp }} != 'object' || m{{# def.currProp }} === null) {\n {{ /* property is not object */ }}\n var old = m{{# def.currProp }};\n m = m{{# def.currProp }} = {{= emptyProp }};\n\n if (this._options.reactive !== false) {\n {{# def.addMsg }} accessPath, type: 'changed', \n oldValue: old, newValue: m });\n }\n\n } else {\n {{ /* property exists, just traverse down the model tree */ }}\n m = m{{# def.currProp }};\n }\n#}}\n"
, include_traverse_tree = "'use strict';\n/* Only use this style of comments, not \"//\" */\n\n/**\n * Inserts code to traverse model tree for `delete` and `splice` accessors.\n */\n{{## def.traverseTree:\n {{ \n var count = it.parsedPath.length-1;\n\n for (var i = 0; i < count; i++) { \n var currNode = it.parsedPath[i];\n var currProp = currNode.property;\n }}\n {{# def.traverseTreeStep }}\n\n {{ } /* for loop */\n\n var i = count;\n while (i--) { /* closing braces for else's above */\n }}\n }\n {{ } /* while loop */ }}\n#}}\n\n\n/**\n * Inserts code to traverse one step in the model tree\n */\n{{## def.traverseTreeStep:\n if (! (m && m.hasOwnProperty && {{# def.wasDefined}} ) )\n treeDoesNotExist = true;\n else {\n m = m{{# def.currProp }};\n {{# def.changeAccessPath }}\n {{ /* brace from else is not closed on purpose - all braces are closed in while loop */ }}\n#}}\n";
var dotDef = {
include_defines: include_defines,
include_create_tree: include_create_tree,
include_traverse_tree: include_traverse_tree,
getPathNodeKey: pathUtils.getPathNodeKey,
modelAccessPrefix: 'this._model._data',
modelPostMessageCode: 'this._model._internalMessenger.postMessage',
modelPostBatchCode: 'this._model.postMessageSync',
internalMessenger: 'this._model._internalMessenger'
};
var modelDotDef = _(dotDef).clone().extend({
modelAccessPrefix: 'this._data',
modelPostMessageCode: 'this._internalMessenger.postMessage',
modelPostBatchCode: 'this.postMessageSync',
internalMessenger: 'this._internalMessenger'
})._();
var dotSettings = _.clone(doT.templateSettings);
dotSettings.strip = false;
var synthesizers = _.mapKeys(templates, function(tmpl) {
return doT.template(tmpl, dotSettings, dotDef);
});
var modelSynthesizers = _.mapToObject(['set', 'del', 'splice'], function(methodName) {
return doT.template(templates[methodName], dotSettings, modelDotDef);
});
/**
* Function that synthesizes accessor methods.
* Function is memoized so accessors are cached (up to 1000).
*
* @param {String} path Model/ModelPath access path
* @param {Array} parsedPath array of path nodes
* @return {Object[Function]}
*/
var synthesizePathMethods = _.memoize(_synthesizePathMethods, undefined, 1000);
function _synthesizePathMethods(path, parsedPath) {
var methods = _.mapKeys(synthesizers, function(synthszr) {
return _synthesize(synthszr, path, parsedPath);
});
return methods;
}
var normalizeSpliceIndex = modelUtils.normalizeSpliceIndex; // used in splice.dot.js
function _synthesize(synthesizer, path, parsedPath) {
var method
, methodCode = synthesizer({
parsedPath: parsedPath,
getPathNodeKey: pathUtils.getPathNodeKey
});
try {
eval(methodCode);
} catch (e) {
throw Error('ModelPath method compilation error; path: ' + path + ', code: ' + methodCode);
}
return method;
// functions used by methods `set`, `delete` and `splice` (synthesized by template)
function addChangeMessage(messages, messagesHash, msg) {
messages.push(msg);
messagesHash[msg.path] = msg;
}
function addTreeChangesMessages(messages, messagesHash, rootPath, oldValue, newValue) {
var oldIsTree = valueIsTree(oldValue)
, newIsTree = valueIsTree(newValue);
if (newIsTree)
addMessages(messages, messagesHash, rootPath, newValue, 'added', 'newValue');
if (oldIsTree)
addMessages(messages, messagesHash, rootPath, oldValue, 'removed', 'oldValue');
}
function addMessages(messages, messagesHash, rootPath, obj, msgType, valueProp) {
_addMessages(rootPath, obj);
function _addMessages(rootPath, obj) {
if (Array.isArray(obj)) {
var pathSyntax = rootPath + '[$$]';
obj.forEach(function(value, index) {
addMessage(value, index, pathSyntax);
});
} else {
var pathSyntax = rootPath + '.$$';
_.eachKey(obj, function(value, key) {
addMessage(value, key, pathSyntax);
});
}
}
function addMessage(value, key, pathSyntax) {
var path = pathSyntax.replace('$$', key)
, existingMsg = messagesHash[path];
if (existingMsg) {
if (existingMsg.type == msgType)
logger.error('setter error: same message type posted on the same path');
else {
existingMsg.type = 'changed';
existingMsg[valueProp] = value;
}
} else {
var msg = { path: path, type: msgType };
msg[valueProp] = value;
addChangeMessage(messages, messagesHash, msg);
}
if (valueIsTree(value))
_addMessages(path, value);
}
}
function cloneTree(value) {
return valueIsNormalObject(value)
? _.deepClone(value)
: value;
}
function protectValue(value) {
return ! valueIsNormalObject(value)
? value
: Array.isArray(value)
? value.slice()
: Object.create(value);
}
function valueIsTree(value) {
return valueIsNormalObject(value)
&& Object.keys(value).length;
}
function valueIsNormalObject(value) {
return value != null
&& typeof value == "object"
&& ! (value instanceof Date)
&& ! (value instanceof RegExp);
}
function addBatchIdsToMessage(msg, batchId, msgId) {
_.defineProperties(msg, {
__batch_id: batchId,
__msg_id: msgId
});
}
}
/**
* Exports `synthesize` function with the following:
*
* - .modelMethods.set - `set` method for Model
* - .modelMethods.del - `del` method for Model
* - .modelMethods.splice - `splice` method for Model
*/
module.exports = synthesizePathMethods;
var modelMethods = _.mapKeys(modelSynthesizers, function(synthesizer) {
return _synthesize(synthesizer, '', []);
});
synthesizePathMethods.modelMethods = modelMethods;
},{"../../util/logger":97,"../change_data":86,"../model_utils":91,"../path_utils":93,"dot":100,"fs":75,"protojs":117}],95:[function(require,module,exports){
'use strict';
/**
* `milo.utils.check`
*
* Check is a module for parameters checking extracted from [Meteor](http://docs.meteor.com/) framework.
*
* It allows to both document and to check parameter types in your function
* making code both readable and stable.
*
*
* ### Usage
*```
* var check = milo.check
* , Match = check.Match;
*
* function My(name, obj, cb) {
* // if any of checks fail an error will be thrown
* check(name, String);
* check(obj, Match.ObjectIncluding({ options: Object }));
* check(cb, Function);
*
* // ... your code
* }
*```
* See [Meteor docs](http://docs.meteor.com/#match) to see how it works
*
*
* ### Patterns
*
* All patterns and functions described in Meteor docs work.
*
* Unlike in Meteor, Object pattern matches instance of any class,
* not only plain object.
*
* In addition to patterns described in Meteor docs the following patterns are implemented
*
* * Match.__ObjectHash__(_pattern_)
*
* Matches an object where all properties match a given pattern
*
* * Match.__Subclass__(_constructor_ [, _matchThisClassToo_])
*
* Matches a class that is a subclass of a given class. If the second parameter
* is true, it will also match the class itself.
*
* Without this pattern to check if _MySubclass_ is a subclass of _MyClass_
* you would have to use
*
* check(MySubclass, Match.Where(function() {
* return MySubclass.prototype instanceof MyClass;
* });
*
*
* Things we explicitly do NOT support:
* - heterogenous arrays
**/
var _ = require('protojs')
, config = require('../config');
var check = function (value, pattern) {
if (config.check === false)
return;
// Record that check got called, if somebody cared.
try {
checkSubtree(value, pattern);
} catch (err) {
if ((err instanceof Match.Error) && err.path)
err.message += " in field " + err.path;
throw err;
}
};
module.exports = check;
var Match = check.Match = {
Optional: function (pattern) {
return new Optional(pattern);
},
OneOf: function (/* arguments */) {
return new OneOf(arguments);
},
Any: ['__any__'],
Where: function (condition) {
return new Where(condition);
},
ObjectIncluding: function (pattern) {
return new ObjectIncluding(pattern);
},
// Matches only signed 32-bit integers
Integer: ['__integer__'],
// Matches string that is a valid identifier, will not allow javascript reserved words
IdentifierString: /^[a-z_$][0-9a-z_$]*$/i,
// Matches hash (object) with values matching pattern
ObjectHash: function(pattern) {
return new ObjectHash(pattern);
},
Subclass: function(Superclass, matchSuperclassToo) {
return new Subclass(Superclass, matchSuperclassToo);
},
// XXX matchers should know how to describe themselves for errors
Error: TypeError,
// Meteor.makeErrorType("Match.Error", function (msg) {
// this.message = "Match error: " + msg;
// The path of the value that failed to match. Initially empty, this gets
// populated by catching and rethrowing the exception as it goes back up the
// stack.
// E.g.: "vals[3].entity.created"
// this.path = "";
// If this gets sent over DDP, don't give full internal details but at least
// provide something better than 500 Internal server error.
// this.sanitizedError = new Meteor.Error(400, "Match failed");
// }),
// Tests to see if value matches pattern. Unlike check, it merely returns true
// or false (unless an error other than Match.Error was thrown).
test: function (value, pattern) {
try {
checkSubtree(value, pattern);
return true;
} catch (e) {
if (e instanceof Match.Error)
return false;
// Rethrow other errors.
throw e;
}
}
};
function Optional(pattern) {
this.pattern = pattern;
};
function OneOf(choices) {
if (choices.length == 0)
throw new Error("Must provide at least one choice to Match.OneOf");
this.choices = choices;
};
function Where(condition) {
this.condition = condition;
};
function ObjectIncluding(pattern) {
this.pattern = pattern;
};
function ObjectHash(pattern) {
this.pattern = pattern;
};
function Subclass(Superclass, matchSuperclassToo) {
this.Superclass = Superclass;
this.matchSuperclass = matchSuperclassToo;
};
var typeofChecks = [
[String, "string"],
[Number, "number"],
[Boolean, "boolean"],
[Function, "function"],
// While we don't allow undefined in JSON, this is good for optional
// arguments with OneOf.
[undefined, "undefined"]
];
function checkSubtree(value, pattern) {
// Match anything!
if (pattern === Match.Any)
return;
// Basic atomic types.
// Do not match boxed objects (e.g. String, Boolean)
for (var i = 0; i < typeofChecks.length; ++i) {
if (pattern === typeofChecks[i][0]) {
if (typeof value === typeofChecks[i][1])
return;
throw new Match.Error("Expected " + typeofChecks[i][1] + ", got " +
typeof value);
}
}
if (pattern === null) {
if (value === null)
return;
throw new Match.Error("Expected null, got " + JSON.stringify(value));
}
// Match.Integer is special type encoded with array
if (pattern === Match.Integer) {
// There is no consistent and reliable way to check if variable is a 64-bit
// integer. One of the popular solutions is to get reminder of division by 1
// but this method fails on really large floats with big precision.
// E.g.: 1.348192308491824e+23 % 1 === 0 in V8
// Bitwise operators work consistantly but always cast variable to 32-bit
// signed integer according to JavaScript specs.
if (typeof value === 'number' && (value | 0) === value)
return
throw new Match.Error('Expected Integer, got '
+ (value instanceof Object ? JSON.stringify(value) : value));
}
if (pattern === Match.IdentifierString) {
if (typeof value === 'string' && Match.IdentifierString.test(value)
&& _jsKeywords.indexOf(key) == -1)
return;
throw new Match.Error('Expected identifier string, got '
+ (value instanceof Object ? JSON.stringify(value) : value));
}
// "Object" is shorthand for Match.ObjectIncluding({});
if (pattern === Object)
pattern = Match.ObjectIncluding({});
// Array (checked AFTER Any, which is implemented as an Array).
if (pattern instanceof Array) {
if (pattern.length !== 1)
throw Error("Bad pattern: arrays must have one type element" +
JSON.stringify(pattern));
if (!Array.isArray(value)) {
throw new Match.Error("Expected array, got " + JSON.stringify(value));
}
value.forEach(function (valueElement, index) {
try {
checkSubtree(valueElement, pattern[0]);
} catch (err) {
if (err instanceof Match.Error) {
err.path = _prependPath(index, err.path);
}
throw err;
}
});
return;
}
// Arbitrary validation checks. The condition can return false or throw a
// Match.Error (ie, it can internally use check()) to fail.
if (pattern instanceof Where) {
if (pattern.condition(value))
return;
// XXX this error is terrible
throw new Match.Error("Failed Match.Where validation");
}
if (pattern instanceof Optional)
pattern = Match.OneOf(undefined, pattern.pattern);
if (pattern instanceof OneOf) {
for (var i = 0; i < pattern.choices.length; ++i) {
try {
checkSubtree(value, pattern.choices[i]);
// No error? Yay, return.
return;
} catch (err) {
// Other errors should be thrown. Match errors just mean try another
// choice.
if (!(err instanceof Match.Error))
throw err;
}
}
// XXX this error is terrible
throw new Match.Error("Failed Match.OneOf or Match.Optional validation");
}
// A function that isn't something we special-case is assumed to be a
// constructor.
if (pattern instanceof Function) {
if (value instanceof pattern)
return;
// XXX what if .name isn't defined
throw new Match.Error("Expected " + pattern.constructor.name);
}
var unknownKeysAllowed = false;
if (pattern instanceof ObjectIncluding) {
unknownKeysAllowed = true;
pattern = pattern.pattern;
}
if (pattern instanceof ObjectHash) {
var keyPattern = pattern.pattern;
var emptyHash = true;
for (var key in value) {
emptyHash = false;
check(value[key], keyPattern);
}
if (emptyHash)
throw new Match.Error("Expected " + pattern.constructor.name);
return;
}
if (pattern instanceof Subclass) {
var Superclass = pattern.Superclass;
if (pattern.matchSuperclass && value == Superclass)
return;
if (! (value.prototype instanceof Superclass))
throw new Match.Error("Expected " + pattern.constructor.name + " of " + Superclass.name);
return;
}
if (typeof pattern !== "object")
throw Error("Bad pattern: unknown pattern type");
// An object, with required and optional keys. Note that this does NOT do
// structural matches against objects of special types that happen to match
// the pattern: this really needs to be a plain old {Object}!
if (typeof value !== 'object')
throw new Match.Error("Expected object, got " + typeof value);
if (value === null)
throw new Match.Error("Expected object, got null");
var requiredPatterns = {};
var optionalPatterns = {};
_.eachKey(pattern, function(subPattern, key) {
if (pattern[key] instanceof Optional)
optionalPatterns[key] = pattern[key].pattern;
else
requiredPatterns[key] = pattern[key];
}, this, true);
_.eachKey(value, function(subValue, key) {
var subValue = value[key];
try {
if (requiredPatterns.hasOwnProperty(key)) {
checkSubtree(subValue, requiredPatterns[key]);
delete requiredPatterns[key];
} else if (optionalPatterns.hasOwnProperty(key)) {
checkSubtree(subValue, optionalPatterns[key]);
} else {
if (!unknownKeysAllowed)
throw new Match.Error("Unknown key");
}
} catch (err) {
if (err instanceof Match.Error)
err.path = _prependPath(key, err.path);
throw err;
}
}, this, true);
_.eachKey(requiredPatterns, function(value, key) {
throw new Match.Error("Missing key '" + key + "'");
}, this, true);
};
var _jsKeywords = ["do", "if", "in", "for", "let", "new", "try", "var", "case",
"else", "enum", "eval", "false", "null", "this", "true", "void", "with",
"break", "catch", "class", "const", "super", "throw", "while", "yield",
"delete", "export", "import", "public", "return", "static", "switch",
"typeof", "default", "extends", "finally", "package", "private", "continue",
"debugger", "function", "arguments", "interface", "protected", "implements",
"instanceof"];
// Assumes the base of path is already escaped properly
// returns key + base
function _prependPath(key, base) {
if ((typeof key) === "number" || key.match(/^[0-9]+$/))
key = "[" + key + "]";
else if (!key.match(Match.IdentifierString) || _jsKeywords.indexOf(key) != -1)
key = JSON.stringify([key]);
if (base && base[0] !== "[")
return key + '.' + base;
return key + base;
};
},{"../config":78,"protojs":117}],96:[function(require,module,exports){
'use strict';
/**
* `milo.util`
*/
var util = {
logger: require('./logger'),
check: require('./check'),
doT: require('dot')
};
module.exports = util;
},{"./check":95,"./logger":97,"dot":100}],97:[function(require,module,exports){
'use strict';
// <a name="utils-logger"></a>
// milo.utils.logger
// -----------
// Application logger that has error, warn, info and debug
// methods, that can be suppressed by setting log level.
// Properties:
// - level
// - 0 - error
// - 1 - warn
// - 2 - info
// - 3 - debug (default)
// - enabled
// true by default. Set to false to disable all logging in browser console.
var Logger = require('./logger_class');
var logger = new Logger({ level: 3 });
module.exports = logger;
},{"./logger_class":98}],98:[function(require,module,exports){
'use strict';
// ### Logger Class
// Properties:
// - level
// - 0 - error
// - 1 - warn
// - 2 - info
// - 3 - debug (default)
// - enabled
// true by default. Set to false to disable all logging in browser console.
var _ = require('protojs')
, Messenger = require('../messenger');
/**
* Log levels.
*/
var levels = [
'error',
'warn',
'info',
'debug'
];
var maxLevelLength = Math.max.apply(Math, levels.map(function(level) { return level.length; }));
/**
* Colors for log levels.
*/
var colors = [
31,
33,
36,
90
];
/**
* Pads the nice output to the longest log level.
*/
function pad(str) {
if (str.length < maxLevelLength)
return str + new Array(maxLevelLength - str.length + 1).join(' ');
return str;
};
function colored(str, color) {
return '\x1B[' + color + 'm' + str + ' -\x1B[39m';
}
var DEFAULT_OPTIONS = {
level: 3,
throwLevel: -1, // never throw
enabled: true,
logPrefix: ''
}
/**
* Expose Messenger methods on Logger prototype
*/
var MESSENGER_PROPERTY = '_messenger';
Messenger.useWith(Logger, MESSENGER_PROPERTY, Messenger.defaultMethods);
/**
* Logger (console).
*
* @api public
*/
function Logger(opts) {
_.extend(this, DEFAULT_OPTIONS);
_.extend(this, opts || {});
var messenger = new Messenger(this);
_.defineProperty(this, MESSENGER_PROPERTY, messenger);
};
/**
* Log method.
*
* @api public
*/
Logger.prototype.log = function (type) {
var index = levels.indexOf(type);
if (! this.enabled || index > this.level)
return this;
var args = _.slice(arguments, 1)
, self = this;
if (index <= this.throwLevel)
throw new Error(logString());
if (index <= this.messageLevel)
this.postMessage('log', { level: index, type: type, str: logString() });
console.log.apply(
console
, [ this.logPrefixColor
? ' ' + colored(this.logPrefix, this.logPrefixColor)
: this.logPrefix,
(this.colors
? ' ' + colored(pad(type), colors[index])
: type) + ':'
].concat(args)
);
return this;
function logString() {
return [self.logPrefix, type + ':'].concat(args).join(' ');
}
};
/**
* Generate methods.
*/
levels.forEach(function (name) {
Logger.prototype[name] = function () {
this.log.apply(this, [name].concat(_.toArray(arguments)));
};
});
module.exports = Logger;
},{"../messenger":79,"protojs":117}],99:[function(require,module,exports){
// doT.js
// 2011-2014, Laura Doktorova, https://github.com/olado/doT
// Licensed under the MIT license.
(function() {
"use strict";
var doT = {
version: "1.0.3",
templateSettings: {
evaluate: /\{\{([\s\S]+?(\}?)+)\}\}/g,
interpolate: /\{\{=([\s\S]+?)\}\}/g,
encode: /\{\{!([\s\S]+?)\}\}/g,
use: /\{\{#([\s\S]+?)\}\}/g,
useParams: /(^|[^\w$])def(?:\.|\[[\'\"])([\w$\.]+)(?:[\'\"]\])?\s*\:\s*([\w$\.]+|\"[^\"]+\"|\'[^\']+\'|\{[^\}]+\})/g,
define: /\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\}\}/g,
defineParams:/^\s*([\w$]+):([\s\S]+)/,
conditional: /\{\{\?(\?)?\s*([\s\S]*?)\s*\}\}/g,
iterate: /\{\{~\s*(?:\}\}|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\}\})/g,
varname: "it",
strip: true,
append: true,
selfcontained: false,
doNotSkipEncoded: false
},
template: undefined, //fn, compile template
compile: undefined //fn, for express
}, _globals;
doT.encodeHTMLSource = function(doNotSkipEncoded) {
var encodeHTMLRules = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'", "/": "/" },
matchHTML = doNotSkipEncoded ? /[&<>"'\/]/g : /&(?!#?\w+;)|<|>|"|'|\//g;
return function(code) {
return code ? code.toString().replace(matchHTML, function(m) {return encodeHTMLRules[m] || m;}) : "";
};
};
_globals = (function(){ return this || (0,eval)("this"); }());
if (typeof module !== "undefined" && module.exports) {
module.exports = doT;
} else if (typeof define === "function" && define.amd) {
define(function(){return doT;});
} else {
_globals.doT = doT;
}
var startend = {
append: { start: "'+(", end: ")+'", startencode: "'+encodeHTML(" },
split: { start: "';out+=(", end: ");out+='", startencode: "';out+=encodeHTML(" }
}, skip = /$^/;
function resolveDefs(c, block, def) {
return ((typeof block === "string") ? block : block.toString())
.replace(c.define || skip, function(m, code, assign, value) {
if (code.indexOf("def.") === 0) {
code = code.substring(4);
}
if (!(code in def)) {
if (assign === ":") {
if (c.defineParams) value.replace(c.defineParams, function(m, param, v) {
def[code] = {arg: param, text: v};
});
if (!(code in def)) def[code]= value;
} else {
new Function("def", "def['"+code+"']=" + value)(def);
}
}
return "";
})
.replace(c.use || skip, function(m, code) {
if (c.useParams) code = code.replace(c.useParams, function(m, s, d, param) {
if (def[d] && def[d].arg && param) {
var rw = (d+":"+param).replace(/'|\\/g, "_");
def.__exp = def.__exp || {};
def.__exp[rw] = def[d].text.replace(new RegExp("(^|[^\\w$])" + def[d].arg + "([^\\w$])", "g"), "$1" + param + "$2");
return s + "def.__exp['"+rw+"']";
}
});
var v = new Function("def", "return " + code)(def);
return v ? resolveDefs(c, v, def) : v;
});
}
function unescape(code) {
return code.replace(/\\('|\\)/g, "$1").replace(/[\r\t\n]/g, " ");
}
doT.template = function(tmpl, c, def) {
c = c || doT.templateSettings;
var cse = c.append ? startend.append : startend.split, needhtmlencode, sid = 0, indv,
str = (c.use || c.define) ? resolveDefs(c, tmpl, def || {}) : tmpl;
str = ("var out='" + (c.strip ? str.replace(/(^|\r|\n)\t* +| +\t*(\r|\n|$)/g," ")
.replace(/\r|\n|\t|\/\*[\s\S]*?\*\//g,""): str)
.replace(/'|\\/g, "\\$&")
.replace(c.interpolate || skip, function(m, code) {
return cse.start + unescape(code) + cse.end;
})
.replace(c.encode || skip, function(m, code) {
needhtmlencode = true;
return cse.startencode + unescape(code) + cse.end;
})
.replace(c.conditional || skip, function(m, elsecase, code) {
return elsecase ?
(code ? "';}else if(" + unescape(code) + "){out+='" : "';}else{out+='") :
(code ? "';if(" + unescape(code) + "){out+='" : "';}out+='");
})
.replace(c.iterate || skip, function(m, iterate, vname, iname) {
if (!iterate) return "';} } out+='";
sid+=1; indv=iname || "i"+sid; iterate=unescape(iterate);
return "';var arr"+sid+"="+iterate+";if(arr"+sid+"){var "+vname+","+indv+"=-1,l"+sid+"=arr"+sid+".length-1;while("+indv+"<l"+sid+"){"
+vname+"=arr"+sid+"["+indv+"+=1];out+='";
})
.replace(c.evaluate || skip, function(m, code) {
return "';" + unescape(code) + "out+='";
})
+ "';return out;")
.replace(/\n/g, "\\n").replace(/\t/g, '\\t').replace(/\r/g, "\\r")
.replace(/(\s|;|\}|^|\{)out\+='';/g, '$1').replace(/\+''/g, "");
//.replace(/(\s|;|\}|^|\{)out\+=''\+/g,'$1out+=');
if (needhtmlencode) {
if (!c.selfcontained && _globals && !_globals._encodeHTML) _globals._encodeHTML = doT.encodeHTMLSource(c.doNotSkipEncoded);
str = "var encodeHTML = typeof _encodeHTML !== 'undefined' ? _encodeHTML : ("
+ doT.encodeHTMLSource.toString() + "(" + (c.doNotSkipEncoded || '') + "));"
+ str;
}
try {
return new Function(c.varname, str);
} catch (e) {
if (typeof console !== "undefined") console.log("Could not create a template function: " + str);
throw e;
}
};
doT.compile = function(tmpl, def) {
return doT.template(tmpl, null, def);
};
}());
},{}],100:[function(require,module,exports){
/* doT + auto-compilation of doT templates
*
* 2012, Laura Doktorova, https://github.com/olado/doT
* Licensed under the MIT license
*
* Compiles .def, .dot, .jst files found under the specified path.
* It ignores sub-directories.
* Template files can have multiple extensions at the same time.
* Files with .def extension can be included in other files via {{#def.name}}
* Files with .dot extension are compiled into functions with the same name and
* can be accessed as renderer.filename
* Files with .jst extension are compiled into .js files. Produced .js file can be
* loaded as a commonJS, AMD module, or just installed into a global variable
* (default is set to window.render).
* All inline defines defined in the .jst file are
* compiled into separate functions and are available via _render.filename.definename
*
* Basic usage:
* var dots = require("dot").process({path: "./views"});
* dots.mytemplate({foo:"hello world"});
*
* The above snippet will:
* 1. Compile all templates in views folder (.dot, .def, .jst)
* 2. Place .js files compiled from .jst templates into the same folder.
* These files can be used with require, i.e. require("./views/mytemplate").
* 3. Return an object with functions compiled from .dot templates as its properties.
* 4. Render mytemplate template.
*/
var fs = require("fs"),
doT = module.exports = require("./doT");
doT.process = function(options) {
//path, destination, global, rendermodule, templateSettings
return new InstallDots(options).compileAll();
};
function InstallDots(o) {
this.__path = o.path || "./";
if (this.__path[this.__path.length-1] !== '/') this.__path += '/';
this.__destination = o.destination || this.__path;
if (this.__destination[this.__destination.length-1] !== '/') this.__destination += '/';
this.__global = o.global || "window.render";
this.__rendermodule = o.rendermodule || {};
this.__settings = o.templateSettings ? copy(o.templateSettings, copy(doT.templateSettings)) : undefined;
this.__includes = {};
}
InstallDots.prototype.compileToFile = function(path, template, def) {
def = def || {};
var modulename = path.substring(path.lastIndexOf("/")+1, path.lastIndexOf("."))
, defs = copy(this.__includes, copy(def))
, settings = this.__settings || doT.templateSettings
, compileoptions = copy(settings)
, defaultcompiled = doT.template(template, settings, defs)
, exports = []
, compiled = ""
, fn;
for (var property in defs) {
if (defs[property] !== def[property] && defs[property] !== this.__includes[property]) {
fn = undefined;
if (typeof defs[property] === 'string') {
fn = doT.template(defs[property], settings, defs);
} else if (typeof defs[property] === 'function') {
fn = defs[property];
} else if (defs[property].arg) {
compileoptions.varname = defs[property].arg;
fn = doT.template(defs[property].text, compileoptions, defs);
}
if (fn) {
compiled += fn.toString().replace('anonymous', property);
exports.push(property);
}
}
}
compiled += defaultcompiled.toString().replace('anonymous', modulename);
fs.writeFileSync(path, "(function(){" + compiled
+ "var itself=" + modulename + ", _encodeHTML=(" + doT.encodeHTMLSource.toString() + "(" + (settings.doNotSkipEncoded || '') + "));"
+ addexports(exports)
+ "if(typeof module!=='undefined' && module.exports) module.exports=itself;else if(typeof define==='function')define(function(){return itself;});else {"
+ this.__global + "=" + this.__global + "||{};" + this.__global + "['" + modulename + "']=itself;}}());");
};
function addexports(exports) {
for (var ret ='', i=0; i< exports.length; i++) {
ret += "itself." + exports[i]+ "=" + exports[i]+";";
}
return ret;
}
function copy(o, to) {
to = to || {};
for (var property in o) {
to[property] = o[property];
}
return to;
}
function readdata(path) {
var data = fs.readFileSync(path);
if (data) return data.toString();
console.log("problems with " + path);
}
InstallDots.prototype.compilePath = function(path) {
var data = readdata(path);
if (data) {
return doT.template(data,
this.__settings || doT.templateSettings,
copy(this.__includes));
}
};
InstallDots.prototype.compileAll = function() {
console.log("Compiling all doT templates...");
var defFolder = this.__path,
sources = fs.readdirSync(defFolder),
k, l, name;
for( k = 0, l = sources.length; k < l; k++) {
name = sources[k];
if (/\.def(\.dot|\.jst)?$/.test(name)) {
console.log("Loaded def " + name);
this.__includes[name.substring(0, name.indexOf('.'))] = readdata(defFolder + name);
}
}
for( k = 0, l = sources.length; k < l; k++) {
name = sources[k];
if (/\.dot(\.def|\.jst)?$/.test(name)) {
console.log("Compiling " + name + " to function");
this.__rendermodule[name.substring(0, name.indexOf('.'))] = this.compilePath(defFolder + name);
}
if (/\.jst(\.dot|\.def)?$/.test(name)) {
console.log("Compiling " + name + " to file");
this.compileToFile(this.__destination + name.substring(0, name.indexOf('.')) + '.js',
readdata(defFolder + name));
}
}
return this.__rendermodule;
};
},{"./doT":99,"fs":75}],101:[function(require,module,exports){
'use strict';
/**
* - [find](#find)
* - [findIndex](#findIndex)
* - [appendArray](#appendArray)
* - [prependArray](#prependArray)
* - [spliceItem](#spliceItem)
* - [toArray](#toArray)
* - [object](#object)
* - [mapToObject](#mapToObject)
* - [unique](#unique)
* - [deepForEach](#deepForEach)
*
* These methods can be [chained](proto.js.html#Proto).
*/
module.exports = {
find: find,
findIndex: findIndex,
appendArray: appendArray,
prependArray: prependArray,
toArray: toArray,
object: object,
mapToObject: mapToObject,
unique: unique,
deepForEach: deepForEach,
spliceItem: spliceItem
};
/**
* Functions that Array [implements natively](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Methods) are also included for convenience - they can be used with array-like objects and for chaining (native functions are always called).
* These functions can be [chained](proto.js.html#Proto) too.
*/
var nativeMethods = ['join', 'pop', 'push', 'concat', 'reverse', 'shift', 'unshift', 'slice', 'splice', 'sort', 'filter', 'forEach', 'some', 'every', 'map', 'indexOf', 'lastIndexOf', 'reduce', 'reduceRight', 'find', 'findIndex'];
for (var i = 0; i < nativeMethods.length; i++) {
var name = nativeMethods[i];
var nativeFunc = Array.prototype[name];
if (!nativeFunc) continue;
module.exports[name] = (function(method) {
return function() {
return method.call.apply(method, arguments);
};
})(nativeFunc);
}
/**
* Implementation of ES6 [Array __find__ method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) (native method is used if available).
* Returns array element that passes callback test.
*
* @param {Array} self array to search in
* @param {Function} callback should return `true` for item to pass the test, passed `value`, `index` and `self` as parameters
* @param {Object} thisArg optional context (`this`) of callback call
* @return {Any}
*/
function find(self, callback, thisArg) {
for (var i = 0; i < self.length; i++) {
var item = self[i];
if (callback.call(thisArg, item, i, self)) {
return item;
}
}
return undefined;
}
/**
* Implementation of ES6 [Array __findIndex__ method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) (native method is used if available).
* Returns the index of array element that passes callback test. Returns `-1` if not found.
*
* @param {Array} self array to search in
* @param {Function} callback should return `true` for item to pass the test, passed `value`, `index` and `self` as parameters
* @param {Object} thisArg optional context (`this`) of callback call
* @return {Integer}
*/
function findIndex(self, callback, thisArg) {
for (var i = 0; i < self.length; i++) {
var item = self[i];
if (callback.call(thisArg, item, i, self)) {
return i;
}
}
return -1;
}
/**
* Appends `sourceArr` to the end of array `self` in place (can be an instance of Array or array-like object).
* Changes the value of `self` (it uses `Array.prototype.splice`) and returns `self`.
*
* @param {Array} self An array that will be modified
* @param {Array} sourceArr An array that will be appended
* @return {Array}
*/
function appendArray(self, sourceArr) {
if (!sourceArr.length) return self;
if (!Array.isArray(sourceArr)) sourceArr = Array.prototype.slice.call(sourceArr);
var args = [self.length, 0].concat(sourceArr);
Array.prototype.splice.apply(self, args);
return self;
}
/**
* Prepends `sourceArr` to the beginnig of array `self` in place (can be an instance of Array or array-like object).
* Changes the value of `self` (it uses `Array.prototype.splice`) and returns `self`.
*
* @param {Array} self An array that will be modified
* @param {Array} sourceArr An array that will be prepended
* @return {Array}
*/
function prependArray(self, sourceArr) {
if (!sourceArr.length) return self;
if (!Array.isArray(sourceArr)) sourceArr = Array.prototype.slice.call(sourceArr);
var args = [0, 0].concat(sourceArr);
Array.prototype.splice.apply(self, args);
return self;
}
/**
* Returns new array created from array-like object (e.g., `arguments` pseudo-array).
*
* @param {PseudoArray} self Object with numeric property length
* @return {Array}
*/
function toArray(self) {
return Array.prototype.slice.call(self);
}
/**
* Returns an object created from the array of `keys` and optional array of `values`.
*
* @param {Array} self Array of keys
* @param {Array|any} values Optional array of values or the value to be assigned to each property.
* @return {Object}
*/
function object(self, values) {
var obj = {};
var valuesIsArray = Array.isArray(values);
for (var i = 0; i < self.length; i++) obj[self[i]] = valuesIsArray ? values[i] : values;
return obj;
}
/**
* Maps array to object.
* Array elements become keys, value are taken from `callback`.
*
* @param {Array} self An array which values will become keys of the result
* @param {Function} callback Callback is passed `value`, `index` and `self` and should return value that will be included in the result.
* @param {Object} thisArg An optional context of iteration (the valueof `this`), will be undefined if this parameter is not passed.
* @return {Object}
*/
function mapToObject(self, callback, thisArg) {
var obj = {};
for (var i = 0; i < self.length; i++) {
var value = self[i];
obj[value] = callback.call(thisArg, value, i, self);
}
return obj;
}
/**
* Returns array without duplicates. Does not modify original array.
*
* @param {Array} self original array
* @param {Function} callback comparison function, should return true for equal items, "===" is used if not passed.
* @return {Array}
*/
function unique(self, callback) {
var filtered = [];
if (callback) {
for (var i = 0; i < self.length; i++) {
var item = self[i];
var index = -1;
for (var j = 0; j < filtered.length; j++) {
if (callback(item, filtered[j])) {
index = i;
break;
}
}
if (index == -1) filtered[filtered.length] = item;
}
} else {
for (var i = 0; i < self.length; i++) {
var item = self[i];
var index = filtered.indexOf(item);
if (index == -1) filtered[filtered.length] = item;
}
}
return filtered;
}
/**
* Iterates array and elements that are arrays calling callback with each element that is not an array. Can be used to iterate over arguments list to avoid checking whether array or list of parameters is passed.
*
* @param {Array} self array of elements and arraysto iterate.
* @param {Function} callback called for each item that is not an array. Callback is passed item, index and original array as parameters.
* @param {Any} thisArg optional callback envocation context
*/
function deepForEach(self, callback, thisArg) {
var index = 0;
_deepForEach(self);
function _deepForEach(arr) {
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
if (Array.isArray(item)) _deepForEach(item, callback, thisArg);
else callback.call(thisArg, item, index++, self);
}
}
}
/**
* Removes item from array that is found using indexOf (i.e. '===')
* Modifies original array and returns the reference to it.
*
* @param {Array} self An array that will be modified
* @param {Any} item item to be removed
* @return {Array}
*/
function spliceItem(self, item) {
var index = self.indexOf(item);
if (index >= 0) self.splice(index, 1);
return self;
}
},{}],102:[function(require,module,exports){
'use strict';
/**
* - [makeFunction](#makeFunction)
* - [partial](#partial)
* - [partialRight](#partialRight)
* - [memoize](#memoize)
* - [delay](#delay)
* - [defer](#defer)
* - [delayed](#delayed)
* - [deferred](#deferred)
* - [deferTicks](#deferTicks)
* - [delayMethod](#delayMethod)
* - [deferMethod](#deferMethod)
* - [debounce](#debounce)
* - [throttle](#throttle)
* - [once](#once)
* - [waitFor](#waitFor)
* - [not](#not)
*
* These methods can be [chained](proto.js.html#Proto)
*/
module.exports = {
makeFunction: makeFunction,
partial: partial,
partialRight: partialRight,
memoize: memoize,
delay: delay,
defer: defer,
delayed: delayed,
deferred: deferred,
deferTicks: deferTicks,
delayMethod: delayMethod,
deferMethod: deferMethod,
debounce: debounce,
throttle: throttle,
once: once,
waitFor: waitFor,
not: not
};
var slice = Array.prototype.slice;
/**
* Similarly to Function constructor creates a function from code.
* Unlike Function constructor, the first argument is a function name
*
* @param {String} self new function name
* @param {String} arg1, arg2, ... the names of function parameters
* @param {String} funcBody function body
* @return {Function}
*/
function makeFunction(self, arg1, arg2, funcBody) {
var name = self,
count = arguments.length - 1,
funcBody = arguments[count],
func, code = '';
for (var i = 1; i < count; i++) code += ', ' + arguments[i];
code = ['func = function ', name, '(', code.slice(2), ') {\n', funcBody, '\n}'].join('');
eval(code);
return func;
}
/**
* Creates a function as a result of partial function application with the passed parameters.
*
* @param {Function} self Function to be applied
* @param {List} arguments Arguments after self will be prepended to the original function call when the partial function is called.
* @return {Function}
*/
function partial(self) { // , ... arguments
var args = slice.call(arguments, 1);
var func = function() {
return self.apply(this, args.concat(slice.call(arguments)));
};
return func;
}
/**
* Creates a function as a result of partial function application with the passed parameters, but parameters are appended on the right.
*
* @param {Function} self Function to be applied
* @param {List} arguments Arguments after self will be appended on the right to the original function call when the partial function is called.
* @return {Function}
*/
function partialRight(self) { // , ... arguments
var args = slice.call(arguments, 1);
var func = function() {
return self.apply(this, slice.call(arguments).concat(args));
};
return func;
}
/**
* Creates a memoized version of the function using supplied hash function as key. If the hash is not supplied, uses its first parameter as the hash.
*
* @param {Function} self function to be memoized
* @param {Function} hashFunc optional hash function that is passed all function arguments and should return cache key.
* @param {Integer} limit optional maximum number of results to be stored in the cache. 1000 by default.
* @return {Function} memoized function
*/
function memoize(self, hashFunc, limit) {
var cache = {},
keysList = [];
limit = limit || 1000;
var func = function() {
var key = hashFunc ? hashFunc.apply(this, arguments) : arguments[0];
if (cache.hasOwnProperty(key)) return cache[key];
var result = cache[key] = self.apply(this, arguments);
keysList.push(key);
if (keysList.length > limit) delete cache[keysList.shift()];
return result;
};
return func;
}
/**
* Delays function execution by a given time in milliseconds.
* The context in function when it is executed is set to `null`.
*
* @param {Function} self function that execution has to be delayed
* @param {Number} wait approximate dalay time in milliseconds
* @param {List} arguments optional arguments that will be passed to the function
*/
function delay(self, wait) { // , arguments
var args = slice.call(arguments, 2);
var id = setTimeout(function() {
self.apply(null, args);
}, wait);
return id;
}
/**
* Defers function execution (executes as soon as execution loop becomes free)
* The context in function when it is executed is set to `null`.
*
* @param {Function} self function that execution has to be delayed
* @param {List} arguments optional arguments that will be passed to the function
*/
function defer(self) { // , arguments
var args = slice.call(arguments, 1);
var id = setTimeout(function() {
self.apply(null, args);
});
return id;
}
/**
* Returns function that will execute the original function `wait` ms after it has been called
* The context in function when it is executed is set to `null`.
* Arguments passed to the function are appended to the arguments passed to delayed.
*
* @param {Function} self function which execution has to be deferred
* @param {Number} wait approximate dalay time in milliseconds
* @param {List} arguments optional arguments that will be passed to the function
* @return {Function}
*/
function delayed(self, wait) { //, ... arguments
var args = slice.call(arguments, 2);
var func = function() { // ... arguments
var passArgs = args.concat(slice.call(arguments));
var context = this;
return setTimeout(function() {
self.apply(context, passArgs);
}, wait);
};
return func;
}
/**
* Returns function that will execute the original function on the next tick once it has been called
* The context in function when it is executed is set to `null`.
* Arguments passed to the function are appended to the arguments passed to deferred.
*
* @param {Function} self function which execution has to be deferred
* @param {List} arguments optional arguments that will be passed to the function
* @return {Function}
*/
function deferred(self) { //, ... arguments
var args = slice.call(arguments, 1);
var func = function() { // ... arguments
var passArgs = args.concat(slice.call(arguments));
var context = this;
return setTimeout(function() {
self.apply(context, passArgs);
});
};
return func;
}
/**
* Defers function execution for `times` ticks (executes after execution loop becomes free `times` times)
* The context in function when it is executed is set to `null`.
*
* @param {Function} self function that execution has to be delayed
* @param {Integer} ticks number of times to defer execution
* @param {List} arguments optional arguments that will be passed to the function
*/
function deferTicks(self, ticks) { // , arguments
var id;
if (ticks < 2) {
var args = slice.call(arguments, 2);
id = setTimeout(function() {
self.apply(null, args);
});
} else {
var args = arguments;
args[1] = ticks - 1;
id = setTimeout(function() {
deferTicks.apply(null, args);
});
}
return id;
}
/**
* Works like _.delay but allows to defer method call of `self` which will be the first _.delayMethod parameter
*
* @param {Object} self object to delay method call of
* @param {Function|String} funcOrMethodName function or name of method
* @param {Number} wait approximate dalay time in milliseconds
* @param {List} arguments arguments to pass to method
*/
function delayMethod(self, funcOrMethodName, wait) { // , ... arguments
var args = slice.call(arguments, 3);
var func = typeof funcOrMethodName == 'string' ? self[funcOrMethodName] : funcOrMethodName;
var id = setTimeout(function() {
func.apply(self, args);
}, wait);
return id;
}
/**
* Works like _.defer but allows to defer method call of `self` which will be the first _.deferMethod parameter
*
* @param {Object} self object to defer method call of
* @param {Function|String} funcOrMethodName function or name of method
* @param {List} arguments arguments to pass to method
*/
function deferMethod(self, funcOrMethodName) { // , ... arguments
var args = slice.call(arguments, 2);
var func = typeof funcOrMethodName == 'string' ? self[funcOrMethodName] : funcOrMethodName;
var id = setTimeout(function() {
func.apply(self, args);
});
return id;
}
/**
* Creates a function that will call original function once it has not been called for a specified time
*
* @param {Function} self function that execution has to be delayed
* @param {Number} wait approximate dalay time in milliseconds
* @param {Boolean} immediate true to invoke funciton immediately and then ignore following calls for wait milliseconds
* @return {Function}
*/
function debounce(self, wait, immediate) {
var timeout, args, context, timestamp, result;
var func = function() {
context = this; // store original context
args = arguments;
timestamp = Date.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) result = self.apply(context, args);
return result;
function later() {
var last = Date.now() - timestamp;
if (last < wait) timeout = setTimeout(later, wait - last);
else {
timeout = null;
if (!immediate) result = self.apply(context, args);
}
}
};
return func;
}
/**
* Returns a function, that, when invoked, will only be triggered at most once during a given window of time.
*
* @param {Function} self function that execution has to be delayed
* @param {Number} wait approximate delay time in milliseconds
* @param {Object} options `{leading: false}` to disable the execution on the leading edge
* @return {Function}
*/
function throttle(self, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
options || (options = {});
var func = function() {
var now = Date.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = self.apply(context, args);
} else if (!timeout && options.trailing !== false) timeout = setTimeout(later, remaining);
return result;
};
return func;
function later() {
previous = options.leading === false ? 0 : Date.now();
timeout = null;
result = self.apply(context, args);
}
}
/**
* Call passed function only once
* @return {Function} self
*/
function once(self) {
var ran = false,
memo;
var func = function() {
if (ran) return memo;
ran = true;
memo = self.apply(this, arguments);
self = null;
return memo;
};
return func;
}
/**
* Execute a function when the condition function returns a truthy value
* it runs the condition function every `checkInterval` milliseconds (default 50)
*
* @param {Function} self function: if it returns true the callback is executed
* @param {Function} callback runs when the condition is true
* @param {Number} maxTimeout timeout before giving up (time in milliseconds)
* @param {Function} timedOutFunc a function called if timeout is reached
* @param {Number} checkInterval time interval when you run the condition function (time in milliseconds), default 50 ms
*/
function waitFor(self, callback, maxTimeout, timedOutFunc, checkInterval) {
var start = Date.now();
checkInterval = checkInterval || 50;
var id = setInterval(testCondition, checkInterval);
return id;
function testCondition() {
if (self()) callback();
else if (Date.now() - start >= maxTimeout) timedOutFunc && timedOutFunc();
else return;
clearInterval(id);
};
}
/**
* returns the function that negates (! operator) the result of the original function
* @param {Function} self function to negate
* @return {Function}
*/
function not(self) {
var func = function() {
return !self.apply(this, arguments);
};
return func;
}
},{}],103:[function(require,module,exports){
'use strict';
module.exports = {
array: require('./array'),
function: require('./function'),
number: require('./number'),
object: require('./object'),
prototype: require('./prototype'),
string: require('./string'),
utils: require('./utils')
};
},{"./array":101,"./function":102,"./number":104,"./object":105,"./prototype":106,"./string":107,"./utils":108}],104:[function(require,module,exports){
'use strict';
/**
* - [isNumeric](#isNumeric)
*/
var numberMethods = module.exports = {
isNumeric: isNumeric
};
/**
* Function to test if a value is numeric
*
* @param {Any} self value to be tested
* @return {Boolean} true if it is a numeric value
*/
function isNumeric(self) {
var result = !isNaN(parseFloat(self)) && isFinite(self);
return result;
}
},{}],105:[function(require,module,exports){
'use strict';
/**
* - [extend](#extend)
* - [clone](#clone)
* - [defineProperty](#defineProperty)
* - [defineProperties](#defineProperties)
* - [deepExtend](#deepExtend)
* - [deepClone](#deepClone)
* - [keys](#keys)
* - [allKeys](#allKeys)
* - [values](#values)
* - [keyOf](#keyOf)
* - [allKeysOf](#allKeysOf)
* - [eachKey](#eachKey)
* - [mapKeys](#mapKeys)
* - [reduceKeys](#reduceKeys)
* - [filterKeys](#filterKeys)
* - [someKey](#someKey)
* - [everyKey](#everyKey)
* - [findValue](#findValue)
* - [findKey](#findKey)
* - [pickKeys](#pickKeys)
* - [omitKeys](#omitKeys)
* - [isEqual](#isEqual)
* - [isNot](#isNot)
*
* All these methods can be [chained](proto.js.html#Proto)
*/
module.exports = {
extend: extend,
clone: clone,
findValue: findValue,
findKey: findKey,
defineProperty: defineProperty,
defineProperties: defineProperties,
deepExtend: deepExtend,
deepClone: deepClone,
keys: keys,
allKeys: allKeys,
values: values,
keyOf: keyOf,
allKeysOf: allKeysOf,
eachKey: eachKey,
mapKeys: mapKeys,
reduceKeys: reduceKeys,
filterKeys: filterKeys,
someKey: someKey,
everyKey: everyKey,
pickKeys: pickKeys,
omitKeys: omitKeys,
isEqual: isEqual,
isNot: isNot
};
var concat = Array.prototype.concat;
/**
* ####Property descriptor constants####
* The sum of these constants can be used as last parameter of defineProperty and defineProperties to determine types of properties.
*/
var constants = module.exports._constants = {
ENUMERABLE: 1,
ENUM: 1,
CONFIGURABLE: 2,
CONF: 2,
WRITABLE: 4,
WRIT: 4
};
/**
* Extends object `self` with the properties of the object `obj` copying all own properties (not those inherited via prototype chain), including non-enumerable properties (unless `onlyEnumerable` is truthy).
* Created properties will have the same descriptors as the propertis of `obj`.
* Returns `self` to allow chaining with other functions.
* Can be used with functions, to copy class methods, e.g.
*
* @param {Object} self An object to be extended
* @param {Object} obj An object which properties will be copied to self
* @param {Boolean} onlyEnumerable Optional flag to prevent copying non-enumerable properties, `false` by default
* @return {Object}
*/
function extend(self, obj, onlyEnumerable) {
var descriptors = {};
var key;
if (onlyEnumerable) {
for (key in obj) {
descriptors[key] = Object.getOwnPropertyDescriptor(obj, key);
}
} else {
var keys = Object.getOwnPropertyNames(obj);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
descriptors[key] = Object.getOwnPropertyDescriptor(obj, key);
}
}
Object.defineProperties(self, descriptors);
return self;
}
/**
* Makes a shallow clone of object `obj` creating an instance of the same class; the properties will have the same descriptors.
* To clone an array use
* ```
* var clonedArray = [].concat(arr);
* ```
* This function should not be used to clone an array, because it is inefficient.
*
* @param {Object} self An object to be cloned
* @param {Boolean} onlyEnumerable Optional flag to prevent copying non-enumerable properties, `false` by default
* @return {Object}
*/
function clone(self, onlyEnumerable) {
var clonedObject;
if (Array.isArray(self)) clonedObject = self.slice();
else if (self instanceof Date) clonedObject = new Date(self);
else if (self instanceof RegExp) clonedObject = new RegExp(self);
if (!clonedObject) {
var descriptors = {};
var key;
if (onlyEnumerable) {
for (key in self) {
descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
}
}
clonedObject = Object.create(self.constructor.prototype, descriptors);
}
return clonedObject;
}
/**
* Analogue of ES6 [Array __find__ method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find).
* Returns the value of object property that passes callback test.
*
* @param {Object} self object to search in
* @param {Function} callback should return `true` for item to pass the test, passed `value`, `key` and `self` as parameters
* @param {Object} thisArg optional context (`this`) of callback call
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
* @return {Any}
*/
function findValue(self, callback, thisArg, onlyEnumerable) {
var result = undefined;
var key;
if (onlyEnumerable) {
for (key in self) {
var item = self[key];
if (callback.call(thisArg, item, key, self)) {
result = item;
break;
}
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
var item = self[key];
if (callback.call(thisArg, item, key, self)) {
result = item;
break;
}
}
}
return result;
}
/**
* Analogue of ES6 [Array __findIndex__ method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex).
* Returns the key of object property that passes callback test. Returns `undefined` if not found (unlike `findIndex`, that returns -1 in this case).
*
* @param {Object} self object to search in
* @param {Function} callback should return `true` for item to pass the test, passed `value`, `key` and `self` as parameters
* @param {Object} thisArg optional context (`this`) of callback call
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
* @return {Integer}
*/
function findKey(self, callback, thisArg, onlyEnumerable) {
var result = undefined;
var key;
if (onlyEnumerable) {
for (key in self) {
var item = self[key];
if (callback.call(thisArg, item, key, self)) {
result = key;
break;
}
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
var item = self[key];
if (callback.call(thisArg, item, key, self)) {
result = key;
break;
}
}
}
return result;
}
/**
* Syntax sugar to shorten usage of `Object.defineProperty`.
* The simplest usage (to add non-enumerable, non-configurable, non-writable property):
* ```
* _.defineProperty(obj, 'key', value);
* ```
*
* To define some other properties use sum of the flags `_.ENUMERABLE` (or `_.ENUM`), `_.CONFIGURABLE` (or `_.CONF`) and `_.WRITABLE` (or `_.WRIT`):
* ```
* _.defineProperty(obj, 'key', value, _.ENUM + _.WRIT);
* ```
* Returns `self`.
*
* @param {Object} self An object to add a property to
* @param {String} propertyName the name of the property that will be added
* @param {Any} value the value of added property
* @param {Integer} decriptorFlags bit mask of property descriptor properties composed from `_.ENUMERABLE` (or `_.ENUM`), `_.CONFIGURABLE` (or `_.CONF`) and `_.WRITABLE` (or `_.WRIT`)
* @return {Object}
*/
function defineProperty(self, propertyName, value, decriptorFlags) {
var descriptor = {
value: value
};
if (decriptorFlags) {
descriptor.enumerable = !!(decriptorFlags & constants.ENUMERABLE);
descriptor.configurable = !!(decriptorFlags & constants.CONFIGURABLE);
descriptor.writable = !!(decriptorFlags & constants.WRITABLE);
}
Object.defineProperty(self, propertyName, descriptor);
return self;
}
/**
* Syntax sugar to shorten usage of `Object.defineProperties`.
* The simplest usage (to add non-enumerable, non-configurable, non-writable properties):
* ```
* _.defineProperties(obj, {
* key1: value1,
* key2: value2
* });
* ```
* To define some other properties use sum of the flags `_.ENUMERABLE` (or `_.ENUM`), `_.CONFIGURABLE` (or `_.CONF`) and `_.WRITABLE` (or `_.WRIT`):
* ```
* _.defineProperties(obj, {
* key1: value1,
* key2: value2
* }, _.ENUM + _.WRIT);
* ```
* Returns `self`.
*
* @param {Object} self An object to add a property to
* @param {Object} propertyValues A map of keys and values of properties thatwill be added. The descriptors of properties will be defined by the following parameters.
* @param {Integer} decriptorFlags bit mask of property descriptor properties composed from `_.ENUMERABLE` (or `_.ENUM`), `_.CONFIGURABLE` (or `_.CONF`) and `_.WRITABLE` (or `_.WRIT`)
* @return {Object}
*/
function defineProperties(self, propertyValues, decriptorFlags) {
var descriptors = {};
var key;
var keys = Object.getOwnPropertyNames(propertyValues);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
var value = propertyValues[key];
var descriptor = {
value: value
};
if (decriptorFlags) {
descriptor.enumerable = !!(decriptorFlags & constants.ENUMERABLE);
descriptor.configurable = !!(decriptorFlags & constants.CONFIGURABLE);
descriptor.writable = !!(decriptorFlags & constants.WRITABLE);
}
descriptors[key] = descriptor;
}
Object.defineProperties(self, descriptors);
return self;
}
/**
* Extends object `self` with properties of `obj` to any depth, without overwrtiting existing object properties of `self` with object properties of `obj`.
* Scalar properties of `obj` will overwrite properties of `self`. Scalar porperties of `self` will also be overwritten.
* Correctly works with recursive objects.
* Usage:
* ```
* var obj = {
* inner: {
* a: 1
* }
* };
*
* _.deepExtend(obj, {
* inner: {
* b: 2
* }
* });
*
* assert.deepEqual(obj, {
* inner: {
* a: 1,
* b: 2
* }
* }); // assert passes
* ```
* Returns `self`.
*
* @param {Object} self An object to be extended
* @param {Object} obj An object with properties to copy to
* @param {Boolean} onlyEnumerable Optional `true` to use only enumerable properties
* @param {Boolean} preserveStructure if true will throw at the attempt to overwrite object with scalar value (including Date and Regex) and vice versa
* @return {Object}
*/
function deepExtend(self, obj, onlyEnumerable, preserveStructure) {
var result = _extendTree(self, obj, onlyEnumerable, preserveStructure, []);
return result;
}
function _extendTree(selfNode, objNode, onlyEnumerable, preserveStructure, objTraversed) {
if (objTraversed.indexOf(objNode) >= 0) return selfNode; // node already traversed, obj has recursion
// store node to recognise recursion
objTraversed.push(objNode);
if (Array.isArray(objNode)) {
for (var key = 0; key < objNode.length; key++) {
var value = objNode[key];
var hasProp = selfNode.hasOwnProperty(key);
var selfValue = selfNode[key];
var isSelfObj = typeof selfValue == "object" && selfValue != null && !(selfValue instanceof RegExp) && !(selfValue instanceof Date);
var isValueObj = typeof value == "object" && value != null && !(value instanceof RegExp) && !(value instanceof Date);
if (preserveStructure && hasProp && isSelfObj != isValueObj) throw new Error("deepExtend");
if (isValueObj) {
if (!hasProp || !isSelfObj) selfNode[key] = (Array.isArray(value)) ? [] : {};
_extendTree(selfNode[key], value, onlyEnumerable, preserveStructure, objTraversed);
} else {
var descriptor = Object.getOwnPropertyDescriptor(objNode, key);
Object.defineProperty(selfNode, key, descriptor);
}
}
} else {
var key;
if (onlyEnumerable) {
for (key in objNode) {
var value = objNode[key];
var hasProp = selfNode.hasOwnProperty(key);
var selfValue = selfNode[key];
var isSelfObj = typeof selfValue == "object" && selfValue != null && !(selfValue instanceof RegExp) && !(selfValue instanceof Date);
var isValueObj = typeof value == "object" && value != null && !(value instanceof RegExp) && !(value instanceof Date);
if (preserveStructure && hasProp && isSelfObj != isValueObj) throw new Error("deepExtend");
if (isValueObj) {
if (!hasProp || !isSelfObj) selfNode[key] = (Array.isArray(value)) ? [] : {};
_extendTree(selfNode[key], value, onlyEnumerable, preserveStructure, objTraversed);
} else {
var descriptor = Object.getOwnPropertyDescriptor(objNode, key);
Object.defineProperty(selfNode, key, descriptor);
}
}
} else {
var keys = Object.getOwnPropertyNames(objNode);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
var value = objNode[key];
var hasProp = selfNode.hasOwnProperty(key);
var selfValue = selfNode[key];
var isSelfObj = typeof selfValue == "object" && selfValue != null && !(selfValue instanceof RegExp) && !(selfValue instanceof Date);
var isValueObj = typeof value == "object" && value != null && !(value instanceof RegExp) && !(value instanceof Date);
if (preserveStructure && hasProp && isSelfObj != isValueObj) throw new Error("deepExtend");
if (isValueObj) {
if (!hasProp || !isSelfObj) selfNode[key] = (Array.isArray(value)) ? [] : {};
_extendTree(selfNode[key], value, onlyEnumerable, preserveStructure, objTraversed);
} else {
var descriptor = Object.getOwnPropertyDescriptor(objNode, key);
Object.defineProperty(selfNode, key, descriptor);
}
}
}
}
return selfNode;
}
/**
* Clones all object tree. Class of original object is not preserved. Returns `self`
*
* @param {Object} self An object to be extended
* @param {Boolean} onlyEnumerable Optional `true` to use only enumerable properties
* @return {Object}
*/
function deepClone(self, onlyEnumerable) {
var clonedObject;
if (self instanceof Date) clonedObject = new Date(self);
else if (self instanceof RegExp) clonedObject = new RegExp(self);
else {
clonedObject = Array.isArray(self) ? [] : {};
_extendTree(clonedObject, self, onlyEnumerable, false, []);
}
return clonedObject;
}
/**
* Returns array of enumerable properties of the object
*
* @param {Object} self object to return keys of
* @return {Array}
*/
function keys(self) {
var keys = Object.keys(self);
return keys;
}
/**
* Returns array of all property names of an object `self` (including non-enumerbale).
* To get only enumerable properties, use `Object.keys()`.
*
* @param {Object} self An object to get all properties of.
* @return {Array}
*/
function allKeys(self) {
var keys = Object.getOwnPropertyNames(self);
return keys;
}
/**
* Returns array of values of the object's keys
*
* @param {Object} self object to return values from
* @return {Array}
*/
function values(self, onlyEnumerable) {
var arr = [];
var key;
if (onlyEnumerable) {
for (key in self) {
arr[arr.length] = self[key];
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
arr[arr.length] = self[key];
}
}
return arr;
}
/**
* An analogue of `indexOf` method of Array prototype.
* Returns the `key` of `searchElement` in the object `self`.
* As object keys are unsorted, if there are several keys that hold `searchElement` any of them can be returned. Use `allKeysOf` to return all keys.
* All own properties are searched (not those inherited via prototype chain), including non-enumerable properties (unless `onlyEnumerable` is truthy).
*
* @param {Object} self An object to search a value in
* @param {Any} searchElement An element that will be searched. An exact equality is tested, so `0` is not the same as `'0'`.
* @param {Boolean} onlyEnumerable An optional true to search among enumerable properties only.
* @return {String}
*/
function keyOf(self, searchElement, onlyEnumerable) {
var foundKey;
var key;
if (onlyEnumerable) {
for (key in self) {
if (searchElement === self[key]) {
foundKey = key;
break;
}
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (searchElement === self[key]) {
foundKey = key;
break;
}
}
}
return foundKey;
}
/**
* Works similarly to the previous function, but returns the array of keys holding `searchElement` as their value.
*
* @param {Object} self An object to search a value in
* @param {Any} searchElement An element that will be searched. An exact equality is tested, so `0` is not the same as `'0'`.
* @param {Boolean} onlyEnumerable An optional true to search among enumerable properties only.
* @return {Array<String>}
*/
function allKeysOf(self, searchElement, onlyEnumerable) {
var foundKeys = [];
var key;
if (onlyEnumerable) {
for (key in self) {
if (searchElement === self[key]) {
foundKeys[foundKeys.length] = key;
}
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (searchElement === self[key]) {
foundKeys[foundKeys.length] = key;
}
}
}
return foundKeys;
}
/**
* An analogue of [forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) method of Array prototype.
* Iterates all own properties of `self` (or only enumerable own properties if `onlyEnumerable` is truthy) calling callback for each key.
* This method should not be used with arrays, it will include `length` property in iteration.
* To iterate array-like objects (e.g., `arguments` pseudo-array) use:
* ```
* _.forEach(arguments, callback, thisArg);
* ```
* Function returns `self` to allow [chaining](proto.js.html)
*
* @param {Object} self An object which properties will be iterated
* @param {Function} callback Callback is passed `value`, `key` and `self`, its return value is not used.
* @param {Object} thisArg An optional context of iteration (the valueof `this`), will be undefined if this parameter is not passed.
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
*/
function eachKey(self, callback, thisArg, onlyEnumerable) {
var key;
if (onlyEnumerable) {
for (key in self) {
callback.call(thisArg, self[key], key, self);
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
callback.call(thisArg, self[key], key, self);
}
}
return self;
}
/**
* An analogue of [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) method of Array prototype.
* Returns the object that is the result of the application of callback to values in all own properties of `self` (or only enumerable own properties if `onlyEnumerable` is truthy).
* The returned object will be the instance of the same class as `self`.
* Property descriptors of the returned object will have the same `enumerable`, `configurable` and `writable` settings as the properties of `self`.
* This method should not be used with arrays, it will include `length` property in iteration.
* To map array-like objects use:
* ```
* var result = _.map(arguments, callback, thisArg);
* ```
*
* @param {Object} self An object which properties will be iterated
* @param {Function} callback Callback is passed `value`, `key` and `self` and should return value that will be included in the map.
* @param {Object} thisArg An optional context of iteration (the valueof `this`), will be undefined if this parameter is not passed.
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
* @return {Object}
*/
function mapKeys(self, callback, thisArg, onlyEnumerable) {
var descriptors = {};
var key;
if (onlyEnumerable) {
for (key in self) {
descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
descriptors[key].value = callback.call(thisArg, self[key], key, self);
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
descriptors[key].value = callback.call(thisArg, self[key], key, self);
}
}
var obj = Object.create(self.constructor.prototype, descriptors);
return obj;
}
/**
* An analogue of [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) method of Array prototype.
* This method reduces the object to a single value. Iteration order is impossible to control with object.
* This method should not be used with arrays, it will include `length` property in iteration.
* To reduce array-like objects use:
* ```
* var result = _.reduce(arguments, callback, initialValue, thisArg);
* ```
*
* @param {Object} self An object which properties will be iterated
* @param {Function} callback Callback is passed `previousValue`, `value`, `key` and `self` and should return value that will be used as the `previousValue` for the next `callback` call.
* @param {Any} initialValue The initial value passed to callback as the first parameter on the first call.
* @param {Object} thisArg An optional context of iteration (the valueof `this`), will be undefined if this parameter is not passed.
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
* @return {Any}
*/
function reduceKeys(self, callback, initialValue, thisArg, onlyEnumerable) {
var memo = initialValue;
var key;
if (onlyEnumerable) {
for (key in self) {
memo = callback.call(thisArg, memo, self[key], key, self);
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
memo = callback.call(thisArg, memo, self[key], key, self);
}
}
return memo;
}
/**
* An analogue of [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) method of Array prototype.
* Returns the new object with keys for which callback returns true.
* Property descriptors of the returned object will have the same `enumerable`, `configurable` and `writable` settings as the properties of `self`.
* To filter array-like objects use:
* ```
* var result = _.filter(arguments, callback, thisArg);
* ```
*
* @param {Object} self An object which properties will be iterated
* @param {Function} callback Callback is passed `value`, `key` and `self`. If it returns truthy value, the key/value will be included in the resulting object.
* @param {Object} thisArg An optional context of iteration (the valueof `this`), will be undefined if this parameter is not passed.
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
* @return {Object}
*/
function filterKeys(self, callback, thisArg, onlyEnumerable) {
var descriptors = {};
var key;
if (onlyEnumerable) {
for (key in self) {
if (callback.call(thisArg, self[key], key, self)) descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (callback.call(thisArg, self[key], key, self)) descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
}
}
var obj = Object.create(self.constructor.prototype, descriptors);
return obj;
}
var _passed = {},
_didNotPass = {};
/**
* An analogue of [some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) method of Array prototype.
*
* @param {Object} self An object which properties will be iterated
* @param {Function} callback Callback is passed `value`, `key` and `self`. If it returns truthy value, the function immeaditely returns `true`.
* @param {Object} thisArg An optional context of iteration (the valueof `this`), will be undefined if this parameter is not passed.
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
* @return {Boolean}
*/
function someKey(self, callback, thisArg, onlyEnumerable) {
var key;
if (onlyEnumerable) {
for (key in self) {
if (callback.call(thisArg, self[key], key, self)) return true;
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (callback.call(thisArg, self[key], key, self)) return true;
}
}
return false;
}
/**
* An analogue of [every](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) method of Array prototype.
*
* @param {Object} self An object which properties will be iterated
* @param {Function} callback Callback is passed `value`, `key` and `self`. If it returns falsy value, the function immeaditely returns `false`.
* @param {Object} thisArg An optional context of iteration (the valueof `this`), will be undefined if this parameter is not passed.
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
* @return {Boolean}
*/
function everyKey(self, callback, thisArg, onlyEnumerable) {
var key;
if (onlyEnumerable) {
for (key in self) {
if (!callback.call(thisArg, self[key], key, self)) return false;
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (!callback.call(thisArg, self[key], key, self)) return false;
}
}
return true;
}
/**
* Returns object of the same class with only specified keys, that are passed as string parameters or array(s) of keys.
*
* @param {Object} self an object to pick keys from
* @param {List<String|Array>} arguments list of keys (or array(s) of keys)
* @return {Object}
*/
function pickKeys(self) { // , ... keys
var keys = concat.apply(Array.prototype, arguments);
var obj = Object.create(self.constructor.prototype);
for (var i = 1; i < keys.length; i++) {
var key = keys[i];
if (self.hasOwnProperty(key)) obj[key] = self[key];
}
return obj;;
}
/**
* Returns object of the same class without specified keys, that are passed as string parameters or array(s) of keys.
*
* @param {Object} self an object to omit keys in
* @param {List<String|Array>} arguments list of keys (or array of keys)
* @return {Object}
*/
function omitKeys(self) { // , ... keys
var clonedObject, onlyEnumerable;
var descriptors = {};
var key;
if (onlyEnumerable) {
for (key in self) {
descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
}
}
clonedObject = Object.create(self.constructor.prototype, descriptors);
var keys = concat.apply(Array.prototype, arguments);
for (var i = 1; i < keys.length; i++) {
delete clonedObject[keys[i]];
}
return clonedObject;;
}
/**
* Performs deep equality test of the object. Does not work with recursive objects
* @param {Any} self object to compare
* @param {Any} obj object to compare
* @return {Boolean}
*/
function isEqual(self, obj) {
var result;
if (self === obj) {
result = self !== 0 || 1 / self == 1 / obj; // 0 and -0 are considered not equal, although 0 === -0 is true
return result;
}
if (self == null || obj == null) {
return false;
}
var className = self.constructor.name;
if (className != obj.constructor.name) {
return false;
}
switch (className) {
case 'String':
result = self == String(obj);
break;
case 'Number':
result = self != +self ? obj != +obj : (self == 0 ? 1 / self == 1 / obj : self == +obj);
break;
case 'Date':
case 'Boolean':
result = +self == +obj;
break;
case 'RegExp':
result = self.source == obj.source && self.global == obj.global && self.multiline == obj.multiline && self.ignoreCase == obj.ignoreCase;
break;
default:
if (typeof self != 'object' || typeof obj != 'object') {
return false;
}
if (Array.isArray(self)) {
if (self.length != obj.length) {
return false;
}
for (var i = 0; i < self.length; i++) {
result = isEqual(self[i], obj[i]);
if (!result) {
return false;
}
}
return true;
} else {
if (Object.getOwnPropertyNames(self).length != Object.getOwnPropertyNames(obj).length) {
return false;
}
result = true;
var key;
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
result = isEqual(self[key], obj[key]);
if (!result) break;
}
return result;
}
}
return result;
}
/**
* The opposite of isEqual
* @param {Any} self object to compare
* @param {Any} obj object to compare
* @return {Boolean}
*/
function isNot(self, obj) {
var equal = !isEqual(self, obj);
return equal;
}
},{}],106:[function(require,module,exports){
'use strict';
var __ = require('../functions/object');
/**
* - [extendProto](#extendProto)
* - [createSubclass](#createSubclass)
* - [makeSubclass](#makeSubclass)
* - [newApply](#newApply)
*
* These methods can be [chained](proto.js.html#Proto)
*/
var prototypeMethods = module.exports = {
extendProto: extendProto,
createSubclass: createSubclass,
makeSubclass: makeSubclass,
newApply: newApply
};
/**
* Adds non-enumerable, non-configurable and non-writable properties to the prototype of constructor function.
* Usage:
* ```
* function MyClass() {}
* _.extendProto(MyClass, {
* method1: function() {},
* method2: function() {}
* });
* ```
* To extend class via object:
* ```
* _.extendProto(obj.constructor, methods);
* ```
* Returns passed constructor, so functions _.extendProto, [_.extend](object.js.html#extend) and _.makeSubclass can be [chained](proto.js.html).
*
* @param {Function} self constructor function
* @param {Object} methods a map of functions, keys will be instance methods (properties of the constructor prototype)
* @return {Function}
*/
function extendProto(self, methods) {
var propDescriptors = {};
var key;
var keys = Object.getOwnPropertyNames(methods);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
propDescriptors[key] = {
enumerable: false,
configurable: false,
writable: false,
value: methods[key]
};
}
Object.defineProperties(self.prototype, propDescriptors);
return self;
}
/**
* Makes a subclass of class `thisClass`.
* The returned function will have specified `name` if supplied.
* The constructor of superclass will be called in subclass constructor by default unless `applyConstructor === false` (not just falsy).
* Copies `thisClass` class methods to created subclass. For them to work correctly they should use `this` to refer to the class rather than explicit superclass name.
*
* @param {Function} thisClass A class to make subclass of
* @param {String} name Optional name of subclass constructor function
* @param {Boolean} applyConstructor Optional false value (not falsy) to prevent call of inherited constructor in the constructor of subclass
* @return {Function}
*/
function createSubclass(self, name, applyConstructor) {
var subclass;
// name is optional
name = name || '';
// apply superclass constructor
var constructorCode = applyConstructor === false ? '' : 'self.apply(this, arguments);';
eval('subclass = function ' + name + '(){ ' + constructorCode + ' }');
// prototype chain
subclass.prototype = Object.create(self.prototype);
// subclass identity
Object.defineProperty(subclass.prototype, 'constructor', {
enumerable: false,
configurable: false,
writable: false,
value: subclass
});
// copy class methods
// - for them to work correctly they should not explictly use superclass name
// and use "this" instead
__.deepExtend(subclass, self, true);
return subclass;
}
/**
* Sets up prototype chain to change `thisClass` (a constructor function) so that it becomes a subclass of `Superclass`.
* Returns `thisClass` so it can be [chained](proto.js.html) with _.extendProto and [_.extend](object.js.html#extend).
*
* @param {Function} thisClass A class that will become a subclass of Superclass
* @param {Function} Superclass A class that will become a superclass of thisClass
* @return {Function}
*/
function makeSubclass(self, Superclass) {
// prototype chain
self.prototype = Object.create(Superclass.prototype);
// subclass identity
Object.defineProperty(self.prototype, 'constructor', {
enumerable: false,
configurable: false,
writable: false,
value: self
});
return self;
}
/**
* Calls constructor `this` with arguments passed as array
*
* @param {Function} thisClass A class constructor that will be called
* @return {Array} args Array of arguments that will be passed to constructor
*/
function newApply(self, args) {
if (!Array.isArray(args)) args = Array.prototype.slice.call(args);
// "null" is context to pass to class constructor, first parameter of bind
var args = [null].concat(args);
var obj = new(Function.prototype.bind.apply(self, args));
return obj;
}
},{"../functions/object":105}],107:[function(require,module,exports){
'use strict';
var slice = Array.prototype.slice;
/**
* - [firstUpperCase](#firstUpperCase)
* - [firstLowerCase](#firstLowerCase)
* - [toRegExp](#toRegExp)
* - [toFunction](#toFunction)
* - [toDate](#toDate)
* - [toQueryString](#toQueryString)
* - [fromQueryString](#fromQueryString)
* - [jsonParse](#jsonParse)
* - [hashCode](#hashCode)
* - [unPrefix](#unPrefix)
* - [format](#format)
*/
var stringMethods = module.exports = {
firstUpperCase: firstUpperCase,
firstLowerCase: firstLowerCase,
toRegExp: toRegExp,
toFunction: toFunction,
toDate: toDate,
toQueryString: toQueryString,
fromQueryString: fromQueryString,
jsonParse: jsonParse,
hashCode: hashCode,
unPrefix: unPrefix,
format: format
};
/**
* Returns string with the first character changed to upper case.
*
* @param {String} self A string that will have its first character replaced
*/
function firstUpperCase(self) {
var str = self ? self[0].toUpperCase() + self.slice(1) : self;
return str;
}
/**
* Returns string with the first character changed to lower case.
*
* @param {String} self A string that will have its first character replaced
*/
function firstLowerCase(self) {
var str = self ? self[0].toLowerCase() + self.slice(1) : self;
return str;
}
/**
* Converts string created by `toString` method of RegExp back to RegExp
*
* @param {String} self string containing regular expression including enclosing "/" symbols and flags
* @return {RegExp}
*/
function toRegExp(self) {
var rx = self.match(regexpStringPattern);
if (rx) {
var newRx = new RegExp(rx[1], rx[2]);
}
return newRx;
}
var regexpStringPattern = /^\/(.*)\/([gimy]*)$/;
/**
* Converts string created by `toString` method of function back to function
*
* @param {String} self string containing full function code
* @return {Function}
*/
function toFunction(self) {
var func;
var code = 'func = ' + self + ';';
try {
eval(code);
} catch (e) {}
return func;
}
/**
* Converts string to date in a safe way so that the result is undefined if date is invalid
*
* @param {String|Date} self string or date object to convert to VALID date
* @return {Date|undefined}
*/
function toDate(self) {
if (self) {
try {
var date = new Date(self);
} catch (e) {}
if (date && date.getTime && !isNaN(date.getTime())) {
return date;
}
}
}
/**
* Convert params object to a url style query string (without "?")
*
* @param {Object} self The object hash to be converted
* @param {Function} encode optional function used to encode data, encodeURIComponent is used if not specified
* @return {String} the resulting query string
*/
function toQueryString(self, encode) {
var qs = '',
params = self || {},
encode = encode || encodeURIComponent;
var key;
var keys = Object.getOwnPropertyNames(params);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
qs += key + "=" + encode(params[key]) + "&";
}
var str = qs.slice(0, -1);
return str;
}
/**
* Convert url style query string (without "?") into object hash
*
* @param {String} self The string to be converted
* @param {Function} decode optional decode function, decodeURIComponent will be used if not supplied
* @return {Object} The resulting object hash
*/
function fromQueryString(self, decode) {
var pairs = self.split('&'),
results = {},
decode = decode || decodeURIComponent;
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i];
var splitPair = pair.split('=');
if (splitPair.length < 2) return;
var key = splitPair[0],
value = decode(splitPair[1] || '');
if (!key) return;
results[key] = value;
}
return results;
}
/**
* Safe JSON.parse, returns undefined if JSON.parse throws an exception
*
* @param {String} self JSON string representation of object
* @return {Object|undefined}
*/
function jsonParse(self) {
try {
var result = JSON.parse(self);
} catch (e) {}
return result;
}
/**
* Dan Bernstein's algorythm to create hash from string
*
* @param {String} self string to convert to hash
* @return {Number}
*/
function hashCode(self) {
var hash = 5381,
str = self,
len = str.length;
for (var i = 0; i < len; i++) {
var char = str.charCodeAt(i);
hash = ((hash << 5) + hash) + char; /* hash * 33 + c */
}
return hash;
}
/**
* Removes given prefix from the string. If string does not begin from the prefix, returns undefined
*
* @param {String} self
* @return {String}
*/
function unPrefix(self, str) {
if (self.indexOf(str) == 0) var result = self.replace(str, '');
return result;
}
/**
* Regex used to identify format vars
* @type {RegExp}
*/
var formatRegexp = /\$[0-9]+|\$\$/g;
/**
* String formatting utility to swap out tokens for variables.
* @param {String} this The string to be formatted
* @param {Array} args The values to be formatted
* @return {String} The formatted string
*/
function format(self) { // , ... arguments
var args = slice.call(arguments, 1);
var result = self.replace(formatRegexp, function(item) {
if (item == '$$') return '$';
item = item.slice(1);
return args[item - 1];
});
return result;
};
},{}],108:[function(require,module,exports){
'use strict';
var slice = Array.prototype.slice;
/**
* - [times](#times)
* - [repeat](#repeat)
* - [tap](#tap)
* - [result](#result)
* - [identity](#identity)
* - [property](#property)
* - [compareProperty](#compareProperty)
* - [noop](#noop)
*/
var utilMethods = module.exports = {
times: times,
repeat: repeat,
tap: tap,
result: result,
identity: identity,
property: property,
compareProperty: compareProperty,
noop: noop
};
/**
* Calls `callback` `self` times with `thisArg` as context. Callback is passed iteration index from 0 to `self-1`
*
* @param {Integer} self
* @param {Function} callback
* @param {Any} thisArg
* @return {Array}
*/
function times(self, callback, thisArg) {
var arr = Array(Math.max(0, self));
for (var i = 0; i < self; i++) arr[i] = callback.call(thisArg, i);
return arr;
}
/**
* Returns array with the first argument repeated `times` times
* @param {Any} self
* @param {Integer} times
* @return {Array}
*/
function repeat(self, times) {
var arr = Array(Math.max(0, times));;
for (var i = 0; i < times; i++) arr[i] = self;
return arr;
}
/**
* Function to tap into chained methods and to inspect intermediary result
*
* @param {Any} self value that's passed between chained methods
* @param {Function} func function that will be called with the value (both as context and as the first parameter)
* @return {Any}
*/
function tap(self, func) {
func.call(self, self);
return self;
};
/**
* Calls function `self` (first parameter of _.result) with given context and arguments
*
* @param {Function|Any} self
* @param {Any} thisArg context
* @param {List} arguments extra arguments
* @return {Any}
*/
function result(self, thisArg) { //, arguments
var args = slice.call(arguments, 2);
var result = typeof self == 'function' ? self.apply(thisArg, args) : self;
return result;
}
/**
* Returns self. Useful for using as an iterator if the actual value needs to be returned. Unlike in underscore and lodash, this function is NOT used as default iterator.
*
* @param {Any} self
* @return {Any}
*/
function identity(self) {
return self;
}
/**
* Returns function that picks the property from the object
*
* @param {String} self
* @return {Function}
*/
function property(self) {
var func = function(obj) {
return obj[self];
};
return func;
}
/**
* Returns function that can be used in array sort to sort by a given property
*
* @param {String} self
* @return {Function}
*/
function compareProperty(self) {
var func = function(a, b) {
return a[self] < b[self] ? -1 : a[self] > b[self] ? 1 : 0;
};
return func;
}
/**
* Function that does nothing
*/
function noop() {
return undefined;
}
},{}],109:[function(require,module,exports){
'use strict';
/**
* - [find](#find)
* - [findIndex](#findIndex)
* - [appendArray](#appendArray)
* - [prependArray](#prependArray)
* - [spliceItem](#spliceItem)
* - [toArray](#toArray)
* - [object](#object)
* - [mapToObject](#mapToObject)
* - [unique](#unique)
* - [deepForEach](#deepForEach)
*
* These methods can be [chained](proto.js.html#Proto).
*/
module.exports = {
find: find,
findIndex: findIndex,
appendArray: appendArray,
prependArray: prependArray,
toArray: toArray,
object: object,
mapToObject: mapToObject,
unique: unique,
deepForEach: deepForEach,
spliceItem: spliceItem
};
/**
* Functions that Array [implements natively](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Methods) are also included for convenience - they can be used with array-like objects and for chaining (native functions are always called).
* These functions can be [chained](proto.js.html#Proto) too.
*/
var nativeMethods = ['join', 'pop', 'push', 'concat', 'reverse', 'shift', 'unshift', 'slice', 'splice', 'sort', 'filter', 'forEach', 'some', 'every', 'map', 'indexOf', 'lastIndexOf', 'reduce', 'reduceRight', 'find', 'findIndex'];
for (var i = 0; i < nativeMethods.length; i++) {
var name = nativeMethods[i];
var nativeFunc = Array.prototype[name];
if (!nativeFunc) continue;
module.exports[name] = (function(method) {
return function() {
this.self = method.apply(this.self, arguments);
return this;
};
})(nativeFunc);
}
/**
* Implementation of ES6 [Array __find__ method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) (native method is used if available).
* Returns array element that passes callback test.
*
* @param {Array} self array to search in
* @param {Function} callback should return `true` for item to pass the test, passed `value`, `index` and `self` as parameters
* @param {Object} thisArg optional context (`this`) of callback call
* @return {Any}
*/
function find(callback, thisArg) {
var self = this.self;
for (var i = 0; i < self.length; i++) {
var item = self[i];
if (callback.call(thisArg, item, i, self)) {
this.self = item;
return this;
}
}
this.self = undefined;
return this;
}
/**
* Implementation of ES6 [Array __findIndex__ method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) (native method is used if available).
* Returns the index of array element that passes callback test. Returns `-1` if not found.
*
* @param {Array} self array to search in
* @param {Function} callback should return `true` for item to pass the test, passed `value`, `index` and `self` as parameters
* @param {Object} thisArg optional context (`this`) of callback call
* @return {Integer}
*/
function findIndex(callback, thisArg) {
var self = this.self;
for (var i = 0; i < self.length; i++) {
var item = self[i];
if (callback.call(thisArg, item, i, self)) {
this.self = i;
return this;
}
}
this.self = -1;
return this;
}
/**
* Appends `sourceArr` to the end of array `self` in place (can be an instance of Array or array-like object).
* Changes the value of `self` (it uses `Array.prototype.splice`) and returns `self`.
*
* @param {Array} self An array that will be modified
* @param {Array} sourceArr An array that will be appended
* @return {Array}
*/
function appendArray(sourceArr) {
if (!sourceArr.length) return this;
if (!Array.isArray(sourceArr)) sourceArr = Array.prototype.slice.call(sourceArr);
var args = [this.self.length, 0].concat(sourceArr);
Array.prototype.splice.apply(this.self, args);
return this;
}
/**
* Prepends `sourceArr` to the beginnig of array `self` in place (can be an instance of Array or array-like object).
* Changes the value of `self` (it uses `Array.prototype.splice`) and returns `self`.
*
* @param {Array} self An array that will be modified
* @param {Array} sourceArr An array that will be prepended
* @return {Array}
*/
function prependArray(sourceArr) {
if (!sourceArr.length) return this;
if (!Array.isArray(sourceArr)) sourceArr = Array.prototype.slice.call(sourceArr);
var args = [0, 0].concat(sourceArr);
Array.prototype.splice.apply(this.self, args);
return this;
}
/**
* Returns new array created from array-like object (e.g., `arguments` pseudo-array).
*
* @param {PseudoArray} self Object with numeric property length
* @return {Array}
*/
function toArray() {
this.self = Array.prototype.slice.call(this.self);
return this;
}
/**
* Returns an object created from the array of `keys` and optional array of `values`.
*
* @param {Array} self Array of keys
* @param {Array|any} values Optional array of values or the value to be assigned to each property.
* @return {Object}
*/
function object(values) {
var obj = {};
var valuesIsArray = Array.isArray(values);
var self = this.self;
for (var i = 0; i < self.length; i++) obj[self[i]] = valuesIsArray ? values[i] : values;
this.self = obj;
return this;
}
/**
* Maps array to object.
* Array elements become keys, value are taken from `callback`.
*
* @param {Array} self An array which values will become keys of the result
* @param {Function} callback Callback is passed `value`, `index` and `self` and should return value that will be included in the result.
* @param {Object} thisArg An optional context of iteration (the valueof `this`), will be undefined if this parameter is not passed.
* @return {Object}
*/
function mapToObject(callback, thisArg) {
var obj = {};
var self = this.self;
for (var i = 0; i < self.length; i++) {
var value = self[i];
obj[value] = callback.call(thisArg, value, i, self);
}
this.self = obj;
return this;
}
/**
* Returns array without duplicates. Does not modify original array.
*
* @param {Array} self original array
* @param {Function} callback comparison function, should return true for equal items, "===" is used if not passed.
* @return {Array}
*/
function unique(callback) {
var filtered = [];
var self = this.self;
if (callback) {
for (var i = 0; i < self.length; i++) {
var item = self[i];
var index = -1;
for (var j = 0; j < filtered.length; j++) {
if (callback(item, filtered[j])) {
index = i;
break;
}
}
if (index == -1) filtered[filtered.length] = item;
}
} else {
for (var i = 0; i < self.length; i++) {
var item = self[i];
var index = filtered.indexOf(item);
if (index == -1) filtered[filtered.length] = item;
}
}
this.self = filtered;
return this;
}
/**
* Iterates array and elements that are arrays calling callback with each element that is not an array. Can be used to iterate over arguments list to avoid checking whether array or list of parameters is passed.
*
* @param {Array} self array of elements and arraysto iterate.
* @param {Function} callback called for each item that is not an array. Callback is passed item, index and original array as parameters.
* @param {Any} thisArg optional callback envocation context
*/
function deepForEach(callback, thisArg) {
var self = this.self;
var index = 0;
_deepForEach(self);
function _deepForEach(arr) {
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
if (Array.isArray(item)) _deepForEach(item, callback, thisArg);
else callback.call(thisArg, item, index++, self);
}
}
}
/**
* Removes item from array that is found using indexOf (i.e. '===')
* Modifies original array and returns the reference to it.
*
* @param {Array} self An array that will be modified
* @param {Any} item item to be removed
* @return {Array}
*/
function spliceItem(item) {
var index = this.self.indexOf(item);
if (index >= 0) this.self.splice(index, 1);
return this;
}
},{}],110:[function(require,module,exports){
'use strict';
/**
* - [makeFunction](#makeFunction)
* - [partial](#partial)
* - [partialRight](#partialRight)
* - [memoize](#memoize)
* - [delay](#delay)
* - [defer](#defer)
* - [delayed](#delayed)
* - [deferred](#deferred)
* - [deferTicks](#deferTicks)
* - [delayMethod](#delayMethod)
* - [deferMethod](#deferMethod)
* - [debounce](#debounce)
* - [throttle](#throttle)
* - [once](#once)
* - [waitFor](#waitFor)
* - [not](#not)
*
* These methods can be [chained](proto.js.html#Proto)
*/
module.exports = {
makeFunction: makeFunction,
partial: partial,
partialRight: partialRight,
memoize: memoize,
delay: delay,
defer: defer,
delayed: delayed,
deferred: deferred,
deferTicks: deferTicks,
delayMethod: delayMethod,
deferMethod: deferMethod,
debounce: debounce,
throttle: throttle,
once: once,
waitFor: waitFor,
not: not
};
var slice = Array.prototype.slice;
/**
* Similarly to Function constructor creates a function from code.
* Unlike Function constructor, the first argument is a function name
*
* @param {String} self new function name
* @param {String} arg1, arg2, ... the names of function parameters
* @param {String} funcBody function body
* @return {Function}
*/
function makeFunction(arg1, arg2, funcBody) {
var name = this.self,
count = arguments.length - 1,
funcBody = arguments[count],
func, code = '';
for (var i = 0; i < count; i++) code += ', ' + arguments[i];
code = ['func = function ', name, '(', code.slice(2), ') {\n', funcBody, '\n}'].join('');
eval(code);
this.self = func;
return this;
}
/**
* Creates a function as a result of partial function application with the passed parameters.
*
* @param {Function} self Function to be applied
* @param {List} arguments Arguments after self will be prepended to the original function call when the partial function is called.
* @return {Function}
*/
function partial() { // , ... arguments
var self = this.self;
var args = slice.call(arguments);
var func = function() {
return self.apply(this, args.concat(slice.call(arguments)));
};
this.self = func;
return this;
}
/**
* Creates a function as a result of partial function application with the passed parameters, but parameters are appended on the right.
*
* @param {Function} self Function to be applied
* @param {List} arguments Arguments after self will be appended on the right to the original function call when the partial function is called.
* @return {Function}
*/
function partialRight() { // , ... arguments
var self = this.self;
var args = slice.call(arguments);
var func = function() {
return self.apply(this, slice.call(arguments).concat(args));
};
this.self = func;
return this;
}
/**
* Creates a memoized version of the function using supplied hash function as key. If the hash is not supplied, uses its first parameter as the hash.
*
* @param {Function} self function to be memoized
* @param {Function} hashFunc optional hash function that is passed all function arguments and should return cache key.
* @param {Integer} limit optional maximum number of results to be stored in the cache. 1000 by default.
* @return {Function} memoized function
*/
function memoize(hashFunc, limit) {
var self = this.self;
var cache = {},
keysList = [];
limit = limit || 1000;
var func = function() {
var key = hashFunc ? hashFunc.apply(this, arguments) : arguments[0];
if (cache.hasOwnProperty(key)) return cache[key];
var result = cache[key] = self.apply(this, arguments);
keysList.push(key);
if (keysList.length > limit) delete cache[keysList.shift()];
return result;
};
this.self = func;
return this;
}
/**
* Delays function execution by a given time in milliseconds.
* The context in function when it is executed is set to `null`.
*
* @param {Function} self function that execution has to be delayed
* @param {Number} wait approximate dalay time in milliseconds
* @param {List} arguments optional arguments that will be passed to the function
*/
function delay(wait) { // , arguments
var self = this.self;
var args = slice.call(arguments, 1);
var id = setTimeout(function() {
self.apply(null, args);
}, wait);
this.self = id;
return this;
}
/**
* Defers function execution (executes as soon as execution loop becomes free)
* The context in function when it is executed is set to `null`.
*
* @param {Function} self function that execution has to be delayed
* @param {List} arguments optional arguments that will be passed to the function
*/
function defer() { // , arguments
var self = this.self;
var args = arguments;
var id = setTimeout(function() {
self.apply(null, args);
});
this.self = id;
return this;
}
/**
* Returns function that will execute the original function `wait` ms after it has been called
* The context in function when it is executed is set to `null`.
* Arguments passed to the function are appended to the arguments passed to delayed.
*
* @param {Function} self function which execution has to be deferred
* @param {Number} wait approximate dalay time in milliseconds
* @param {List} arguments optional arguments that will be passed to the function
* @return {Function}
*/
function delayed(wait) { //, ... arguments
var self = this.self;
var args = slice.call(arguments, 1);
var func = function() { // ... arguments
var passArgs = args.concat(slice.call(arguments));
var context = this;
return setTimeout(function() {
self.apply(context, passArgs);
}, wait);
};
this.self = func;
return this;
}
/**
* Returns function that will execute the original function on the next tick once it has been called
* The context in function when it is executed is set to `null`.
* Arguments passed to the function are appended to the arguments passed to deferred.
*
* @param {Function} self function which execution has to be deferred
* @param {List} arguments optional arguments that will be passed to the function
* @return {Function}
*/
function deferred() { //, ... arguments
var self = this.self;
var args = arguments;
var func = function() { // ... arguments
var passArgs = args.concat(slice.call(arguments));
var context = this;
return setTimeout(function() {
self.apply(context, passArgs);
});
};
this.self = func;
return this;
}
/**
* Defers function execution for `times` ticks (executes after execution loop becomes free `times` times)
* The context in function when it is executed is set to `null`.
*
* @param {Function} self function that execution has to be delayed
* @param {Integer} ticks number of times to defer execution
* @param {List} arguments optional arguments that will be passed to the function
*/
function deferTicks(ticks) { // , arguments
var self = this.self;
var id;
if (ticks < 2) {
var args = slice.call(arguments, 1);
id = setTimeout(function() {
self.apply(null, args);
});
} else {
var args = arguments;
args[0] = ticks - 1;
id = setTimeout(function() {
deferTicks.apply({
self: self
}, args);
});
}
this.self = id;
return this;
}
/**
* Works like _.delay but allows to defer method call of `self` which will be the first _.delayMethod parameter
*
* @param {Object} self object to delay method call of
* @param {Function|String} funcOrMethodName function or name of method
* @param {Number} wait approximate dalay time in milliseconds
* @param {List} arguments arguments to pass to method
*/
function delayMethod(funcOrMethodName, wait) { // , ... arguments
var self = this.self;
var args = slice.call(arguments, 2);
var func = typeof funcOrMethodName == 'string' ? self[funcOrMethodName] : funcOrMethodName;
var id = setTimeout(function() {
func.apply(self, args);
}, wait);
this.self = id;
return this;
}
/**
* Works like _.defer but allows to defer method call of `self` which will be the first _.deferMethod parameter
*
* @param {Object} self object to defer method call of
* @param {Function|String} funcOrMethodName function or name of method
* @param {List} arguments arguments to pass to method
*/
function deferMethod(funcOrMethodName) { // , ... arguments
var self = this.self;
var args = slice.call(arguments, 1);
var func = typeof funcOrMethodName == 'string' ? self[funcOrMethodName] : funcOrMethodName;
var id = setTimeout(function() {
func.apply(self, args);
});
this.self = id;
return this;
}
/**
* Creates a function that will call original function once it has not been called for a specified time
*
* @param {Function} self function that execution has to be delayed
* @param {Number} wait approximate dalay time in milliseconds
* @param {Boolean} immediate true to invoke funciton immediately and then ignore following calls for wait milliseconds
* @return {Function}
*/
function debounce(wait, immediate) {
var self = this.self;
var timeout, args, context, timestamp, result;
var func = function() {
context = this; // store original context
args = arguments;
timestamp = Date.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) result = self.apply(context, args);
return result;
function later() {
var last = Date.now() - timestamp;
if (last < wait) timeout = setTimeout(later, wait - last);
else {
timeout = null;
if (!immediate) result = self.apply(context, args);
}
}
};
this.self = func;
return this;
}
/**
* Returns a function, that, when invoked, will only be triggered at most once during a given window of time.
*
* @param {Function} self function that execution has to be delayed
* @param {Number} wait approximate delay time in milliseconds
* @param {Object} options `{leading: false}` to disable the execution on the leading edge
* @return {Function}
*/
function throttle(wait, options) {
var self = this.self;
var context, args, result;
var timeout = null;
var previous = 0;
options || (options = {});
var func = function() {
var now = Date.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = self.apply(context, args);
} else if (!timeout && options.trailing !== false) timeout = setTimeout(later, remaining);
return result;
};
this.self = func;
return this;
function later() {
previous = options.leading === false ? 0 : Date.now();
timeout = null;
result = self.apply(context, args);
}
}
/**
* Call passed function only once
* @return {Function} self
*/
function once() {
var self = this.self;
var ran = false,
memo;
var func = function() {
if (ran) return memo;
ran = true;
memo = self.apply(this, arguments);
self = null;
return memo;
};
this.self = func;
return this;
}
/**
* Execute a function when the condition function returns a truthy value
* it runs the condition function every `checkInterval` milliseconds (default 50)
*
* @param {Function} self function: if it returns true the callback is executed
* @param {Function} callback runs when the condition is true
* @param {Number} maxTimeout timeout before giving up (time in milliseconds)
* @param {Function} timedOutFunc a function called if timeout is reached
* @param {Number} checkInterval time interval when you run the condition function (time in milliseconds), default 50 ms
*/
function waitFor(callback, maxTimeout, timedOutFunc, checkInterval) {
var self = this.self;
var start = Date.now();
checkInterval = checkInterval || 50;
var id = setInterval(testCondition, checkInterval);
this.self = id;
return this;
function testCondition() {
if (self()) callback();
else if (Date.now() - start >= maxTimeout) timedOutFunc && timedOutFunc();
else return;
clearInterval(id);
};
}
/**
* returns the function that negates (! operator) the result of the original function
* @param {Function} self function to negate
* @return {Function}
*/
function not() {
var self = this.self;
var func = function() {
return !self.apply(this, arguments);
};
this.self = func;
return this;
}
},{}],111:[function(require,module,exports){
arguments[4][103][0].apply(exports,arguments)
},{"./array":109,"./function":110,"./number":112,"./object":113,"./prototype":114,"./string":115,"./utils":116}],112:[function(require,module,exports){
'use strict';
/**
* - [isNumeric](#isNumeric)
*/
var numberMethods = module.exports = {
isNumeric: isNumeric
};
/**
* Function to test if a value is numeric
*
* @param {Any} self value to be tested
* @return {Boolean} true if it is a numeric value
*/
function isNumeric() {
var result = !isNaN(parseFloat(this.self)) && isFinite(this.self);
this.self = result;
return this;
}
},{}],113:[function(require,module,exports){
'use strict';
/**
* - [extend](#extend)
* - [clone](#clone)
* - [defineProperty](#defineProperty)
* - [defineProperties](#defineProperties)
* - [deepExtend](#deepExtend)
* - [deepClone](#deepClone)
* - [keys](#keys)
* - [allKeys](#allKeys)
* - [values](#values)
* - [keyOf](#keyOf)
* - [allKeysOf](#allKeysOf)
* - [eachKey](#eachKey)
* - [mapKeys](#mapKeys)
* - [reduceKeys](#reduceKeys)
* - [filterKeys](#filterKeys)
* - [someKey](#someKey)
* - [everyKey](#everyKey)
* - [findValue](#findValue)
* - [findKey](#findKey)
* - [pickKeys](#pickKeys)
* - [omitKeys](#omitKeys)
* - [isEqual](#isEqual)
* - [isNot](#isNot)
*
* All these methods can be [chained](proto.js.html#Proto)
*/
module.exports = {
extend: extend,
clone: clone,
findValue: findValue,
findKey: findKey,
defineProperty: defineProperty,
defineProperties: defineProperties,
deepExtend: deepExtend,
deepClone: deepClone,
keys: keys,
allKeys: allKeys,
values: values,
keyOf: keyOf,
allKeysOf: allKeysOf,
eachKey: eachKey,
mapKeys: mapKeys,
reduceKeys: reduceKeys,
filterKeys: filterKeys,
someKey: someKey,
everyKey: everyKey,
pickKeys: pickKeys,
omitKeys: omitKeys,
isEqual: isEqual,
isNot: isNot
};
var concat = Array.prototype.concat;
/**
* ####Property descriptor constants####
* The sum of these constants can be used as last parameter of defineProperty and defineProperties to determine types of properties.
*/
var constants = module.exports._constants = {
ENUMERABLE: 1,
ENUM: 1,
CONFIGURABLE: 2,
CONF: 2,
WRITABLE: 4,
WRIT: 4
};
/**
* Extends object `self` with the properties of the object `obj` copying all own properties (not those inherited via prototype chain), including non-enumerable properties (unless `onlyEnumerable` is truthy).
* Created properties will have the same descriptors as the propertis of `obj`.
* Returns `self` to allow chaining with other functions.
* Can be used with functions, to copy class methods, e.g.
*
* @param {Object} self An object to be extended
* @param {Object} obj An object which properties will be copied to self
* @param {Boolean} onlyEnumerable Optional flag to prevent copying non-enumerable properties, `false` by default
* @return {Object}
*/
function extend(obj, onlyEnumerable) {
var descriptors = {};
var key;
if (onlyEnumerable) {
for (key in obj) {
descriptors[key] = Object.getOwnPropertyDescriptor(obj, key);
}
} else {
var keys = Object.getOwnPropertyNames(obj);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
descriptors[key] = Object.getOwnPropertyDescriptor(obj, key);
}
}
Object.defineProperties(this.self, descriptors);
return this;
}
/**
* Makes a shallow clone of object `obj` creating an instance of the same class; the properties will have the same descriptors.
* To clone an array use
* ```
* var clonedArray = [].concat(arr);
* ```
* This function should not be used to clone an array, because it is inefficient.
*
* @param {Object} self An object to be cloned
* @param {Boolean} onlyEnumerable Optional flag to prevent copying non-enumerable properties, `false` by default
* @return {Object}
*/
function clone(onlyEnumerable) {
var self = this.self;
var clonedObject;
if (Array.isArray(self)) clonedObject = self.slice();
else if (self instanceof Date) clonedObject = new Date(self);
else if (self instanceof RegExp) clonedObject = new RegExp(self);
if (!clonedObject) {
var descriptors = {};
var key;
if (onlyEnumerable) {
for (key in self) {
descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
}
}
clonedObject = Object.create(self.constructor.prototype, descriptors);
}
this.self = clonedObject;
return this;
}
/**
* Analogue of ES6 [Array __find__ method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find).
* Returns the value of object property that passes callback test.
*
* @param {Object} self object to search in
* @param {Function} callback should return `true` for item to pass the test, passed `value`, `key` and `self` as parameters
* @param {Object} thisArg optional context (`this`) of callback call
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
* @return {Any}
*/
function findValue(callback, thisArg, onlyEnumerable) {
var self = this.self;
var result = undefined;
var key;
if (onlyEnumerable) {
for (key in self) {
var item = self[key];
if (callback.call(thisArg, item, key, self)) {
result = item;
break;
}
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
var item = self[key];
if (callback.call(thisArg, item, key, self)) {
result = item;
break;
}
}
}
this.self = result;
return this;
}
/**
* Analogue of ES6 [Array __findIndex__ method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex).
* Returns the key of object property that passes callback test. Returns `undefined` if not found (unlike `findIndex`, that returns -1 in this case).
*
* @param {Object} self object to search in
* @param {Function} callback should return `true` for item to pass the test, passed `value`, `key` and `self` as parameters
* @param {Object} thisArg optional context (`this`) of callback call
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
* @return {Integer}
*/
function findKey(callback, thisArg, onlyEnumerable) {
var self = this.self;
var result = undefined;
var key;
if (onlyEnumerable) {
for (key in self) {
var item = self[key];
if (callback.call(thisArg, item, key, self)) {
result = key;
break;
}
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
var item = self[key];
if (callback.call(thisArg, item, key, self)) {
result = key;
break;
}
}
}
this.self = result;
return this;
}
/**
* Syntax sugar to shorten usage of `Object.defineProperty`.
* The simplest usage (to add non-enumerable, non-configurable, non-writable property):
* ```
* _.defineProperty(obj, 'key', value);
* ```
*
* To define some other properties use sum of the flags `_.ENUMERABLE` (or `_.ENUM`), `_.CONFIGURABLE` (or `_.CONF`) and `_.WRITABLE` (or `_.WRIT`):
* ```
* _.defineProperty(obj, 'key', value, _.ENUM + _.WRIT);
* ```
* Returns `self`.
*
* @param {Object} self An object to add a property to
* @param {String} propertyName the name of the property that will be added
* @param {Any} value the value of added property
* @param {Integer} decriptorFlags bit mask of property descriptor properties composed from `_.ENUMERABLE` (or `_.ENUM`), `_.CONFIGURABLE` (or `_.CONF`) and `_.WRITABLE` (or `_.WRIT`)
* @return {Object}
*/
function defineProperty(propertyName, value, decriptorFlags) {
var descriptor = {
value: value
};
if (decriptorFlags) {
descriptor.enumerable = !!(decriptorFlags & constants.ENUMERABLE);
descriptor.configurable = !!(decriptorFlags & constants.CONFIGURABLE);
descriptor.writable = !!(decriptorFlags & constants.WRITABLE);
}
Object.defineProperty(this.self, propertyName, descriptor);
return this;
}
/**
* Syntax sugar to shorten usage of `Object.defineProperties`.
* The simplest usage (to add non-enumerable, non-configurable, non-writable properties):
* ```
* _.defineProperties(obj, {
* key1: value1,
* key2: value2
* });
* ```
* To define some other properties use sum of the flags `_.ENUMERABLE` (or `_.ENUM`), `_.CONFIGURABLE` (or `_.CONF`) and `_.WRITABLE` (or `_.WRIT`):
* ```
* _.defineProperties(obj, {
* key1: value1,
* key2: value2
* }, _.ENUM + _.WRIT);
* ```
* Returns `self`.
*
* @param {Object} self An object to add a property to
* @param {Object} propertyValues A map of keys and values of properties thatwill be added. The descriptors of properties will be defined by the following parameters.
* @param {Integer} decriptorFlags bit mask of property descriptor properties composed from `_.ENUMERABLE` (or `_.ENUM`), `_.CONFIGURABLE` (or `_.CONF`) and `_.WRITABLE` (or `_.WRIT`)
* @return {Object}
*/
function defineProperties(propertyValues, decriptorFlags) {
var self = this.self;
var descriptors = {};
var key;
var keys = Object.getOwnPropertyNames(propertyValues);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
var value = propertyValues[key];
var descriptor = {
value: value
};
if (decriptorFlags) {
descriptor.enumerable = !!(decriptorFlags & constants.ENUMERABLE);
descriptor.configurable = !!(decriptorFlags & constants.CONFIGURABLE);
descriptor.writable = !!(decriptorFlags & constants.WRITABLE);
}
descriptors[key] = descriptor;
}
Object.defineProperties(self, descriptors);
this.self = self;
return this;
}
/**
* Extends object `self` with properties of `obj` to any depth, without overwrtiting existing object properties of `self` with object properties of `obj`.
* Scalar properties of `obj` will overwrite properties of `self`. Scalar porperties of `self` will also be overwritten.
* Correctly works with recursive objects.
* Usage:
* ```
* var obj = {
* inner: {
* a: 1
* }
* };
*
* _.deepExtend(obj, {
* inner: {
* b: 2
* }
* });
*
* assert.deepEqual(obj, {
* inner: {
* a: 1,
* b: 2
* }
* }); // assert passes
* ```
* Returns `self`.
*
* @param {Object} self An object to be extended
* @param {Object} obj An object with properties to copy to
* @param {Boolean} onlyEnumerable Optional `true` to use only enumerable properties
* @param {Boolean} preserveStructure if true will throw at the attempt to overwrite object with scalar value (including Date and Regex) and vice versa
* @return {Object}
*/
function deepExtend(obj, onlyEnumerable, preserveStructure) {
var result = _extendTree(this.self, obj, onlyEnumerable, preserveStructure, []);
this.self = result;
return this;
}
function _extendTree(selfNode, objNode, onlyEnumerable, preserveStructure, objTraversed) {
if (objTraversed.indexOf(objNode) >= 0) return selfNode; // node already traversed, obj has recursion
// store node to recognise recursion
objTraversed.push(objNode);
if (Array.isArray(objNode)) {
for (var key = 0; key < objNode.length; key++) {
var value = objNode[key];
var hasProp = selfNode.hasOwnProperty(key);
var selfValue = selfNode[key];
var isSelfObj = typeof selfValue == "object" && selfValue != null && !(selfValue instanceof RegExp) && !(selfValue instanceof Date);
var isValueObj = typeof value == "object" && value != null && !(value instanceof RegExp) && !(value instanceof Date);
if (preserveStructure && hasProp && isSelfObj != isValueObj) throw new Error("deepExtend");
if (isValueObj) {
if (!hasProp || !isSelfObj) selfNode[key] = (Array.isArray(value)) ? [] : {};
_extendTree(selfNode[key], value, onlyEnumerable, preserveStructure, objTraversed);
} else {
var descriptor = Object.getOwnPropertyDescriptor(objNode, key);
Object.defineProperty(selfNode, key, descriptor);
}
}
} else {
var key;
if (onlyEnumerable) {
for (key in objNode) {
var value = objNode[key];
var hasProp = selfNode.hasOwnProperty(key);
var selfValue = selfNode[key];
var isSelfObj = typeof selfValue == "object" && selfValue != null && !(selfValue instanceof RegExp) && !(selfValue instanceof Date);
var isValueObj = typeof value == "object" && value != null && !(value instanceof RegExp) && !(value instanceof Date);
if (preserveStructure && hasProp && isSelfObj != isValueObj) throw new Error("deepExtend");
if (isValueObj) {
if (!hasProp || !isSelfObj) selfNode[key] = (Array.isArray(value)) ? [] : {};
_extendTree(selfNode[key], value, onlyEnumerable, preserveStructure, objTraversed);
} else {
var descriptor = Object.getOwnPropertyDescriptor(objNode, key);
Object.defineProperty(selfNode, key, descriptor);
}
}
} else {
var keys = Object.getOwnPropertyNames(objNode);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
var value = objNode[key];
var hasProp = selfNode.hasOwnProperty(key);
var selfValue = selfNode[key];
var isSelfObj = typeof selfValue == "object" && selfValue != null && !(selfValue instanceof RegExp) && !(selfValue instanceof Date);
var isValueObj = typeof value == "object" && value != null && !(value instanceof RegExp) && !(value instanceof Date);
if (preserveStructure && hasProp && isSelfObj != isValueObj) throw new Error("deepExtend");
if (isValueObj) {
if (!hasProp || !isSelfObj) selfNode[key] = (Array.isArray(value)) ? [] : {};
_extendTree(selfNode[key], value, onlyEnumerable, preserveStructure, objTraversed);
} else {
var descriptor = Object.getOwnPropertyDescriptor(objNode, key);
Object.defineProperty(selfNode, key, descriptor);
}
}
}
}
return selfNode;
}
/**
* Clones all object tree. Class of original object is not preserved. Returns `self`
*
* @param {Object} self An object to be extended
* @param {Boolean} onlyEnumerable Optional `true` to use only enumerable properties
* @return {Object}
*/
function deepClone(onlyEnumerable) {
var self = this.self;
var clonedObject;
if (self instanceof Date) clonedObject = new Date(self);
else if (self instanceof RegExp) clonedObject = new RegExp(self);
else {
clonedObject = Array.isArray(self) ? [] : {};
_extendTree(clonedObject, self, onlyEnumerable, false, []);
}
this.self = clonedObject;
return this;
}
/**
* Returns array of enumerable properties of the object
*
* @param {Object} self object to return keys of
* @return {Array}
*/
function keys() {
var keys = Object.keys(this.self);
this.self = keys;
return this;
}
/**
* Returns array of all property names of an object `self` (including non-enumerbale).
* To get only enumerable properties, use `Object.keys()`.
*
* @param {Object} self An object to get all properties of.
* @return {Array}
*/
function allKeys() {
var keys = Object.getOwnPropertyNames(this.self);
this.self = keys;
return this;
}
/**
* Returns array of values of the object's keys
*
* @param {Object} self object to return values from
* @return {Array}
*/
function values(onlyEnumerable) {
var arr = [];
var self = this.self;
var key;
if (onlyEnumerable) {
for (key in self) {
arr[arr.length] = self[key];
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
arr[arr.length] = self[key];
}
}
this.self = arr;
return this;
}
/**
* An analogue of `indexOf` method of Array prototype.
* Returns the `key` of `searchElement` in the object `self`.
* As object keys are unsorted, if there are several keys that hold `searchElement` any of them can be returned. Use `allKeysOf` to return all keys.
* All own properties are searched (not those inherited via prototype chain), including non-enumerable properties (unless `onlyEnumerable` is truthy).
*
* @param {Object} self An object to search a value in
* @param {Any} searchElement An element that will be searched. An exact equality is tested, so `0` is not the same as `'0'`.
* @param {Boolean} onlyEnumerable An optional true to search among enumerable properties only.
* @return {String}
*/
function keyOf(searchElement, onlyEnumerable) {
var foundKey;
var self = this.self;
var key;
if (onlyEnumerable) {
for (key in self) {
if (searchElement === self[key]) {
foundKey = key;
break;
}
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (searchElement === self[key]) {
foundKey = key;
break;
}
}
}
this.self = foundKey;
return this;
}
/**
* Works similarly to the previous function, but returns the array of keys holding `searchElement` as their value.
*
* @param {Object} self An object to search a value in
* @param {Any} searchElement An element that will be searched. An exact equality is tested, so `0` is not the same as `'0'`.
* @param {Boolean} onlyEnumerable An optional true to search among enumerable properties only.
* @return {Array<String>}
*/
function allKeysOf(searchElement, onlyEnumerable) {
var foundKeys = [];
var self = this.self;
var key;
if (onlyEnumerable) {
for (key in self) {
if (searchElement === self[key]) {
foundKeys[foundKeys.length] = key;
}
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (searchElement === self[key]) {
foundKeys[foundKeys.length] = key;
}
}
}
this.self = foundKeys;
return this;
}
/**
* An analogue of [forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) method of Array prototype.
* Iterates all own properties of `self` (or only enumerable own properties if `onlyEnumerable` is truthy) calling callback for each key.
* This method should not be used with arrays, it will include `length` property in iteration.
* To iterate array-like objects (e.g., `arguments` pseudo-array) use:
* ```
* _.forEach(arguments, callback, thisArg);
* ```
* Function returns `self` to allow [chaining](proto.js.html)
*
* @param {Object} self An object which properties will be iterated
* @param {Function} callback Callback is passed `value`, `key` and `self`, its return value is not used.
* @param {Object} thisArg An optional context of iteration (the valueof `this`), will be undefined if this parameter is not passed.
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
*/
function eachKey(callback, thisArg, onlyEnumerable) {
var self = this.self;
var key;
if (onlyEnumerable) {
for (key in self) {
callback.call(thisArg, self[key], key, self);
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
callback.call(thisArg, self[key], key, self);
}
}
return this;
}
/**
* An analogue of [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) method of Array prototype.
* Returns the object that is the result of the application of callback to values in all own properties of `self` (or only enumerable own properties if `onlyEnumerable` is truthy).
* The returned object will be the instance of the same class as `self`.
* Property descriptors of the returned object will have the same `enumerable`, `configurable` and `writable` settings as the properties of `self`.
* This method should not be used with arrays, it will include `length` property in iteration.
* To map array-like objects use:
* ```
* var result = _.map(arguments, callback, thisArg);
* ```
*
* @param {Object} self An object which properties will be iterated
* @param {Function} callback Callback is passed `value`, `key` and `self` and should return value that will be included in the map.
* @param {Object} thisArg An optional context of iteration (the valueof `this`), will be undefined if this parameter is not passed.
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
* @return {Object}
*/
function mapKeys(callback, thisArg, onlyEnumerable) {
var self = this.self;
var descriptors = {};
var key;
if (onlyEnumerable) {
for (key in self) {
descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
descriptors[key].value = callback.call(thisArg, self[key], key, self);
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
descriptors[key].value = callback.call(thisArg, self[key], key, self);
}
}
var obj = Object.create(self.constructor.prototype, descriptors);
this.self = obj;
return this;
}
/**
* An analogue of [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) method of Array prototype.
* This method reduces the object to a single value. Iteration order is impossible to control with object.
* This method should not be used with arrays, it will include `length` property in iteration.
* To reduce array-like objects use:
* ```
* var result = _.reduce(arguments, callback, initialValue, thisArg);
* ```
*
* @param {Object} self An object which properties will be iterated
* @param {Function} callback Callback is passed `previousValue`, `value`, `key` and `self` and should return value that will be used as the `previousValue` for the next `callback` call.
* @param {Any} initialValue The initial value passed to callback as the first parameter on the first call.
* @param {Object} thisArg An optional context of iteration (the valueof `this`), will be undefined if this parameter is not passed.
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
* @return {Any}
*/
function reduceKeys(callback, initialValue, thisArg, onlyEnumerable) {
var memo = initialValue;
var self = this.self;
var key;
if (onlyEnumerable) {
for (key in self) {
memo = callback.call(thisArg, memo, self[key], key, self);
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
memo = callback.call(thisArg, memo, self[key], key, self);
}
}
this.self = memo;
return this;
}
/**
* An analogue of [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) method of Array prototype.
* Returns the new object with keys for which callback returns true.
* Property descriptors of the returned object will have the same `enumerable`, `configurable` and `writable` settings as the properties of `self`.
* To filter array-like objects use:
* ```
* var result = _.filter(arguments, callback, thisArg);
* ```
*
* @param {Object} self An object which properties will be iterated
* @param {Function} callback Callback is passed `value`, `key` and `self`. If it returns truthy value, the key/value will be included in the resulting object.
* @param {Object} thisArg An optional context of iteration (the valueof `this`), will be undefined if this parameter is not passed.
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
* @return {Object}
*/
function filterKeys(callback, thisArg, onlyEnumerable) {
var descriptors = {};
var self = this.self;
var key;
if (onlyEnumerable) {
for (key in self) {
if (callback.call(thisArg, self[key], key, self)) descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (callback.call(thisArg, self[key], key, self)) descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
}
}
var obj = Object.create(self.constructor.prototype, descriptors);
this.self = obj;
return this;
}
var _passed = {},
_didNotPass = {};
/**
* An analogue of [some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) method of Array prototype.
*
* @param {Object} self An object which properties will be iterated
* @param {Function} callback Callback is passed `value`, `key` and `self`. If it returns truthy value, the function immeaditely returns `true`.
* @param {Object} thisArg An optional context of iteration (the valueof `this`), will be undefined if this parameter is not passed.
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
* @return {Boolean}
*/
function someKey(callback, thisArg, onlyEnumerable) {
var self = this.self;
var key;
if (onlyEnumerable) {
for (key in self) {
if (callback.call(thisArg, self[key], key, self)) return true;
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (callback.call(thisArg, self[key], key, self)) return true;
}
}
this.self = false;
return this;
}
/**
* An analogue of [every](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) method of Array prototype.
*
* @param {Object} self An object which properties will be iterated
* @param {Function} callback Callback is passed `value`, `key` and `self`. If it returns falsy value, the function immeaditely returns `false`.
* @param {Object} thisArg An optional context of iteration (the valueof `this`), will be undefined if this parameter is not passed.
* @param {Boolean} onlyEnumerable An optional `true` to iterate enumerable properties only.
* @return {Boolean}
*/
function everyKey(callback, thisArg, onlyEnumerable) {
var self = this.self;
var key;
if (onlyEnumerable) {
for (key in self) {
if (!callback.call(thisArg, self[key], key, self)) return false;
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
if (!callback.call(thisArg, self[key], key, self)) return false;
}
}
this.self = true;
return this;
}
/**
* Returns object of the same class with only specified keys, that are passed as string parameters or array(s) of keys.
*
* @param {Object} self an object to pick keys from
* @param {List<String|Array>} arguments list of keys (or array(s) of keys)
* @return {Object}
*/
function pickKeys() { // , ... keys
var self = this.self;
var keys = concat.apply(Array.prototype, arguments);
var obj = Object.create(self.constructor.prototype);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (self.hasOwnProperty(key)) obj[key] = self[key];
}
this.self = obj;
return this;;
}
/**
* Returns object of the same class without specified keys, that are passed as string parameters or array(s) of keys.
*
* @param {Object} self an object to omit keys in
* @param {List<String|Array>} arguments list of keys (or array of keys)
* @return {Object}
*/
function omitKeys() { // , ... keys
var self = this.self;
var clonedObject, onlyEnumerable;
var descriptors = {};
var key;
if (onlyEnumerable) {
for (key in self) {
descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
}
} else {
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
descriptors[key] = Object.getOwnPropertyDescriptor(self, key);
}
}
clonedObject = Object.create(self.constructor.prototype, descriptors);
var keys = concat.apply(Array.prototype, arguments);
for (var i = 0; i < keys.length; i++) {
delete clonedObject[keys[i]];
}
this.self = clonedObject;
return this;;
}
/**
* Performs deep equality test of the object. Does not work with recursive objects
* @param {Any} self object to compare
* @param {Any} obj object to compare
* @return {Boolean}
*/
function isEqual(obj) {
var self = this.self;
var result;
if (self === obj) {
result = self !== 0 || 1 / self == 1 / obj; // 0 and -0 are considered not equal, although 0 === -0 is true
this.self = result;
return this;
}
if (self == null || obj == null) {
this.self = false;
return this;
}
var className = self.constructor.name;
if (className != obj.constructor.name) {
this.self = false;
return this;
}
switch (className) {
case 'String':
result = self == String(obj);
break;
case 'Number':
result = self != +self ? obj != +obj : (self == 0 ? 1 / self == 1 / obj : self == +obj);
break;
case 'Date':
case 'Boolean':
result = +self == +obj;
break;
case 'RegExp':
result = self.source == obj.source && self.global == obj.global && self.multiline == obj.multiline && self.ignoreCase == obj.ignoreCase;
break;
default:
if (typeof self != 'object' || typeof obj != 'object') {
this.self = false;
return this;
}
if (Array.isArray(self)) {
if (self.length != obj.length) {
this.self = false;
return this;
}
for (var i = 0; i < self.length; i++) {
result = isEqual.call({
self: self[i]
}, obj[i]).self;
if (!result) {
this.self = false;
return this;
}
}
this.self = true;
return this;
} else {
if (Object.getOwnPropertyNames(self).length != Object.getOwnPropertyNames(obj).length) {
this.self = false;
return this;
}
result = true;
var key;
var keys = Object.getOwnPropertyNames(self);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
result = isEqual.call({
self: self[key]
}, obj[key]).self;
if (!result) break;
}
this.self = result;
return this;
}
}
this.self = result;
return this;
}
/**
* The opposite of isEqual
* @param {Any} self object to compare
* @param {Any} obj object to compare
* @return {Boolean}
*/
function isNot(obj) {
var equal = !isEqual.call({
self: this.self
}, obj).self;
this.self = equal;
return this;
}
},{}],114:[function(require,module,exports){
'use strict';
var __ = require('../functions/object');
/**
* - [extendProto](#extendProto)
* - [createSubclass](#createSubclass)
* - [makeSubclass](#makeSubclass)
* - [newApply](#newApply)
*
* These methods can be [chained](proto.js.html#Proto)
*/
var prototypeMethods = module.exports = {
extendProto: extendProto,
createSubclass: createSubclass,
makeSubclass: makeSubclass,
newApply: newApply
};
/**
* Adds non-enumerable, non-configurable and non-writable properties to the prototype of constructor function.
* Usage:
* ```
* function MyClass() {}
* _.extendProto(MyClass, {
* method1: function() {},
* method2: function() {}
* });
* ```
* To extend class via object:
* ```
* _.extendProto(obj.constructor, methods);
* ```
* Returns passed constructor, so functions _.extendProto, [_.extend](object.js.html#extend) and _.makeSubclass can be [chained](proto.js.html).
*
* @param {Function} self constructor function
* @param {Object} methods a map of functions, keys will be instance methods (properties of the constructor prototype)
* @return {Function}
*/
function extendProto(methods) {
var self = this.self;
var propDescriptors = {};
var key;
var keys = Object.getOwnPropertyNames(methods);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
propDescriptors[key] = {
enumerable: false,
configurable: false,
writable: false,
value: methods[key]
};
}
Object.defineProperties(self.prototype, propDescriptors);
this.self = self;
return this;
}
/**
* Makes a subclass of class `thisClass`.
* The returned function will have specified `name` if supplied.
* The constructor of superclass will be called in subclass constructor by default unless `applyConstructor === false` (not just falsy).
* Copies `thisClass` class methods to created subclass. For them to work correctly they should use `this` to refer to the class rather than explicit superclass name.
*
* @param {Function} thisClass A class to make subclass of
* @param {String} name Optional name of subclass constructor function
* @param {Boolean} applyConstructor Optional false value (not falsy) to prevent call of inherited constructor in the constructor of subclass
* @return {Function}
*/
function createSubclass(name, applyConstructor) {
var self = this.self;
var subclass;
// name is optional
name = name || '';
// apply superclass constructor
var constructorCode = applyConstructor === false ? '' : 'self.apply(this, arguments);';
eval('subclass = function ' + name + '(){ ' + constructorCode + ' }');
// prototype chain
subclass.prototype = Object.create(self.prototype);
// subclass identity
Object.defineProperty(subclass.prototype, 'constructor', {
enumerable: false,
configurable: false,
writable: false,
value: subclass
});
// copy class methods
// - for them to work correctly they should not explictly use superclass name
// and use "this" instead
__.deepExtend(subclass, self, true);
this.self = subclass;
return this;
}
/**
* Sets up prototype chain to change `thisClass` (a constructor function) so that it becomes a subclass of `Superclass`.
* Returns `thisClass` so it can be [chained](proto.js.html) with _.extendProto and [_.extend](object.js.html#extend).
*
* @param {Function} thisClass A class that will become a subclass of Superclass
* @param {Function} Superclass A class that will become a superclass of thisClass
* @return {Function}
*/
function makeSubclass(Superclass) {
var self = this.self;
// prototype chain
self.prototype = Object.create(Superclass.prototype);
// subclass identity
Object.defineProperty(self.prototype, 'constructor', {
enumerable: false,
configurable: false,
writable: false,
value: self
});
this.self = self;
return this;
}
/**
* Calls constructor `this` with arguments passed as array
*
* @param {Function} thisClass A class constructor that will be called
* @return {Array} args Array of arguments that will be passed to constructor
*/
function newApply(args) {
var self = this.self;
if (!Array.isArray(args)) args = Array.prototype.slice.call(args);
// "null" is context to pass to class constructor, first parameter of bind
var args = [null].concat(args);
var obj = new(Function.prototype.bind.apply(self, args));
this.self = obj;
return this;
}
},{"../functions/object":105}],115:[function(require,module,exports){
'use strict';
var slice = Array.prototype.slice;
/**
* - [firstUpperCase](#firstUpperCase)
* - [firstLowerCase](#firstLowerCase)
* - [toRegExp](#toRegExp)
* - [toFunction](#toFunction)
* - [toDate](#toDate)
* - [toQueryString](#toQueryString)
* - [fromQueryString](#fromQueryString)
* - [jsonParse](#jsonParse)
* - [hashCode](#hashCode)
* - [unPrefix](#unPrefix)
* - [format](#format)
*/
var stringMethods = module.exports = {
firstUpperCase: firstUpperCase,
firstLowerCase: firstLowerCase,
toRegExp: toRegExp,
toFunction: toFunction,
toDate: toDate,
toQueryString: toQueryString,
fromQueryString: fromQueryString,
jsonParse: jsonParse,
hashCode: hashCode,
unPrefix: unPrefix,
format: format
};
/**
* Returns string with the first character changed to upper case.
*
* @param {String} self A string that will have its first character replaced
*/
function firstUpperCase() {
var self = this.self;
var str = self ? self[0].toUpperCase() + self.slice(1) : self;
this.self = str;
return this;
}
/**
* Returns string with the first character changed to lower case.
*
* @param {String} self A string that will have its first character replaced
*/
function firstLowerCase() {
var self = this.self;
var str = self ? self[0].toLowerCase() + self.slice(1) : self;
this.self = str;
return this;
}
/**
* Converts string created by `toString` method of RegExp back to RegExp
*
* @param {String} self string containing regular expression including enclosing "/" symbols and flags
* @return {RegExp}
*/
function toRegExp() {
var self = this.self;
var rx = self.match(regexpStringPattern);
if (rx) {
var newRx = new RegExp(rx[1], rx[2]);
}
this.self = newRx;
return this;
}
var regexpStringPattern = /^\/(.*)\/([gimy]*)$/;
/**
* Converts string created by `toString` method of function back to function
*
* @param {String} self string containing full function code
* @return {Function}
*/
function toFunction() {
var self = this.self;
var func;
var code = 'func = ' + self + ';';
try {
eval(code);
} catch (e) {}
this.self = func;
return this;
}
/**
* Converts string to date in a safe way so that the result is undefined if date is invalid
*
* @param {String|Date} self string or date object to convert to VALID date
* @return {Date|undefined}
*/
function toDate() {
var self = this.self;
if (self) {
try {
var date = new Date(self);
} catch (e) {}
if (date && date.getTime && !isNaN(date.getTime())) {
this.self = date;
return this;
}
}
this.self = undefined;
return this;
}
/**
* Convert params object to a url style query string (without "?")
*
* @param {Object} self The object hash to be converted
* @param {Function} encode optional function used to encode data, encodeURIComponent is used if not specified
* @return {String} the resulting query string
*/
function toQueryString(encode) {
var self = this.self;
var qs = '',
params = self || {},
encode = encode || encodeURIComponent;
var key;
var keys = Object.getOwnPropertyNames(params);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
qs += key + "=" + encode(params[key]) + "&";
}
var str = qs.slice(0, -1);
this.self = str;
return this;
}
/**
* Convert url style query string (without "?") into object hash
*
* @param {String} self The string to be converted
* @param {Function} decode optional decode function, decodeURIComponent will be used if not supplied
* @return {Object} The resulting object hash
*/
function fromQueryString(decode) {
var self = this.self;
var pairs = self.split('&'),
results = {},
decode = decode || decodeURIComponent;
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i];
var splitPair = pair.split('=');
if (splitPair.length < 2) return;
var key = splitPair[0],
value = decode(splitPair[1] || '');
if (!key) return;
results[key] = value;
}
this.self = results;
return this;
}
/**
* Safe JSON.parse, returns undefined if JSON.parse throws an exception
*
* @param {String} self JSON string representation of object
* @return {Object|undefined}
*/
function jsonParse() {
var self = this.self;
try {
var result = JSON.parse(self);
} catch (e) {}
this.self = result;
return this;
}
/**
* Dan Bernstein's algorythm to create hash from string
*
* @param {String} self string to convert to hash
* @return {Number}
*/
function hashCode() {
var self = this.self;
var hash = 5381,
str = self,
len = str.length;
for (var i = 0; i < len; i++) {
var char = str.charCodeAt(i);
hash = ((hash << 5) + hash) + char; /* hash * 33 + c */
}
this.self = hash;
return this;
}
/**
* Removes given prefix from the string. If string does not begin from the prefix, returns undefined
*
* @param {String} self
* @return {String}
*/
function unPrefix(str) {
var self = this.self;
if (self.indexOf(str) == 0) var result = self.replace(str, '');
this.self = result;
return this;
}
/**
* Regex used to identify format vars
* @type {RegExp}
*/
var formatRegexp = /\$[0-9]+|\$\$/g;
/**
* String formatting utility to swap out tokens for variables.
* @param {String} this The string to be formatted
* @param {Array} args The values to be formatted
* @return {String} The formatted string
*/
function format() { // , ... arguments
var self = this.self;
var args = arguments;
var result = self.replace(formatRegexp, function(item) {
if (item == '$$') return '$';
item = item.slice(1);
return args[item - 1];
});
this.self = result;
return this;
};
},{}],116:[function(require,module,exports){
'use strict';
var slice = Array.prototype.slice;
/**
* - [times](#times)
* - [repeat](#repeat)
* - [tap](#tap)
* - [result](#result)
* - [identity](#identity)
* - [property](#property)
* - [compareProperty](#compareProperty)
* - [noop](#noop)
*/
var utilMethods = module.exports = {
times: times,
repeat: repeat,
tap: tap,
result: result,
identity: identity,
property: property,
compareProperty: compareProperty,
noop: noop
};
/**
* Calls `callback` `self` times with `thisArg` as context. Callback is passed iteration index from 0 to `self-1`
*
* @param {Integer} self
* @param {Function} callback
* @param {Any} thisArg
* @return {Array}
*/
function times(callback, thisArg) {
var self = this.self;
var arr = Array(Math.max(0, self));
for (var i = 0; i < self; i++) arr[i] = callback.call(thisArg, i);
this.self = arr;
return this;
}
/**
* Returns array with the first argument repeated `times` times
* @param {Any} self
* @param {Integer} times
* @return {Array}
*/
function repeat(times) {
var self = this.self;
var arr = Array(Math.max(0, times));;
for (var i = 0; i < times; i++) arr[i] = self;
this.self = arr;
return this;
}
/**
* Function to tap into chained methods and to inspect intermediary result
*
* @param {Any} self value that's passed between chained methods
* @param {Function} func function that will be called with the value (both as context and as the first parameter)
* @return {Any}
*/
function tap(func) {
var self = this.self;
func.call(self, self);
this.self = self;
return this;
};
/**
* Calls function `self` (first parameter of _.result) with given context and arguments
*
* @param {Function|Any} self
* @param {Any} thisArg context
* @param {List} arguments extra arguments
* @return {Any}
*/
function result(thisArg) { //, arguments
var args = slice.call(arguments, 1);
var result = typeof self == 'function' ? self.apply(thisArg, args) : self;
this.self = result;
return this;
}
/**
* Returns self. Useful for using as an iterator if the actual value needs to be returned. Unlike in underscore and lodash, this function is NOT used as default iterator.
*
* @param {Any} self
* @return {Any}
*/
function identity() {
var self = this.self;
this.self = self;
return this;
}
/**
* Returns function that picks the property from the object
*
* @param {String} self
* @return {Function}
*/
function property() {
var self = this.self;
var func = function(obj) {
return obj[self];
};
this.self = func;
return this;
}
/**
* Returns function that can be used in array sort to sort by a given property
*
* @param {String} self
* @return {Function}
*/
function compareProperty() {
var self = this.self;
var func = function(a, b) {
return a[self] < b[self] ? -1 : a[self] > b[self] ? 1 : 0;
};
this.self = func;
return this;
}
/**
* Function that does nothing
*/
function noop() {
this.self = undefined;
return this;
}
},{}],117:[function(require,module,exports){
'use strict';
/**
* Chaining
* ========
*
* `_` can be used to create a wrapped value (object, function, array, etc.) to allow chaining of Proto functions.
* To unwrap, `_` method of a wrapped value should be used.
* Usage:
* ```
* var arr = _({ 0: 3, 1: 4, 2: 5, length: 3})
* .toArray()
* .prependArray([1, 2])
* .appendArray([6, 7, 8])
* ._();
* ```
* A wrapped object is an instance of `_` (`Proto` class).
*
* Chaining is implemented for development convenience, but it has performance overhead, not only to wrap and unwrap values but in each function call.
* Although all Proto functions are implemented as methods operating on this and the overhead to redefine them as functions is very small, the overhead to redefine them as methods of wrapped value is slightly higher - chaining is 15-25% slower than using functions (properties of _ that take the first parameter).
* In cases when performance is critical, you may want to avoid using chaining.
*
* @param {Any} self A value to be wrapped
* @return {Proto}
*/
function Proto(self) {
// wrap passed parameter in _ object
var wrapped = Object.create(Proto.prototype);
wrapped.self = self;
return wrapped;
};
var funcs = require('./dotjs/functions');
var methods = require('./dotjs/methods');
for (var lib in funcs) {
var name;
var libFuncs = funcs[lib];
var libMethods = methods[lib];
for (name in libFuncs) {
Proto[name] = libFuncs[name];
Proto.prototype[name] = libMethods[name];
}
// add constants
if (lib == 'object')
for (name in libFuncs._constants)
Proto[name] = libFuncs._constants[name];
}
Proto.prototype._ = function() {
return this.self;
};
/**
* In windows environment, a global `_` value is preserved in `_.underscore`
*/
if (typeof window == 'object') {
// preserve existing _ object
if (window._)
Proto.underscore = window._
// expose global _ and Proto
window._ = Proto;
}
if (typeof module == 'object' && module.exports) {
// export for node/browserify
module.exports = Proto;
}
},{"./dotjs/functions":103,"./dotjs/methods":111}],118:[function(require,module,exports){
module.exports={
"name": "milojs",
"version": "1.4.3",
"description": "Browser/nodejs reactive programming and data driven DOM manipulation with modular components.",
"keywords": [
"framework",
"reactive",
"reactive programming",
"binding",
"data binding",
"mvc",
"model",
"view",
"controller",
"component",
"messenger",
"one-page app"
],
"main": "lib/milo.js",
"scripts": {
"test": "./node_modules/.bin/mocha --recursive --reporter=spec",
"test-cov": "istanbul cover -x 'test' --dir ./coverage/node node_modules/mocha/bin/_mocha -- --recursive --reporter=spec",
"test-browser": "grunt karma && karma start --single-run --browsers Chrome",
"test-travis": "npm run test-cov && grunt build && karma start --single-run --browsers Firefox && istanbul report"
},
"repository": {
"type": "git",
"url": "git://github.com/milojs/milo.git"
},
"author": "MailOnline",
"license": "BSD",
"bugs": {
"url": "https://github.com/milojs/milo/issues"
},
"dependencies": {
"base32": "milojs/base32-js.git",
"milo-core": "^1.0.3"
},
"devDependencies": {
"async": "~0.2.9",
"brfs": "0.0.8",
"browserify": "~2.35.4",
"grunt": "~0.4.1",
"grunt-browserify": "~1.2.11",
"grunt-contrib-copy": "^0.8.2",
"grunt-contrib-uglify": "~0.2.7",
"grunt-contrib-watch": "~0.5.3",
"grunt-exorcise": "^1.0.0",
"grunt-istanbul": "^0.6.1",
"grunt-karma": "^0.8.2",
"grunt-mocha-test": "~0.7.0",
"istanbul": "^0.4.0",
"karma": "~0.12",
"karma-chrome-launcher": "~0.1.2",
"karma-coverage": "^0.5.3",
"karma-firefox-launcher": "^0.1.6",
"karma-mocha": "~0.1.1",
"karma-spec-reporter": "0.0.6",
"karma-webdriver-launcher": "^0.2.0",
"mocha": "~1.16.2"
}
}
},{}]},{},[44])
;
//# sourceMappingURL=milo.bundle.map |
app1/exe/d.Excel/scripts/unfollow.js | mdimai666/predicate | /*eslint strict:0*/
/*global CasperError, console, phantom, require*/
//
var E = require('E');
var casper = require("casper").create({
waitTimeout: 9000,
viewportSize: {
width: 320,
height: 568
},
pageSettings: {
userAgent: "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.98 Safari/537.36 Vivaldi/1.6.689.40"
}
});
var doShotWhenError = true;
var login = casper.cli.get(0);
var pass = casper.cli.get(1);
var users = casper.cli.get(2);
var doFollow = false;
var users = users.split(',');
var user1 = users[0];
if (!login || !pass) {
casper.echo("not param").exit(1);
}
var f_error = function (msg) {
msg = msg || "timeout terminate";
if (doShotWhenError)
E.saveError();
casper.die("error: " + msg).exit();
};
E.coo.load(login);
E.insta.start(login, pass, unfollow, f_error, false, user1);
var xx = require('casper').selectXPath;
var lang;
var iteration = 0;
function unfollow_end() {
casper.echo(E.progress(100)).echo("--OK");
}
function unfollow() {
casper.echo("begin unfollow");
lang = E.lang();
casper.then(unfollow_next);
}
function unfollow_next() {
if (iteration >= users.length) {
unfollow_end();
return;
}
var link = users[iteration];
casper.echo("link -> " + link);
var flink = "https://instagram.com/" + link;
iteration++;
if (link === user1)
this.then(follow2);
else
//this.thenOpen(flink, follow2);
this.open(flink,{headers: {'Accept-Language': 'en-US'}}).then(follow2);
var p = (iteration / users.length * 100) | 0;
casper.echo(E.progress(p))
}
function follow2() {
casper.waitForSelector("#react-root", function () {
try {
var L = -1;
var S = false;
//status of follow
S = E.insta.checkFollow();
//button num
L = 1;
casper.echo("status of follow = " + (S));
if (doFollow != S) {
casper.echo("try unfollow")
casper.thenClick(xx("(//button)[" + (L + 1) + "]")).then(function () {
this.echo("...ok");
});
//return true;
}
else {
casper.echo("action is not required");
//return true;
}
}
catch (ex) {
}
//call next
this.then(unfollow_next);
}, f_error);
};
casper.run();
|
src/components/RegistrationForm/RegistrationForm.js | ThomasBem/ps-react-thomasbem | import React from 'react';
import PropTypes from 'prop-types';
import TextInput from '../TextInput';
import PasswordInput from '../PasswordInput';
/** Registration form with built-in validation. */
class RegistrationForm extends React.Component {
constructor(props) {
super(props);
this.state = {
user: {
email: '',
password: ''
},
errors: {},
submitted: false,
};
}
onChange = (event) => {
const user = this.state.user;
user[event.target.name] = event.target.value;
this.setState({user});
}
// Returns a number from 0 to 100 that represents password quality.
// For simplicity, just returning % of min length entered.
// Could enhance with checks for number, special char, unique characters, etc.
passwordQuality(password) {
if (!password) return null;
if (password.length >= this.props.minPasswordLength) return 100;
const percentOfMinLength = parseInt(password.length/this.props.minPasswordLength * 100, 10);
return percentOfMinLength;
}
validate({email, password}) {
const errors = {};
const {minPasswordLength} = this.props;
if (!email) errors.email = 'Email required.';
if (password.length < minPasswordLength) errors.password = `Password must be at least ${minPasswordLength} characters.`;
this.setState({errors});
const formIsValid = Object.getOwnPropertyNames(errors).length === 0;
return formIsValid;
}
onSubmit = () => {
const {user} = this.state;
const formIsValid = this.validate(user);
if (formIsValid) {
this.props.onSubmit(user);
this.setState({submitted: true});
}
}
render() {
const {errors, submitted} = this.state;
const {email, password} = this.state.user;
return (
submitted ?
<h2>{this.props.confirmationMessage}</h2> :
<div>
<TextInput
htmlId="registration-form-email"
name="email"
onChange={this.onChange}
label="Email"
value={email}
error={errors.email}
required />
<PasswordInput
htmlId="registration-form-password"
name="password"
value={password}
onChange={this.onChange}
quality={this.passwordQuality(password)}
showVisibilityToggle
maxLength={50}
error={errors.password} />
<input type="submit" value="Register" onClick={this.onSubmit} />
</div>
)
}
}
RegistrationForm.propTypes = {
/** Message displayed upon successful submission */
confirmationMessage: PropTypes.string,
/** Called when form is submitted */
onSubmit: PropTypes.func.isRequired,
/** Minimum password length */
minPasswordLength: PropTypes.number
}
RegistrationForm.defaultProps = {
confirmationMessage: "Thanks for registering!",
minPasswordLength: 8
};
export default RegistrationForm; |
node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | ubik23/cmx | import React from 'react';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
React.render(<HelloWorld />, document.getElementById('react-root'));
|
src/parser/demonhunter/havoc/modules/spells/azeritetraits/FuriousGaze.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import { formatNumber, formatPercentage } from 'common/format';
import { calculateAzeriteEffects } from 'common/stats';
import ItemStatistic from 'interface/statistics/ItemStatistic';
import BoringSpellValueText from 'interface/statistics/components/BoringSpellValueText';
import HasteIcon from 'interface/icons/Haste';
import StatTracker from 'parser/shared/modules/StatTracker';
import Events from 'parser/core/Events';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import SpellLink from 'common/SpellLink';
import AbilityTracker from 'parser/shared/modules/AbilityTracker';
const furiousGazeStats = traits => Object.values(traits).reduce((obj, rank) => {
const [haste] = calculateAzeriteEffects(SPELLS.FURIOUS_GAZE.id, rank);
obj.haste += haste;
return obj;
}, {
haste: 0,
});
const FURIOUS_GAZE_DURATION = 12000;
/**
* Furious Gaze
* When Eye Beam finishes fully channeling, your Haste is increased by 887 for 12 sec.
*
* Example Report: /report/ABH7D8W1Qaqv96mt/7-Mythic+MOTHER+-+Kill+(4:18)/Harwezz/statistics
*/
class FuriousGaze extends Analyzer{
static dependencies = {
abilityTracker: AbilityTracker,
statTracker: StatTracker,
};
haste = 0;
furiousGazeProcsCounter = 0;
furiousGazeStartTime = undefined;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTrait(SPELLS.FURIOUS_GAZE.id);
if (!this.active) {
return;
}
const { haste } = furiousGazeStats(this.selectedCombatant.traitsBySpellId[SPELLS.FURIOUS_GAZE.id]);
this.haste = haste;
this.statTracker.add(SPELLS.FURIOUS_GAZE_BUFF.id, {
haste,
});
this.addEventListener(Events.applybuff.by(SELECTED_PLAYER).spell(SPELLS.FURIOUS_GAZE_BUFF), this.onFuriousGazeApply);
this.addEventListener(Events.removebuff.by(SELECTED_PLAYER).spell(SPELLS.FURIOUS_GAZE_BUFF), this.onFuriousGazeRemove);
}
onFuriousGazeApply(event) {
// https://www.warcraftlogs.com/reports/TGzmk4bXDZJndpj7#fight=6&type=auras&source=5&ability=273232&start=2497903&end=2523828&view=events
// The log sometimes applies a new buff before the last one was finished.
// This causes buffs to be counted multiple times so we only handle events
// when we know the previous event succesfully finished
if (this.furiousGazeStartTime === undefined) {
this.furiousGazeStartTime = event.timestamp;
}
}
onFuriousGazeRemove(event) {
if (this.furiousGazeStartTime !== undefined) {
// https://www.warcraftlogs.com/reports/fNL9mkXcMp1GdnQ3#fight=27&type=auras&source=176&ability=273232&start=3811599&end=3841408
// When Furious Gaze is active, triggering the buff again causes the buff duration
// to extend. Because of this we only get 1 applyBuff and 1 removeBuff event,
// which would throw off the average and missed Furous Gaze calculations
this.furiousGazeProcsCounter += Math.round((event.timestamp - this.furiousGazeStartTime) / FURIOUS_GAZE_DURATION);
this.furiousGazeStartTime = undefined;
}
}
get averageHaste() {
return this.buffUptime * this.haste;
}
get buffUptime() {
return this.selectedCombatant.getBuffUptime(SPELLS.FURIOUS_GAZE_BUFF.id) / this.owner.fightDuration;
}
get eyeBeamCasts() {
return this.abilityTracker.getAbility(SPELLS.EYE_BEAM.id).casts || 0;
}
get suggestionThresholds() {
return {
actual: this.eyeBeamCasts - this.furiousGazeProcsCounter,
isGreaterThan: {
minor: 0,
average: 0,
major: 1,
},
style: 'number',
};
}
suggestions(when) {
when(this.suggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<>Try to not interupt the channeling of <SpellLink id={SPELLS.EYE_BEAM.id} /> to get the <SpellLink id={SPELLS.FURIOUS_GAZE.id} /> buff from its azerite trait for a DPS gain.</>)
.icon(SPELLS.FURIOUS_GAZE.icon)
.actual(<>{actual} cancelled <SpellLink id={SPELLS.EYE_BEAM.id} /> channels. </>)
.recommended(`No cancelled channels is recommended.`);
});
}
statistic() {
return (
<ItemStatistic
size="flexible"
tooltip={(
<>
<SpellLink id={SPELLS.FURIOUS_GAZE.id} /> buff is only gained when you fully complete<br />
the channel of <SpellLink id={SPELLS.EYE_BEAM.id} />. Cancelling the channel <br />
prematurely will result in not receiving the buff and will <br />
translate in a considerable DPS loss.<br /><br />
{formatPercentage(this.buffUptime)}% uptime<br />
{this.furiousGazeProcsCounter} out of {this.eyeBeamCasts} possible procs of <SpellLink id={SPELLS.FURIOUS_GAZE.id} /><br />
</>
)}
>
<BoringSpellValueText spell={SPELLS.FURIOUS_GAZE}>
<HasteIcon /> {formatNumber(this.averageHaste)} <small>average Haste</small><br />
{this.eyeBeamCasts - this.furiousGazeProcsCounter} <small><SpellLink id={SPELLS.FURIOUS_GAZE.id} /> buffs lost</small><br />
</BoringSpellValueText>
</ItemStatistic>
);
}
}
export default FuriousGaze;
|
src/svg-icons/action/settings-voice.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsVoice = (props) => (
<SvgIcon {...props}>
<path d="M7 24h2v-2H7v2zm5-11c1.66 0 2.99-1.34 2.99-3L15 4c0-1.66-1.34-3-3-3S9 2.34 9 4v6c0 1.66 1.34 3 3 3zm-1 11h2v-2h-2v2zm4 0h2v-2h-2v2zm4-14h-1.7c0 3-2.54 5.1-5.3 5.1S6.7 13 6.7 10H5c0 3.41 2.72 6.23 6 6.72V20h2v-3.28c3.28-.49 6-3.31 6-6.72z"/>
</SvgIcon>
);
ActionSettingsVoice = pure(ActionSettingsVoice);
ActionSettingsVoice.displayName = 'ActionSettingsVoice';
ActionSettingsVoice.muiName = 'SvgIcon';
export default ActionSettingsVoice;
|
ajax/libs/webshim/1.14.0/dev/shims/moxie/js/moxie.js | kartikrao31/cdnjs | /**
* mOxie - multi-runtime File API & XMLHttpRequest L2 Polyfill
* v1.2.1
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*
* Date: 2014-05-14
*/
/**
* Compiled inline version. (Library mode)
*/
/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
/*globals $code */
(function(exports, undefined) {
"use strict";
var modules = {};
function require(ids, callback) {
var module, defs = [];
for (var i = 0; i < ids.length; ++i) {
module = modules[ids[i]] || resolve(ids[i]);
if (!module) {
throw 'module definition dependecy not found: ' + ids[i];
}
defs.push(module);
}
callback.apply(null, defs);
}
function define(id, dependencies, definition) {
if (typeof id !== 'string') {
throw 'invalid module definition, module id must be defined and be a string';
}
if (dependencies === undefined) {
throw 'invalid module definition, dependencies must be specified';
}
if (definition === undefined) {
throw 'invalid module definition, definition function must be specified';
}
require(dependencies, function() {
modules[id] = definition.apply(null, arguments);
});
}
function defined(id) {
return !!modules[id];
}
function resolve(id) {
var target = exports;
var fragments = id.split(/[.\/]/);
for (var fi = 0; fi < fragments.length; ++fi) {
if (!target[fragments[fi]]) {
return;
}
target = target[fragments[fi]];
}
return target;
}
function expose(ids) {
for (var i = 0; i < ids.length; i++) {
var target = exports;
var id = ids[i];
var fragments = id.split(/[.\/]/);
for (var fi = 0; fi < fragments.length - 1; ++fi) {
if (target[fragments[fi]] === undefined) {
target[fragments[fi]] = {};
}
target = target[fragments[fi]];
}
target[fragments[fragments.length - 1]] = modules[id];
}
}
// Included from: src/javascript/core/utils/Basic.js
/**
* Basic.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/utils/Basic', [], function() {
/**
Gets the true type of the built-in object (better version of typeof).
@author Angus Croll (http://javascriptweblog.wordpress.com/)
@method typeOf
@for Utils
@static
@param {Object} o Object to check.
@return {String} Object [[Class]]
*/
var typeOf = function(o) {
var undef;
if (o === undef) {
return 'undefined';
} else if (o === null) {
return 'null';
} else if (o.nodeType) {
return 'node';
}
// the snippet below is awesome, however it fails to detect null, undefined and arguments types in IE lte 8
return ({}).toString.call(o).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
};
/**
Extends the specified object with another object.
@method extend
@static
@param {Object} target Object to extend.
@param {Object} [obj]* Multiple objects to extend with.
@return {Object} Same as target, the extended object.
*/
var extend = function(target) {
var undef;
each(arguments, function(arg, i) {
if (i > 0) {
each(arg, function(value, key) {
if (value !== undef) {
if (typeOf(target[key]) === typeOf(value) && !!~inArray(typeOf(value), ['array', 'object'])) {
extend(target[key], value);
} else {
target[key] = value;
}
}
});
}
});
return target;
};
/**
Executes the callback function for each item in array/object. If you return false in the
callback it will break the loop.
@method each
@static
@param {Object} obj Object to iterate.
@param {function} callback Callback function to execute for each item.
*/
var each = function(obj, callback) {
var length, key, i, undef;
if (obj) {
try {
length = obj.length;
} catch(ex) {
length = undef;
}
if (length === undef) {
// Loop object items
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (callback(obj[key], key) === false) {
return;
}
}
}
} else {
// Loop array items
for (i = 0; i < length; i++) {
if (callback(obj[i], i) === false) {
return;
}
}
}
}
};
/**
Checks if object is empty.
@method isEmptyObj
@static
@param {Object} o Object to check.
@return {Boolean}
*/
var isEmptyObj = function(obj) {
var prop;
if (!obj || typeOf(obj) !== 'object') {
return true;
}
for (prop in obj) {
return false;
}
return true;
};
/**
Recieve an array of functions (usually async) to call in sequence, each function
receives a callback as first argument that it should call, when it completes. Finally,
after everything is complete, main callback is called. Passing truthy value to the
callback as a first argument will interrupt the sequence and invoke main callback
immediately.
@method inSeries
@static
@param {Array} queue Array of functions to call in sequence
@param {Function} cb Main callback that is called in the end, or in case of error
*/
var inSeries = function(queue, cb) {
var i = 0, length = queue.length;
if (typeOf(cb) !== 'function') {
cb = function() {};
}
if (!queue || !queue.length) {
cb();
}
function callNext(i) {
if (typeOf(queue[i]) === 'function') {
queue[i](function(error) {
/*jshint expr:true */
++i < length && !error ? callNext(i) : cb(error);
});
}
}
callNext(i);
};
/**
Recieve an array of functions (usually async) to call in parallel, each function
receives a callback as first argument that it should call, when it completes. After
everything is complete, main callback is called. Passing truthy value to the
callback as a first argument will interrupt the process and invoke main callback
immediately.
@method inParallel
@static
@param {Array} queue Array of functions to call in sequence
@param {Function} cb Main callback that is called in the end, or in case of erro
*/
var inParallel = function(queue, cb) {
var count = 0, num = queue.length, cbArgs = new Array(num);
each(queue, function(fn, i) {
fn(function(error) {
if (error) {
return cb(error);
}
var args = [].slice.call(arguments);
args.shift(); // strip error - undefined or not
cbArgs[i] = args;
count++;
if (count === num) {
cbArgs.unshift(null);
cb.apply(this, cbArgs);
}
});
});
};
/**
Find an element in array and return it's index if present, otherwise return -1.
@method inArray
@static
@param {Mixed} needle Element to find
@param {Array} array
@return {Int} Index of the element, or -1 if not found
*/
var inArray = function(needle, array) {
if (array) {
if (Array.prototype.indexOf) {
return Array.prototype.indexOf.call(array, needle);
}
for (var i = 0, length = array.length; i < length; i++) {
if (array[i] === needle) {
return i;
}
}
}
return -1;
};
/**
Returns elements of first array if they are not present in second. And false - otherwise.
@private
@method arrayDiff
@param {Array} needles
@param {Array} array
@return {Array|Boolean}
*/
var arrayDiff = function(needles, array) {
var diff = [];
if (typeOf(needles) !== 'array') {
needles = [needles];
}
if (typeOf(array) !== 'array') {
array = [array];
}
for (var i in needles) {
if (inArray(needles[i], array) === -1) {
diff.push(needles[i]);
}
}
return diff.length ? diff : false;
};
/**
Find intersection of two arrays.
@private
@method arrayIntersect
@param {Array} array1
@param {Array} array2
@return {Array} Intersection of two arrays or null if there is none
*/
var arrayIntersect = function(array1, array2) {
var result = [];
each(array1, function(item) {
if (inArray(item, array2) !== -1) {
result.push(item);
}
});
return result.length ? result : null;
};
/**
Forces anything into an array.
@method toArray
@static
@param {Object} obj Object with length field.
@return {Array} Array object containing all items.
*/
var toArray = function(obj) {
var i, arr = [];
for (i = 0; i < obj.length; i++) {
arr[i] = obj[i];
}
return arr;
};
/**
Generates an unique ID. This is 99.99% unique since it takes the current time and 5 random numbers.
The only way a user would be able to get the same ID is if the two persons at the same exact milisecond manages
to get 5 the same random numbers between 0-65535 it also uses a counter so each call will be guaranteed to be page unique.
It's more probable for the earth to be hit with an ansteriod. Y
@method guid
@static
@param {String} prefix to prepend (by default 'o' will be prepended).
@method guid
@return {String} Virtually unique id.
*/
var guid = (function() {
var counter = 0;
return function(prefix) {
var guid = new Date().getTime().toString(32), i;
for (i = 0; i < 5; i++) {
guid += Math.floor(Math.random() * 65535).toString(32);
}
return (prefix || 'o_') + guid + (counter++).toString(32);
};
}());
/**
Trims white spaces around the string
@method trim
@static
@param {String} str
@return {String}
*/
var trim = function(str) {
if (!str) {
return str;
}
return String.prototype.trim ? String.prototype.trim.call(str) : str.toString().replace(/^\s*/, '').replace(/\s*$/, '');
};
/**
Parses the specified size string into a byte value. For example 10kb becomes 10240.
@method parseSizeStr
@static
@param {String/Number} size String to parse or number to just pass through.
@return {Number} Size in bytes.
*/
var parseSizeStr = function(size) {
if (typeof(size) !== 'string') {
return size;
}
var muls = {
t: 1099511627776,
g: 1073741824,
m: 1048576,
k: 1024
},
mul;
size = /^([0-9]+)([mgk]?)$/.exec(size.toLowerCase().replace(/[^0-9mkg]/g, ''));
mul = size[2];
size = +size[1];
if (muls.hasOwnProperty(mul)) {
size *= muls[mul];
}
return size;
};
return {
guid: guid,
typeOf: typeOf,
extend: extend,
each: each,
isEmptyObj: isEmptyObj,
inSeries: inSeries,
inParallel: inParallel,
inArray: inArray,
arrayDiff: arrayDiff,
arrayIntersect: arrayIntersect,
toArray: toArray,
trim: trim,
parseSizeStr: parseSizeStr
};
});
// Included from: src/javascript/core/I18n.js
/**
* I18n.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/core/I18n", [
"moxie/core/utils/Basic"
], function(Basic) {
var i18n = {};
return {
/**
* Extends the language pack object with new items.
*
* @param {Object} pack Language pack items to add.
* @return {Object} Extended language pack object.
*/
addI18n: function(pack) {
return Basic.extend(i18n, pack);
},
/**
* Translates the specified string by checking for the english string in the language pack lookup.
*
* @param {String} str String to look for.
* @return {String} Translated string or the input string if it wasn't found.
*/
translate: function(str) {
return i18n[str] || str;
},
/**
* Shortcut for translate function
*
* @param {String} str String to look for.
* @return {String} Translated string or the input string if it wasn't found.
*/
_: function(str) {
return this.translate(str);
},
/**
* Pseudo sprintf implementation - simple way to replace tokens with specified values.
*
* @param {String} str String with tokens
* @return {String} String with replaced tokens
*/
sprintf: function(str) {
var args = [].slice.call(arguments, 1);
return str.replace(/%[a-z]/g, function() {
var value = args.shift();
return Basic.typeOf(value) !== 'undefined' ? value : '';
});
}
};
});
// Included from: src/javascript/core/utils/Mime.js
/**
* Mime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/core/utils/Mime", [
"moxie/core/utils/Basic",
"moxie/core/I18n"
], function(Basic, I18n) {
var mimeData = "" +
"application/msword,doc dot," +
"application/pdf,pdf," +
"application/pgp-signature,pgp," +
"application/postscript,ps ai eps," +
"application/rtf,rtf," +
"application/vnd.ms-excel,xls xlb," +
"application/vnd.ms-powerpoint,ppt pps pot," +
"application/zip,zip," +
"application/x-shockwave-flash,swf swfl," +
"application/vnd.openxmlformats-officedocument.wordprocessingml.document,docx," +
"application/vnd.openxmlformats-officedocument.wordprocessingml.template,dotx," +
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,xlsx," +
"application/vnd.openxmlformats-officedocument.presentationml.presentation,pptx," +
"application/vnd.openxmlformats-officedocument.presentationml.template,potx," +
"application/vnd.openxmlformats-officedocument.presentationml.slideshow,ppsx," +
"application/x-javascript,js," +
"application/json,json," +
"audio/mpeg,mp3 mpga mpega mp2," +
"audio/x-wav,wav," +
"audio/x-m4a,m4a," +
"audio/ogg,oga ogg," +
"audio/aiff,aiff aif," +
"audio/flac,flac," +
"audio/aac,aac," +
"audio/ac3,ac3," +
"audio/x-ms-wma,wma," +
"image/bmp,bmp," +
"image/gif,gif," +
"image/jpeg,jpg jpeg jpe," +
"image/photoshop,psd," +
"image/png,png," +
"image/svg+xml,svg svgz," +
"image/tiff,tiff tif," +
"text/plain,asc txt text diff log," +
"text/html,htm html xhtml," +
"text/css,css," +
"text/csv,csv," +
"text/rtf,rtf," +
"video/mpeg,mpeg mpg mpe m2v," +
"video/quicktime,qt mov," +
"video/mp4,mp4," +
"video/x-m4v,m4v," +
"video/x-flv,flv," +
"video/x-ms-wmv,wmv," +
"video/avi,avi," +
"video/webm,webm," +
"video/3gpp,3gpp 3gp," +
"video/3gpp2,3g2," +
"video/vnd.rn-realvideo,rv," +
"video/ogg,ogv," +
"video/x-matroska,mkv," +
"application/vnd.oasis.opendocument.formula-template,otf," +
"application/octet-stream,exe";
var Mime = {
mimes: {},
extensions: {},
// Parses the default mime types string into a mimes and extensions lookup maps
addMimeType: function (mimeData) {
var items = mimeData.split(/,/), i, ii, ext;
for (i = 0; i < items.length; i += 2) {
ext = items[i + 1].split(/ /);
// extension to mime lookup
for (ii = 0; ii < ext.length; ii++) {
this.mimes[ext[ii]] = items[i];
}
// mime to extension lookup
this.extensions[items[i]] = ext;
}
},
extList2mimes: function (filters, addMissingExtensions) {
var self = this, ext, i, ii, type, mimes = [];
// convert extensions to mime types list
for (i = 0; i < filters.length; i++) {
ext = filters[i].extensions.split(/\s*,\s*/);
for (ii = 0; ii < ext.length; ii++) {
// if there's an asterisk in the list, then accept attribute is not required
if (ext[ii] === '*') {
return [];
}
type = self.mimes[ext[ii]];
if (!type) {
if (addMissingExtensions && /^\w+$/.test(ext[ii])) {
mimes.push('.' + ext[ii]);
} else {
return []; // accept all
}
} else if (Basic.inArray(type, mimes) === -1) {
mimes.push(type);
}
}
}
return mimes;
},
mimes2exts: function(mimes) {
var self = this, exts = [];
Basic.each(mimes, function(mime) {
if (mime === '*') {
exts = [];
return false;
}
// check if this thing looks like mime type
var m = mime.match(/^(\w+)\/(\*|\w+)$/);
if (m) {
if (m[2] === '*') {
// wildcard mime type detected
Basic.each(self.extensions, function(arr, mime) {
if ((new RegExp('^' + m[1] + '/')).test(mime)) {
[].push.apply(exts, self.extensions[mime]);
}
});
} else if (self.extensions[mime]) {
[].push.apply(exts, self.extensions[mime]);
}
}
});
return exts;
},
mimes2extList: function(mimes) {
var accept = [], exts = [];
if (Basic.typeOf(mimes) === 'string') {
mimes = Basic.trim(mimes).split(/\s*,\s*/);
}
exts = this.mimes2exts(mimes);
accept.push({
title: I18n.translate('Files'),
extensions: exts.length ? exts.join(',') : '*'
});
// save original mimes string
accept.mimes = mimes;
return accept;
},
getFileExtension: function(fileName) {
var matches = fileName && fileName.match(/\.([^.]+)$/);
if (matches) {
return matches[1].toLowerCase();
}
return '';
},
getFileMime: function(fileName) {
return this.mimes[this.getFileExtension(fileName)] || '';
}
};
Mime.addMimeType(mimeData);
return Mime;
});
// Included from: src/javascript/core/utils/Env.js
/**
* Env.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/core/utils/Env", [
"moxie/core/utils/Basic"
], function(Basic) {
// UAParser.js v0.6.2
// Lightweight JavaScript-based User-Agent string parser
// https://github.com/faisalman/ua-parser-js
//
// Copyright © 2012-2013 Faisalman <[email protected]>
// Dual licensed under GPLv2 & MIT
var UAParser = (function (undefined) {
//////////////
// Constants
/////////////
var EMPTY = '',
UNKNOWN = '?',
FUNC_TYPE = 'function',
UNDEF_TYPE = 'undefined',
OBJ_TYPE = 'object',
MAJOR = 'major',
MODEL = 'model',
NAME = 'name',
TYPE = 'type',
VENDOR = 'vendor',
VERSION = 'version',
ARCHITECTURE= 'architecture',
CONSOLE = 'console',
MOBILE = 'mobile',
TABLET = 'tablet';
///////////
// Helper
//////////
var util = {
has : function (str1, str2) {
return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1;
},
lowerize : function (str) {
return str.toLowerCase();
}
};
///////////////
// Map helper
//////////////
var mapper = {
rgx : function () {
// loop through all regexes maps
for (var result, i = 0, j, k, p, q, matches, match, args = arguments; i < args.length; i += 2) {
var regex = args[i], // even sequence (0,2,4,..)
props = args[i + 1]; // odd sequence (1,3,5,..)
// construct object barebones
if (typeof(result) === UNDEF_TYPE) {
result = {};
for (p in props) {
q = props[p];
if (typeof(q) === OBJ_TYPE) {
result[q[0]] = undefined;
} else {
result[q] = undefined;
}
}
}
// try matching uastring with regexes
for (j = k = 0; j < regex.length; j++) {
matches = regex[j].exec(this.getUA());
if (!!matches) {
for (p = 0; p < props.length; p++) {
match = matches[++k];
q = props[p];
// check if given property is actually array
if (typeof(q) === OBJ_TYPE && q.length > 0) {
if (q.length == 2) {
if (typeof(q[1]) == FUNC_TYPE) {
// assign modified match
result[q[0]] = q[1].call(this, match);
} else {
// assign given value, ignore regex match
result[q[0]] = q[1];
}
} else if (q.length == 3) {
// check whether function or regex
if (typeof(q[1]) === FUNC_TYPE && !(q[1].exec && q[1].test)) {
// call function (usually string mapper)
result[q[0]] = match ? q[1].call(this, match, q[2]) : undefined;
} else {
// sanitize match using given regex
result[q[0]] = match ? match.replace(q[1], q[2]) : undefined;
}
} else if (q.length == 4) {
result[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined;
}
} else {
result[q] = match ? match : undefined;
}
}
break;
}
}
if(!!matches) break; // break the loop immediately if match found
}
return result;
},
str : function (str, map) {
for (var i in map) {
// check if array
if (typeof(map[i]) === OBJ_TYPE && map[i].length > 0) {
for (var j = 0; j < map[i].length; j++) {
if (util.has(map[i][j], str)) {
return (i === UNKNOWN) ? undefined : i;
}
}
} else if (util.has(map[i], str)) {
return (i === UNKNOWN) ? undefined : i;
}
}
return str;
}
};
///////////////
// String map
//////////////
var maps = {
browser : {
oldsafari : {
major : {
'1' : ['/8', '/1', '/3'],
'2' : '/4',
'?' : '/'
},
version : {
'1.0' : '/8',
'1.2' : '/1',
'1.3' : '/3',
'2.0' : '/412',
'2.0.2' : '/416',
'2.0.3' : '/417',
'2.0.4' : '/419',
'?' : '/'
}
}
},
device : {
sprint : {
model : {
'Evo Shift 4G' : '7373KT'
},
vendor : {
'HTC' : 'APA',
'Sprint' : 'Sprint'
}
}
},
os : {
windows : {
version : {
'ME' : '4.90',
'NT 3.11' : 'NT3.51',
'NT 4.0' : 'NT4.0',
'2000' : 'NT 5.0',
'XP' : ['NT 5.1', 'NT 5.2'],
'Vista' : 'NT 6.0',
'7' : 'NT 6.1',
'8' : 'NT 6.2',
'8.1' : 'NT 6.3',
'RT' : 'ARM'
}
}
}
};
//////////////
// Regex map
/////////////
var regexes = {
browser : [[
// Presto based
/(opera\smini)\/((\d+)?[\w\.-]+)/i, // Opera Mini
/(opera\s[mobiletab]+).+version\/((\d+)?[\w\.-]+)/i, // Opera Mobi/Tablet
/(opera).+version\/((\d+)?[\w\.]+)/i, // Opera > 9.80
/(opera)[\/\s]+((\d+)?[\w\.]+)/i // Opera < 9.80
], [NAME, VERSION, MAJOR], [
/\s(opr)\/((\d+)?[\w\.]+)/i // Opera Webkit
], [[NAME, 'Opera'], VERSION, MAJOR], [
// Mixed
/(kindle)\/((\d+)?[\w\.]+)/i, // Kindle
/(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?((\d+)?[\w\.]+)*/i,
// Lunascape/Maxthon/Netfront/Jasmine/Blazer
// Trident based
/(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?((\d+)?[\w\.]*)/i,
// Avant/IEMobile/SlimBrowser/Baidu
/(?:ms|\()(ie)\s((\d+)?[\w\.]+)/i, // Internet Explorer
// Webkit/KHTML based
/(rekonq)((?:\/)[\w\.]+)*/i, // Rekonq
/(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron)\/((\d+)?[\w\.-]+)/i
// Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron
], [NAME, VERSION, MAJOR], [
/(trident).+rv[:\s]((\d+)?[\w\.]+).+like\sgecko/i // IE11
], [[NAME, 'IE'], VERSION, MAJOR], [
/(yabrowser)\/((\d+)?[\w\.]+)/i // Yandex
], [[NAME, 'Yandex'], VERSION, MAJOR], [
/(comodo_dragon)\/((\d+)?[\w\.]+)/i // Comodo Dragon
], [[NAME, /_/g, ' '], VERSION, MAJOR], [
/(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?((\d+)?[\w\.]+)/i
// Chrome/OmniWeb/Arora/Tizen/Nokia
], [NAME, VERSION, MAJOR], [
/(dolfin)\/((\d+)?[\w\.]+)/i // Dolphin
], [[NAME, 'Dolphin'], VERSION, MAJOR], [
/((?:android.+)crmo|crios)\/((\d+)?[\w\.]+)/i // Chrome for Android/iOS
], [[NAME, 'Chrome'], VERSION, MAJOR], [
/((?:android.+))version\/((\d+)?[\w\.]+)\smobile\ssafari/i // Android Browser
], [[NAME, 'Android Browser'], VERSION, MAJOR], [
/version\/((\d+)?[\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari
], [VERSION, MAJOR, [NAME, 'Mobile Safari']], [
/version\/((\d+)?[\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile
], [VERSION, MAJOR, NAME], [
/webkit.+?(mobile\s?safari|safari)((\/[\w\.]+))/i // Safari < 3.0
], [NAME, [MAJOR, mapper.str, maps.browser.oldsafari.major], [VERSION, mapper.str, maps.browser.oldsafari.version]], [
/(konqueror)\/((\d+)?[\w\.]+)/i, // Konqueror
/(webkit|khtml)\/((\d+)?[\w\.]+)/i
], [NAME, VERSION, MAJOR], [
// Gecko based
/(navigator|netscape)\/((\d+)?[\w\.-]+)/i // Netscape
], [[NAME, 'Netscape'], VERSION, MAJOR], [
/(swiftfox)/i, // Swiftfox
/(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?((\d+)?[\w\.\+]+)/i,
// IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror
/(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/((\d+)?[\w\.-]+)/i,
// Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix
/(mozilla)\/((\d+)?[\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla
// Other
/(uc\s?browser|polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|qqbrowser)[\/\s]?((\d+)?[\w\.]+)/i,
// UCBrowser/Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/QQBrowser
/(links)\s\(((\d+)?[\w\.]+)/i, // Links
/(gobrowser)\/?((\d+)?[\w\.]+)*/i, // GoBrowser
/(ice\s?browser)\/v?((\d+)?[\w\._]+)/i, // ICE Browser
/(mosaic)[\/\s]((\d+)?[\w\.]+)/i // Mosaic
], [NAME, VERSION, MAJOR]
],
engine : [[
/(presto)\/([\w\.]+)/i, // Presto
/(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m
/(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links
/(icab)[\/\s]([23]\.[\d\.]+)/i // iCab
], [NAME, VERSION], [
/rv\:([\w\.]+).*(gecko)/i // Gecko
], [VERSION, NAME]
],
os : [[
// Windows based
/(windows)\snt\s6\.2;\s(arm)/i, // Windows RT
/(windows\sphone(?:\sos)*|windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i
], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [
/(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i
], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [
// Mobile/Embedded OS
/\((bb)(10);/i // BlackBerry 10
], [[NAME, 'BlackBerry'], VERSION], [
/(blackberry)\w*\/?([\w\.]+)*/i, // Blackberry
/(tizen)\/([\w\.]+)/i, // Tizen
/(android|webos|palm\os|qnx|bada|rim\stablet\sos|meego)[\/\s-]?([\w\.]+)*/i
// Android/WebOS/Palm/QNX/Bada/RIM/MeeGo
], [NAME, VERSION], [
/(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i // Symbian
], [[NAME, 'Symbian'], VERSION],[
/mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS
], [[NAME, 'Firefox OS'], VERSION], [
// Console
/(nintendo|playstation)\s([wids3portablevu]+)/i, // Nintendo/Playstation
// GNU/Linux based
/(mint)[\/\s\(]?(\w+)*/i, // Mint
/(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk)[\/\s-]?([\w\.-]+)*/i,
// Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware
// Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk
/(hurd|linux)\s?([\w\.]+)*/i, // Hurd/Linux
/(gnu)\s?([\w\.]+)*/i // GNU
], [NAME, VERSION], [
/(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS
], [[NAME, 'Chromium OS'], VERSION],[
// Solaris
/(sunos)\s?([\w\.]+\d)*/i // Solaris
], [[NAME, 'Solaris'], VERSION], [
// BSD based
/\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly
], [NAME, VERSION],[
/(ip[honead]+)(?:.*os\s*([\w]+)*\slike\smac|;\sopera)/i // iOS
], [[NAME, 'iOS'], [VERSION, /_/g, '.']], [
/(mac\sos\sx)\s?([\w\s\.]+\w)*/i // Mac OS
], [NAME, [VERSION, /_/g, '.']], [
// Other
/(haiku)\s(\w+)/i, // Haiku
/(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i, // AIX
/(macintosh|mac(?=_powerpc)|plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos)/i,
// Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS
/(unix)\s?([\w\.]+)*/i // UNIX
], [NAME, VERSION]
]
};
/////////////////
// Constructor
////////////////
var UAParser = function (uastring) {
var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY);
this.getBrowser = function () {
return mapper.rgx.apply(this, regexes.browser);
};
this.getEngine = function () {
return mapper.rgx.apply(this, regexes.engine);
};
this.getOS = function () {
return mapper.rgx.apply(this, regexes.os);
};
this.getResult = function() {
return {
ua : this.getUA(),
browser : this.getBrowser(),
engine : this.getEngine(),
os : this.getOS()
};
};
this.getUA = function () {
return ua;
};
this.setUA = function (uastring) {
ua = uastring;
return this;
};
this.setUA(ua);
};
return new UAParser().getResult();
})();
function version_compare(v1, v2, operator) {
// From: http://phpjs.org/functions
// + original by: Philippe Jausions (http://pear.php.net/user/jausions)
// + original by: Aidan Lister (http://aidanlister.com/)
// + reimplemented by: Kankrelune (http://www.webfaktory.info/)
// + improved by: Brett Zamir (http://brett-zamir.me)
// + improved by: Scott Baker
// + improved by: Theriault
// * example 1: version_compare('8.2.5rc', '8.2.5a');
// * returns 1: 1
// * example 2: version_compare('8.2.50', '8.2.52', '<');
// * returns 2: true
// * example 3: version_compare('5.3.0-dev', '5.3.0');
// * returns 3: -1
// * example 4: version_compare('4.1.0.52','4.01.0.51');
// * returns 4: 1
// Important: compare must be initialized at 0.
var i = 0,
x = 0,
compare = 0,
// vm maps textual PHP versions to negatives so they're less than 0.
// PHP currently defines these as CASE-SENSITIVE. It is important to
// leave these as negatives so that they can come before numerical versions
// and as if no letters were there to begin with.
// (1alpha is < 1 and < 1.1 but > 1dev1)
// If a non-numerical value can't be mapped to this table, it receives
// -7 as its value.
vm = {
'dev': -6,
'alpha': -5,
'a': -5,
'beta': -4,
'b': -4,
'RC': -3,
'rc': -3,
'#': -2,
'p': 1,
'pl': 1
},
// This function will be called to prepare each version argument.
// It replaces every _, -, and + with a dot.
// It surrounds any nonsequence of numbers/dots with dots.
// It replaces sequences of dots with a single dot.
// version_compare('4..0', '4.0') == 0
// Important: A string of 0 length needs to be converted into a value
// even less than an unexisting value in vm (-7), hence [-8].
// It's also important to not strip spaces because of this.
// version_compare('', ' ') == 1
prepVersion = function (v) {
v = ('' + v).replace(/[_\-+]/g, '.');
v = v.replace(/([^.\d]+)/g, '.$1.').replace(/\.{2,}/g, '.');
return (!v.length ? [-8] : v.split('.'));
},
// This converts a version component to a number.
// Empty component becomes 0.
// Non-numerical component becomes a negative number.
// Numerical component becomes itself as an integer.
numVersion = function (v) {
return !v ? 0 : (isNaN(v) ? vm[v] || -7 : parseInt(v, 10));
};
v1 = prepVersion(v1);
v2 = prepVersion(v2);
x = Math.max(v1.length, v2.length);
for (i = 0; i < x; i++) {
if (v1[i] == v2[i]) {
continue;
}
v1[i] = numVersion(v1[i]);
v2[i] = numVersion(v2[i]);
if (v1[i] < v2[i]) {
compare = -1;
break;
} else if (v1[i] > v2[i]) {
compare = 1;
break;
}
}
if (!operator) {
return compare;
}
// Important: operator is CASE-SENSITIVE.
// "No operator" seems to be treated as "<."
// Any other values seem to make the function return null.
switch (operator) {
case '>':
case 'gt':
return (compare > 0);
case '>=':
case 'ge':
return (compare >= 0);
case '<=':
case 'le':
return (compare <= 0);
case '==':
case '=':
case 'eq':
return (compare === 0);
case '<>':
case '!=':
case 'ne':
return (compare !== 0);
case '':
case '<':
case 'lt':
return (compare < 0);
default:
return null;
}
}
var can = (function() {
var caps = {
define_property: (function() {
/* // currently too much extra code required, not exactly worth it
try { // as of IE8, getters/setters are supported only on DOM elements
var obj = {};
if (Object.defineProperty) {
Object.defineProperty(obj, 'prop', {
enumerable: true,
configurable: true
});
return true;
}
} catch(ex) {}
if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) {
return true;
}*/
return false;
}()),
create_canvas: (function() {
// On the S60 and BB Storm, getContext exists, but always returns undefined
// so we actually have to call getContext() to verify
// github.com/Modernizr/Modernizr/issues/issue/97/
var el = document.createElement('canvas');
return !!(el.getContext && el.getContext('2d'));
}()),
return_response_type: function(responseType) {
try {
if (Basic.inArray(responseType, ['', 'text', 'document']) !== -1) {
return true;
} else if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
xhr.open('get', '/'); // otherwise Gecko throws an exception
if ('responseType' in xhr) {
xhr.responseType = responseType;
// as of 23.0.1271.64, Chrome switched from throwing exception to merely logging it to the console (why? o why?)
if (xhr.responseType !== responseType) {
return false;
}
return true;
}
}
} catch (ex) {}
return false;
},
// ideas for this heavily come from Modernizr (http://modernizr.com/)
use_data_uri: (function() {
var du = new Image();
du.onload = function() {
caps.use_data_uri = (du.width === 1 && du.height === 1);
};
setTimeout(function() {
du.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP8AAAAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==";
}, 1);
return false;
}()),
use_data_uri_over32kb: function() { // IE8
return caps.use_data_uri && (Env.browser !== 'IE' || Env.version >= 9);
},
use_data_uri_of: function(bytes) {
return (caps.use_data_uri && bytes < 33000 || caps.use_data_uri_over32kb());
},
use_fileinput: function() {
var el = document.createElement('input');
el.setAttribute('type', 'file');
return !el.disabled;
}
};
return function(cap) {
var args = [].slice.call(arguments);
args.shift(); // shift of cap
return Basic.typeOf(caps[cap]) === 'function' ? caps[cap].apply(this, args) : !!caps[cap];
};
}());
var Env = {
can: can,
browser: UAParser.browser.name,
version: parseFloat(UAParser.browser.major),
os: UAParser.os.name, // everybody intuitively types it in a lowercase for some reason
osVersion: UAParser.os.version,
verComp: version_compare,
swf_url: "../flash/Moxie.swf",
xap_url: "../silverlight/Moxie.xap",
global_event_dispatcher: "moxie.core.EventTarget.instance.dispatchEvent"
};
// for backward compatibility
// @deprecated Use `Env.os` instead
Env.OS = Env.os;
return Env;
});
// Included from: src/javascript/core/utils/Dom.js
/**
* Dom.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/utils/Dom', ['moxie/core/utils/Env'], function(Env) {
/**
Get DOM Element by it's id.
@method get
@for Utils
@param {String} id Identifier of the DOM Element
@return {DOMElement}
*/
var get = function(id) {
if (typeof id !== 'string') {
return id;
}
return document.getElementById(id);
};
/**
Checks if specified DOM element has specified class.
@method hasClass
@static
@param {Object} obj DOM element like object to add handler to.
@param {String} name Class name
*/
var hasClass = function(obj, name) {
if (!obj.className) {
return false;
}
var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
return regExp.test(obj.className);
};
/**
Adds specified className to specified DOM element.
@method addClass
@static
@param {Object} obj DOM element like object to add handler to.
@param {String} name Class name
*/
var addClass = function(obj, name) {
if (!hasClass(obj, name)) {
obj.className = !obj.className ? name : obj.className.replace(/\s+$/, '') + ' ' + name;
}
};
/**
Removes specified className from specified DOM element.
@method removeClass
@static
@param {Object} obj DOM element like object to add handler to.
@param {String} name Class name
*/
var removeClass = function(obj, name) {
if (obj.className) {
var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
obj.className = obj.className.replace(regExp, function($0, $1, $2) {
return $1 === ' ' && $2 === ' ' ? ' ' : '';
});
}
};
/**
Returns a given computed style of a DOM element.
@method getStyle
@static
@param {Object} obj DOM element like object.
@param {String} name Style you want to get from the DOM element
*/
var getStyle = function(obj, name) {
if (obj.currentStyle) {
return obj.currentStyle[name];
} else if (window.getComputedStyle) {
return window.getComputedStyle(obj, null)[name];
}
};
/**
Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields.
@method getPos
@static
@param {Element} node HTML element or element id to get x, y position from.
@param {Element} root Optional root element to stop calculations at.
@return {object} Absolute position of the specified element object with x, y fields.
*/
var getPos = function(node, root) {
var x = 0, y = 0, parent, doc = document, nodeRect, rootRect;
node = node;
root = root || doc.body;
// Returns the x, y cordinate for an element on IE 6 and IE 7
function getIEPos(node) {
var bodyElm, rect, x = 0, y = 0;
if (node) {
rect = node.getBoundingClientRect();
bodyElm = doc.compatMode === "CSS1Compat" ? doc.documentElement : doc.body;
x = rect.left + bodyElm.scrollLeft;
y = rect.top + bodyElm.scrollTop;
}
return {
x : x,
y : y
};
}
// Use getBoundingClientRect on IE 6 and IE 7 but not on IE 8 in standards mode
if (node && node.getBoundingClientRect && Env.browser === 'IE' && (!doc.documentMode || doc.documentMode < 8)) {
nodeRect = getIEPos(node);
rootRect = getIEPos(root);
return {
x : nodeRect.x - rootRect.x,
y : nodeRect.y - rootRect.y
};
}
parent = node;
while (parent && parent != root && parent.nodeType) {
x += parent.offsetLeft || 0;
y += parent.offsetTop || 0;
parent = parent.offsetParent;
}
parent = node.parentNode;
while (parent && parent != root && parent.nodeType) {
x -= parent.scrollLeft || 0;
y -= parent.scrollTop || 0;
parent = parent.parentNode;
}
return {
x : x,
y : y
};
};
/**
Returns the size of the specified node in pixels.
@method getSize
@static
@param {Node} node Node to get the size of.
@return {Object} Object with a w and h property.
*/
var getSize = function(node) {
return {
w : node.offsetWidth || node.clientWidth,
h : node.offsetHeight || node.clientHeight
};
};
return {
get: get,
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
getStyle: getStyle,
getPos: getPos,
getSize: getSize
};
});
// Included from: src/javascript/core/Exceptions.js
/**
* Exceptions.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/Exceptions', [
'moxie/core/utils/Basic'
], function(Basic) {
function _findKey(obj, value) {
var key;
for (key in obj) {
if (obj[key] === value) {
return key;
}
}
return null;
}
return {
RuntimeError: (function() {
var namecodes = {
NOT_INIT_ERR: 1,
NOT_SUPPORTED_ERR: 9,
JS_ERR: 4
};
function RuntimeError(code) {
this.code = code;
this.name = _findKey(namecodes, code);
this.message = this.name + ": RuntimeError " + this.code;
}
Basic.extend(RuntimeError, namecodes);
RuntimeError.prototype = Error.prototype;
return RuntimeError;
}()),
OperationNotAllowedException: (function() {
function OperationNotAllowedException(code) {
this.code = code;
this.name = 'OperationNotAllowedException';
}
Basic.extend(OperationNotAllowedException, {
NOT_ALLOWED_ERR: 1
});
OperationNotAllowedException.prototype = Error.prototype;
return OperationNotAllowedException;
}()),
ImageError: (function() {
var namecodes = {
WRONG_FORMAT: 1,
MAX_RESOLUTION_ERR: 2
};
function ImageError(code) {
this.code = code;
this.name = _findKey(namecodes, code);
this.message = this.name + ": ImageError " + this.code;
}
Basic.extend(ImageError, namecodes);
ImageError.prototype = Error.prototype;
return ImageError;
}()),
FileException: (function() {
var namecodes = {
NOT_FOUND_ERR: 1,
SECURITY_ERR: 2,
ABORT_ERR: 3,
NOT_READABLE_ERR: 4,
ENCODING_ERR: 5,
NO_MODIFICATION_ALLOWED_ERR: 6,
INVALID_STATE_ERR: 7,
SYNTAX_ERR: 8
};
function FileException(code) {
this.code = code;
this.name = _findKey(namecodes, code);
this.message = this.name + ": FileException " + this.code;
}
Basic.extend(FileException, namecodes);
FileException.prototype = Error.prototype;
return FileException;
}()),
DOMException: (function() {
var namecodes = {
INDEX_SIZE_ERR: 1,
DOMSTRING_SIZE_ERR: 2,
HIERARCHY_REQUEST_ERR: 3,
WRONG_DOCUMENT_ERR: 4,
INVALID_CHARACTER_ERR: 5,
NO_DATA_ALLOWED_ERR: 6,
NO_MODIFICATION_ALLOWED_ERR: 7,
NOT_FOUND_ERR: 8,
NOT_SUPPORTED_ERR: 9,
INUSE_ATTRIBUTE_ERR: 10,
INVALID_STATE_ERR: 11,
SYNTAX_ERR: 12,
INVALID_MODIFICATION_ERR: 13,
NAMESPACE_ERR: 14,
INVALID_ACCESS_ERR: 15,
VALIDATION_ERR: 16,
TYPE_MISMATCH_ERR: 17,
SECURITY_ERR: 18,
NETWORK_ERR: 19,
ABORT_ERR: 20,
URL_MISMATCH_ERR: 21,
QUOTA_EXCEEDED_ERR: 22,
TIMEOUT_ERR: 23,
INVALID_NODE_TYPE_ERR: 24,
DATA_CLONE_ERR: 25
};
function DOMException(code) {
this.code = code;
this.name = _findKey(namecodes, code);
this.message = this.name + ": DOMException " + this.code;
}
Basic.extend(DOMException, namecodes);
DOMException.prototype = Error.prototype;
return DOMException;
}()),
EventException: (function() {
function EventException(code) {
this.code = code;
this.name = 'EventException';
}
Basic.extend(EventException, {
UNSPECIFIED_EVENT_TYPE_ERR: 0
});
EventException.prototype = Error.prototype;
return EventException;
}())
};
});
// Included from: src/javascript/core/EventTarget.js
/**
* EventTarget.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/EventTarget', [
'moxie/core/Exceptions',
'moxie/core/utils/Basic'
], function(x, Basic) {
/**
Parent object for all event dispatching components and objects
@class EventTarget
@constructor EventTarget
*/
function EventTarget() {
// hash of event listeners by object uid
var eventpool = {};
Basic.extend(this, {
/**
Unique id of the event dispatcher, usually overriden by children
@property uid
@type String
*/
uid: null,
/**
Can be called from within a child in order to acquire uniqie id in automated manner
@method init
*/
init: function() {
if (!this.uid) {
this.uid = Basic.guid('uid_');
}
},
/**
Register a handler to a specific event dispatched by the object
@method addEventListener
@param {String} type Type or basically a name of the event to subscribe to
@param {Function} fn Callback function that will be called when event happens
@param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first
@param {Object} [scope=this] A scope to invoke event handler in
*/
addEventListener: function(type, fn, priority, scope) {
var self = this, list;
type = Basic.trim(type);
if (/\s/.test(type)) {
// multiple event types were passed for one handler
Basic.each(type.split(/\s+/), function(type) {
self.addEventListener(type, fn, priority, scope);
});
return;
}
type = type.toLowerCase();
priority = parseInt(priority, 10) || 0;
list = eventpool[this.uid] && eventpool[this.uid][type] || [];
list.push({fn : fn, priority : priority, scope : scope || this});
if (!eventpool[this.uid]) {
eventpool[this.uid] = {};
}
eventpool[this.uid][type] = list;
},
/**
Check if any handlers were registered to the specified event
@method hasEventListener
@param {String} type Type or basically a name of the event to check
@return {Mixed} Returns a handler if it was found and false, if - not
*/
hasEventListener: function(type) {
return type ? !!(eventpool[this.uid] && eventpool[this.uid][type]) : !!eventpool[this.uid];
},
/**
Unregister the handler from the event, or if former was not specified - unregister all handlers
@method removeEventListener
@param {String} type Type or basically a name of the event
@param {Function} [fn] Handler to unregister
*/
removeEventListener: function(type, fn) {
type = type.toLowerCase();
var list = eventpool[this.uid] && eventpool[this.uid][type], i;
if (list) {
if (fn) {
for (i = list.length - 1; i >= 0; i--) {
if (list[i].fn === fn) {
list.splice(i, 1);
break;
}
}
} else {
list = [];
}
// delete event list if it has become empty
if (!list.length) {
delete eventpool[this.uid][type];
// and object specific entry in a hash if it has no more listeners attached
if (Basic.isEmptyObj(eventpool[this.uid])) {
delete eventpool[this.uid];
}
}
}
},
/**
Remove all event handlers from the object
@method removeAllEventListeners
*/
removeAllEventListeners: function() {
if (eventpool[this.uid]) {
delete eventpool[this.uid];
}
},
/**
Dispatch the event
@method dispatchEvent
@param {String/Object} Type of event or event object to dispatch
@param {Mixed} [...] Variable number of arguments to be passed to a handlers
@return {Boolean} true by default and false if any handler returned false
*/
dispatchEvent: function(type) {
var uid, list, args, tmpEvt, evt = {}, result = true, undef;
if (Basic.typeOf(type) !== 'string') {
// we can't use original object directly (because of Silverlight)
tmpEvt = type;
if (Basic.typeOf(tmpEvt.type) === 'string') {
type = tmpEvt.type;
if (tmpEvt.total !== undef && tmpEvt.loaded !== undef) { // progress event
evt.total = tmpEvt.total;
evt.loaded = tmpEvt.loaded;
}
evt.async = tmpEvt.async || false;
} else {
throw new x.EventException(x.EventException.UNSPECIFIED_EVENT_TYPE_ERR);
}
}
// check if event is meant to be dispatched on an object having specific uid
if (type.indexOf('::') !== -1) {
(function(arr) {
uid = arr[0];
type = arr[1];
}(type.split('::')));
} else {
uid = this.uid;
}
type = type.toLowerCase();
list = eventpool[uid] && eventpool[uid][type];
if (list) {
// sort event list by prority
list.sort(function(a, b) { return b.priority - a.priority; });
args = [].slice.call(arguments);
// first argument will be pseudo-event object
args.shift();
evt.type = type;
args.unshift(evt);
// Dispatch event to all listeners
var queue = [];
Basic.each(list, function(handler) {
// explicitly set the target, otherwise events fired from shims do not get it
args[0].target = handler.scope;
// if event is marked as async, detach the handler
if (evt.async) {
queue.push(function(cb) {
setTimeout(function() {
cb(handler.fn.apply(handler.scope, args) === false);
}, 1);
});
} else {
queue.push(function(cb) {
cb(handler.fn.apply(handler.scope, args) === false); // if handler returns false stop propagation
});
}
});
if (queue.length) {
Basic.inSeries(queue, function(err) {
result = !err;
});
}
}
return result;
},
/**
Alias for addEventListener
@method bind
@protected
*/
bind: function() {
this.addEventListener.apply(this, arguments);
},
/**
Alias for removeEventListener
@method unbind
@protected
*/
unbind: function() {
this.removeEventListener.apply(this, arguments);
},
/**
Alias for removeAllEventListeners
@method unbindAll
@protected
*/
unbindAll: function() {
this.removeAllEventListeners.apply(this, arguments);
},
/**
Alias for dispatchEvent
@method trigger
@protected
*/
trigger: function() {
return this.dispatchEvent.apply(this, arguments);
},
/**
Converts properties of on[event] type to corresponding event handlers,
is used to avoid extra hassle around the process of calling them back
@method convertEventPropsToHandlers
@private
*/
convertEventPropsToHandlers: function(handlers) {
var h;
if (Basic.typeOf(handlers) !== 'array') {
handlers = [handlers];
}
for (var i = 0; i < handlers.length; i++) {
h = 'on' + handlers[i];
if (Basic.typeOf(this[h]) === 'function') {
this.addEventListener(handlers[i], this[h]);
} else if (Basic.typeOf(this[h]) === 'undefined') {
this[h] = null; // object must have defined event properties, even if it doesn't make use of them
}
}
}
});
}
EventTarget.instance = new EventTarget();
return EventTarget;
});
// Included from: src/javascript/core/utils/Encode.js
/**
* Encode.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/utils/Encode', [], function() {
/**
Encode string with UTF-8
@method utf8_encode
@for Utils
@static
@param {String} str String to encode
@return {String} UTF-8 encoded string
*/
var utf8_encode = function(str) {
return unescape(encodeURIComponent(str));
};
/**
Decode UTF-8 encoded string
@method utf8_decode
@static
@param {String} str String to decode
@return {String} Decoded string
*/
var utf8_decode = function(str_data) {
return decodeURIComponent(escape(str_data));
};
/**
Decode Base64 encoded string (uses browser's default method if available),
from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_decode.js
@method atob
@static
@param {String} data String to decode
@return {String} Decoded string
*/
var atob = function(data, utf8) {
if (typeof(window.atob) === 'function') {
return utf8 ? utf8_decode(window.atob(data)) : window.atob(data);
}
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Thunder.m
// + input by: Aman Gupta
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
// * returns 1: 'Kevin van Zonneveld'
// mozilla has this native
// - but breaks in 2.0.0.12!
//if (typeof this.window.atob == 'function') {
// return atob(data);
//}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
dec = "",
tmp_arr = [];
if (!data) {
return data;
}
data += '';
do { // unpack four hexets into three octets using index points in b64
h1 = b64.indexOf(data.charAt(i++));
h2 = b64.indexOf(data.charAt(i++));
h3 = b64.indexOf(data.charAt(i++));
h4 = b64.indexOf(data.charAt(i++));
bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
o1 = bits >> 16 & 0xff;
o2 = bits >> 8 & 0xff;
o3 = bits & 0xff;
if (h3 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1);
} else if (h4 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1, o2);
} else {
tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
}
} while (i < data.length);
dec = tmp_arr.join('');
return utf8 ? utf8_decode(dec) : dec;
};
/**
Base64 encode string (uses browser's default method if available),
from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_encode.js
@method btoa
@static
@param {String} data String to encode
@return {String} Base64 encoded string
*/
var btoa = function(data, utf8) {
if (utf8) {
utf8_encode(data);
}
if (typeof(window.btoa) === 'function') {
return window.btoa(data);
}
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Bayron Guevara
// + improved by: Thunder.m
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Rafał Kukawski (http://kukawski.pl)
// * example 1: base64_encode('Kevin van Zonneveld');
// * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
// mozilla has this native
// - but breaks in 2.0.0.12!
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = "",
tmp_arr = [];
if (!data) {
return data;
}
do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
var r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
};
return {
utf8_encode: utf8_encode,
utf8_decode: utf8_decode,
atob: atob,
btoa: btoa
};
});
// Included from: src/javascript/runtime/Runtime.js
/**
* Runtime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/runtime/Runtime', [
"moxie/core/utils/Basic",
"moxie/core/utils/Dom",
"moxie/core/EventTarget"
], function(Basic, Dom, EventTarget) {
var runtimeConstructors = {}, runtimes = {};
/**
Common set of methods and properties for every runtime instance
@class Runtime
@param {Object} options
@param {String} type Sanitized name of the runtime
@param {Object} [caps] Set of capabilities that differentiate specified runtime
@param {Object} [modeCaps] Set of capabilities that do require specific operational mode
@param {String} [preferredMode='browser'] Preferred operational mode to choose if no required capabilities were requested
*/
function Runtime(options, type, caps, modeCaps, preferredMode) {
/**
Dispatched when runtime is initialized and ready.
Results in RuntimeInit on a connected component.
@event Init
*/
/**
Dispatched when runtime fails to initialize.
Results in RuntimeError on a connected component.
@event Error
*/
var self = this
, _shim
, _uid = Basic.guid(type + '_')
, defaultMode = preferredMode || 'browser'
;
options = options || {};
// register runtime in private hash
runtimes[_uid] = this;
/**
Default set of capabilities, which can be redifined later by specific runtime
@private
@property caps
@type Object
*/
caps = Basic.extend({
// Runtime can:
// provide access to raw binary data of the file
access_binary: false,
// provide access to raw binary data of the image (image extension is optional)
access_image_binary: false,
// display binary data as thumbs for example
display_media: false,
// make cross-domain requests
do_cors: false,
// accept files dragged and dropped from the desktop
drag_and_drop: false,
// filter files in selection dialog by their extensions
filter_by_extension: true,
// resize image (and manipulate it raw data of any file in general)
resize_image: false,
// periodically report how many bytes of total in the file were uploaded (loaded)
report_upload_progress: false,
// provide access to the headers of http response
return_response_headers: false,
// support response of specific type, which should be passed as an argument
// e.g. runtime.can('return_response_type', 'blob')
return_response_type: false,
// return http status code of the response
return_status_code: true,
// send custom http header with the request
send_custom_headers: false,
// pick up the files from a dialog
select_file: false,
// select whole folder in file browse dialog
select_folder: false,
// select multiple files at once in file browse dialog
select_multiple: true,
// send raw binary data, that is generated after image resizing or manipulation of other kind
send_binary_string: false,
// send cookies with http request and therefore retain session
send_browser_cookies: true,
// send data formatted as multipart/form-data
send_multipart: true,
// slice the file or blob to smaller parts
slice_blob: false,
// upload file without preloading it to memory, stream it out directly from disk
stream_upload: false,
// programmatically trigger file browse dialog
summon_file_dialog: false,
// upload file of specific size, size should be passed as argument
// e.g. runtime.can('upload_filesize', '500mb')
upload_filesize: true,
// initiate http request with specific http method, method should be passed as argument
// e.g. runtime.can('use_http_method', 'put')
use_http_method: true
}, caps);
// default to the mode that is compatible with preferred caps
if (options.preferred_caps) {
defaultMode = Runtime.getMode(modeCaps, options.preferred_caps, defaultMode);
}
// small extension factory here (is meant to be extended with actual extensions constructors)
_shim = (function() {
var objpool = {};
return {
exec: function(uid, comp, fn, args) {
if (_shim[comp]) {
if (!objpool[uid]) {
objpool[uid] = {
context: this,
instance: new _shim[comp]()
};
}
if (objpool[uid].instance[fn]) {
return objpool[uid].instance[fn].apply(this, args);
}
}
},
removeInstance: function(uid) {
delete objpool[uid];
},
removeAllInstances: function() {
var self = this;
Basic.each(objpool, function(obj, uid) {
if (Basic.typeOf(obj.instance.destroy) === 'function') {
obj.instance.destroy.call(obj.context);
}
self.removeInstance(uid);
});
}
};
}());
// public methods
Basic.extend(this, {
/**
Specifies whether runtime instance was initialized or not
@property initialized
@type {Boolean}
@default false
*/
initialized: false, // shims require this flag to stop initialization retries
/**
Unique ID of the runtime
@property uid
@type {String}
*/
uid: _uid,
/**
Runtime type (e.g. flash, html5, etc)
@property type
@type {String}
*/
type: type,
/**
Runtime (not native one) may operate in browser or client mode.
@property mode
@private
@type {String|Boolean} current mode or false, if none possible
*/
mode: Runtime.getMode(modeCaps, (options.required_caps), defaultMode),
/**
id of the DOM container for the runtime (if available)
@property shimid
@type {String}
*/
shimid: _uid + '_container',
/**
Number of connected clients. If equal to zero, runtime can be destroyed
@property clients
@type {Number}
*/
clients: 0,
/**
Runtime initialization options
@property options
@type {Object}
*/
options: options,
/**
Checks if the runtime has specific capability
@method can
@param {String} cap Name of capability to check
@param {Mixed} [value] If passed, capability should somehow correlate to the value
@param {Object} [refCaps] Set of capabilities to check the specified cap against (defaults to internal set)
@return {Boolean} true if runtime has such capability and false, if - not
*/
can: function(cap, value) {
var refCaps = arguments[2] || caps;
// if cap var is a comma-separated list of caps, convert it to object (key/value)
if (Basic.typeOf(cap) === 'string' && Basic.typeOf(value) === 'undefined') {
cap = Runtime.parseCaps(cap);
}
if (Basic.typeOf(cap) === 'object') {
for (var key in cap) {
if (!this.can(key, cap[key], refCaps)) {
return false;
}
}
return true;
}
// check the individual cap
if (Basic.typeOf(refCaps[cap]) === 'function') {
return refCaps[cap].call(this, value);
} else {
return (value === refCaps[cap]);
}
},
/**
Returns container for the runtime as DOM element
@method getShimContainer
@return {DOMElement}
*/
getShimContainer: function() {
var container, shimContainer = Dom.get(this.shimid);
// if no container for shim, create one
if (!shimContainer) {
container = this.options.container ? Dom.get(this.options.container) : document.body;
// create shim container and insert it at an absolute position into the outer container
shimContainer = document.createElement('div');
shimContainer.id = this.shimid;
shimContainer.className = 'moxie-shim moxie-shim-' + this.type;
Basic.extend(shimContainer.style, {
position: 'absolute',
top: '0px',
left: '0px',
width: '1px',
height: '1px',
overflow: 'hidden'
});
container.appendChild(shimContainer);
container = null;
}
return shimContainer;
},
/**
Returns runtime as DOM element (if appropriate)
@method getShim
@return {DOMElement}
*/
getShim: function() {
return _shim;
},
/**
Invokes a method within the runtime itself (might differ across the runtimes)
@method shimExec
@param {Mixed} []
@protected
@return {Mixed} Depends on the action and component
*/
shimExec: function(component, action) {
var args = [].slice.call(arguments, 2);
return self.getShim().exec.call(this, this.uid, component, action, args);
},
/**
Operaional interface that is used by components to invoke specific actions on the runtime
(is invoked in the scope of component)
@method exec
@param {Mixed} []*
@protected
@return {Mixed} Depends on the action and component
*/
exec: function(component, action) { // this is called in the context of component, not runtime
var args = [].slice.call(arguments, 2);
if (self[component] && self[component][action]) {
return self[component][action].apply(this, args);
}
return self.shimExec.apply(this, arguments);
},
/**
Destroys the runtime (removes all events and deletes DOM structures)
@method destroy
*/
destroy: function() {
if (!self) {
return; // obviously already destroyed
}
var shimContainer = Dom.get(this.shimid);
if (shimContainer) {
shimContainer.parentNode.removeChild(shimContainer);
}
if (_shim) {
_shim.removeAllInstances();
}
this.unbindAll();
delete runtimes[this.uid];
this.uid = null; // mark this runtime as destroyed
_uid = self = _shim = shimContainer = null;
}
});
// once we got the mode, test against all caps
if (this.mode && options.required_caps && !this.can(options.required_caps)) {
this.mode = false;
}
}
/**
Default order to try different runtime types
@property order
@type String
@static
*/
Runtime.order = 'html5,flash,silverlight,html4';
/**
Retrieves runtime from private hash by it's uid
@method getRuntime
@private
@static
@param {String} uid Unique identifier of the runtime
@return {Runtime|Boolean} Returns runtime, if it exists and false, if - not
*/
Runtime.getRuntime = function(uid) {
return runtimes[uid] ? runtimes[uid] : false;
};
/**
Register constructor for the Runtime of new (or perhaps modified) type
@method addConstructor
@static
@param {String} type Runtime type (e.g. flash, html5, etc)
@param {Function} construct Constructor for the Runtime type
*/
Runtime.addConstructor = function(type, constructor) {
constructor.prototype = EventTarget.instance;
runtimeConstructors[type] = constructor;
};
/**
Get the constructor for the specified type.
method getConstructor
@static
@param {String} type Runtime type (e.g. flash, html5, etc)
@return {Function} Constructor for the Runtime type
*/
Runtime.getConstructor = function(type) {
return runtimeConstructors[type] || null;
};
/**
Get info about the runtime (uid, type, capabilities)
@method getInfo
@static
@param {String} uid Unique identifier of the runtime
@return {Mixed} Info object or null if runtime doesn't exist
*/
Runtime.getInfo = function(uid) {
var runtime = Runtime.getRuntime(uid);
if (runtime) {
return {
uid: runtime.uid,
type: runtime.type,
mode: runtime.mode,
can: function() {
return runtime.can.apply(runtime, arguments);
}
};
}
return null;
};
/**
Convert caps represented by a comma-separated string to the object representation.
@method parseCaps
@static
@param {String} capStr Comma-separated list of capabilities
@return {Object}
*/
Runtime.parseCaps = function(capStr) {
var capObj = {};
if (Basic.typeOf(capStr) !== 'string') {
return capStr || {};
}
Basic.each(capStr.split(','), function(key) {
capObj[key] = true; // we assume it to be - true
});
return capObj;
};
/**
Test the specified runtime for specific capabilities.
@method can
@static
@param {String} type Runtime type (e.g. flash, html5, etc)
@param {String|Object} caps Set of capabilities to check
@return {Boolean} Result of the test
*/
Runtime.can = function(type, caps) {
var runtime
, constructor = Runtime.getConstructor(type)
, mode
;
if (constructor) {
runtime = new constructor({
required_caps: caps
});
mode = runtime.mode;
runtime.destroy();
return !!mode;
}
return false;
};
/**
Figure out a runtime that supports specified capabilities.
@method thatCan
@static
@param {String|Object} caps Set of capabilities to check
@param {String} [runtimeOrder] Comma-separated list of runtimes to check against
@return {String} Usable runtime identifier or null
*/
Runtime.thatCan = function(caps, runtimeOrder) {
var types = (runtimeOrder || Runtime.order).split(/\s*,\s*/);
for (var i in types) {
if (Runtime.can(types[i], caps)) {
return types[i];
}
}
return null;
};
/**
Figure out an operational mode for the specified set of capabilities.
@method getMode
@static
@param {Object} modeCaps Set of capabilities that depend on particular runtime mode
@param {Object} [requiredCaps] Supplied set of capabilities to find operational mode for
@param {String|Boolean} [defaultMode='browser'] Default mode to use
@return {String|Boolean} Compatible operational mode
*/
Runtime.getMode = function(modeCaps, requiredCaps, defaultMode) {
var mode = null;
if (Basic.typeOf(defaultMode) === 'undefined') { // only if not specified
defaultMode = 'browser';
}
if (requiredCaps && !Basic.isEmptyObj(modeCaps)) {
// loop over required caps and check if they do require the same mode
Basic.each(requiredCaps, function(value, cap) {
if (modeCaps.hasOwnProperty(cap)) {
var capMode = modeCaps[cap](value);
// make sure we always have an array
if (typeof(capMode) === 'string') {
capMode = [capMode];
}
if (!mode) {
mode = capMode;
} else if (!(mode = Basic.arrayIntersect(mode, capMode))) {
// if cap requires conflicting mode - runtime cannot fulfill required caps
return (mode = false);
}
}
});
if (mode) {
return Basic.inArray(defaultMode, mode) !== -1 ? defaultMode : mode[0];
} else if (mode === false) {
return false;
}
}
return defaultMode;
};
/**
Capability check that always returns true
@private
@static
@return {True}
*/
Runtime.capTrue = function() {
return true;
};
/**
Capability check that always returns false
@private
@static
@return {False}
*/
Runtime.capFalse = function() {
return false;
};
/**
Evaluate the expression to boolean value and create a function that always returns it.
@private
@static
@param {Mixed} expr Expression to evaluate
@return {Function} Function returning the result of evaluation
*/
Runtime.capTest = function(expr) {
return function() {
return !!expr;
};
};
return Runtime;
});
// Included from: src/javascript/runtime/RuntimeClient.js
/**
* RuntimeClient.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/runtime/RuntimeClient', [
'moxie/core/Exceptions',
'moxie/core/utils/Basic',
'moxie/runtime/Runtime'
], function(x, Basic, Runtime) {
/**
Set of methods and properties, required by a component to acquire ability to connect to a runtime
@class RuntimeClient
*/
return function RuntimeClient() {
var runtime;
Basic.extend(this, {
/**
Connects to the runtime specified by the options. Will either connect to existing runtime or create a new one.
Increments number of clients connected to the specified runtime.
@method connectRuntime
@param {Mixed} options Can be a runtme uid or a set of key-value pairs defining requirements and pre-requisites
*/
connectRuntime: function(options) {
var comp = this, ruid;
function initialize(items) {
var type, constructor;
// if we ran out of runtimes
if (!items.length) {
comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
runtime = null;
return;
}
type = items.shift();
constructor = Runtime.getConstructor(type);
if (!constructor) {
initialize(items);
return;
}
// try initializing the runtime
runtime = new constructor(options);
runtime.bind('Init', function() {
// mark runtime as initialized
runtime.initialized = true;
// jailbreak ...
setTimeout(function() {
runtime.clients++;
// this will be triggered on component
comp.trigger('RuntimeInit', runtime);
}, 1);
});
runtime.bind('Error', function() {
runtime.destroy(); // runtime cannot destroy itself from inside at a right moment, thus we do it here
initialize(items);
});
/*runtime.bind('Exception', function() { });*/
// check if runtime managed to pick-up operational mode
if (!runtime.mode) {
runtime.trigger('Error');
return;
}
runtime.init();
}
// check if a particular runtime was requested
if (Basic.typeOf(options) === 'string') {
ruid = options;
} else if (Basic.typeOf(options.ruid) === 'string') {
ruid = options.ruid;
}
if (ruid) {
runtime = Runtime.getRuntime(ruid);
if (runtime) {
runtime.clients++;
return runtime;
} else {
// there should be a runtime and there's none - weird case
throw new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR);
}
}
// initialize a fresh one, that fits runtime list and required features best
initialize((options.runtime_order || Runtime.order).split(/\s*,\s*/));
},
/**
Returns the runtime to which the client is currently connected.
@method getRuntime
@return {Runtime} Runtime or null if client is not connected
*/
getRuntime: function() {
if (runtime && runtime.uid) {
return runtime;
}
runtime = null; // make sure we do not leave zombies rambling around
return null;
},
/**
Disconnects from the runtime. Decrements number of clients connected to the specified runtime.
@method disconnectRuntime
*/
disconnectRuntime: function() {
if (runtime && --runtime.clients <= 0) {
runtime.destroy();
runtime = null;
}
}
});
};
});
// Included from: src/javascript/file/Blob.js
/**
* Blob.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/file/Blob', [
'moxie/core/utils/Basic',
'moxie/core/utils/Encode',
'moxie/runtime/RuntimeClient'
], function(Basic, Encode, RuntimeClient) {
var blobpool = {};
/**
@class Blob
@constructor
@param {String} ruid Unique id of the runtime, to which this blob belongs to
@param {Object} blob Object "Native" blob object, as it is represented in the runtime
*/
function Blob(ruid, blob) {
function _sliceDetached(start, end, type) {
var blob, data = blobpool[this.uid];
if (Basic.typeOf(data) !== 'string' || !data.length) {
return null; // or throw exception
}
blob = new Blob(null, {
type: type,
size: end - start
});
blob.detach(data.substr(start, blob.size));
return blob;
}
RuntimeClient.call(this);
if (ruid) {
this.connectRuntime(ruid);
}
if (!blob) {
blob = {};
} else if (Basic.typeOf(blob) === 'string') { // dataUrl or binary string
blob = { data: blob };
}
Basic.extend(this, {
/**
Unique id of the component
@property uid
@type {String}
*/
uid: blob.uid || Basic.guid('uid_'),
/**
Unique id of the connected runtime, if falsy, then runtime will have to be initialized
before this Blob can be used, modified or sent
@property ruid
@type {String}
*/
ruid: ruid,
/**
Size of blob
@property size
@type {Number}
@default 0
*/
size: blob.size || 0,
/**
Mime type of blob
@property type
@type {String}
@default ''
*/
type: blob.type || '',
/**
@method slice
@param {Number} [start=0]
*/
slice: function(start, end, type) {
if (this.isDetached()) {
return _sliceDetached.apply(this, arguments);
}
return this.getRuntime().exec.call(this, 'Blob', 'slice', this.getSource(), start, end, type);
},
/**
Returns "native" blob object (as it is represented in connected runtime) or null if not found
@method getSource
@return {Blob} Returns "native" blob object or null if not found
*/
getSource: function() {
if (!blobpool[this.uid]) {
return null;
}
return blobpool[this.uid];
},
/**
Detaches blob from any runtime that it depends on and initialize with standalone value
@method detach
@protected
@param {DOMString} [data=''] Standalone value
*/
detach: function(data) {
if (this.ruid) {
this.getRuntime().exec.call(this, 'Blob', 'destroy');
this.disconnectRuntime();
this.ruid = null;
}
data = data || '';
// if dataUrl, convert to binary string
var matches = data.match(/^data:([^;]*);base64,/);
if (matches) {
this.type = matches[1];
data = Encode.atob(data.substring(data.indexOf('base64,') + 7));
}
this.size = data.length;
blobpool[this.uid] = data;
},
/**
Checks if blob is standalone (detached of any runtime)
@method isDetached
@protected
@return {Boolean}
*/
isDetached: function() {
return !this.ruid && Basic.typeOf(blobpool[this.uid]) === 'string';
},
/**
Destroy Blob and free any resources it was using
@method destroy
*/
destroy: function() {
this.detach();
delete blobpool[this.uid];
}
});
if (blob.data) {
this.detach(blob.data); // auto-detach if payload has been passed
} else {
blobpool[this.uid] = blob;
}
}
return Blob;
});
// Included from: src/javascript/file/File.js
/**
* File.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/file/File', [
'moxie/core/utils/Basic',
'moxie/core/utils/Mime',
'moxie/file/Blob'
], function(Basic, Mime, Blob) {
/**
@class File
@extends Blob
@constructor
@param {String} ruid Unique id of the runtime, to which this blob belongs to
@param {Object} file Object "Native" file object, as it is represented in the runtime
*/
function File(ruid, file) {
var name, type;
if (!file) { // avoid extra errors in case we overlooked something
file = {};
}
// figure out the type
if (file.type && file.type !== '') {
type = file.type;
} else {
type = Mime.getFileMime(file.name);
}
// sanitize file name or generate new one
if (file.name) {
name = file.name.replace(/\\/g, '/');
name = name.substr(name.lastIndexOf('/') + 1);
} else {
var prefix = type.split('/')[0];
name = Basic.guid((prefix !== '' ? prefix : 'file') + '_');
if (Mime.extensions[type]) {
name += '.' + Mime.extensions[type][0]; // append proper extension if possible
}
}
Blob.apply(this, arguments);
Basic.extend(this, {
/**
File mime type
@property type
@type {String}
@default ''
*/
type: type || '',
/**
File name
@property name
@type {String}
@default UID
*/
name: name || Basic.guid('file_'),
/**
Date of last modification
@property lastModifiedDate
@type {String}
@default now
*/
lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString() // Thu Aug 23 2012 19:40:00 GMT+0400 (GET)
});
}
File.prototype = Blob.prototype;
return File;
});
// Included from: src/javascript/file/FileInput.js
/**
* FileInput.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/file/FileInput', [
'moxie/core/utils/Basic',
'moxie/core/utils/Mime',
'moxie/core/utils/Dom',
'moxie/core/Exceptions',
'moxie/core/EventTarget',
'moxie/core/I18n',
'moxie/file/File',
'moxie/runtime/Runtime',
'moxie/runtime/RuntimeClient'
], function(Basic, Mime, Dom, x, EventTarget, I18n, File, Runtime, RuntimeClient) {
/**
Provides a convenient way to create cross-browser file-picker. Generates file selection dialog on click,
converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory
with _FileReader_ or uploaded to a server through _XMLHttpRequest_.
@class FileInput
@constructor
@extends EventTarget
@uses RuntimeClient
@param {Object|String|DOMElement} options If options is string or node, argument is considered as _browse\_button_.
@param {String|DOMElement} options.browse_button DOM Element to turn into file picker.
@param {Array} [options.accept] Array of mime types to accept. By default accepts all.
@param {String} [options.file='file'] Name of the file field (not the filename).
@param {Boolean} [options.multiple=false] Enable selection of multiple files.
@param {Boolean} [options.directory=false] Turn file input into the folder input (cannot be both at the same time).
@param {String|DOMElement} [options.container] DOM Element to use as a container for file-picker. Defaults to parentNode
for _browse\_button_.
@param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support.
@example
<div id="container">
<a id="file-picker" href="javascript:;">Browse...</a>
</div>
<script>
var fileInput = new mOxie.FileInput({
browse_button: 'file-picker', // or document.getElementById('file-picker')
container: 'container',
accept: [
{title: "Image files", extensions: "jpg,gif,png"} // accept only images
],
multiple: true // allow multiple file selection
});
fileInput.onchange = function(e) {
// do something to files array
console.info(e.target.files); // or this.files or fileInput.files
};
fileInput.init(); // initialize
</script>
*/
var dispatches = [
/**
Dispatched when runtime is connected and file-picker is ready to be used.
@event ready
@param {Object} event
*/
'ready',
/**
Dispatched right after [ready](#event_ready) event, and whenever [refresh()](#method_refresh) is invoked.
Check [corresponding documentation entry](#method_refresh) for more info.
@event refresh
@param {Object} event
*/
/**
Dispatched when selection of files in the dialog is complete.
@event change
@param {Object} event
*/
'change',
'cancel', // TODO: might be useful
/**
Dispatched when mouse cursor enters file-picker area. Can be used to style element
accordingly.
@event mouseenter
@param {Object} event
*/
'mouseenter',
/**
Dispatched when mouse cursor leaves file-picker area. Can be used to style element
accordingly.
@event mouseleave
@param {Object} event
*/
'mouseleave',
/**
Dispatched when functional mouse button is pressed on top of file-picker area.
@event mousedown
@param {Object} event
*/
'mousedown',
/**
Dispatched when functional mouse button is released on top of file-picker area.
@event mouseup
@param {Object} event
*/
'mouseup'
];
function FileInput(options) {
var self = this,
container, browseButton, defaults;
// if flat argument passed it should be browse_button id
if (Basic.inArray(Basic.typeOf(options), ['string', 'node']) !== -1) {
options = { browse_button : options };
}
// this will help us to find proper default container
browseButton = Dom.get(options.browse_button);
if (!browseButton) {
// browse button is required
throw new x.DOMException(x.DOMException.NOT_FOUND_ERR);
}
// figure out the options
defaults = {
accept: [{
title: I18n.translate('All Files'),
extensions: '*'
}],
name: 'file',
multiple: false,
required_caps: false,
container: browseButton.parentNode || document.body
};
options = Basic.extend({}, defaults, options);
// convert to object representation
if (typeof(options.required_caps) === 'string') {
options.required_caps = Runtime.parseCaps(options.required_caps);
}
// normalize accept option (could be list of mime types or array of title/extensions pairs)
if (typeof(options.accept) === 'string') {
options.accept = Mime.mimes2extList(options.accept);
}
container = Dom.get(options.container);
// make sure we have container
if (!container) {
container = document.body;
}
// make container relative, if it's not
if (Dom.getStyle(container, 'position') === 'static') {
container.style.position = 'relative';
}
container = browseButton = null; // IE
RuntimeClient.call(self);
Basic.extend(self, {
/**
Unique id of the component
@property uid
@protected
@readOnly
@type {String}
@default UID
*/
uid: Basic.guid('uid_'),
/**
Unique id of the connected runtime, if any.
@property ruid
@protected
@type {String}
*/
ruid: null,
/**
Unique id of the runtime container. Useful to get hold of it for various manipulations.
@property shimid
@protected
@type {String}
*/
shimid: null,
/**
Array of selected mOxie.File objects
@property files
@type {Array}
@default null
*/
files: null,
/**
Initializes the file-picker, connects it to runtime and dispatches event ready when done.
@method init
*/
init: function() {
self.convertEventPropsToHandlers(dispatches);
self.bind('RuntimeInit', function(e, runtime) {
self.ruid = runtime.uid;
self.shimid = runtime.shimid;
self.bind("Ready", function() {
self.trigger("Refresh");
}, 999);
self.bind("Change", function() {
var files = runtime.exec.call(self, 'FileInput', 'getFiles');
self.files = [];
Basic.each(files, function(file) {
// ignore empty files (IE10 for example hangs if you try to send them via XHR)
if (file.size === 0) {
return true;
}
self.files.push(new File(self.ruid, file));
});
}, 999);
// re-position and resize shim container
self.bind('Refresh', function() {
var pos, size, browseButton, shimContainer;
browseButton = Dom.get(options.browse_button);
shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist
if (browseButton) {
pos = Dom.getPos(browseButton, Dom.get(options.container));
size = Dom.getSize(browseButton);
if (shimContainer) {
Basic.extend(shimContainer.style, {
top : pos.y + 'px',
left : pos.x + 'px',
width : size.w + 'px',
height : size.h + 'px'
});
}
}
shimContainer = browseButton = null;
});
runtime.exec.call(self, 'FileInput', 'init', options);
});
// runtime needs: options.required_features, options.runtime_order and options.container
self.connectRuntime(Basic.extend({}, options, {
required_caps: {
select_file: true
}
}));
},
/**
Disables file-picker element, so that it doesn't react to mouse clicks.
@method disable
@param {Boolean} [state=true] Disable component if - true, enable if - false
*/
disable: function(state) {
var runtime = this.getRuntime();
if (runtime) {
runtime.exec.call(this, 'FileInput', 'disable', Basic.typeOf(state) === 'undefined' ? true : state);
}
},
/**
Reposition and resize dialog trigger to match the position and size of browse_button element.
@method refresh
*/
refresh: function() {
self.trigger("Refresh");
},
/**
Destroy component.
@method destroy
*/
destroy: function() {
var runtime = this.getRuntime();
if (runtime) {
runtime.exec.call(this, 'FileInput', 'destroy');
this.disconnectRuntime();
}
if (Basic.typeOf(this.files) === 'array') {
// no sense in leaving associated files behind
Basic.each(this.files, function(file) {
file.destroy();
});
}
this.files = null;
}
});
}
FileInput.prototype = EventTarget.instance;
return FileInput;
});
// Included from: src/javascript/runtime/RuntimeTarget.js
/**
* RuntimeTarget.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/runtime/RuntimeTarget', [
'moxie/core/utils/Basic',
'moxie/runtime/RuntimeClient',
"moxie/core/EventTarget"
], function(Basic, RuntimeClient, EventTarget) {
/**
Instance of this class can be used as a target for the events dispatched by shims,
when allowing them onto components is for either reason inappropriate
@class RuntimeTarget
@constructor
@protected
@extends EventTarget
*/
function RuntimeTarget() {
this.uid = Basic.guid('uid_');
RuntimeClient.call(this);
this.destroy = function() {
this.disconnectRuntime();
this.unbindAll();
};
}
RuntimeTarget.prototype = EventTarget.instance;
return RuntimeTarget;
});
// Included from: src/javascript/file/FileReader.js
/**
* FileReader.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/file/FileReader', [
'moxie/core/utils/Basic',
'moxie/core/utils/Encode',
'moxie/core/Exceptions',
'moxie/core/EventTarget',
'moxie/file/Blob',
'moxie/file/File',
'moxie/runtime/RuntimeTarget'
], function(Basic, Encode, x, EventTarget, Blob, File, RuntimeTarget) {
/**
Utility for preloading o.Blob/o.File objects in memory. By design closely follows [W3C FileReader](http://www.w3.org/TR/FileAPI/#dfn-filereader)
interface. Where possible uses native FileReader, where - not falls back to shims.
@class FileReader
@constructor FileReader
@extends EventTarget
@uses RuntimeClient
*/
var dispatches = [
/**
Dispatched when the read starts.
@event loadstart
@param {Object} event
*/
'loadstart',
/**
Dispatched while reading (and decoding) blob, and reporting partial Blob data (progess.loaded/progress.total).
@event progress
@param {Object} event
*/
'progress',
/**
Dispatched when the read has successfully completed.
@event load
@param {Object} event
*/
'load',
/**
Dispatched when the read has been aborted. For instance, by invoking the abort() method.
@event abort
@param {Object} event
*/
'abort',
/**
Dispatched when the read has failed.
@event error
@param {Object} event
*/
'error',
/**
Dispatched when the request has completed (either in success or failure).
@event loadend
@param {Object} event
*/
'loadend'
];
function FileReader() {
var self = this, _fr;
Basic.extend(this, {
/**
UID of the component instance.
@property uid
@type {String}
*/
uid: Basic.guid('uid_'),
/**
Contains current state of FileReader object. Can take values of FileReader.EMPTY, FileReader.LOADING
and FileReader.DONE.
@property readyState
@type {Number}
@default FileReader.EMPTY
*/
readyState: FileReader.EMPTY,
/**
Result of the successful read operation.
@property result
@type {String}
*/
result: null,
/**
Stores the error of failed asynchronous read operation.
@property error
@type {DOMError}
*/
error: null,
/**
Initiates reading of File/Blob object contents to binary string.
@method readAsBinaryString
@param {Blob|File} blob Object to preload
*/
readAsBinaryString: function(blob) {
_read.call(this, 'readAsBinaryString', blob);
},
/**
Initiates reading of File/Blob object contents to dataURL string.
@method readAsDataURL
@param {Blob|File} blob Object to preload
*/
readAsDataURL: function(blob) {
_read.call(this, 'readAsDataURL', blob);
},
/**
Initiates reading of File/Blob object contents to string.
@method readAsText
@param {Blob|File} blob Object to preload
*/
readAsText: function(blob) {
_read.call(this, 'readAsText', blob);
},
/**
Aborts preloading process.
@method abort
*/
abort: function() {
this.result = null;
if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) {
return;
} else if (this.readyState === FileReader.LOADING) {
this.readyState = FileReader.DONE;
}
if (_fr) {
_fr.getRuntime().exec.call(this, 'FileReader', 'abort');
}
this.trigger('abort');
this.trigger('loadend');
},
/**
Destroy component and release resources.
@method destroy
*/
destroy: function() {
this.abort();
if (_fr) {
_fr.getRuntime().exec.call(this, 'FileReader', 'destroy');
_fr.disconnectRuntime();
}
self = _fr = null;
}
});
function _read(op, blob) {
_fr = new RuntimeTarget();
function error(err) {
self.readyState = FileReader.DONE;
self.error = err;
self.trigger('error');
loadEnd();
}
function loadEnd() {
_fr.destroy();
_fr = null;
self.trigger('loadend');
}
function exec(runtime) {
_fr.bind('Error', function(e, err) {
error(err);
});
_fr.bind('Progress', function(e) {
self.result = runtime.exec.call(_fr, 'FileReader', 'getResult');
self.trigger(e);
});
_fr.bind('Load', function(e) {
self.readyState = FileReader.DONE;
self.result = runtime.exec.call(_fr, 'FileReader', 'getResult');
self.trigger(e);
loadEnd();
});
runtime.exec.call(_fr, 'FileReader', 'read', op, blob);
}
this.convertEventPropsToHandlers(dispatches);
if (this.readyState === FileReader.LOADING) {
return error(new x.DOMException(x.DOMException.INVALID_STATE_ERR));
}
this.readyState = FileReader.LOADING;
this.trigger('loadstart');
// if source is o.Blob/o.File
if (blob instanceof Blob) {
if (blob.isDetached()) {
var src = blob.getSource();
switch (op) {
case 'readAsText':
case 'readAsBinaryString':
this.result = src;
break;
case 'readAsDataURL':
this.result = 'data:' + blob.type + ';base64,' + Encode.btoa(src);
break;
}
this.readyState = FileReader.DONE;
this.trigger('load');
loadEnd();
} else {
exec(_fr.connectRuntime(blob.ruid));
}
} else {
error(new x.DOMException(x.DOMException.NOT_FOUND_ERR));
}
}
}
/**
Initial FileReader state
@property EMPTY
@type {Number}
@final
@static
@default 0
*/
FileReader.EMPTY = 0;
/**
FileReader switches to this state when it is preloading the source
@property LOADING
@type {Number}
@final
@static
@default 1
*/
FileReader.LOADING = 1;
/**
Preloading is complete, this is a final state
@property DONE
@type {Number}
@final
@static
@default 2
*/
FileReader.DONE = 2;
FileReader.prototype = EventTarget.instance;
return FileReader;
});
// Included from: src/javascript/core/utils/Url.js
/**
* Url.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/utils/Url', [], function() {
/**
Parse url into separate components and fill in absent parts with parts from current url,
based on https://raw.github.com/kvz/phpjs/master/functions/url/parse_url.js
@method parseUrl
@for Utils
@static
@param {String} url Url to parse (defaults to empty string if undefined)
@return {Object} Hash containing extracted uri components
*/
var parseUrl = function(url, currentUrl) {
var key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'fragment']
, i = key.length
, ports = {
http: 80,
https: 443
}
, uri = {}
, regex = /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/
, m = regex.exec(url || '')
;
while (i--) {
if (m[i]) {
uri[key[i]] = m[i];
}
}
// when url is relative, we set the origin and the path ourselves
if (!uri.scheme) {
// come up with defaults
if (!currentUrl || typeof(currentUrl) === 'string') {
currentUrl = parseUrl(currentUrl || document.location.href);
}
uri.scheme = currentUrl.scheme;
uri.host = currentUrl.host;
uri.port = currentUrl.port;
var path = '';
// for urls without trailing slash we need to figure out the path
if (/^[^\/]/.test(uri.path)) {
path = currentUrl.path;
// if path ends with a filename, strip it
if (!/(\/|\/[^\.]+)$/.test(path)) {
path = path.replace(/\/[^\/]+$/, '/');
} else {
path += '/';
}
}
uri.path = path + (uri.path || ''); // site may reside at domain.com or domain.com/subdir
}
if (!uri.port) {
uri.port = ports[uri.scheme] || 80;
}
uri.port = parseInt(uri.port, 10);
if (!uri.path) {
uri.path = "/";
}
delete uri.source;
return uri;
};
/**
Resolve url - among other things will turn relative url to absolute
@method resolveUrl
@static
@param {String} url Either absolute or relative
@return {String} Resolved, absolute url
*/
var resolveUrl = function(url) {
var ports = { // we ignore default ports
http: 80,
https: 443
}
, urlp = parseUrl(url)
;
return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : '');
};
/**
Check if specified url has the same origin as the current document
@method hasSameOrigin
@param {String|Object} url
@return {Boolean}
*/
var hasSameOrigin = function(url) {
function origin(url) {
return [url.scheme, url.host, url.port].join('/');
}
if (typeof url === 'string') {
url = parseUrl(url);
}
return origin(parseUrl()) === origin(url);
};
return {
parseUrl: parseUrl,
resolveUrl: resolveUrl,
hasSameOrigin: hasSameOrigin
};
});
// Included from: src/javascript/file/FileReaderSync.js
/**
* FileReaderSync.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/file/FileReaderSync', [
'moxie/core/utils/Basic',
'moxie/runtime/RuntimeClient',
'moxie/core/utils/Encode'
], function(Basic, RuntimeClient, Encode) {
/**
Synchronous FileReader implementation. Something like this is available in WebWorkers environment, here
it can be used to read only preloaded blobs/files and only below certain size (not yet sure what that'd be,
but probably < 1mb). Not meant to be used directly by user.
@class FileReaderSync
@private
@constructor
*/
return function() {
RuntimeClient.call(this);
Basic.extend(this, {
uid: Basic.guid('uid_'),
readAsBinaryString: function(blob) {
return _read.call(this, 'readAsBinaryString', blob);
},
readAsDataURL: function(blob) {
return _read.call(this, 'readAsDataURL', blob);
},
/*readAsArrayBuffer: function(blob) {
return _read.call(this, 'readAsArrayBuffer', blob);
},*/
readAsText: function(blob) {
return _read.call(this, 'readAsText', blob);
}
});
function _read(op, blob) {
if (blob.isDetached()) {
var src = blob.getSource();
switch (op) {
case 'readAsBinaryString':
return src;
case 'readAsDataURL':
return 'data:' + blob.type + ';base64,' + Encode.btoa(src);
case 'readAsText':
var txt = '';
for (var i = 0, length = src.length; i < length; i++) {
txt += String.fromCharCode(src[i]);
}
return txt;
}
} else {
var result = this.connectRuntime(blob.ruid).exec.call(this, 'FileReaderSync', 'read', op, blob);
this.disconnectRuntime();
return result;
}
}
};
});
// Included from: src/javascript/xhr/FormData.js
/**
* FormData.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/xhr/FormData", [
"moxie/core/Exceptions",
"moxie/core/utils/Basic",
"moxie/file/Blob"
], function(x, Basic, Blob) {
/**
FormData
@class FormData
@constructor
*/
function FormData() {
var _blob, _fields = [];
Basic.extend(this, {
/**
Append another key-value pair to the FormData object
@method append
@param {String} name Name for the new field
@param {String|Blob|Array|Object} value Value for the field
*/
append: function(name, value) {
var self = this, valueType = Basic.typeOf(value);
// according to specs value might be either Blob or String
if (value instanceof Blob) {
_blob = {
name: name,
value: value // unfortunately we can only send single Blob in one FormData
};
} else if ('array' === valueType) {
name += '[]';
Basic.each(value, function(value) {
self.append(name, value);
});
} else if ('object' === valueType) {
Basic.each(value, function(value, key) {
self.append(name + '[' + key + ']', value);
});
} else if ('null' === valueType || 'undefined' === valueType || 'number' === valueType && isNaN(value)) {
self.append(name, "false");
} else {
_fields.push({
name: name,
value: value.toString()
});
}
},
/**
Checks if FormData contains Blob.
@method hasBlob
@return {Boolean}
*/
hasBlob: function() {
return !!this.getBlob();
},
/**
Retrieves blob.
@method getBlob
@return {Object} Either Blob if found or null
*/
getBlob: function() {
return _blob && _blob.value || null;
},
/**
Retrieves blob field name.
@method getBlobName
@return {String} Either Blob field name or null
*/
getBlobName: function() {
return _blob && _blob.name || null;
},
/**
Loop over the fields in FormData and invoke the callback for each of them.
@method each
@param {Function} cb Callback to call for each field
*/
each: function(cb) {
Basic.each(_fields, function(field) {
cb(field.value, field.name);
});
if (_blob) {
cb(_blob.value, _blob.name);
}
},
destroy: function() {
_blob = null;
_fields = [];
}
});
}
return FormData;
});
// Included from: src/javascript/xhr/XMLHttpRequest.js
/**
* XMLHttpRequest.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/xhr/XMLHttpRequest", [
"moxie/core/utils/Basic",
"moxie/core/Exceptions",
"moxie/core/EventTarget",
"moxie/core/utils/Encode",
"moxie/core/utils/Url",
"moxie/runtime/Runtime",
"moxie/runtime/RuntimeTarget",
"moxie/file/Blob",
"moxie/file/FileReaderSync",
"moxie/xhr/FormData",
"moxie/core/utils/Env",
"moxie/core/utils/Mime"
], function(Basic, x, EventTarget, Encode, Url, Runtime, RuntimeTarget, Blob, FileReaderSync, FormData, Env, Mime) {
var httpCode = {
100: 'Continue',
101: 'Switching Protocols',
102: 'Processing',
200: 'OK',
201: 'Created',
202: 'Accepted',
203: 'Non-Authoritative Information',
204: 'No Content',
205: 'Reset Content',
206: 'Partial Content',
207: 'Multi-Status',
226: 'IM Used',
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Found',
303: 'See Other',
304: 'Not Modified',
305: 'Use Proxy',
306: 'Reserved',
307: 'Temporary Redirect',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed',
413: 'Request Entity Too Large',
414: 'Request-URI Too Long',
415: 'Unsupported Media Type',
416: 'Requested Range Not Satisfiable',
417: 'Expectation Failed',
422: 'Unprocessable Entity',
423: 'Locked',
424: 'Failed Dependency',
426: 'Upgrade Required',
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout',
505: 'HTTP Version Not Supported',
506: 'Variant Also Negotiates',
507: 'Insufficient Storage',
510: 'Not Extended'
};
function XMLHttpRequestUpload() {
this.uid = Basic.guid('uid_');
}
XMLHttpRequestUpload.prototype = EventTarget.instance;
/**
Implementation of XMLHttpRequest
@class XMLHttpRequest
@constructor
@uses RuntimeClient
@extends EventTarget
*/
var dispatches = ['loadstart', 'progress', 'abort', 'error', 'load', 'timeout', 'loadend']; // & readystatechange (for historical reasons)
var NATIVE = 1, RUNTIME = 2;
function XMLHttpRequest() {
var self = this,
// this (together with _p() @see below) is here to gracefully upgrade to setter/getter syntax where possible
props = {
/**
The amount of milliseconds a request can take before being terminated. Initially zero. Zero means there is no timeout.
@property timeout
@type Number
@default 0
*/
timeout: 0,
/**
Current state, can take following values:
UNSENT (numeric value 0)
The object has been constructed.
OPENED (numeric value 1)
The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.
HEADERS_RECEIVED (numeric value 2)
All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.
LOADING (numeric value 3)
The response entity body is being received.
DONE (numeric value 4)
@property readyState
@type Number
@default 0 (UNSENT)
*/
readyState: XMLHttpRequest.UNSENT,
/**
True when user credentials are to be included in a cross-origin request. False when they are to be excluded
in a cross-origin request and when cookies are to be ignored in its response. Initially false.
@property withCredentials
@type Boolean
@default false
*/
withCredentials: false,
/**
Returns the HTTP status code.
@property status
@type Number
@default 0
*/
status: 0,
/**
Returns the HTTP status text.
@property statusText
@type String
*/
statusText: "",
/**
Returns the response type. Can be set to change the response type. Values are:
the empty string (default), "arraybuffer", "blob", "document", "json", and "text".
@property responseType
@type String
*/
responseType: "",
/**
Returns the document response entity body.
Throws an "InvalidStateError" exception if responseType is not the empty string or "document".
@property responseXML
@type Document
*/
responseXML: null,
/**
Returns the text response entity body.
Throws an "InvalidStateError" exception if responseType is not the empty string or "text".
@property responseText
@type String
*/
responseText: null,
/**
Returns the response entity body (http://www.w3.org/TR/XMLHttpRequest/#response-entity-body).
Can become: ArrayBuffer, Blob, Document, JSON, Text
@property response
@type Mixed
*/
response: null
},
_async = true,
_url,
_method,
_headers = {},
_user,
_password,
_encoding = null,
_mimeType = null,
// flags
_sync_flag = false,
_send_flag = false,
_upload_events_flag = false,
_upload_complete_flag = false,
_error_flag = false,
_same_origin_flag = false,
// times
_start_time,
_timeoutset_time,
_finalMime = null,
_finalCharset = null,
_options = {},
_xhr,
_responseHeaders = '',
_responseHeadersBag
;
Basic.extend(this, props, {
/**
Unique id of the component
@property uid
@type String
*/
uid: Basic.guid('uid_'),
/**
Target for Upload events
@property upload
@type XMLHttpRequestUpload
*/
upload: new XMLHttpRequestUpload(),
/**
Sets the request method, request URL, synchronous flag, request username, and request password.
Throws a "SyntaxError" exception if one of the following is true:
method is not a valid HTTP method.
url cannot be resolved.
url contains the "user:password" format in the userinfo production.
Throws a "SecurityError" exception if method is a case-insensitive match for CONNECT, TRACE or TRACK.
Throws an "InvalidAccessError" exception if one of the following is true:
Either user or password is passed as argument and the origin of url does not match the XMLHttpRequest origin.
There is an associated XMLHttpRequest document and either the timeout attribute is not zero,
the withCredentials attribute is true, or the responseType attribute is not the empty string.
@method open
@param {String} method HTTP method to use on request
@param {String} url URL to request
@param {Boolean} [async=true] If false request will be done in synchronous manner. Asynchronous by default.
@param {String} [user] Username to use in HTTP authentication process on server-side
@param {String} [password] Password to use in HTTP authentication process on server-side
*/
open: function(method, url, async, user, password) {
var urlp;
// first two arguments are required
if (!method || !url) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 2 - check if any code point in method is higher than U+00FF or after deflating method it does not match the method
if (/[\u0100-\uffff]/.test(method) || Encode.utf8_encode(method) !== method) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 3
if (!!~Basic.inArray(method.toUpperCase(), ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'TRACE', 'TRACK'])) {
_method = method.toUpperCase();
}
// 4 - allowing these methods poses a security risk
if (!!~Basic.inArray(_method, ['CONNECT', 'TRACE', 'TRACK'])) {
throw new x.DOMException(x.DOMException.SECURITY_ERR);
}
// 5
url = Encode.utf8_encode(url);
// 6 - Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error, throw a "SyntaxError".
urlp = Url.parseUrl(url);
_same_origin_flag = Url.hasSameOrigin(urlp);
// 7 - manually build up absolute url
_url = Url.resolveUrl(url);
// 9-10, 12-13
if ((user || password) && !_same_origin_flag) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
_user = user || urlp.user;
_password = password || urlp.pass;
// 11
_async = async || true;
if (_async === false && (_p('timeout') || _p('withCredentials') || _p('responseType') !== "")) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
// 14 - terminate abort()
// 15 - terminate send()
// 18
_sync_flag = !_async;
_send_flag = false;
_headers = {};
_reset.call(this);
// 19
_p('readyState', XMLHttpRequest.OPENED);
// 20
this.convertEventPropsToHandlers(['readystatechange']); // unify event handlers
this.dispatchEvent('readystatechange');
},
/**
Appends an header to the list of author request headers, or if header is already
in the list of author request headers, combines its value with value.
Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set.
Throws a "SyntaxError" exception if header is not a valid HTTP header field name or if value
is not a valid HTTP header field value.
@method setRequestHeader
@param {String} header
@param {String|Number} value
*/
setRequestHeader: function(header, value) {
var uaHeaders = [ // these headers are controlled by the user agent
"accept-charset",
"accept-encoding",
"access-control-request-headers",
"access-control-request-method",
"connection",
"content-length",
"cookie",
"cookie2",
"content-transfer-encoding",
"date",
"expect",
"host",
"keep-alive",
"origin",
"referer",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"user-agent",
"via"
];
// 1-2
if (_p('readyState') !== XMLHttpRequest.OPENED || _send_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 3
if (/[\u0100-\uffff]/.test(header) || Encode.utf8_encode(header) !== header) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 4
/* this step is seemingly bypassed in browsers, probably to allow various unicode characters in header values
if (/[\u0100-\uffff]/.test(value) || Encode.utf8_encode(value) !== value) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}*/
header = Basic.trim(header).toLowerCase();
// setting of proxy-* and sec-* headers is prohibited by spec
if (!!~Basic.inArray(header, uaHeaders) || /^(proxy\-|sec\-)/.test(header)) {
return false;
}
// camelize
// browsers lowercase header names (at least for custom ones)
// header = header.replace(/\b\w/g, function($1) { return $1.toUpperCase(); });
if (!_headers[header]) {
_headers[header] = value;
} else {
// http://tools.ietf.org/html/rfc2616#section-4.2 (last paragraph)
_headers[header] += ', ' + value;
}
return true;
},
/**
Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2.
@method getAllResponseHeaders
@return {String} reponse headers or empty string
*/
getAllResponseHeaders: function() {
return _responseHeaders || '';
},
/**
Returns the header field value from the response of which the field name matches header,
unless the field name is Set-Cookie or Set-Cookie2.
@method getResponseHeader
@param {String} header
@return {String} value(s) for the specified header or null
*/
getResponseHeader: function(header) {
header = header.toLowerCase();
if (_error_flag || !!~Basic.inArray(header, ['set-cookie', 'set-cookie2'])) {
return null;
}
if (_responseHeaders && _responseHeaders !== '') {
// if we didn't parse response headers until now, do it and keep for later
if (!_responseHeadersBag) {
_responseHeadersBag = {};
Basic.each(_responseHeaders.split(/\r\n/), function(line) {
var pair = line.split(/:\s+/);
if (pair.length === 2) { // last line might be empty, omit
pair[0] = Basic.trim(pair[0]); // just in case
_responseHeadersBag[pair[0].toLowerCase()] = { // simply to retain header name in original form
header: pair[0],
value: Basic.trim(pair[1])
};
}
});
}
if (_responseHeadersBag.hasOwnProperty(header)) {
return _responseHeadersBag[header].header + ': ' + _responseHeadersBag[header].value;
}
}
return null;
},
/**
Sets the Content-Type header for the response to mime.
Throws an "InvalidStateError" exception if the state is LOADING or DONE.
Throws a "SyntaxError" exception if mime is not a valid media type.
@method overrideMimeType
@param String mime Mime type to set
*/
overrideMimeType: function(mime) {
var matches, charset;
// 1
if (!!~Basic.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 2
mime = Basic.trim(mime.toLowerCase());
if (/;/.test(mime) && (matches = mime.match(/^([^;]+)(?:;\scharset\=)?(.*)$/))) {
mime = matches[1];
if (matches[2]) {
charset = matches[2];
}
}
if (!Mime.mimes[mime]) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 3-4
_finalMime = mime;
_finalCharset = charset;
},
/**
Initiates the request. The optional argument provides the request entity body.
The argument is ignored if request method is GET or HEAD.
Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set.
@method send
@param {Blob|Document|String|FormData} [data] Request entity body
@param {Object} [options] Set of requirements and pre-requisities for runtime initialization
*/
send: function(data, options) {
if (Basic.typeOf(options) === 'string') {
_options = { ruid: options };
} else if (!options) {
_options = {};
} else {
_options = options;
}
this.convertEventPropsToHandlers(dispatches);
this.upload.convertEventPropsToHandlers(dispatches);
// 1-2
if (this.readyState !== XMLHttpRequest.OPENED || _send_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 3
// sending Blob
if (data instanceof Blob) {
_options.ruid = data.ruid;
_mimeType = data.type || 'application/octet-stream';
}
// FormData
else if (data instanceof FormData) {
if (data.hasBlob()) {
var blob = data.getBlob();
_options.ruid = blob.ruid;
_mimeType = blob.type || 'application/octet-stream';
}
}
// DOMString
else if (typeof data === 'string') {
_encoding = 'UTF-8';
_mimeType = 'text/plain;charset=UTF-8';
// data should be converted to Unicode and encoded as UTF-8
data = Encode.utf8_encode(data);
}
// if withCredentials not set, but requested, set it automatically
if (!this.withCredentials) {
this.withCredentials = (_options.required_caps && _options.required_caps.send_browser_cookies) && !_same_origin_flag;
}
// 4 - storage mutex
// 5
_upload_events_flag = (!_sync_flag && this.upload.hasEventListener()); // DSAP
// 6
_error_flag = false;
// 7
_upload_complete_flag = !data;
// 8 - Asynchronous steps
if (!_sync_flag) {
// 8.1
_send_flag = true;
// 8.2
// this.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr
// 8.3
//if (!_upload_complete_flag) {
// this.upload.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr
//}
}
// 8.5 - Return the send() method call, but continue running the steps in this algorithm.
_doXHR.call(this, data);
},
/**
Cancels any network activity.
@method abort
*/
abort: function() {
_error_flag = true;
_sync_flag = false;
if (!~Basic.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED, XMLHttpRequest.DONE])) {
_p('readyState', XMLHttpRequest.DONE);
_send_flag = false;
if (_xhr) {
_xhr.getRuntime().exec.call(_xhr, 'XMLHttpRequest', 'abort', _upload_complete_flag);
} else {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
_upload_complete_flag = true;
} else {
_p('readyState', XMLHttpRequest.UNSENT);
}
},
destroy: function() {
if (_xhr) {
if (Basic.typeOf(_xhr.destroy) === 'function') {
_xhr.destroy();
}
_xhr = null;
}
this.unbindAll();
if (this.upload) {
this.upload.unbindAll();
this.upload = null;
}
}
});
/* this is nice, but maybe too lengthy
// if supported by JS version, set getters/setters for specific properties
o.defineProperty(this, 'readyState', {
configurable: false,
get: function() {
return _p('readyState');
}
});
o.defineProperty(this, 'timeout', {
configurable: false,
get: function() {
return _p('timeout');
},
set: function(value) {
if (_sync_flag) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
// timeout still should be measured relative to the start time of request
_timeoutset_time = (new Date).getTime();
_p('timeout', value);
}
});
// the withCredentials attribute has no effect when fetching same-origin resources
o.defineProperty(this, 'withCredentials', {
configurable: false,
get: function() {
return _p('withCredentials');
},
set: function(value) {
// 1-2
if (!~o.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED]) || _send_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 3-4
if (_anonymous_flag || _sync_flag) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
// 5
_p('withCredentials', value);
}
});
o.defineProperty(this, 'status', {
configurable: false,
get: function() {
return _p('status');
}
});
o.defineProperty(this, 'statusText', {
configurable: false,
get: function() {
return _p('statusText');
}
});
o.defineProperty(this, 'responseType', {
configurable: false,
get: function() {
return _p('responseType');
},
set: function(value) {
// 1
if (!!~o.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 2
if (_sync_flag) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
// 3
_p('responseType', value.toLowerCase());
}
});
o.defineProperty(this, 'responseText', {
configurable: false,
get: function() {
// 1
if (!~o.inArray(_p('responseType'), ['', 'text'])) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 2-3
if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
return _p('responseText');
}
});
o.defineProperty(this, 'responseXML', {
configurable: false,
get: function() {
// 1
if (!~o.inArray(_p('responseType'), ['', 'document'])) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 2-3
if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
return _p('responseXML');
}
});
o.defineProperty(this, 'response', {
configurable: false,
get: function() {
if (!!~o.inArray(_p('responseType'), ['', 'text'])) {
if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) {
return '';
}
}
if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) {
return null;
}
return _p('response');
}
});
*/
function _p(prop, value) {
if (!props.hasOwnProperty(prop)) {
return;
}
if (arguments.length === 1) { // get
return Env.can('define_property') ? props[prop] : self[prop];
} else { // set
if (Env.can('define_property')) {
props[prop] = value;
} else {
self[prop] = value;
}
}
}
/*
function _toASCII(str, AllowUnassigned, UseSTD3ASCIIRules) {
// TODO: http://tools.ietf.org/html/rfc3490#section-4.1
return str.toLowerCase();
}
*/
function _doXHR(data) {
var self = this;
_start_time = new Date().getTime();
_xhr = new RuntimeTarget();
function loadEnd() {
if (_xhr) { // it could have been destroyed by now
_xhr.destroy();
_xhr = null;
}
self.dispatchEvent('loadend');
self = null;
}
function exec(runtime) {
_xhr.bind('LoadStart', function(e) {
_p('readyState', XMLHttpRequest.LOADING);
self.dispatchEvent('readystatechange');
self.dispatchEvent(e);
if (_upload_events_flag) {
self.upload.dispatchEvent(e);
}
});
_xhr.bind('Progress', function(e) {
if (_p('readyState') !== XMLHttpRequest.LOADING) {
_p('readyState', XMLHttpRequest.LOADING); // LoadStart unreliable (in Flash for example)
self.dispatchEvent('readystatechange');
}
self.dispatchEvent(e);
});
_xhr.bind('UploadProgress', function(e) {
if (_upload_events_flag) {
self.upload.dispatchEvent({
type: 'progress',
lengthComputable: false,
total: e.total,
loaded: e.loaded
});
}
});
_xhr.bind('Load', function(e) {
_p('readyState', XMLHttpRequest.DONE);
_p('status', Number(runtime.exec.call(_xhr, 'XMLHttpRequest', 'getStatus') || 0));
_p('statusText', httpCode[_p('status')] || "");
_p('response', runtime.exec.call(_xhr, 'XMLHttpRequest', 'getResponse', _p('responseType')));
if (!!~Basic.inArray(_p('responseType'), ['text', ''])) {
_p('responseText', _p('response'));
} else if (_p('responseType') === 'document') {
_p('responseXML', _p('response'));
}
_responseHeaders = runtime.exec.call(_xhr, 'XMLHttpRequest', 'getAllResponseHeaders');
self.dispatchEvent('readystatechange');
if (_p('status') > 0) { // status 0 usually means that server is unreachable
if (_upload_events_flag) {
self.upload.dispatchEvent(e);
}
self.dispatchEvent(e);
} else {
_error_flag = true;
self.dispatchEvent('error');
}
loadEnd();
});
_xhr.bind('Abort', function(e) {
self.dispatchEvent(e);
loadEnd();
});
_xhr.bind('Error', function(e) {
_error_flag = true;
_p('readyState', XMLHttpRequest.DONE);
self.dispatchEvent('readystatechange');
_upload_complete_flag = true;
self.dispatchEvent(e);
loadEnd();
});
runtime.exec.call(_xhr, 'XMLHttpRequest', 'send', {
url: _url,
method: _method,
async: _async,
user: _user,
password: _password,
headers: _headers,
mimeType: _mimeType,
encoding: _encoding,
responseType: self.responseType,
withCredentials: self.withCredentials,
options: _options
}, data);
}
// clarify our requirements
if (typeof(_options.required_caps) === 'string') {
_options.required_caps = Runtime.parseCaps(_options.required_caps);
}
_options.required_caps = Basic.extend({}, _options.required_caps, {
return_response_type: self.responseType
});
if (data instanceof FormData) {
_options.required_caps.send_multipart = true;
}
if (!_same_origin_flag) {
_options.required_caps.do_cors = true;
}
if (_options.ruid) { // we do not need to wait if we can connect directly
exec(_xhr.connectRuntime(_options));
} else {
_xhr.bind('RuntimeInit', function(e, runtime) {
exec(runtime);
});
_xhr.bind('RuntimeError', function(e, err) {
self.dispatchEvent('RuntimeError', err);
});
_xhr.connectRuntime(_options);
}
}
function _reset() {
_p('responseText', "");
_p('responseXML', null);
_p('response', null);
_p('status', 0);
_p('statusText', "");
_start_time = _timeoutset_time = null;
}
}
XMLHttpRequest.UNSENT = 0;
XMLHttpRequest.OPENED = 1;
XMLHttpRequest.HEADERS_RECEIVED = 2;
XMLHttpRequest.LOADING = 3;
XMLHttpRequest.DONE = 4;
XMLHttpRequest.prototype = EventTarget.instance;
return XMLHttpRequest;
});
// Included from: src/javascript/runtime/Transporter.js
/**
* Transporter.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/runtime/Transporter", [
"moxie/core/utils/Basic",
"moxie/core/utils/Encode",
"moxie/runtime/RuntimeClient",
"moxie/core/EventTarget"
], function(Basic, Encode, RuntimeClient, EventTarget) {
function Transporter() {
var mod, _runtime, _data, _size, _pos, _chunk_size;
RuntimeClient.call(this);
Basic.extend(this, {
uid: Basic.guid('uid_'),
state: Transporter.IDLE,
result: null,
transport: function(data, type, options) {
var self = this;
options = Basic.extend({
chunk_size: 204798
}, options);
// should divide by three, base64 requires this
if ((mod = options.chunk_size % 3)) {
options.chunk_size += 3 - mod;
}
_chunk_size = options.chunk_size;
_reset.call(this);
_data = data;
_size = data.length;
if (Basic.typeOf(options) === 'string' || options.ruid) {
_run.call(self, type, this.connectRuntime(options));
} else {
// we require this to run only once
var cb = function(e, runtime) {
self.unbind("RuntimeInit", cb);
_run.call(self, type, runtime);
};
this.bind("RuntimeInit", cb);
this.connectRuntime(options);
}
},
abort: function() {
var self = this;
self.state = Transporter.IDLE;
if (_runtime) {
_runtime.exec.call(self, 'Transporter', 'clear');
self.trigger("TransportingAborted");
}
_reset.call(self);
},
destroy: function() {
this.unbindAll();
_runtime = null;
this.disconnectRuntime();
_reset.call(this);
}
});
function _reset() {
_size = _pos = 0;
_data = this.result = null;
}
function _run(type, runtime) {
var self = this;
_runtime = runtime;
//self.unbind("RuntimeInit");
self.bind("TransportingProgress", function(e) {
_pos = e.loaded;
if (_pos < _size && Basic.inArray(self.state, [Transporter.IDLE, Transporter.DONE]) === -1) {
_transport.call(self);
}
}, 999);
self.bind("TransportingComplete", function() {
_pos = _size;
self.state = Transporter.DONE;
_data = null; // clean a bit
self.result = _runtime.exec.call(self, 'Transporter', 'getAsBlob', type || '');
}, 999);
self.state = Transporter.BUSY;
self.trigger("TransportingStarted");
_transport.call(self);
}
function _transport() {
var self = this,
chunk,
bytesLeft = _size - _pos;
if (_chunk_size > bytesLeft) {
_chunk_size = bytesLeft;
}
chunk = Encode.btoa(_data.substr(_pos, _chunk_size));
_runtime.exec.call(self, 'Transporter', 'receive', chunk, _size);
}
}
Transporter.IDLE = 0;
Transporter.BUSY = 1;
Transporter.DONE = 2;
Transporter.prototype = EventTarget.instance;
return Transporter;
});
// Included from: src/javascript/runtime/html5/Runtime.js
/**
* Runtime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/*global File:true */
/**
Defines constructor for HTML5 runtime.
@class moxie/runtime/html5/Runtime
@private
*/
define("moxie/runtime/html5/Runtime", [
"moxie/core/utils/Basic",
"moxie/core/Exceptions",
"moxie/runtime/Runtime",
"moxie/core/utils/Env"
], function(Basic, x, Runtime, Env) {
var type = "html5", extensions = {};
function Html5Runtime(options) {
var I = this
, Test = Runtime.capTest
, True = Runtime.capTrue
;
var caps = Basic.extend({
access_binary: Test(window.FileReader || window.File && window.File.getAsDataURL),
access_image_binary: function() {
return I.can('access_binary') && !!extensions.Image;
},
display_media: Test(Env.can('create_canvas') || Env.can('use_data_uri_over32kb')),
do_cors: Test(window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()),
drag_and_drop: Test(function() {
// this comes directly from Modernizr: http://www.modernizr.com/
var div = document.createElement('div');
// IE has support for drag and drop since version 5, but doesn't support dropping files from desktop
return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && (Env.browser !== 'IE' || Env.version > 9);
}()),
filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest
return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10);
}()),
return_response_headers: True,
return_response_type: function(responseType) {
if (responseType === 'json' && !!window.JSON) { // we can fake this one even if it's not supported
return true;
}
return Env.can('return_response_type', responseType);
},
return_status_code: True,
report_upload_progress: Test(window.XMLHttpRequest && new XMLHttpRequest().upload),
resize_image: function() {
return I.can('access_binary') && Env.can('create_canvas');
},
select_file: function() {
return Env.can('use_fileinput') && window.File;
},
select_folder: function() {
return I.can('select_file') && Env.browser === 'Chrome' && Env.version >= 21;
},
select_multiple: function() {
// it is buggy on Safari Windows and iOS
return I.can('select_file') &&
!(Env.browser === 'Safari' && Env.os === 'Windows') &&
!(Env.os === 'iOS' && Env.verComp(Env.osVersion, "7.0.4", '<'));
},
send_binary_string: Test(window.XMLHttpRequest && (new XMLHttpRequest().sendAsBinary || (window.Uint8Array && window.ArrayBuffer))),
send_custom_headers: Test(window.XMLHttpRequest),
send_multipart: function() {
return !!(window.XMLHttpRequest && new XMLHttpRequest().upload && window.FormData) || I.can('send_binary_string');
},
slice_blob: Test(window.File && (File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice)),
stream_upload: function(){
return I.can('slice_blob') && I.can('send_multipart');
},
summon_file_dialog: Test(function() { // yeah... some dirty sniffing here...
return (Env.browser === 'Firefox' && Env.version >= 4) ||
(Env.browser === 'Opera' && Env.version >= 12) ||
(Env.browser === 'IE' && Env.version >= 10) ||
!!~Basic.inArray(Env.browser, ['Chrome', 'Safari']);
}()),
upload_filesize: True
},
arguments[2]
);
Runtime.call(this, options, (arguments[1] || type), caps);
Basic.extend(this, {
init : function() {
this.trigger("Init");
},
destroy: (function(destroy) { // extend default destroy method
return function() {
destroy.call(I);
destroy = I = null;
};
}(this.destroy))
});
Basic.extend(this.getShim(), extensions);
}
Runtime.addConstructor(type, Html5Runtime);
return extensions;
});
// Included from: src/javascript/runtime/html5/file/Blob.js
/**
* Blob.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html5/file/Blob
@private
*/
define("moxie/runtime/html5/file/Blob", [
"moxie/runtime/html5/Runtime",
"moxie/file/Blob"
], function(extensions, Blob) {
function HTML5Blob() {
function w3cBlobSlice(blob, start, end) {
var blobSlice;
if (window.File.prototype.slice) {
try {
blob.slice(); // depricated version will throw WRONG_ARGUMENTS_ERR exception
return blob.slice(start, end);
} catch (e) {
// depricated slice method
return blob.slice(start, end - start);
}
// slice method got prefixed: https://bugzilla.mozilla.org/show_bug.cgi?id=649672
} else if ((blobSlice = window.File.prototype.webkitSlice || window.File.prototype.mozSlice)) {
return blobSlice.call(blob, start, end);
} else {
return null; // or throw some exception
}
}
this.slice = function() {
return new Blob(this.getRuntime().uid, w3cBlobSlice.apply(this, arguments));
};
}
return (extensions.Blob = HTML5Blob);
});
// Included from: src/javascript/core/utils/Events.js
/**
* Events.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/utils/Events', [
'moxie/core/utils/Basic'
], function(Basic) {
var eventhash = {}, uid = 'moxie_' + Basic.guid();
// IE W3C like event funcs
function preventDefault() {
this.returnValue = false;
}
function stopPropagation() {
this.cancelBubble = true;
}
/**
Adds an event handler to the specified object and store reference to the handler
in objects internal Plupload registry (@see removeEvent).
@method addEvent
@for Utils
@static
@param {Object} obj DOM element like object to add handler to.
@param {String} name Name to add event listener to.
@param {Function} callback Function to call when event occurs.
@param {String} [key] that might be used to add specifity to the event record.
*/
var addEvent = function(obj, name, callback, key) {
var func, events;
name = name.toLowerCase();
// Add event listener
if (obj.addEventListener) {
func = callback;
obj.addEventListener(name, func, false);
} else if (obj.attachEvent) {
func = function() {
var evt = window.event;
if (!evt.target) {
evt.target = evt.srcElement;
}
evt.preventDefault = preventDefault;
evt.stopPropagation = stopPropagation;
callback(evt);
};
obj.attachEvent('on' + name, func);
}
// Log event handler to objects internal mOxie registry
if (!obj[uid]) {
obj[uid] = Basic.guid();
}
if (!eventhash.hasOwnProperty(obj[uid])) {
eventhash[obj[uid]] = {};
}
events = eventhash[obj[uid]];
if (!events.hasOwnProperty(name)) {
events[name] = [];
}
events[name].push({
func: func,
orig: callback, // store original callback for IE
key: key
});
};
/**
Remove event handler from the specified object. If third argument (callback)
is not specified remove all events with the specified name.
@method removeEvent
@static
@param {Object} obj DOM element to remove event listener(s) from.
@param {String} name Name of event listener to remove.
@param {Function|String} [callback] might be a callback or unique key to match.
*/
var removeEvent = function(obj, name, callback) {
var type, undef;
name = name.toLowerCase();
if (obj[uid] && eventhash[obj[uid]] && eventhash[obj[uid]][name]) {
type = eventhash[obj[uid]][name];
} else {
return;
}
for (var i = type.length - 1; i >= 0; i--) {
// undefined or not, key should match
if (type[i].orig === callback || type[i].key === callback) {
if (obj.removeEventListener) {
obj.removeEventListener(name, type[i].func, false);
} else if (obj.detachEvent) {
obj.detachEvent('on'+name, type[i].func);
}
type[i].orig = null;
type[i].func = null;
type.splice(i, 1);
// If callback was passed we are done here, otherwise proceed
if (callback !== undef) {
break;
}
}
}
// If event array got empty, remove it
if (!type.length) {
delete eventhash[obj[uid]][name];
}
// If mOxie registry has become empty, remove it
if (Basic.isEmptyObj(eventhash[obj[uid]])) {
delete eventhash[obj[uid]];
// IE doesn't let you remove DOM object property with - delete
try {
delete obj[uid];
} catch(e) {
obj[uid] = undef;
}
}
};
/**
Remove all kind of events from the specified object
@method removeAllEvents
@static
@param {Object} obj DOM element to remove event listeners from.
@param {String} [key] unique key to match, when removing events.
*/
var removeAllEvents = function(obj, key) {
if (!obj || !obj[uid]) {
return;
}
Basic.each(eventhash[obj[uid]], function(events, name) {
removeEvent(obj, name, key);
});
};
return {
addEvent: addEvent,
removeEvent: removeEvent,
removeAllEvents: removeAllEvents
};
});
// Included from: src/javascript/runtime/html5/file/FileInput.js
/**
* FileInput.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html5/file/FileInput
@private
*/
define("moxie/runtime/html5/file/FileInput", [
"moxie/runtime/html5/Runtime",
"moxie/core/utils/Basic",
"moxie/core/utils/Dom",
"moxie/core/utils/Events",
"moxie/core/utils/Mime",
"moxie/core/utils/Env"
], function(extensions, Basic, Dom, Events, Mime, Env) {
function FileInput() {
var _files = [], _options;
Basic.extend(this, {
init: function(options) {
var comp = this, I = comp.getRuntime(), input, shimContainer, mimes, browseButton, zIndex, top;
_options = options;
_files = [];
// figure out accept string
mimes = _options.accept.mimes || Mime.extList2mimes(_options.accept, I.can('filter_by_extension'));
shimContainer = I.getShimContainer();
shimContainer.innerHTML = '<input id="' + I.uid +'" type="file" style="font-size:999px;opacity:0;"' +
(_options.multiple && I.can('select_multiple') ? 'multiple' : '') +
(_options.directory && I.can('select_folder') ? 'webkitdirectory directory' : '') + // Chrome 11+
(mimes ? ' accept="' + mimes.join(',') + '"' : '') + ' />';
input = Dom.get(I.uid);
// prepare file input to be placed underneath the browse_button element
Basic.extend(input.style, {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%'
});
browseButton = Dom.get(_options.browse_button);
// Route click event to the input[type=file] element for browsers that support such behavior
if (I.can('summon_file_dialog')) {
if (Dom.getStyle(browseButton, 'position') === 'static') {
browseButton.style.position = 'relative';
}
zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 1;
browseButton.style.zIndex = zIndex;
shimContainer.style.zIndex = zIndex - 1;
Events.addEvent(browseButton, 'click', function(e) {
var input = Dom.get(I.uid);
if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file]
input.click();
}
e.preventDefault();
}, comp.uid);
}
/* Since we have to place input[type=file] on top of the browse_button for some browsers,
browse_button loses interactivity, so we restore it here */
top = I.can('summon_file_dialog') ? browseButton : shimContainer;
Events.addEvent(top, 'mouseover', function() {
comp.trigger('mouseenter');
}, comp.uid);
Events.addEvent(top, 'mouseout', function() {
comp.trigger('mouseleave');
}, comp.uid);
Events.addEvent(top, 'mousedown', function() {
comp.trigger('mousedown');
}, comp.uid);
Events.addEvent(Dom.get(_options.container), 'mouseup', function() {
comp.trigger('mouseup');
}, comp.uid);
input.onchange = function onChange() { // there should be only one handler for this
_files = [];
if (_options.directory) {
// folders are represented by dots, filter them out (Chrome 11+)
Basic.each(this.files, function(file) {
if (file.name !== ".") { // if it doesn't looks like a folder
_files.push(file);
}
});
} else {
_files = [].slice.call(this.files);
}
// clearing the value enables the user to select the same file again if they want to
if (Env.browser !== 'IE' && Env.browser !== 'IEMobile') {
this.value = '';
} else {
// in IE input[type="file"] is read-only so the only way to reset it is to re-insert it
var clone = this.cloneNode(true);
this.parentNode.replaceChild(clone, this);
clone.onchange = onChange;
}
comp.trigger('change');
};
// ready event is perfectly asynchronous
comp.trigger({
type: 'ready',
async: true
});
shimContainer = null;
},
getFiles: function() {
return _files;
},
disable: function(state) {
var I = this.getRuntime(), input;
if ((input = Dom.get(I.uid))) {
input.disabled = !!state;
}
},
destroy: function() {
var I = this.getRuntime()
, shim = I.getShim()
, shimContainer = I.getShimContainer()
;
Events.removeAllEvents(shimContainer, this.uid);
Events.removeAllEvents(_options && Dom.get(_options.container), this.uid);
Events.removeAllEvents(_options && Dom.get(_options.browse_button), this.uid);
if (shimContainer) {
shimContainer.innerHTML = '';
}
shim.removeInstance(this.uid);
_files = _options = shimContainer = shim = null;
}
});
}
return (extensions.FileInput = FileInput);
});
// Included from: src/javascript/runtime/html5/file/FileReader.js
/**
* FileReader.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html5/file/FileReader
@private
*/
define("moxie/runtime/html5/file/FileReader", [
"moxie/runtime/html5/Runtime",
"moxie/core/utils/Encode",
"moxie/core/utils/Basic"
], function(extensions, Encode, Basic) {
function FileReader() {
var _fr, _convertToBinary = false;
Basic.extend(this, {
read: function(op, blob) {
var target = this;
_fr = new window.FileReader();
_fr.addEventListener('progress', function(e) {
target.trigger(e);
});
_fr.addEventListener('load', function(e) {
target.trigger(e);
});
_fr.addEventListener('error', function(e) {
target.trigger(e, _fr.error);
});
_fr.addEventListener('loadend', function() {
_fr = null;
});
if (Basic.typeOf(_fr[op]) === 'function') {
_convertToBinary = false;
_fr[op](blob.getSource());
} else if (op === 'readAsBinaryString') { // readAsBinaryString is depricated in general and never existed in IE10+
_convertToBinary = true;
_fr.readAsDataURL(blob.getSource());
}
},
getResult: function() {
return _fr && _fr.result ? (_convertToBinary ? _toBinary(_fr.result) : _fr.result) : null;
},
abort: function() {
if (_fr) {
_fr.abort();
}
},
destroy: function() {
_fr = null;
}
});
function _toBinary(str) {
return Encode.atob(str.substring(str.indexOf('base64,') + 7));
}
}
return (extensions.FileReader = FileReader);
});
// Included from: src/javascript/runtime/html5/xhr/XMLHttpRequest.js
/**
* XMLHttpRequest.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/*global ActiveXObject:true */
/**
@class moxie/runtime/html5/xhr/XMLHttpRequest
@private
*/
define("moxie/runtime/html5/xhr/XMLHttpRequest", [
"moxie/runtime/html5/Runtime",
"moxie/core/utils/Basic",
"moxie/core/utils/Mime",
"moxie/core/utils/Url",
"moxie/file/File",
"moxie/file/Blob",
"moxie/xhr/FormData",
"moxie/core/Exceptions",
"moxie/core/utils/Env"
], function(extensions, Basic, Mime, Url, File, Blob, FormData, x, Env) {
function XMLHttpRequest() {
var self = this
, _xhr
, _filename
;
Basic.extend(this, {
send: function(meta, data) {
var target = this
, isGecko2_5_6 = (Env.browser === 'Mozilla' && Env.version >= 4 && Env.version < 7)
, isAndroidBrowser = Env.browser === 'Android Browser'
, mustSendAsBinary = false
;
// extract file name
_filename = meta.url.replace(/^.+?\/([\w\-\.]+)$/, '$1').toLowerCase();
_xhr = _getNativeXHR();
_xhr.open(meta.method, meta.url, meta.async, meta.user, meta.password);
// prepare data to be sent
if (data instanceof Blob) {
if (data.isDetached()) {
mustSendAsBinary = true;
}
data = data.getSource();
} else if (data instanceof FormData) {
if (data.hasBlob()) {
if (data.getBlob().isDetached()) {
data = _prepareMultipart.call(target, data); // _xhr must be instantiated and be in OPENED state
mustSendAsBinary = true;
} else if ((isGecko2_5_6 || isAndroidBrowser) && Basic.typeOf(data.getBlob().getSource()) === 'blob' && window.FileReader) {
// Gecko 2/5/6 can't send blob in FormData: https://bugzilla.mozilla.org/show_bug.cgi?id=649150
// Android browsers (default one and Dolphin) seem to have the same issue, see: #613
_preloadAndSend.call(target, meta, data);
return; // _preloadAndSend will reinvoke send() with transmutated FormData =%D
}
}
// transfer fields to real FormData
if (data instanceof FormData) { // if still a FormData, e.g. not mangled by _prepareMultipart()
var fd = new window.FormData();
data.each(function(value, name) {
if (value instanceof Blob) {
fd.append(name, value.getSource());
} else {
fd.append(name, value);
}
});
data = fd;
}
}
// if XHR L2
if (_xhr.upload) {
if (meta.withCredentials) {
_xhr.withCredentials = true;
}
_xhr.addEventListener('load', function(e) {
target.trigger(e);
});
_xhr.addEventListener('error', function(e) {
target.trigger(e);
});
// additionally listen to progress events
_xhr.addEventListener('progress', function(e) {
target.trigger(e);
});
_xhr.upload.addEventListener('progress', function(e) {
target.trigger({
type: 'UploadProgress',
loaded: e.loaded,
total: e.total
});
});
// ... otherwise simulate XHR L2
} else {
_xhr.onreadystatechange = function onReadyStateChange() {
// fake Level 2 events
switch (_xhr.readyState) {
case 1: // XMLHttpRequest.OPENED
// readystatechanged is fired twice for OPENED state (in IE and Mozilla) - neu
break;
// looks like HEADERS_RECEIVED (state 2) is not reported in Opera (or it's old versions) - neu
case 2: // XMLHttpRequest.HEADERS_RECEIVED
break;
case 3: // XMLHttpRequest.LOADING
// try to fire progress event for not XHR L2
var total, loaded;
try {
if (Url.hasSameOrigin(meta.url)) { // Content-Length not accessible for cross-domain on some browsers
total = _xhr.getResponseHeader('Content-Length') || 0; // old Safari throws an exception here
}
if (_xhr.responseText) { // responseText was introduced in IE7
loaded = _xhr.responseText.length;
}
} catch(ex) {
total = loaded = 0;
}
target.trigger({
type: 'progress',
lengthComputable: !!total,
total: parseInt(total, 10),
loaded: loaded
});
break;
case 4: // XMLHttpRequest.DONE
// release readystatechange handler (mostly for IE)
_xhr.onreadystatechange = function() {};
// usually status 0 is returned when server is unreachable, but FF also fails to status 0 for 408 timeout
if (_xhr.status === 0) {
target.trigger('error');
} else {
target.trigger('load');
}
break;
}
};
}
// set request headers
if (!Basic.isEmptyObj(meta.headers)) {
Basic.each(meta.headers, function(value, header) {
_xhr.setRequestHeader(header, value);
});
}
// request response type
if ("" !== meta.responseType && 'responseType' in _xhr) {
if ('json' === meta.responseType && !Env.can('return_response_type', 'json')) { // we can fake this one
_xhr.responseType = 'text';
} else {
_xhr.responseType = meta.responseType;
}
}
// send ...
if (!mustSendAsBinary) {
_xhr.send(data);
} else {
if (_xhr.sendAsBinary) { // Gecko
_xhr.sendAsBinary(data);
} else { // other browsers having support for typed arrays
(function() {
// mimic Gecko's sendAsBinary
var ui8a = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
ui8a[i] = (data.charCodeAt(i) & 0xff);
}
_xhr.send(ui8a.buffer);
}());
}
}
target.trigger('loadstart');
},
getStatus: function() {
// according to W3C spec it should return 0 for readyState < 3, but instead it throws an exception
try {
if (_xhr) {
return _xhr.status;
}
} catch(ex) {}
return 0;
},
getResponse: function(responseType) {
var I = this.getRuntime();
try {
switch (responseType) {
case 'blob':
var file = new File(I.uid, _xhr.response);
// try to extract file name from content-disposition if possible (might be - not, if CORS for example)
var disposition = _xhr.getResponseHeader('Content-Disposition');
if (disposition) {
// extract filename from response header if available
var match = disposition.match(/filename=([\'\"'])([^\1]+)\1/);
if (match) {
_filename = match[2];
}
}
file.name = _filename;
// pre-webkit Opera doesn't set type property on the blob response
if (!file.type) {
file.type = Mime.getFileMime(_filename);
}
return file;
case 'json':
if (!Env.can('return_response_type', 'json')) {
return _xhr.status === 200 && !!window.JSON ? JSON.parse(_xhr.responseText) : null;
}
return _xhr.response;
case 'document':
return _getDocument(_xhr);
default:
return _xhr.responseText !== '' ? _xhr.responseText : null; // against the specs, but for consistency across the runtimes
}
} catch(ex) {
return null;
}
},
getAllResponseHeaders: function() {
try {
return _xhr.getAllResponseHeaders();
} catch(ex) {}
return '';
},
abort: function() {
if (_xhr) {
_xhr.abort();
}
},
destroy: function() {
self = _filename = null;
}
});
// here we go... ugly fix for ugly bug
function _preloadAndSend(meta, data) {
var target = this, blob, fr;
// get original blob
blob = data.getBlob().getSource();
// preload blob in memory to be sent as binary string
fr = new window.FileReader();
fr.onload = function() {
// overwrite original blob
data.append(data.getBlobName(), new Blob(null, {
type: blob.type,
data: fr.result
}));
// invoke send operation again
self.send.call(target, meta, data);
};
fr.readAsBinaryString(blob);
}
function _getNativeXHR() {
if (window.XMLHttpRequest && !(Env.browser === 'IE' && Env.version < 8)) { // IE7 has native XHR but it's buggy
return new window.XMLHttpRequest();
} else {
return (function() {
var progIDs = ['Msxml2.XMLHTTP.6.0', 'Microsoft.XMLHTTP']; // if 6.0 available, use it, otherwise failback to default 3.0
for (var i = 0; i < progIDs.length; i++) {
try {
return new ActiveXObject(progIDs[i]);
} catch (ex) {}
}
})();
}
}
// @credits Sergey Ilinsky (http://www.ilinsky.com/)
function _getDocument(xhr) {
var rXML = xhr.responseXML;
var rText = xhr.responseText;
// Try parsing responseText (@see: http://www.ilinsky.com/articles/XMLHttpRequest/#bugs-ie-responseXML-content-type)
if (Env.browser === 'IE' && rText && rXML && !rXML.documentElement && /[^\/]+\/[^\+]+\+xml/.test(xhr.getResponseHeader("Content-Type"))) {
rXML = new window.ActiveXObject("Microsoft.XMLDOM");
rXML.async = false;
rXML.validateOnParse = false;
rXML.loadXML(rText);
}
// Check if there is no error in document
if (rXML) {
if ((Env.browser === 'IE' && rXML.parseError !== 0) || !rXML.documentElement || rXML.documentElement.tagName === "parsererror") {
return null;
}
}
return rXML;
}
function _prepareMultipart(fd) {
var boundary = '----moxieboundary' + new Date().getTime()
, dashdash = '--'
, crlf = '\r\n'
, multipart = ''
, I = this.getRuntime()
;
if (!I.can('send_binary_string')) {
throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR);
}
_xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
// append multipart parameters
fd.each(function(value, name) {
// Firefox 3.6 failed to convert multibyte characters to UTF-8 in sendAsBinary(),
// so we try it here ourselves with: unescape(encodeURIComponent(value))
if (value instanceof Blob) {
// Build RFC2388 blob
multipart += dashdash + boundary + crlf +
'Content-Disposition: form-data; name="' + name + '"; filename="' + unescape(encodeURIComponent(value.name || 'blob')) + '"' + crlf +
'Content-Type: ' + (value.type || 'application/octet-stream') + crlf + crlf +
value.getSource() + crlf;
} else {
multipart += dashdash + boundary + crlf +
'Content-Disposition: form-data; name="' + name + '"' + crlf + crlf +
unescape(encodeURIComponent(value)) + crlf;
}
});
multipart += dashdash + boundary + dashdash + crlf;
return multipart;
}
}
return (extensions.XMLHttpRequest = XMLHttpRequest);
});
// Included from: src/javascript/runtime/html5/utils/BinaryReader.js
/**
* BinaryReader.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html5/utils/BinaryReader
@private
*/
define("moxie/runtime/html5/utils/BinaryReader", [], function() {
return function() {
var II = false, bin;
// Private functions
function read(idx, size) {
var mv = II ? 0 : -8 * (size - 1), sum = 0, i;
for (i = 0; i < size; i++) {
sum |= (bin.charCodeAt(idx + i) << Math.abs(mv + i*8));
}
return sum;
}
function putstr(segment, idx, length) {
length = arguments.length === 3 ? length : bin.length - idx - 1;
bin = bin.substr(0, idx) + segment + bin.substr(length + idx);
}
function write(idx, num, size) {
var str = '', mv = II ? 0 : -8 * (size - 1), i;
for (i = 0; i < size; i++) {
str += String.fromCharCode((num >> Math.abs(mv + i*8)) & 255);
}
putstr(str, idx, size);
}
// Public functions
return {
II: function(order) {
if (order === undefined) {
return II;
} else {
II = order;
}
},
init: function(binData) {
II = false;
bin = binData;
},
SEGMENT: function(idx, length, segment) {
switch (arguments.length) {
case 1:
return bin.substr(idx, bin.length - idx - 1);
case 2:
return bin.substr(idx, length);
case 3:
putstr(segment, idx, length);
break;
default: return bin;
}
},
BYTE: function(idx) {
return read(idx, 1);
},
SHORT: function(idx) {
return read(idx, 2);
},
LONG: function(idx, num) {
if (num === undefined) {
return read(idx, 4);
} else {
write(idx, num, 4);
}
},
SLONG: function(idx) { // 2's complement notation
var num = read(idx, 4);
return (num > 2147483647 ? num - 4294967296 : num);
},
STRING: function(idx, size) {
var str = '';
for (size += idx; idx < size; idx++) {
str += String.fromCharCode(read(idx, 1));
}
return str;
}
};
};
});
// Included from: src/javascript/runtime/flash/Runtime.js
/**
* Runtime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/*global ActiveXObject:true */
/**
Defines constructor for Flash runtime.
@class moxie/runtime/flash/Runtime
@private
*/
define("moxie/runtime/flash/Runtime", [
"moxie/core/utils/Basic",
"moxie/core/utils/Env",
"moxie/core/utils/Dom",
"moxie/core/Exceptions",
"moxie/runtime/Runtime"
], function(Basic, Env, Dom, x, Runtime) {
var type = 'flash', extensions = {};
/**
Get the version of the Flash Player
@method getShimVersion
@private
@return {Number} Flash Player version
*/
function getShimVersion() {
var version;
try {
version = navigator.plugins['Shockwave Flash'];
version = version.description;
} catch (e1) {
try {
version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
} catch (e2) {
version = '0.0';
}
}
version = version.match(/\d+/g);
return parseFloat(version[0] + '.' + version[1]);
}
/**
Constructor for the Flash Runtime
@class FlashRuntime
@extends Runtime
*/
function FlashRuntime(options) {
var I = this, initTimer;
options = Basic.extend({ swf_url: Env.swf_url }, options);
Runtime.call(this, options, type, {
access_binary: function(value) {
return value && I.mode === 'browser';
},
access_image_binary: function(value) {
return value && I.mode === 'browser';
},
display_media: Runtime.capTrue,
do_cors: Runtime.capTrue,
drag_and_drop: false,
report_upload_progress: function() {
return I.mode === 'client';
},
resize_image: Runtime.capTrue,
return_response_headers: false,
return_response_type: function(responseType) {
if (responseType === 'json' && !!window.JSON) {
return true;
}
return !Basic.arrayDiff(responseType, ['', 'text', 'document']) || I.mode === 'browser';
},
return_status_code: function(code) {
return I.mode === 'browser' || !Basic.arrayDiff(code, [200, 404]);
},
select_file: Runtime.capTrue,
select_multiple: Runtime.capTrue,
send_binary_string: function(value) {
return value && I.mode === 'browser';
},
send_browser_cookies: function(value) {
return value && I.mode === 'browser';
},
send_custom_headers: function(value) {
return value && I.mode === 'browser';
},
send_multipart: Runtime.capTrue,
slice_blob: function(value) {
return value && I.mode === 'browser';
},
stream_upload: function(value) {
return value && I.mode === 'browser';
},
summon_file_dialog: false,
upload_filesize: function(size) {
return Basic.parseSizeStr(size) <= 2097152 || I.mode === 'client';
},
use_http_method: function(methods) {
return !Basic.arrayDiff(methods, ['GET', 'POST']);
}
}, {
// capabilities that require specific mode
access_binary: function(value) {
return value ? 'browser' : 'client';
},
access_image_binary: function(value) {
return value ? 'browser' : 'client';
},
report_upload_progress: function(value) {
return value ? 'browser' : 'client';
},
return_response_type: function(responseType) {
return Basic.arrayDiff(responseType, ['', 'text', 'json', 'document']) ? 'browser' : ['client', 'browser'];
},
return_status_code: function(code) {
return Basic.arrayDiff(code, [200, 404]) ? 'browser' : ['client', 'browser'];
},
send_binary_string: function(value) {
return value ? 'browser' : 'client';
},
send_browser_cookies: function(value) {
return value ? 'browser' : 'client';
},
send_custom_headers: function(value) {
return value ? 'browser' : 'client';
},
stream_upload: function(value) {
return value ? 'client' : 'browser';
},
upload_filesize: function(size) {
return Basic.parseSizeStr(size) >= 2097152 ? 'client' : 'browser';
}
}, 'client');
// minimal requirement for Flash Player version
if (getShimVersion() < 10) {
this.mode = false; // with falsy mode, runtime won't operable, no matter what the mode was before
}
Basic.extend(this, {
getShim: function() {
return Dom.get(this.uid);
},
shimExec: function(component, action) {
var args = [].slice.call(arguments, 2);
return I.getShim().exec(this.uid, component, action, args);
},
init: function() {
var html, el, container;
container = this.getShimContainer();
// if not the minimal height, shims are not initialized in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc)
Basic.extend(container.style, {
position: 'absolute',
top: '-8px',
left: '-8px',
width: '9px',
height: '9px',
overflow: 'hidden'
});
// insert flash object
html = '<object id="' + this.uid + '" type="application/x-shockwave-flash" data="' + options.swf_url + '" ';
if (Env.browser === 'IE') {
html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
}
html += 'width="100%" height="100%" style="outline:0">' +
'<param name="movie" value="' + options.swf_url + '" />' +
'<param name="flashvars" value="uid=' + escape(this.uid) + '&target=' + Env.global_event_dispatcher + '" />' +
'<param name="wmode" value="transparent" />' +
'<param name="allowscriptaccess" value="always" />' +
'</object>';
if (Env.browser === 'IE') {
el = document.createElement('div');
container.appendChild(el);
el.outerHTML = html;
el = container = null; // just in case
} else {
container.innerHTML = html;
}
// Init is dispatched by the shim
initTimer = setTimeout(function() {
if (I && !I.initialized) { // runtime might be already destroyed by this moment
I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
}
}, 5000);
},
destroy: (function(destroy) { // extend default destroy method
return function() {
destroy.call(I);
clearTimeout(initTimer); // initialization check might be still onwait
options = initTimer = destroy = I = null;
};
}(this.destroy))
}, extensions);
}
Runtime.addConstructor(type, FlashRuntime);
return extensions;
});
// Included from: src/javascript/runtime/flash/file/Blob.js
/**
* Blob.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/flash/file/Blob
@private
*/
define("moxie/runtime/flash/file/Blob", [
"moxie/runtime/flash/Runtime",
"moxie/file/Blob"
], function(extensions, Blob) {
var FlashBlob = {
slice: function(blob, start, end, type) {
var self = this.getRuntime();
if (start < 0) {
start = Math.max(blob.size + start, 0);
} else if (start > 0) {
start = Math.min(start, blob.size);
}
if (end < 0) {
end = Math.max(blob.size + end, 0);
} else if (end > 0) {
end = Math.min(end, blob.size);
}
blob = self.shimExec.call(this, 'Blob', 'slice', start, end, type || '');
if (blob) {
blob = new Blob(self.uid, blob);
}
return blob;
}
};
return (extensions.Blob = FlashBlob);
});
// Included from: src/javascript/runtime/flash/file/FileInput.js
/**
* FileInput.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/flash/file/FileInput
@private
*/
define("moxie/runtime/flash/file/FileInput", [
"moxie/runtime/flash/Runtime"
], function(extensions) {
var FileInput = {
init: function(options) {
this.getRuntime().shimExec.call(this, 'FileInput', 'init', {
name: options.name,
accept: options.accept,
multiple: options.multiple
});
this.trigger('ready');
}
};
return (extensions.FileInput = FileInput);
});
// Included from: src/javascript/runtime/flash/file/FileReader.js
/**
* FileReader.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/flash/file/FileReader
@private
*/
define("moxie/runtime/flash/file/FileReader", [
"moxie/runtime/flash/Runtime",
"moxie/core/utils/Encode"
], function(extensions, Encode) {
var _result = '';
function _formatData(data, op) {
switch (op) {
case 'readAsText':
return Encode.atob(data, 'utf8');
case 'readAsBinaryString':
return Encode.atob(data);
case 'readAsDataURL':
return data;
}
return null;
}
var FileReader = {
read: function(op, blob) {
var target = this, self = target.getRuntime();
// special prefix for DataURL read mode
if (op === 'readAsDataURL') {
_result = 'data:' + (blob.type || '') + ';base64,';
}
target.bind('Progress', function(e, data) {
if (data) {
_result += _formatData(data, op);
}
});
return self.shimExec.call(this, 'FileReader', 'readAsBase64', blob.uid);
},
getResult: function() {
return _result;
},
destroy: function() {
_result = null;
}
};
return (extensions.FileReader = FileReader);
});
// Included from: src/javascript/runtime/flash/file/FileReaderSync.js
/**
* FileReaderSync.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/flash/file/FileReaderSync
@private
*/
define("moxie/runtime/flash/file/FileReaderSync", [
"moxie/runtime/flash/Runtime",
"moxie/core/utils/Encode"
], function(extensions, Encode) {
function _formatData(data, op) {
switch (op) {
case 'readAsText':
return Encode.atob(data, 'utf8');
case 'readAsBinaryString':
return Encode.atob(data);
case 'readAsDataURL':
return data;
}
return null;
}
var FileReaderSync = {
read: function(op, blob) {
var result, self = this.getRuntime();
result = self.shimExec.call(this, 'FileReaderSync', 'readAsBase64', blob.uid);
if (!result) {
return null; // or throw ex
}
// special prefix for DataURL read mode
if (op === 'readAsDataURL') {
result = 'data:' + (blob.type || '') + ';base64,' + result;
}
return _formatData(result, op, blob.type);
}
};
return (extensions.FileReaderSync = FileReaderSync);
});
// Included from: src/javascript/runtime/flash/xhr/XMLHttpRequest.js
/**
* XMLHttpRequest.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/flash/xhr/XMLHttpRequest
@private
*/
define("moxie/runtime/flash/xhr/XMLHttpRequest", [
"moxie/runtime/flash/Runtime",
"moxie/core/utils/Basic",
"moxie/file/Blob",
"moxie/file/File",
"moxie/file/FileReaderSync",
"moxie/xhr/FormData",
"moxie/runtime/Transporter"
], function(extensions, Basic, Blob, File, FileReaderSync, FormData, Transporter) {
var XMLHttpRequest = {
send: function(meta, data) {
var target = this, self = target.getRuntime();
function send() {
meta.transport = self.mode;
self.shimExec.call(target, 'XMLHttpRequest', 'send', meta, data);
}
function appendBlob(name, blob) {
self.shimExec.call(target, 'XMLHttpRequest', 'appendBlob', name, blob.uid);
data = null;
send();
}
function attachBlob(blob, cb) {
var tr = new Transporter();
tr.bind("TransportingComplete", function() {
cb(this.result);
});
tr.transport(blob.getSource(), blob.type, {
ruid: self.uid
});
}
// copy over the headers if any
if (!Basic.isEmptyObj(meta.headers)) {
Basic.each(meta.headers, function(value, header) {
self.shimExec.call(target, 'XMLHttpRequest', 'setRequestHeader', header, value.toString()); // Silverlight doesn't accept integers into the arguments of type object
});
}
// transfer over multipart params and blob itself
if (data instanceof FormData) {
var blobField;
data.each(function(value, name) {
if (value instanceof Blob) {
blobField = name;
} else {
self.shimExec.call(target, 'XMLHttpRequest', 'append', name, value);
}
});
if (!data.hasBlob()) {
data = null;
send();
} else {
var blob = data.getBlob();
if (blob.isDetached()) {
attachBlob(blob, function(attachedBlob) {
blob.destroy();
appendBlob(blobField, attachedBlob);
});
} else {
appendBlob(blobField, blob);
}
}
} else if (data instanceof Blob) {
if (data.isDetached()) {
attachBlob(data, function(attachedBlob) {
data.destroy();
data = attachedBlob.uid;
send();
});
} else {
data = data.uid;
send();
}
} else {
send();
}
},
getResponse: function(responseType) {
var frs, blob, self = this.getRuntime();
blob = self.shimExec.call(this, 'XMLHttpRequest', 'getResponseAsBlob');
if (blob) {
blob = new File(self.uid, blob);
if ('blob' === responseType) {
return blob;
}
try {
frs = new FileReaderSync();
if (!!~Basic.inArray(responseType, ["", "text"])) {
return frs.readAsText(blob);
} else if ('json' === responseType && !!window.JSON) {
return JSON.parse(frs.readAsText(blob));
}
} finally {
blob.destroy();
}
}
return null;
},
abort: function(upload_complete_flag) {
var self = this.getRuntime();
self.shimExec.call(this, 'XMLHttpRequest', 'abort');
this.dispatchEvent('readystatechange');
// this.dispatchEvent('progress');
this.dispatchEvent('abort');
//if (!upload_complete_flag) {
// this.dispatchEvent('uploadprogress');
//}
}
};
return (extensions.XMLHttpRequest = XMLHttpRequest);
});
// Included from: src/javascript/runtime/flash/runtime/Transporter.js
/**
* Transporter.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/flash/runtime/Transporter
@private
*/
define("moxie/runtime/flash/runtime/Transporter", [
"moxie/runtime/flash/Runtime",
"moxie/file/Blob"
], function(extensions, Blob) {
var Transporter = {
getAsBlob: function(type) {
var self = this.getRuntime()
, blob = self.shimExec.call(this, 'Transporter', 'getAsBlob', type)
;
if (blob) {
return new Blob(self.uid, blob);
}
return null;
}
};
return (extensions.Transporter = Transporter);
});
// Included from: src/javascript/runtime/silverlight/Runtime.js
/**
* RunTime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/*global ActiveXObject:true */
/**
Defines constructor for Silverlight runtime.
@class moxie/runtime/silverlight/Runtime
@private
*/
define("moxie/runtime/silverlight/Runtime", [
"moxie/core/utils/Basic",
"moxie/core/utils/Env",
"moxie/core/utils/Dom",
"moxie/core/Exceptions",
"moxie/runtime/Runtime"
], function(Basic, Env, Dom, x, Runtime) {
var type = "silverlight", extensions = {};
function isInstalled(version) {
var isVersionSupported = false, control = null, actualVer,
actualVerArray, reqVerArray, requiredVersionPart, actualVersionPart, index = 0;
try {
try {
control = new ActiveXObject('AgControl.AgControl');
if (control.IsVersionSupported(version)) {
isVersionSupported = true;
}
control = null;
} catch (e) {
var plugin = navigator.plugins["Silverlight Plug-In"];
if (plugin) {
actualVer = plugin.description;
if (actualVer === "1.0.30226.2") {
actualVer = "2.0.30226.2";
}
actualVerArray = actualVer.split(".");
while (actualVerArray.length > 3) {
actualVerArray.pop();
}
while ( actualVerArray.length < 4) {
actualVerArray.push(0);
}
reqVerArray = version.split(".");
while (reqVerArray.length > 4) {
reqVerArray.pop();
}
do {
requiredVersionPart = parseInt(reqVerArray[index], 10);
actualVersionPart = parseInt(actualVerArray[index], 10);
index++;
} while (index < reqVerArray.length && requiredVersionPart === actualVersionPart);
if (requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart)) {
isVersionSupported = true;
}
}
}
} catch (e2) {
isVersionSupported = false;
}
return isVersionSupported;
}
/**
Constructor for the Silverlight Runtime
@class SilverlightRuntime
@extends Runtime
*/
function SilverlightRuntime(options) {
var I = this, initTimer;
options = Basic.extend({ xap_url: Env.xap_url }, options);
Runtime.call(this, options, type, {
access_binary: Runtime.capTrue,
access_image_binary: Runtime.capTrue,
display_media: Runtime.capTrue,
do_cors: Runtime.capTrue,
drag_and_drop: false,
report_upload_progress: Runtime.capTrue,
resize_image: Runtime.capTrue,
return_response_headers: function(value) {
return value && I.mode === 'client';
},
return_response_type: function(responseType) {
if (responseType !== 'json') {
return true;
} else {
return !!window.JSON;
}
},
return_status_code: function(code) {
return I.mode === 'client' || !Basic.arrayDiff(code, [200, 404]);
},
select_file: Runtime.capTrue,
select_multiple: Runtime.capTrue,
send_binary_string: Runtime.capTrue,
send_browser_cookies: function(value) {
return value && I.mode === 'browser';
},
send_custom_headers: function(value) {
return value && I.mode === 'client';
},
send_multipart: Runtime.capTrue,
slice_blob: Runtime.capTrue,
stream_upload: true,
summon_file_dialog: false,
upload_filesize: Runtime.capTrue,
use_http_method: function(methods) {
return I.mode === 'client' || !Basic.arrayDiff(methods, ['GET', 'POST']);
}
}, {
// capabilities that require specific mode
return_response_headers: function(value) {
return value ? 'client' : 'browser';
},
return_status_code: function(code) {
return Basic.arrayDiff(code, [200, 404]) ? 'client' : ['client', 'browser'];
},
send_browser_cookies: function(value) {
return value ? 'browser' : 'client';
},
send_custom_headers: function(value) {
return value ? 'client' : 'browser';
},
use_http_method: function(methods) {
return Basic.arrayDiff(methods, ['GET', 'POST']) ? 'client' : ['client', 'browser'];
}
});
// minimal requirement
if (!isInstalled('2.0.31005.0') || Env.browser === 'Opera') {
this.mode = false;
}
Basic.extend(this, {
getShim: function() {
return Dom.get(this.uid).content.Moxie;
},
shimExec: function(component, action) {
var args = [].slice.call(arguments, 2);
return I.getShim().exec(this.uid, component, action, args);
},
init : function() {
var container;
container = this.getShimContainer();
container.innerHTML = '<object id="' + this.uid + '" data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%" style="outline:none;">' +
'<param name="source" value="' + options.xap_url + '"/>' +
'<param name="background" value="Transparent"/>' +
'<param name="windowless" value="true"/>' +
'<param name="enablehtmlaccess" value="true"/>' +
'<param name="initParams" value="uid=' + this.uid + ',target=' + Env.global_event_dispatcher + '"/>' +
'</object>';
// Init is dispatched by the shim
initTimer = setTimeout(function() {
if (I && !I.initialized) { // runtime might be already destroyed by this moment
I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
}
}, Env.OS !== 'Windows'? 10000 : 5000); // give it more time to initialize in non Windows OS (like Mac)
},
destroy: (function(destroy) { // extend default destroy method
return function() {
destroy.call(I);
clearTimeout(initTimer); // initialization check might be still onwait
options = initTimer = destroy = I = null;
};
}(this.destroy))
}, extensions);
}
Runtime.addConstructor(type, SilverlightRuntime);
return extensions;
});
// Included from: src/javascript/runtime/silverlight/file/Blob.js
/**
* Blob.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/silverlight/file/Blob
@private
*/
define("moxie/runtime/silverlight/file/Blob", [
"moxie/runtime/silverlight/Runtime",
"moxie/core/utils/Basic",
"moxie/runtime/flash/file/Blob"
], function(extensions, Basic, Blob) {
return (extensions.Blob = Basic.extend({}, Blob));
});
// Included from: src/javascript/runtime/silverlight/file/FileInput.js
/**
* FileInput.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/silverlight/file/FileInput
@private
*/
define("moxie/runtime/silverlight/file/FileInput", [
"moxie/runtime/silverlight/Runtime"
], function(extensions) {
var FileInput = {
init: function(options) {
function toFilters(accept) {
var filter = '';
for (var i = 0; i < accept.length; i++) {
filter += (filter !== '' ? '|' : '') + accept[i].title + " | *." + accept[i].extensions.replace(/,/g, ';*.');
}
return filter;
}
this.getRuntime().shimExec.call(this, 'FileInput', 'init', toFilters(options.accept), options.name, options.multiple);
this.trigger('ready');
}
};
return (extensions.FileInput = FileInput);
});
// Included from: src/javascript/runtime/silverlight/file/FileReader.js
/**
* FileReader.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/silverlight/file/FileReader
@private
*/
define("moxie/runtime/silverlight/file/FileReader", [
"moxie/runtime/silverlight/Runtime",
"moxie/core/utils/Basic",
"moxie/runtime/flash/file/FileReader"
], function(extensions, Basic, FileReader) {
return (extensions.FileReader = Basic.extend({}, FileReader));
});
// Included from: src/javascript/runtime/silverlight/file/FileReaderSync.js
/**
* FileReaderSync.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/silverlight/file/FileReaderSync
@private
*/
define("moxie/runtime/silverlight/file/FileReaderSync", [
"moxie/runtime/silverlight/Runtime",
"moxie/core/utils/Basic",
"moxie/runtime/flash/file/FileReaderSync"
], function(extensions, Basic, FileReaderSync) {
return (extensions.FileReaderSync = Basic.extend({}, FileReaderSync));
});
// Included from: src/javascript/runtime/silverlight/xhr/XMLHttpRequest.js
/**
* XMLHttpRequest.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/silverlight/xhr/XMLHttpRequest
@private
*/
define("moxie/runtime/silverlight/xhr/XMLHttpRequest", [
"moxie/runtime/silverlight/Runtime",
"moxie/core/utils/Basic",
"moxie/runtime/flash/xhr/XMLHttpRequest"
], function(extensions, Basic, XMLHttpRequest) {
return (extensions.XMLHttpRequest = Basic.extend({}, XMLHttpRequest));
});
// Included from: src/javascript/runtime/silverlight/runtime/Transporter.js
/**
* Transporter.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/silverlight/runtime/Transporter
@private
*/
define("moxie/runtime/silverlight/runtime/Transporter", [
"moxie/runtime/silverlight/Runtime",
"moxie/core/utils/Basic",
"moxie/runtime/flash/runtime/Transporter"
], function(extensions, Basic, Transporter) {
return (extensions.Transporter = Basic.extend({}, Transporter));
});
// Included from: src/javascript/runtime/html4/Runtime.js
/**
* Runtime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/*global File:true */
/**
Defines constructor for HTML4 runtime.
@class moxie/runtime/html4/Runtime
@private
*/
define("moxie/runtime/html4/Runtime", [
"moxie/core/utils/Basic",
"moxie/core/Exceptions",
"moxie/runtime/Runtime",
"moxie/core/utils/Env"
], function(Basic, x, Runtime, Env) {
var type = 'html4', extensions = {};
function Html4Runtime(options) {
var I = this
, Test = Runtime.capTest
, True = Runtime.capTrue
;
Runtime.call(this, options, type, {
access_binary: Test(window.FileReader || window.File && File.getAsDataURL),
access_image_binary: false,
display_media: Test(extensions.Image && (Env.can('create_canvas') || Env.can('use_data_uri_over32kb'))),
do_cors: false,
drag_and_drop: false,
filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest
return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10);
}()),
resize_image: function() {
return extensions.Image && I.can('access_binary') && Env.can('create_canvas');
},
report_upload_progress: false,
return_response_headers: false,
return_response_type: function(responseType) {
if (responseType === 'json' && !!window.JSON) {
return true;
}
return !!~Basic.inArray(responseType, ['text', 'document', '']);
},
return_status_code: function(code) {
return !Basic.arrayDiff(code, [200, 404]);
},
select_file: function() {
return Env.can('use_fileinput');
},
select_multiple: false,
send_binary_string: false,
send_custom_headers: false,
send_multipart: true,
slice_blob: false,
stream_upload: function() {
return I.can('select_file');
},
summon_file_dialog: Test(function() { // yeah... some dirty sniffing here...
return (Env.browser === 'Firefox' && Env.version >= 4) ||
(Env.browser === 'Opera' && Env.version >= 12) ||
!!~Basic.inArray(Env.browser, ['Chrome', 'Safari']);
}()),
upload_filesize: True,
use_http_method: function(methods) {
return !Basic.arrayDiff(methods, ['GET', 'POST']);
}
});
Basic.extend(this, {
init : function() {
this.trigger("Init");
},
destroy: (function(destroy) { // extend default destroy method
return function() {
destroy.call(I);
destroy = I = null;
};
}(this.destroy))
});
Basic.extend(this.getShim(), extensions);
}
Runtime.addConstructor(type, Html4Runtime);
return extensions;
});
// Included from: src/javascript/runtime/html4/file/FileInput.js
/**
* FileInput.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html4/file/FileInput
@private
*/
define("moxie/runtime/html4/file/FileInput", [
"moxie/runtime/html4/Runtime",
"moxie/core/utils/Basic",
"moxie/core/utils/Dom",
"moxie/core/utils/Events",
"moxie/core/utils/Mime",
"moxie/core/utils/Env"
], function(extensions, Basic, Dom, Events, Mime, Env) {
function FileInput() {
var _uid, _files = [], _mimes = [], _options;
function addInput() {
var comp = this, I = comp.getRuntime(), shimContainer, browseButton, currForm, form, input, uid;
uid = Basic.guid('uid_');
shimContainer = I.getShimContainer(); // we get new ref everytime to avoid memory leaks in IE
if (_uid) { // move previous form out of the view
currForm = Dom.get(_uid + '_form');
if (currForm) {
Basic.extend(currForm.style, { top: '100%' });
}
}
// build form in DOM, since innerHTML version not able to submit file for some reason
form = document.createElement('form');
form.setAttribute('id', uid + '_form');
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('encoding', 'multipart/form-data');
Basic.extend(form.style, {
overflow: 'hidden',
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%'
});
input = document.createElement('input');
input.setAttribute('id', uid);
input.setAttribute('type', 'file');
input.setAttribute('name', _options.name || 'Filedata');
input.setAttribute('accept', _mimes.join(','));
Basic.extend(input.style, {
fontSize: '999px',
opacity: 0
});
form.appendChild(input);
shimContainer.appendChild(form);
// prepare file input to be placed underneath the browse_button element
Basic.extend(input.style, {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%'
});
if (Env.browser === 'IE' && Env.version < 10) {
Basic.extend(input.style, {
filter : "progid:DXImageTransform.Microsoft.Alpha(opacity=0)"
});
}
input.onchange = function() { // there should be only one handler for this
var file;
if (!this.value) {
return;
}
if (this.files) {
file = this.files[0];
} else {
file = {
name: this.value
};
}
_files = [file];
this.onchange = function() {}; // clear event handler
addInput.call(comp);
// after file is initialized as o.File, we need to update form and input ids
comp.bind('change', function onChange() {
var input = Dom.get(uid), form = Dom.get(uid + '_form'), file;
comp.unbind('change', onChange);
if (comp.files.length && input && form) {
file = comp.files[0];
input.setAttribute('id', file.uid);
form.setAttribute('id', file.uid + '_form');
// set upload target
form.setAttribute('target', file.uid + '_iframe');
}
input = form = null;
}, 998);
input = form = null;
comp.trigger('change');
};
// route click event to the input
if (I.can('summon_file_dialog')) {
browseButton = Dom.get(_options.browse_button);
Events.removeEvent(browseButton, 'click', comp.uid);
Events.addEvent(browseButton, 'click', function(e) {
if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file]
input.click();
}
e.preventDefault();
}, comp.uid);
}
_uid = uid;
shimContainer = currForm = browseButton = null;
}
Basic.extend(this, {
init: function(options) {
var comp = this, I = comp.getRuntime(), shimContainer;
// figure out accept string
_options = options;
_mimes = options.accept.mimes || Mime.extList2mimes(options.accept, I.can('filter_by_extension'));
shimContainer = I.getShimContainer();
(function() {
var browseButton, zIndex, top;
browseButton = Dom.get(options.browse_button);
// Route click event to the input[type=file] element for browsers that support such behavior
if (I.can('summon_file_dialog')) {
if (Dom.getStyle(browseButton, 'position') === 'static') {
browseButton.style.position = 'relative';
}
zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 1;
browseButton.style.zIndex = zIndex;
shimContainer.style.zIndex = zIndex - 1;
}
/* Since we have to place input[type=file] on top of the browse_button for some browsers,
browse_button loses interactivity, so we restore it here */
top = I.can('summon_file_dialog') ? browseButton : shimContainer;
Events.addEvent(top, 'mouseover', function() {
comp.trigger('mouseenter');
}, comp.uid);
Events.addEvent(top, 'mouseout', function() {
comp.trigger('mouseleave');
}, comp.uid);
Events.addEvent(top, 'mousedown', function() {
comp.trigger('mousedown');
}, comp.uid);
Events.addEvent(Dom.get(options.container), 'mouseup', function() {
comp.trigger('mouseup');
}, comp.uid);
browseButton = null;
}());
addInput.call(this);
shimContainer = null;
// trigger ready event asynchronously
comp.trigger({
type: 'ready',
async: true
});
},
getFiles: function() {
return _files;
},
disable: function(state) {
var input;
if ((input = Dom.get(_uid))) {
input.disabled = !!state;
}
},
destroy: function() {
var I = this.getRuntime()
, shim = I.getShim()
, shimContainer = I.getShimContainer()
;
Events.removeAllEvents(shimContainer, this.uid);
Events.removeAllEvents(_options && Dom.get(_options.container), this.uid);
Events.removeAllEvents(_options && Dom.get(_options.browse_button), this.uid);
if (shimContainer) {
shimContainer.innerHTML = '';
}
shim.removeInstance(this.uid);
_uid = _files = _mimes = _options = shimContainer = shim = null;
}
});
}
return (extensions.FileInput = FileInput);
});
// Included from: src/javascript/runtime/html4/file/FileReader.js
/**
* FileReader.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html4/file/FileReader
@private
*/
define("moxie/runtime/html4/file/FileReader", [
"moxie/runtime/html4/Runtime",
"moxie/runtime/html5/file/FileReader"
], function(extensions, FileReader) {
return (extensions.FileReader = FileReader);
});
// Included from: src/javascript/runtime/html4/xhr/XMLHttpRequest.js
/**
* XMLHttpRequest.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html4/xhr/XMLHttpRequest
@private
*/
define("moxie/runtime/html4/xhr/XMLHttpRequest", [
"moxie/runtime/html4/Runtime",
"moxie/core/utils/Basic",
"moxie/core/utils/Dom",
"moxie/core/utils/Url",
"moxie/core/Exceptions",
"moxie/core/utils/Events",
"moxie/file/Blob",
"moxie/xhr/FormData"
], function(extensions, Basic, Dom, Url, x, Events, Blob, FormData) {
function XMLHttpRequest() {
var _status, _response, _iframe;
function cleanup(cb) {
var target = this, uid, form, inputs, i, hasFile = false;
if (!_iframe) {
return;
}
uid = _iframe.id.replace(/_iframe$/, '');
form = Dom.get(uid + '_form');
if (form) {
inputs = form.getElementsByTagName('input');
i = inputs.length;
while (i--) {
switch (inputs[i].getAttribute('type')) {
case 'hidden':
inputs[i].parentNode.removeChild(inputs[i]);
break;
case 'file':
hasFile = true; // flag the case for later
break;
}
}
inputs = [];
if (!hasFile) { // we need to keep the form for sake of possible retries
form.parentNode.removeChild(form);
}
form = null;
}
// without timeout, request is marked as canceled (in console)
setTimeout(function() {
Events.removeEvent(_iframe, 'load', target.uid);
if (_iframe.parentNode) { // #382
_iframe.parentNode.removeChild(_iframe);
}
// check if shim container has any other children, if - not, remove it as well
var shimContainer = target.getRuntime().getShimContainer();
if (!shimContainer.children.length) {
shimContainer.parentNode.removeChild(shimContainer);
}
shimContainer = _iframe = null;
cb();
}, 1);
}
Basic.extend(this, {
send: function(meta, data) {
var target = this, I = target.getRuntime(), uid, form, input, blob;
_status = _response = null;
function createIframe() {
var container = I.getShimContainer() || document.body
, temp = document.createElement('div')
;
// IE 6 won't be able to set the name using setAttribute or iframe.name
temp.innerHTML = '<iframe id="' + uid + '_iframe" name="' + uid + '_iframe" src="javascript:""" style="display:none"></iframe>';
_iframe = temp.firstChild;
container.appendChild(_iframe);
/* _iframe.onreadystatechange = function() {
console.info(_iframe.readyState);
};*/
Events.addEvent(_iframe, 'load', function() { // _iframe.onload doesn't work in IE lte 8
var el;
try {
el = _iframe.contentWindow.document || _iframe.contentDocument || window.frames[_iframe.id].document;
// try to detect some standard error pages
if (/^4(0[0-9]|1[0-7]|2[2346])\s/.test(el.title)) { // test if title starts with 4xx HTTP error
_status = el.title.replace(/^(\d+).*$/, '$1');
} else {
_status = 200;
// get result
_response = Basic.trim(el.body.innerHTML);
// we need to fire these at least once
target.trigger({
type: 'progress',
loaded: _response.length,
total: _response.length
});
if (blob) { // if we were uploading a file
target.trigger({
type: 'uploadprogress',
loaded: blob.size || 1025,
total: blob.size || 1025
});
}
}
} catch (ex) {
if (Url.hasSameOrigin(meta.url)) {
// if response is sent with error code, iframe in IE gets redirected to res://ieframe.dll/http_x.htm
// which obviously results to cross domain error (wtf?)
_status = 404;
} else {
cleanup.call(target, function() {
target.trigger('error');
});
return;
}
}
cleanup.call(target, function() {
target.trigger('load');
});
}, target.uid);
} // end createIframe
// prepare data to be sent and convert if required
if (data instanceof FormData && data.hasBlob()) {
blob = data.getBlob();
uid = blob.uid;
input = Dom.get(uid);
form = Dom.get(uid + '_form');
if (!form) {
throw new x.DOMException(x.DOMException.NOT_FOUND_ERR);
}
} else {
uid = Basic.guid('uid_');
form = document.createElement('form');
form.setAttribute('id', uid + '_form');
form.setAttribute('method', meta.method);
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('encoding', 'multipart/form-data');
form.setAttribute('target', uid + '_iframe');
I.getShimContainer().appendChild(form);
}
if (data instanceof FormData) {
data.each(function(value, name) {
if (value instanceof Blob) {
if (input) {
input.setAttribute('name', name);
}
} else {
var hidden = document.createElement('input');
Basic.extend(hidden, {
type : 'hidden',
name : name,
value : value
});
// make sure that input[type="file"], if it's there, comes last
if (input) {
form.insertBefore(hidden, input);
} else {
form.appendChild(hidden);
}
}
});
}
// set destination url
form.setAttribute("action", meta.url);
createIframe();
form.submit();
target.trigger('loadstart');
},
getStatus: function() {
return _status;
},
getResponse: function(responseType) {
if ('json' === responseType) {
// strip off <pre>..</pre> tags that might be enclosing the response
if (Basic.typeOf(_response) === 'string' && !!window.JSON) {
try {
return JSON.parse(_response.replace(/^\s*<pre[^>]*>/, '').replace(/<\/pre>\s*$/, ''));
} catch (ex) {
return null;
}
}
} else if ('document' === responseType) {
}
return _response;
},
abort: function() {
var target = this;
if (_iframe && _iframe.contentWindow) {
if (_iframe.contentWindow.stop) { // FireFox/Safari/Chrome
_iframe.contentWindow.stop();
} else if (_iframe.contentWindow.document.execCommand) { // IE
_iframe.contentWindow.document.execCommand('Stop');
} else {
_iframe.src = "about:blank";
}
}
cleanup.call(this, function() {
// target.dispatchEvent('readystatechange');
target.dispatchEvent('abort');
});
}
});
}
return (extensions.XMLHttpRequest = XMLHttpRequest);
});
expose(["moxie/core/utils/Basic","moxie/core/I18n","moxie/core/utils/Mime","moxie/core/utils/Env","moxie/core/utils/Dom","moxie/core/Exceptions","moxie/core/EventTarget","moxie/core/utils/Encode","moxie/runtime/Runtime","moxie/runtime/RuntimeClient","moxie/file/Blob","moxie/file/File","moxie/file/FileInput","moxie/runtime/RuntimeTarget","moxie/file/FileReader","moxie/core/utils/Url","moxie/file/FileReaderSync","moxie/xhr/FormData","moxie/xhr/XMLHttpRequest","moxie/runtime/Transporter","moxie/core/utils/Events"]);
})(this);/**
* o.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/*global moxie:true */
/**
Globally exposed namespace with the most frequently used public classes and handy methods.
@class o
@static
@private
*/
(function(exports) {
"use strict";
var o = {}, inArray = exports.moxie.core.utils.Basic.inArray;
// directly add some public classes
// (we do it dynamically here, since for custom builds we cannot know beforehand what modules were included)
(function addAlias(ns) {
var name, itemType;
for (name in ns) {
itemType = typeof(ns[name]);
if (itemType === 'object' && !~inArray(name, ['Exceptions', 'Env', 'Mime'])) {
addAlias(ns[name]);
} else if (itemType === 'function') {
o[name] = ns[name];
}
}
})(exports.moxie);
// add some manually
o.Env = exports.moxie.core.utils.Env;
o.Mime = exports.moxie.core.utils.Mime;
o.Exceptions = exports.moxie.core.Exceptions;
// expose globally
exports.mOxie = o;
if (!exports.o) {
exports.o = o;
}
return o;
})(this);
|
test/e2e/basepath/pages/absolute-url-no-basepath.js | JeromeFitz/next.js | import React from 'react'
import Link from 'next/link'
export async function getServerSideProps({ query: { port } }) {
if (!port) {
throw new Error('port required')
}
return { props: { port } }
}
export default function Page({ port }) {
return (
<>
<Link href={`http://localhost:${port}/rewrite-no-basepath`}>
<a id="absolute-link">http://localhost:{port}/rewrite-no-basepath</a>
</Link>
</>
)
}
|
node_modules/material-ui/svg-icons/maps/local-see.js | manojadd/bob-demo | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _pure = require('recompose/pure');
var _pure2 = _interopRequireDefault(_pure);
var _SvgIcon = require('../../SvgIcon');
var _SvgIcon2 = _interopRequireDefault(_SvgIcon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MapsLocalSee = function MapsLocalSee(props) {
return _react2.default.createElement(
_SvgIcon2.default,
props,
_react2.default.createElement('circle', { cx: '12', cy: '12', r: '3.2' }),
_react2.default.createElement('path', { d: 'M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z' })
);
};
MapsLocalSee = (0, _pure2.default)(MapsLocalSee);
MapsLocalSee.displayName = 'MapsLocalSee';
MapsLocalSee.muiName = 'SvgIcon';
exports.default = MapsLocalSee; |
src/js/components/Select.js | kylebyerly-hp/grommet | // (C) Copyright 2014 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { findDOMNode } from 'react-dom';
import classnames from 'classnames';
import CSSClassnames from '../utils/CSSClassnames';
import Props from '../utils/Props';
import KeyboardAccelerators from '../utils/KeyboardAccelerators';
import Drop from '../utils/Drop';
import Button from './Button';
import CheckBox from './CheckBox';
import RadioButton from './RadioButton';
import Search from './Search';
import CaretDownIcon from './icons/base/CaretDown';
import Intl from '../utils/Intl';
import { announce } from '../utils/Announcer';
const CLASS_ROOT = CSSClassnames.SELECT;
const INPUT = CSSClassnames.INPUT;
export default class Select extends Component {
constructor(props, context) {
super(props, context);
this._onAddDrop = this._onAddDrop.bind(this);
this._onRemoveDrop = this._onRemoveDrop.bind(this);
this._onForceClose = this._onForceClose.bind(this);
this._onSearchChange = this._onSearchChange.bind(this);
this._onNextOption = this._onNextOption.bind(this);
this._onPreviousOption = this._onPreviousOption.bind(this);
this._onEnter = this._onEnter.bind(this);
this._stopPropagation = this._stopPropagation.bind(this);
this._onInputKeyDown = this._onInputKeyDown.bind(this);
this._announceOptions = this._announceOptions.bind(this);
this.state = {
announceChange: false,
activeOptionIndex: -1,
dropActive: false,
searchText: '',
value: this._normalizeValue(props, {})
};
}
componentWillReceiveProps (nextProps) {
if (nextProps.hasOwnProperty('value')) {
this.setState({ value: this._normalizeValue(nextProps, this.state) });
}
}
componentDidUpdate (prevProps, prevState) {
const { inline, options } = this.props;
const { announceChange, dropActive } = this.state;
const { intl } = this.context;
// Set up keyboard listeners appropriate to the current state.
let activeKeyboardHandlers = {
up: this._onPreviousOption,
down: this._onNextOption,
enter: this._onEnter,
left: this._stopPropagation,
right: this._stopPropagation
};
if (! inline) {
activeKeyboardHandlers.esc = this._onForceClose;
activeKeyboardHandlers.tab = this._onForceClose;
}
// the order here is important, need to turn off keys before turning on
if (! dropActive && prevState.dropActive) {
document.removeEventListener('click', this._onRemoveDrop);
KeyboardAccelerators.stopListeningToKeyboard(this,
activeKeyboardHandlers);
if (this._drop) {
this._drop.remove();
this._drop = undefined;
}
}
if ((inline && ! prevProps.inline) ||
(dropActive && ! prevState.dropActive)) {
if (! inline) {
document.addEventListener('click', this._onRemoveDrop);
}
KeyboardAccelerators.startListeningToKeyboard(this,
activeKeyboardHandlers);
if (! inline) {
// If this is inside a FormField, place the drop in reference to it.
const control = this.valueRef || this.inputRef;
this._drop = new Drop(control,
this._renderOptions(`${CLASS_ROOT}__drop`), {
align: { top: 'bottom', left: 'left' },
context: this.context,
responsive: false // so suggestion changes don't re-align
});
}
if (this._searchRef) {
this._searchRef.focus();
this._searchRef._inputRef.select();
}
} else if (dropActive && prevState.dropActive) {
this._drop.render(this._renderOptions(`${CLASS_ROOT}__drop`));
}
if (announceChange && options) {
const matchResultsMessage = Intl.getMessage(
intl, 'Match Results', {
count: options.length
}
);
let navigationHelpMessage = '';
if (options.length) {
navigationHelpMessage = `(${Intl.getMessage(intl, 'Navigation Help')})`;
}
announce(`${matchResultsMessage} ${navigationHelpMessage}`);
this.setState({ announceChange: false });
}
}
componentWillUnmount () {
document.removeEventListener('click', this._onRemoveDrop);
if (this._drop) {
this._drop.remove();
}
}
_normalizeValue (props, state) {
const { multiple, value } = props;
let normalizedValue = value;
if (multiple) {
if (value) {
if (! Array.isArray(value)) {
normalizedValue = [value];
}
} else {
normalizedValue = [];
}
}
return normalizedValue;
}
_announceOptions (index) {
const { intl } = this.context;
const labelMessage = this._renderValue(this.props.options[index]);
const enterSelectMessage = Intl.getMessage(intl, 'Enter Select');
announce(`${labelMessage} ${enterSelectMessage}`);
}
_onInputKeyDown (event) {
const up = 38;
const down = 40;
if (event.keyCode === up || event.keyCode === down) {
// stop the input to move the cursor when options are present
event.preventDefault();
}
}
_onSearchChange (event) {
const { inline } = this.props;
this.setState({
announceChange: true,
activeOptionIndex: -1,
dropActive: ! inline,
searchText: event.target.value
});
if (this.props.onSearch) {
this.props.onSearch(event);
}
}
_onAddDrop (event) {
const { options, value } = this.props;
event.preventDefault();
// Get values of options, so we can highlight selected option
if (options) {
const optionValues = options.map((option) => {
if (option && typeof option === 'object') {
return option.value;
} else {
return option;
}
});
const activeOptionIndex = optionValues.indexOf(value);
this.setState({
dropActive: true,
activeOptionIndex: activeOptionIndex
});
}
}
_onRemoveDrop (event) {
if (!this._searchRef ||
!findDOMNode(this._searchRef).contains(event.target)) {
this.setState({dropActive: false});
}
}
_onForceClose () {
this.setState({dropActive: false});
}
_onNextOption (event) {
event.preventDefault();
let index = this.state.activeOptionIndex;
index = Math.min(index + 1, this.props.options.length - 1);
this.setState({activeOptionIndex: index},
this._announceOptions.bind(this, index));
}
_onPreviousOption (event) {
event.preventDefault();
let index = this.state.activeOptionIndex;
index = Math.max(index - 1, 0);
this.setState({activeOptionIndex: index},
this._announceOptions.bind(this, index));
}
_valueForSelectedOption (option) {
const { multiple } = this.props;
const { value } = this.state;
let nextValue;
if (multiple) {
nextValue = value.slice(0);
let index;
for (index = 0; index < nextValue.length; index += 1) {
if (this._valueEqualsOption(nextValue[index], option)) {
break;
}
}
if (index < nextValue.length) {
// already existing, remove
nextValue.splice(index, 1);
} else {
// not there, add
nextValue.push(option);
}
} else {
nextValue = option;
}
return nextValue;
}
_onEnter (event) {
const { onChange, options } = this.props;
const { activeOptionIndex } = this.state;
const { intl } = this.context;
if (activeOptionIndex >= 0) {
event.preventDefault(); // prevent submitting forms
const option = options[activeOptionIndex];
const value = this._valueForSelectedOption(option);
this.setState({ dropActive: false, value }, () => {
const optionMessage = this._renderLabel(option);
const selectedMessage = Intl.getMessage(intl, 'Selected');
announce(`${optionMessage} ${selectedMessage}`);
});
if (onChange) {
onChange({ target: this.inputRef, option, value });
}
} else {
this.setState({ dropActive: false });
}
}
_stopPropagation () {
if (findDOMNode(this._searchRef).contains(document.activeElement)) {
return true;
}
}
_onClickOption (option) {
const { onChange } = this.props;
const value = this._valueForSelectedOption(option);
this.setState({ dropActive: false, value });
if (onChange) {
onChange({ target: this.inputRef, option, value });
}
}
_renderLabel (option) {
if (option && typeof option === 'object') {
// revert for announce as label is often a complex object
return option.label || option.value || '';
} else {
return (undefined === option || null === option) ? '' : option;
}
}
_renderValue (option) {
const { intl } = this.context;
if (Array.isArray(option)) {
// Could be an Array when !inline+multiple
if (1 === option.length) {
return this._renderValue(option[0]);
} else if (option.length > 1) {
const selectedMultiple = Intl.getMessage(
intl, 'Selected Multiple', {
count: option.length
}
);
return selectedMultiple;
}
} else if (option && typeof option === 'object') {
return option.label || option.value || '';
} else {
return (undefined === option || null === option) ? '' : option;
}
}
_valueEqualsOption (value, option) {
let result = false;
if (value && typeof value === 'object') {
if (option && typeof option === 'object') {
result = (value.value === option.value);
} else {
result = (value.value === option);
}
} else {
if (option && typeof option === 'object') {
result = (value === option.value);
} else {
result = (value === option);
}
}
return result;
}
_optionSelected (option, value) {
let result = false;
if (value && Array.isArray(value)) {
result = value.some(val => this._valueEqualsOption(val, option));
} else {
result = this._valueEqualsOption(value, option);
}
return result;
}
_renderOptions (className, restProps={}) {
const { intl } = this.context;
const {
id, inline, multiple, options, onSearch, value,
searchPlaceHolder = Intl.getMessage(intl, 'Search')
} = this.props;
const { activeOptionIndex, searchText } = this.state;
let search;
if (onSearch) {
search = (
<Search className={`${CLASS_ROOT}__search`}
ref={(ref) => this._searchRef = ref}
inline={true} fill={true} responsive={false} pad="medium"
placeHolder={searchPlaceHolder} value={searchText}
onDOMChange={this._onSearchChange}
onKeyDown={this._onInputKeyDown} />
);
}
let items;
if (options) {
items = options.map((option, index) => {
const selected = this._optionSelected(option, value);
let content = this._renderLabel(option);
let classes = classnames(
{
[`${CLASS_ROOT}__option`]: true,
[`${CLASS_ROOT}__option--element`]: React.isValidElement(content),
[`${CLASS_ROOT}__option--selected`]: selected,
[`${CLASS_ROOT}__option--active`]:
index === activeOptionIndex
}
);
if (option && option.icon) {
content = (
<span>{option.icon} {content}</span>
);
}
let itemOnClick;
if (inline) {
const itemId = `${option ? (option.value || option) : index}`;
const Type = (multiple ? CheckBox : RadioButton );
content = (
<Type
key={itemId}
id={id ? `${id}-${itemId}` : undefined}
label={content}
checked={selected}
onChange={this._onClickOption.bind(this, option)}
/>
);
} else {
itemOnClick = (e) => {
e.stopPropagation();
this._onClickOption.bind(this, option)();
};
}
return (
<li key={index} className={classes} onClick={itemOnClick}>
{content}
</li>
);
});
}
let onClick;
if (! inline) {
onClick = this._onRemoveDrop;
}
return (
<div {...restProps} className={className}>
{search}
<ol className={`${CLASS_ROOT}__options`} onClick={onClick}>
{items}
</ol>
</div>
);
}
render () {
const { className, inline, placeHolder, value } = this.props;
const { active } = this.state;
const { intl } = this.context;
let classes = classnames(
CLASS_ROOT,
{
[`${CLASS_ROOT}--active`]: active,
[`${CLASS_ROOT}--inline`]: inline
},
className
);
const restProps = Props.omit(this.props, Object.keys(Select.propTypes));
if (inline) {
return this._renderOptions(classes, restProps);
} else {
const renderedValue = this._renderValue(value);
const shouldRenderElement = React.isValidElement(renderedValue);
return (
<div className={classes} onClick={this._onAddDrop}>
{shouldRenderElement ? (
<div ref={ref => this.valueRef = ref}
className={`${CLASS_ROOT}__value`}>
{renderedValue}
</div>
) : null}
<input {...restProps} ref={ref => this.inputRef = ref}
type={shouldRenderElement ? 'hidden' : 'text'}
className={`${INPUT} ${CLASS_ROOT}__input`}
placeholder={placeHolder} readOnly={true}
value={(!shouldRenderElement && renderedValue) || ''} />
<Button className={`${CLASS_ROOT}__control`}
a11yTitle={Intl.getMessage(intl, 'Select Icon')}
icon={<CaretDownIcon />}
onClick={this._onAddDrop} />
</div>
);
}
}
}
const valueType = PropTypes.oneOfType([
PropTypes.shape({
label: PropTypes.node,
value: PropTypes.any
}),
PropTypes.string,
PropTypes.number
]);
Select.propTypes = {
inline: PropTypes.bool,
multiple: PropTypes.bool,
onSearch: PropTypes.func,
onChange: PropTypes.func, // (value(s))
placeHolder: PropTypes.string,
searchPlaceHolder: PropTypes.string,
options: PropTypes.arrayOf(valueType).isRequired,
value: PropTypes.oneOfType([valueType, PropTypes.arrayOf(valueType)])
};
Select.contextTypes = {
intl: PropTypes.object
};
|
ajax/libs/forerunnerdb/1.3.720/fdb-legacy.js | jonobr1/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
CollectionGroup = _dereq_('../lib/CollectionGroup'),
View = _dereq_('../lib/View'),
Highchart = _dereq_('../lib/Highchart'),
Persist = _dereq_('../lib/Persist'),
Document = _dereq_('../lib/Document'),
Overview = _dereq_('../lib/Overview'),
OldView = _dereq_('../lib/OldView'),
OldViewBind = _dereq_('../lib/OldView.Bind'),
Grid = _dereq_('../lib/Grid');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/CollectionGroup":6,"../lib/Core":7,"../lib/Document":9,"../lib/Grid":11,"../lib/Highchart":12,"../lib/OldView":29,"../lib/OldView.Bind":28,"../lib/Overview":32,"../lib/Persist":34,"../lib/View":40}],2:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver;
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
this._keyArr = sharedPathSolver.parse(orderBy, true);
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
sharedPathSolver = new Path();
/**
* Gets / sets the primary key used by the active bucket.
* @returns {String} The current primary key.
*/
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof sharedPathSolver.get(obj, sortType.path);
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.value === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.value === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += sharedPathSolver.get(obj, sortType.path);
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Path":33,"./Shared":39}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param data
* @param options
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visited === undefined) { resultArr._visited = 0; }
resultArr._visited++;
result = this.sortAsc(thisDataPathVal, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":33,"./Shared":39}],4:[function(_dereq_,module,exports){
"use strict";
var crcTable,
checksum;
crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
/**
* Returns a checksum of a string.
* @param {String} str The string to checksum.
* @return {Number} The checksum generated.
*/
checksum = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
module.exports = checksum;
},{}],5:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Overload,
ReactorIO,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name, options) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this.sharedPathSolver = sharedPathSolver;
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
if (this._options.db) {
this.db(this._options.db);
}
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Index2d = _dereq_('./Index2d');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
sharedPathSolver = new Path();
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback.call(this, false, true); }
return true;
}
} else {
if (callback) { callback.call(this, false, true); }
return true;
}
if (callback) { callback.call(this, false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', {
keyName: keyName,
oldData: oldKey
});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = this.serialiser.convert(new Date());
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = new Overload('Collection.prototype.setData', {
'*': function (data) {
return this.$main.call(this, data, {});
},
'*, object': function (data, options) {
return this.$main.call(this, data, options);
},
'*, function': function (data, callback) {
return this.$main.call(this, data, {}, callback);
},
'*, *, function': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
'*, *, *': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
'$main': function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var deferredSetting = this.deferredCalls(),
oldData = [].concat(this._data);
// Switch off deferred calls since setData should be
// a synchronous call
this.deferredCalls(false);
options = this.options(options);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
// Remove all items from the collection
this.remove({});
// Insert the new data
this.insert(data);
// Switch deferred calls back to previous settings
this.deferredCalls(deferredSetting);
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback.call(this); }
return this;
}
});
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a hash string
jString = this.hash(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This should use remove so that chain reactor events are properly
// TODO: handled, but ensure that chunking is switched off
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.emit('immediateChange', {type: 'truncate'});
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback.call(this); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj, callback);
break;
case 'update':
returnData.result = this.update(query, obj, {}, callback);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback.call(this); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when the update is
* complete.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
} else {
// Decouple the update data
update = this.decouple(update);
}
// Handle transform
update = this.transformIn(update);
return this._handleUpdate(query, update, options, callback);
};
Collection.prototype._handleUpdate = function (query, update, options, callback) {
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
if (this.chainWillSend()) {
this.chainSend('update', {
query: query,
update: update,
dataSet: this.decouple(updated)
}, options);
}
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
if (callback) { callback.call(this); }
this.emit('immediateChange', {type: 'update', data: updated});
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.emit('immediateChange', {type: 'remove', data: returnArr});
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback.call(this, resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback.call(this, resultObj); }
this._onChange();
this.emit('immediateChange', {type: 'insert', data: inserted});
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
if (self.chainWillSend()) {
self.chainSend('insert', {
dataSet: self.decouple([doc])
}, {
index: index
});
}
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
hash = this.hash(doc),
pk = this._primaryKey;
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[pk], doc);
this._primaryCrc.uniqueSet(doc[pk], hash);
this._crcLookup.uniqueSet(hash, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
hash = this.hash(doc),
pk = this._primaryKey;
// Remove from primary key index
this._primaryIndex.unSet(doc[pk]);
this._primaryCrc.unSet(doc[pk]);
this._crcLookup.unSet(hash);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options),
coll;
coll = new Collection();
coll.db(this._db);
coll.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
return coll;
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinIndex,
joinSource = {},
joinQuery,
joinPath,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinSourceData,
resultRemove = [],
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
waterfallCollection,
matcher;
if (!(options instanceof Array)) {
options = this.options(options);
}
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Check if the query is an array (multi-operation waterfall query)
if (query instanceof Array) {
waterfallCollection = this;
// Loop the query operations
for (i = 0; i < query.length; i++) {
// Execute each operation and pass the result into the next
// query operation
waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {});
}
return waterfallCollection.find();
}
// Pre-process any data-changing query operators first
if (query.$findSub) {
// Check we have all the parts we need
if (!query.$findSub.$path) {
throw('$findSub missing $path property!');
}
return this.findSub(
query.$findSub.$query,
query.$findSub.$path,
query.$findSub.$subQuery,
query.$findSub.$subOptions
);
}
if (query.$findSubOne) {
// Check we have all the parts we need
if (!query.$findSubOne.$path) {
throw('$findSubOne missing $path property!');
}
return this.findSubOne(
query.$findSubOne.$query,
query.$findSubOne.$path,
query.$findSubOne.$subQuery,
query.$findSubOne.$subOptions
);
}
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
// Check if the query tries to limit by data that would only exist after
// the join operation has been completed
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get references to the join sources
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinSourceData = analysis.joinsOn[joinIndex];
joinSourceKey = joinSourceData.key;
joinSourceType = joinSourceData.type;
joinSourceIdentifier = joinSourceData.id;
joinPath = new Path(analysis.joinQueries[joinSourceKey]);
joinQuery = joinPath.value(query)[0];
joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinSourceKey]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource));
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
this.spliceArrayByIndexList(resultArr, resultRemove);
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformIn(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformOut(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Convert the index object to an array of key val objects
var self = this,
keys = sharedPathSolver.parse(sortObj, true);
if (keys.length) {
// Execute sort
arr.sort(function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < keys.length; i++) {
indexData = keys[i];
if (indexData.value === 1) {
result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (result !== 0) {
return result;
}
}
return result;
});
}
return arr;
};
// Commented as we have a new method that was originally implemented for binary trees.
// This old method actually has problems with nested sort objects
/*Collection.prototype.sortold = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};*/
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
/*Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};*/
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
/*Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};*/
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinSourceIndex,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinMatch,
joinSources = [],
joinSourceReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
pkQueryType,
lookupResult,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
}).length;
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Check suitability of querying key value index
pkQueryType = typeof query[this._primaryKey];
if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
lookupResult = this._primaryIndex.lookup(query, options);
analysis.indexMatch.push({
lookup: lookupResult,
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) {
// Loop the join sources and keep a reference to them
for (joinSourceKey in options.$join[joinSourceIndex]) {
if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
joinMatch = options.$join[joinSourceIndex][joinSourceKey];
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
joinSources.push({
id: joinSourceIdentifier,
type: joinSourceType,
key: joinSourceKey
});
// Check if the join uses an $as operator
if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) {
joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as);
} else {
joinSourceReferences.push(joinSourceKey);
}
}
}
}
// Loop the join source references and determine if the query references
// any of the sources that are used in the join. If there no queries against
// joined sources the find method can use a code path optimised for this.
// Queries against joined sources requires the joined sources to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinSourceReferences.length; index++) {
// Check if the query references any source data that the join will create
queryPath = this._queryReferencesSource(query, joinSourceReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinSources[index].key] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinSources;
analysis.queriesOn = analysis.queriesOn.concat(joinSources);
}
return analysis;
};
/**
* Checks if the passed query references a source object (such
* as a collection) by name.
* @param {Object} query The query object to scan.
* @param {String} sourceName The source name to scan for in the query.
* @param {String=} path The path to scan from.
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesSource = function (query, sourceName, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === sourceName) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesSource(query[i], sourceName, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._findSub(this.find(match), path, subDocQuery, subDocOptions);
};
Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
};
/**
* Finds the first sub-document from the collection's documents that matches
* the subDocQuery parameter.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
if (options.type) {
// Check if the specified type is available
if (Shared.index[options.type]) {
// We found the type, generate it
index = new Shared.index[options.type](keys, options, this);
} else {
throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)');
}
} else {
// Create default index type
index = new IndexHashMap(keys, options, this);
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', {
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data.dataSet);
self.update({}, obj1);
} else {
self.insert(packet.data.dataSet);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data.dataSet);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload('Db.prototype.collection', {
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Index2d":13,"./IndexBinaryTree":14,"./IndexHashMap":15,"./KeyValueStore":16,"./Metrics":17,"./Overload":31,"./Path":33,"./ReactorIO":37,"./Shared":39}],6:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Events');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {String=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Remove old data
this._data.remove(chainPacket.data.oldData);
// Add new data
this._data.insert(chainPacket.data.dataSet);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Add new data
this._data.insert(chainPacket.data.dataSet);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
delete this._listeners;
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
/**
* Creates a new collectionGroup instance or returns an existing
* instance if one already exists with the passed name.
* @func collectionGroup
* @memberOf Db
* @param {String} name The name of the instance.
* @returns {*}
*/
Db.prototype.collectionGroup = function (name) {
var self = this;
if (name) {
// Handle being passed an instance
if (name instanceof CollectionGroup) {
return name;
}
if (this._collectionGroup && this._collectionGroup[name]) {
return this._collectionGroup[name];
}
this._collectionGroup[name] = new CollectionGroup(name).db(this);
self.emit('create', self._collectionGroup[name], 'collectionGroup', name);
return this._collectionGroup[name];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":5,"./Shared":39}],7:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (val) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":8,"./Metrics.js":17,"./Overload":31,"./Shared":39}],8:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Checksum,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Checksum = _dereq_('./Checksum.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.Checksum = Checksum;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Checksum.js":4,"./Collection.js":5,"./Metrics.js":17,"./Overload":31,"./Shared":39}],9:[function(_dereq_,module,exports){
"use strict";
// TODO: Remove the _update* methods because we are already mixing them
// TODO: in now via Mixin.Updating and update autobind to extend the _update*
// TODO: methods like we already do with collection
var Shared,
Collection,
Db;
Shared = _dereq_('./Shared');
/**
* Creates a new Document instance. Documents allow you to create individual
* objects that can have standard ForerunnerDB CRUD operations run against
* them, as well as data-binding if the AutoBind module is included in your
* project.
* @name Document
* @class Document
* @constructor
*/
var FdbDocument = function () {
this.init.apply(this, arguments);
};
FdbDocument.prototype.init = function (name) {
this._name = name;
this._data = {};
};
Shared.addModule('Document', FdbDocument);
Shared.mixin(FdbDocument.prototype, 'Mixin.Common');
Shared.mixin(FdbDocument.prototype, 'Mixin.Events');
Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor');
Shared.mixin(FdbDocument.prototype, 'Mixin.Constants');
Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers');
Shared.mixin(FdbDocument.prototype, 'Mixin.Matching');
Shared.mixin(FdbDocument.prototype, 'Mixin.Updating');
Shared.mixin(FdbDocument.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @func state
* @memberof Document
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'state');
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Document
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'db');
/**
* Gets / sets the document name.
* @func name
* @memberof Document
* @param {String=} val The name to assign
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'name');
/**
* Sets the data for the document.
* @func setData
* @memberof Document
* @param data
* @param options
* @returns {Document}
*/
FdbDocument.prototype.setData = function (data, options) {
var i,
$unset;
if (data) {
options = options || {
$decouple: true
};
if (options && options.$decouple === true) {
data = this.decouple(data);
}
if (this._linked) {
$unset = {};
// Remove keys that don't exist in the new data from the current object
for (i in this._data) {
if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) {
// Check if existing data has key
if (data[i] === undefined) {
// Add property name to those to unset
$unset[i] = 1;
}
}
}
data.$unset = $unset;
// Now update the object with new data
this.updateObject(this._data, data, {});
} else {
// Straight data assignment
this._data = data;
}
this.deferEmit('change', {type: 'setData', data: this.decouple(this._data)});
}
return this;
};
/**
* Gets the document's data returned as a single object.
* @func find
* @memberof Document
* @param {Object} query The query object - currently unused, just
* provide a blank object e.g. {}
* @param {Object=} options An options object.
* @returns {Object} The document's data object.
*/
FdbDocument.prototype.find = function (query, options) {
var result;
if (options && options.$decouple === false) {
result = this._data;
} else {
result = this.decouple(this._data);
}
return result;
};
/**
* Modifies the document. This will update the document with the data held in 'update'.
* @func update
* @memberof Document
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
FdbDocument.prototype.update = function (query, update, options) {
var result = this.updateObject(this._data, update, query, options);
if (result) {
this.deferEmit('change', {type: 'update', data: this.decouple(this._data)});
}
};
/**
* Internal method for document updating.
* @func updateObject
* @memberof Document
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
FdbDocument.prototype.updateObject = Collection.prototype.updateObject;
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @func _isPositionalKey
* @memberof Document
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
FdbDocument.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Updates a property on an object depending on if the collection is
* currently running data-binding or not.
* @func _updateProperty
* @memberof Document
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
FdbDocument.prototype._updateProperty = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, val);
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"');
}
} else {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"');
}
}
};
/**
* Increments a value for a property on a document by the passed number.
* @func _updateIncrement
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
FdbDocument.prototype._updateIncrement = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] + val);
} else {
doc[prop] += val;
}
};
/**
* Changes the index of an item in the passed array.
* @func _updateSpliceMove
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) {
if (this._linked) {
window.jQuery.observable(arr).move(indexFrom, indexTo);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
} else {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
}
};
/**
* Inserts an item into the passed array at the specified index.
* @func _updateSplicePush
* @memberof Document
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updateSplicePush = function (arr, index, doc) {
if (arr.length > index) {
if (this._linked) {
window.jQuery.observable(arr).insert(index, doc);
} else {
arr.splice(index, 0, doc);
}
} else {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
}
};
/**
* Inserts an item at the end of an array.
* @func _updatePush
* @memberof Document
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updatePush = function (arr, doc) {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
};
/**
* Removes an item from the passed array.
* @func _updatePull
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
FdbDocument.prototype._updatePull = function (arr, index) {
if (this._linked) {
window.jQuery.observable(arr).remove(index);
} else {
arr.splice(index, 1);
}
};
/**
* Multiplies a value for a property on a document by the passed number.
* @func _updateMultiply
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
FdbDocument.prototype._updateMultiply = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] * val);
} else {
doc[prop] *= val;
}
};
/**
* Renames a property on a document to the passed property.
* @func _updateRename
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
FdbDocument.prototype._updateRename = function (doc, prop, val) {
var existingVal = doc[prop];
if (this._linked) {
window.jQuery.observable(doc).setProperty(val, existingVal);
window.jQuery.observable(doc).removeProperty(prop);
} else {
doc[val] = existingVal;
delete doc[prop];
}
};
/**
* Deletes a property on a document.
* @func _updateUnset
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
FdbDocument.prototype._updateUnset = function (doc, prop) {
if (this._linked) {
window.jQuery.observable(doc).removeProperty(prop);
} else {
delete doc[prop];
}
};
/**
* Drops the document.
* @func drop
* @memberof Document
* @returns {boolean} True if successful, false if not.
*/
FdbDocument.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._db && this._name) {
if (this._db && this._db._document && this._db._document[this._name]) {
this._state = 'dropped';
delete this._db._document[this._name];
delete this._data;
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._listeners;
return true;
}
}
} else {
return true;
}
return false;
};
/**
* Creates a new document instance or returns an existing
* instance if one already exists with the passed name.
* @func document
* @memberOf Db
* @param {String} name The name of the instance.
* @returns {*}
*/
Db.prototype.document = function (name) {
var self = this;
if (name) {
// Handle being passed an instance
if (name instanceof FdbDocument) {
if (name.state() !== 'droppped') {
return name;
} else {
name = name.name();
}
}
if (this._document && this._document[name]) {
return this._document[name];
}
this._document = this._document || {};
this._document[name] = new FdbDocument(name).db(this);
self.emit('create', self._document[name], 'document', name);
return this._document[name];
} else {
// Return an object of document data
return this._document;
}
};
/**
* Returns an array of documents the DB currently has.
* @func documents
* @memberof Db
* @returns {Array} An array of objects containing details of each document
* the database is currently managing.
*/
Db.prototype.documents = function () {
var arr = [],
item,
i;
for (i in this._document) {
if (this._document.hasOwnProperty(i)) {
item = this._document[i];
arr.push({
name: i,
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Document');
module.exports = FdbDocument;
},{"./Collection":5,"./Shared":39}],10:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - [email protected]
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders;
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to longitude/latitude.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
latitude: lat,
longitude: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
module.exports = GeoHash;
},{}],11:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
View,
CollectionInit,
DbInit,
ReactorIO;
//Shared = ForerunnerDB.shared;
Shared = _dereq_('./Shared');
/**
* Creates a new grid instance.
* @name Grid
* @class Grid
* @param {String} selector jQuery selector.
* @param {String} template The template selector.
* @param {Object=} options The options object to apply to the grid.
* @constructor
*/
var Grid = function (selector, template, options) {
this.init.apply(this, arguments);
};
Grid.prototype.init = function (selector, template, options) {
var self = this;
this._selector = selector;
this._template = template;
this._options = options || {};
this._debug = {};
this._id = this.objectId();
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
};
Shared.addModule('Grid', Grid);
Shared.mixin(Grid.prototype, 'Mixin.Common');
Shared.mixin(Grid.prototype, 'Mixin.ChainReactor');
Shared.mixin(Grid.prototype, 'Mixin.Constants');
Shared.mixin(Grid.prototype, 'Mixin.Triggers');
Shared.mixin(Grid.prototype, 'Mixin.Events');
Shared.mixin(Grid.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
View = _dereq_('./View');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @func state
* @memberof Grid
* @param {String=} val The name of the state to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'state');
/**
* Gets / sets the current name.
* @func name
* @memberof Grid
* @param {String=} val The name to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'name');
/**
* Executes an insert against the grid's underlying data-source.
* @func insert
* @memberof Grid
*/
Grid.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the grid's underlying data-source.
* @func update
* @memberof Grid
*/
Grid.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the grid's underlying data-source.
* @func updateById
* @memberof Grid
*/
Grid.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the grid's underlying data-source.
* @func remove
* @memberof Grid
*/
Grid.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Sets the collection from which the grid will assemble its data.
* @func from
* @memberof Grid
* @param {Collection} collection The collection to use to assemble grid data.
* @returns {Grid}
*/
Grid.prototype.from = function (collection) {
//var self = this;
if (collection !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
}
if (typeof(collection) === 'string') {
collection = this._db.collection(collection);
}
this._from = collection;
this._from.on('drop', this._collectionDroppedWrap);
this.refresh();
}
return this;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Grid
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Grid.prototype, 'db', function (db) {
if (db) {
// Apply the same debug settings
this.debug(db.debug());
}
return this.$super.apply(this, arguments);
});
Grid.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from grid
delete this._from;
}
};
/**
* Drops a grid and all it's stored data from the database.
* @func drop
* @memberof Grid
* @returns {boolean} True on success, false on failure.
*/
Grid.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
// Remove data-binding
this._from.unlink(this._selector, this.template());
// Kill listeners and references
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping grid ' + this._selector);
}
this._state = 'dropped';
if (this._db && this._selector) {
delete this._db._grid[this._selector];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._selector;
delete this._template;
delete this._from;
delete this._db;
delete this._listeners;
return true;
}
} else {
return true;
}
return false;
};
/**
* Gets / sets the grid's HTML template to use when rendering.
* @func template
* @memberof Grid
* @param {Selector} template The template's jQuery selector.
* @returns {*}
*/
Grid.prototype.template = function (template) {
if (template !== undefined) {
this._template = template;
return this;
}
return this._template;
};
Grid.prototype._sortGridClick = function (e) {
var elem = window.jQuery(e.currentTarget),
sortColText = elem.attr('data-grid-sort') || '',
sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1,
sortCols = sortColText.split(','),
sortObj = {},
i;
// Remove all grid sort tags from the grid
window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir');
// Flip the sort direction
elem.attr('data-grid-dir', sortColDir);
for (i = 0; i < sortCols.length; i++) {
sortObj[sortCols] = sortColDir;
}
Shared.mixin(sortObj, this._options.$orderBy);
this._from.orderBy(sortObj);
this.emit('sort', sortObj);
};
/**
* Refreshes the grid data such as ordering etc.
* @func refresh
* @memberof Grid
*/
Grid.prototype.refresh = function () {
if (this._from) {
if (this._from.link) {
var self = this,
elem = window.jQuery(this._selector),
sortClickListener = function () {
self._sortGridClick.apply(self, arguments);
};
// Clear the container
elem.html('');
if (self._from.orderBy) {
// Remove listeners
elem.off('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Remove listeners
elem.off('click', '[data-grid-filter]', sortClickListener);
}
// Set wrap name if none is provided
self._options.$wrap = self._options.$wrap || 'gridRow';
// Auto-bind the data to the grid template
self._from.link(self._selector, self.template(), self._options);
// Check if the data source (collection or view) has an
// orderBy method (usually only views) and if so activate
// the sorting system
if (self._from.orderBy) {
// Listen for sort requests
elem.on('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Listen for filter requests
var queryObj = {};
elem.find('[data-grid-filter]').each(function (index, filterElem) {
filterElem = window.jQuery(filterElem);
var filterField = filterElem.attr('data-grid-filter'),
filterVarType = filterElem.attr('data-grid-vartype'),
filterSort = {},
title = filterElem.html(),
dropDownButton,
dropDownMenu,
template,
filterQuery,
filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField);
filterSort[filterField] = 1;
filterQuery = {
$distinct: filterSort
};
filterView
.query(filterQuery)
.orderBy(filterSort)
.from(self._from._from);
template = [
'<div class="dropdown" id="' + self._id + '_' + filterField + '">',
'<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">',
title + ' <span class="caret"></span>',
'</button>',
'</div>'
];
dropDownButton = window.jQuery(template.join(''));
dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>');
dropDownButton.append(dropDownMenu);
filterElem.html(dropDownButton);
// Data-link the underlying data to the grid filter drop-down
filterView.link(dropDownMenu, {
template: [
'<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">',
'<input type="search" class="form-control gridFilterSearch" placeholder="Search...">',
'<span class="input-group-btn">',
'<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',
'</span>',
'</li>',
'<li role="presentation" class="divider"></li>',
'<li role="presentation" data-val="$all">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox" checked> All',
'</a>',
'</li>',
'<li role="presentation" class="divider"></li>',
'{^{for options}}',
'<li role="presentation" data-link="data-val{:' + filterField + '}">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox"> {^{:' + filterField + '}}',
'</a>',
'</li>',
'{{/for}}'
].join('')
}, {
$wrap: 'options'
});
elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) {
var elem = window.jQuery(this),
query = filterView.query(),
search = elem.val();
if (search) {
query[filterField] = new RegExp(search, 'gi');
} else {
delete query[filterField];
}
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) {
// Clear search text box
window.jQuery(this).parents('li').find('.gridFilterSearch').val('');
// Clear view query
var query = filterView.query();
delete query[filterField];
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) {
e.stopPropagation();
var fieldValue,
elem = $(this),
checkbox = elem.find('input[type="checkbox"]'),
checked,
addMode = true,
fieldInArr,
liElem,
i;
// If the checkbox is not the one clicked on
if (!window.jQuery(e.target).is('input')) {
// Set checkbox to opposite of current value
checkbox.prop('checked', !checkbox.prop('checked'));
checked = checkbox.is(':checked');
} else {
checkbox.prop('checked', checkbox.prop('checked'));
checked = checkbox.is(':checked');
}
liElem = window.jQuery(this);
fieldValue = liElem.attr('data-val');
// Check if the selection is the "all" option
if (fieldValue === '$all') {
// Remove the field from the query
delete queryObj[filterField];
// Clear all other checkboxes
liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false);
} else {
// Clear the "all" checkbox
liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false);
// Check if the type needs casting
switch (filterVarType) {
case 'integer':
fieldValue = parseInt(fieldValue, 10);
break;
case 'float':
fieldValue = parseFloat(fieldValue);
break;
default:
}
// Check if the item exists already
queryObj[filterField] = queryObj[filterField] || {
$in: []
};
fieldInArr = queryObj[filterField].$in;
for (i = 0; i < fieldInArr.length; i++) {
if (fieldInArr[i] === fieldValue) {
// Item already exists
if (checked === false) {
// Remove the item
fieldInArr.splice(i, 1);
}
addMode = false;
break;
}
}
if (addMode && checked) {
fieldInArr.push(fieldValue);
}
if (!fieldInArr.length) {
// Remove the field from the query
delete queryObj[filterField];
}
}
// Set the view query
self._from.queryData(queryObj);
if (self._from.pageFirst) {
self._from.pageFirst();
}
});
});
}
self.emit('refresh');
} else {
throw('Grid requires the AutoBind module in order to operate!');
}
}
return this;
};
/**
* Returns the number of documents currently in the grid.
* @func count
* @memberof Grid
* @returns {Number}
*/
Grid.prototype.count = function () {
return this._from.count();
};
/**
* Creates a grid and assigns the collection as its data source.
* @func grid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.grid = View.prototype.grid = function (selector, template, options) {
if (this._db && this._db._grid ) {
if (selector !== undefined) {
if (template !== undefined) {
if (!this._db._grid[selector]) {
var grid = new Grid(selector, template, options)
.db(this._db)
.from(this);
this._grid = this._grid || [];
this._grid.push(grid);
this._db._grid[selector] = grid;
return grid;
} else {
throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector);
}
}
return this._db._grid[selector];
}
return this._db._grid;
}
};
/**
* Removes a grid safely from the DOM. Must be called when grid is
* no longer required / is being removed from DOM otherwise references
* will stick around and cause memory leaks.
* @func unGrid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) {
var i,
grid;
if (this._db && this._db._grid ) {
if (selector && template) {
if (this._db._grid[selector]) {
grid = this._db._grid[selector];
delete this._db._grid[selector];
return grid.drop();
} else {
throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name);
}
} else {
// No parameters passed, remove all grids from this module
for (i in this._db._grid) {
if (this._db._grid.hasOwnProperty(i)) {
grid = this._db._grid[i];
delete this._db._grid[i];
grid.drop();
if (this.debug()) {
console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"');
}
}
}
this._db._grid = {};
}
}
};
/**
* Adds a grid to the internal grid lookup.
* @func _addGrid
* @memberof Collection
* @param {Grid} grid The grid to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) {
if (grid !== undefined) {
this._grid = this._grid || [];
this._grid.push(grid);
}
return this;
};
/**
* Removes a grid from the internal grid lookup.
* @func _removeGrid
* @memberof Collection
* @param {Grid} grid The grid to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) {
if (grid !== undefined && this._grid) {
var index = this._grid.indexOf(grid);
if (index > -1) {
this._grid.splice(index, 1);
}
}
return this;
};
// Extend DB with grids init
Db.prototype.init = function () {
this._grid = {};
DbInit.apply(this, arguments);
};
/**
* Determine if a grid with the passed name already exists.
* @func gridExists
* @memberof Db
* @param {String} selector The jQuery selector to bind the grid to.
* @returns {boolean}
*/
Db.prototype.gridExists = function (selector) {
return Boolean(this._grid[selector]);
};
/**
* Creates a grid based on the passed arguments.
* @func grid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.grid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Removes a grid based on the passed arguments.
* @func unGrid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.unGrid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Returns an array of grids the DB currently has.
* @func grids
* @memberof Db
* @returns {Array} An array of objects containing details of each grid
* the database is currently managing.
*/
Db.prototype.grids = function () {
var arr = [],
item,
i;
for (i in this._grid) {
if (this._grid.hasOwnProperty(i)) {
item = this._grid[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Grid');
module.exports = Grid;
},{"./Collection":5,"./CollectionGroup":6,"./ReactorIO":37,"./Shared":39,"./View":40}],12:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Collection,
CollectionInit,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The constructor.
*
* @constructor
*/
var Highchart = function (collection, options) {
this.init.apply(this, arguments);
};
Highchart.prototype.init = function (collection, options) {
this._options = options;
this._selector = window.jQuery(this._options.selector);
if (!this._selector[0]) {
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector);
}
this._listeners = {};
this._collection = collection;
// Setup the chart
this._options.series = [];
// Disable attribution on highcharts
options.chartOptions = options.chartOptions || {};
options.chartOptions.credits = false;
// Set the data for the chart
var data,
seriesObj,
chartData;
switch (this._options.type) {
case 'pie':
// Create chart from data
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
// Generate graph data from collection data
data = this._collection.find();
seriesObj = {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)',
style: {
color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black'
}
}
};
chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField);
window.jQuery.extend(seriesObj, this._options.seriesOptions);
window.jQuery.extend(seriesObj, {
name: this._options.seriesName,
data: chartData
});
this._chart.addSeries(seriesObj, true, true);
break;
case 'line':
case 'area':
case 'column':
case 'bar':
// Generate graph data from collection data
chartData = this.seriesDataFromCollectionData(
this._options.seriesField,
this._options.keyField,
this._options.valField,
this._options.orderBy,
this._options
);
this._options.chartOptions.xAxis = chartData.xAxis;
this._options.chartOptions.series = chartData.series;
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
break;
default:
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type);
}
// Hook the collection events to auto-update the chart
this._hookEvents();
};
Shared.addModule('Highchart', Highchart);
Collection = Shared.modules.Collection;
CollectionInit = Collection.prototype.init;
Shared.mixin(Highchart.prototype, 'Mixin.Common');
Shared.mixin(Highchart.prototype, 'Mixin.Events');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Highchart.prototype, 'state');
/**
* Generate pie-chart series data from the given collection data array.
* @param data
* @param keyField
* @param valField
* @returns {Array}
*/
Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) {
var graphData = [],
i;
for (i = 0; i < data.length; i++) {
graphData.push([data[i][keyField], data[i][valField]]);
}
return graphData;
};
/**
* Generate line-chart series data from the given collection data array.
* @param seriesField
* @param keyField
* @param valField
* @param orderBy
*/
Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy, options) {
var data = this._collection.distinct(seriesField),
seriesData = [],
xAxis = options && options.chartOptions && options.chartOptions.xAxis ? options.chartOptions.xAxis : {
categories: []
},
seriesName,
query,
dataSearch,
seriesValues,
sData,
i, k;
// What we WANT to output:
/*series: [{
name: 'Responses',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}]*/
// Loop keys
for (i = 0; i < data.length; i++) {
seriesName = data[i];
query = {};
query[seriesField] = seriesName;
seriesValues = [];
dataSearch = this._collection.find(query, {
orderBy: orderBy
});
// Loop the keySearch data and grab the value for each item
for (k = 0; k < dataSearch.length; k++) {
if (xAxis.categories) {
xAxis.categories.push(dataSearch[k][keyField]);
seriesValues.push(dataSearch[k][valField]);
} else {
seriesValues.push([dataSearch[k][keyField], dataSearch[k][valField]]);
}
}
sData = {
name: seriesName,
data: seriesValues
};
if (options.seriesOptions) {
for (k in options.seriesOptions) {
if (options.seriesOptions.hasOwnProperty(k)) {
sData[k] = options.seriesOptions[k];
}
}
}
seriesData.push(sData);
}
return {
xAxis: xAxis,
series: seriesData
};
};
/**
* Hook the events the chart needs to know about from the internal collection.
* @private
*/
Highchart.prototype._hookEvents = function () {
var self = this;
self._collection.on('change', function () {
self._changeListener.apply(self, arguments);
});
// If the collection is dropped, clean up after ourselves
self._collection.on('drop', function () {
self.drop.apply(self);
});
};
/**
* Handles changes to the collection data that the chart is reading from and then
* updates the data in the chart display.
* @private
*/
Highchart.prototype._changeListener = function () {
var self = this;
// Update the series data on the chart
if (typeof self._collection !== 'undefined' && self._chart) {
var data = self._collection.find(),
i;
switch (self._options.type) {
case 'pie':
self._chart.series[0].setData(
self.pieDataFromCollectionData(
data,
self._options.keyField,
self._options.valField
),
true,
true
);
break;
case 'bar':
case 'line':
case 'area':
case 'column':
var seriesData = self.seriesDataFromCollectionData(
self._options.seriesField,
self._options.keyField,
self._options.valField,
self._options.orderBy,
self._options
);
if (seriesData.xAxis.categories) {
self._chart.xAxis[0].setCategories(
seriesData.xAxis.categories
);
}
for (i = 0; i < seriesData.series.length; i++) {
if (self._chart.series[i]) {
// Series exists, set it's data
self._chart.series[i].setData(
seriesData.series[i].data,
true,
true
);
} else {
// Series data does not yet exist, add a new series
self._chart.addSeries(
seriesData.series[i],
true,
true
);
}
}
break;
default:
break;
}
}
};
/**
* Destroys the chart and all internal references.
* @returns {Boolean}
*/
Highchart.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
if (this._chart) {
this._chart.destroy();
}
if (this._collection) {
this._collection.off('change', this._changeListener);
this._collection.off('drop', this.drop);
if (this._collection._highcharts) {
delete this._collection._highcharts[this._options.selector];
}
}
delete this._chart;
delete this._options;
delete this._collection;
this.emit('drop', this);
if (callback) {
callback(false, true);
}
delete this._listeners;
return true;
} else {
return true;
}
};
// Extend collection with highchart init
Collection.prototype.init = function () {
this._highcharts = {};
CollectionInit.apply(this, arguments);
};
/**
* Creates a pie chart from the collection.
* @type {Overload}
*/
Collection.prototype.pieChart = new Overload({
/**
* Chart via options object.
* @func pieChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'pie';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'pie';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func pieChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {String} seriesName The name of the series to display on the chart.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) {
options = options || {};
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
options.seriesName = seriesName;
// Call the main chart method
this.pieChart(options);
}
});
/**
* Creates a line chart from the collection.
* @type {Overload}
*/
Collection.prototype.lineChart = new Overload({
/**
* Chart via selector.
* @func lineChart
* @memberof Highchart
* @param {String} selector The chart selector.
* @returns {*}
*/
'string': function (selector) {
return this._highcharts[selector];
},
/**
* Chart via options object.
* @func lineChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'line';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'line';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func lineChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.lineChart(options);
}
});
/**
* Creates an area chart from the collection.
* @type {Overload}
*/
Collection.prototype.areaChart = new Overload({
/**
* Chart via options object.
* @func areaChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'area';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'area';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func areaChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.areaChart(options);
}
});
/**
* Creates a column chart from the collection.
* @type {Overload}
*/
Collection.prototype.columnChart = new Overload({
/**
* Chart via options object.
* @func columnChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'column';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'column';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func columnChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.columnChart(options);
}
});
/**
* Creates a bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.barChart = new Overload({
/**
* Chart via options object.
* @func barChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func barChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.barChart(options);
}
});
/**
* Creates a stacked bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.stackedBarChart = new Overload({
/**
* Chart via options object.
* @func stackedBarChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
options.plotOptions = options.plotOptions || {};
options.plotOptions.series = options.plotOptions.series || {};
options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func stackedBarChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.stackedBarChart(options);
}
});
/**
* Removes a chart from the page by it's selector.
* @memberof Collection
* @param {String} selector The chart selector.
*/
Collection.prototype.dropChart = function (selector) {
if (this._highcharts && this._highcharts[selector]) {
this._highcharts[selector].drop();
}
};
Shared.finishModule('Highchart');
module.exports = Highchart;
},{"./Overload":31,"./Shared":39}],13:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
/**
* Create the index.
* @param {Object} keys The object with the keys that the user wishes the index
* to operate on.
* @param {Object} options Can be undefined, if passed is an object with arbitrary
* options keys and values.
* @param {Collection} collection The collection the index should be created for.
*/
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.lookup = function (query, options) {
// Loop the indexed keys and determine if the query has any operators
// that we want to handle differently from a standard lookup
var keys = this._btree.keys(),
pathStr,
pathVal,
results,
i;
for (i = 0; i < keys.length; i++) {
pathStr = keys[i].path;
pathVal = sharedPathSolver.get(query, pathStr);
if (typeof pathVal === 'object') {
if (pathVal.$near) {
results = [];
// Do a near point lookup
results = results.concat(this.near(pathStr, pathVal.$near, options));
}
if (pathVal.$geoWithin) {
results = [];
// Do a geoWithin shape lookup
results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options));
}
return results;
}
}
return this._btree.lookup(query, options);
};
Index2d.prototype.near = function (pathStr, query, options) {
var self = this,
geoHash,
neighbours,
visited,
search,
results,
finalResults = [],
precision,
maxDistanceKm,
distance,
distCache,
latLng,
pk = this._collection.primaryKey(),
i;
// Calculate the required precision to encapsulate the distance
// TODO: Instead of opting for the "one size larger" than the distance boxes,
// TODO: we should calculate closest divisible box size as a multiple and then
// TODO: scan neighbours until we have covered the area otherwise we risk
// TODO: opening the results up to vastly more information as the box size
// TODO: increases dramatically between the geohash precisions
if (query.$distanceUnits === 'km') {
maxDistanceKm = query.$maxDistance;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
} else if (query.$distanceUnits === 'miles') {
maxDistanceKm = query.$maxDistance * 1.60934;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i;
break;
}
}
if (precision === 0) {
precision = 1;
}
}
// Get the lngLat geohash from the query
geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision);
// Calculate 9 box geohashes
neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'});
// Lookup all matching co-ordinates from the btree
results = [];
visited = 0;
for (i = 0; i < 9; i++) {
search = this._btree.startsWith(pathStr, neighbours[i]);
visited += search._visited;
results = results.concat(search);
}
// Work with original data
results = this._collection._primaryIndex.lookup(results);
if (results.length) {
distance = {};
// Loop the results and calculate distance
for (i = 0; i < results.length; i++) {
latLng = sharedPathSolver.get(results[i], pathStr);
distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]);
if (distCache <= maxDistanceKm) {
// Add item inside radius distance
finalResults.push(results[i]);
}
}
// Sort by distance from center
finalResults.sort(function (a, b) {
return self.sortAsc(distance[a[pk]], distance[b[pk]]);
});
}
// Return data
return finalResults;
};
Index2d.prototype.geoWithin = function (pathStr, query, options) {
return [];
};
Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) {
var R = 6371; // kilometres
var lat1Rad = this.toRadians(lat1);
var lat2Rad = this.toRadians(lat2);
var lat2MinusLat1Rad = this.toRadians(lat2-lat1);
var lng2MinusLng1Rad = this.toRadians(lng2-lng1);
var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
Index2d.prototype.toRadians = function (degrees) {
return degrees * 0.01747722222222;
};
Index2d.prototype.match = function (query, options) {
// TODO: work out how to represent that this is a better match if the query has $near than
// TODO: a basic btree index which will not be able to resolve a $near operator
return this._btree.match(query, options);
};
Index2d.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index2d.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index2d.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index['2d'] = Index2d;
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":3,"./GeoHash":10,"./Path":33,"./Shared":39}],14:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options) {
return this._btree.lookup(query, options);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.btree = IndexBinaryTree;
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":3,"./Path":33,"./Shared":39}],15:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.hashed = IndexHashMap;
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":33,"./Shared":39}],16:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk]) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":39}],17:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":30,"./Shared":39}],18:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],19:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
* Creates a chain link between the current reactor node and the passed
* reactor node. Chain packets that are send by this reactor node will
* then be propagated to the passed node for subsequent packets.
* @param {*} obj The chain reactor node to link to.
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
/**
* Removes a chain link between the current reactor node and the passed
* reactor node. Chain packets sent from this reactor node will no longer
* be received by the passed node.
* @param {*} obj The chain reactor node to unlink from.
*/
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
/**
* Determines if this chain reactor node has any listeners downstream.
* @returns {Boolean} True if there are nodes downstream of this node.
*/
chainWillSend: function () {
return Boolean(this._chain);
},
/**
* Sends a chain reactor packet downstream from this node to any of its
* chained targets that were linked to this node via a call to chain().
* @param {String} type The type of chain reactor packet to send. This
* can be any string but the receiving reactor nodes will not react to
* it unless they recognise the string. Built-in strings include: "insert",
* "update", "remove", "setData" and "debug".
* @param {Object} data A data object that usually contains a key called
* "dataSet" which is an array of items to work on, and can contain other
* custom keys that help describe the operation.
* @param {Object=} options An options object. Can also contain custom
* key/value pairs that your custom chain reactor code can operate on.
*/
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index,
dataCopy = this.decouple(data, count);
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, dataCopy[index], options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
/**
* Handles receiving a chain reactor message that was sent via the chainSend()
* method. Creates the chain packet object and then allows it to be processed.
* @param {Object} sender The node that is sending the packet.
* @param {String} type The type of packet.
* @param {Object} data The data related to the packet.
* @param {Object=} options An options object.
*/
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
},
cancelPropagate = false;
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + ' Received data from parent reactor node');
}
// Check if we have a chain handler method
if (this._chainHandler) {
// Fire our internal handler
cancelPropagate = this._chainHandler(chainPacket);
}
// Check if we were told to cancel further propagation
if (!cancelPropagate) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Generates a JSON serialisation-compatible object instance. After the
* instance has been passed through this method, it will be able to survive
* a JSON.stringify() and JSON.parse() cycle and still end up as an
* instance at the end. Further information about this process can be found
* in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks
* @param {*} val The object instance such as "new Date()" or "new RegExp()".
*/
make: function (val) {
// This is a conversion request, hand over to serialiser
return serialiser.convert(val);
},
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined && data !== "") {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return JSON.parse(data, serialiser.reviver());
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
//return serialiser.stringify(data);
return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Generates a unique hash for the passed object.
* @param {Object} obj The object to generate a hash for.
* @returns {String}
*/
hash: function (obj) {
return JSON.stringify(obj);
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return 'ForerunnerDB ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
},
/**
* Registers a timed callback that will overwrite itself if
* the same id is used within the timeout period. Useful
* for de-bouncing fast-calls.
* @param {String} id An ID for the call (use the same one
* to debounce the same calls).
* @param {Function} callback The callback method to call on
* timeout.
* @param {Number} timeout The timeout in milliseconds before
* the callback is called.
*/
debounce: function (id, callback, timeout) {
var self = this,
newData;
self._debounce = self._debounce || {};
if (self._debounce[id]) {
// Clear timeout for this item
clearTimeout(self._debounce[id].timeout);
}
newData = {
callback: callback,
timeout: setTimeout(function () {
// Delete existing reference
delete self._debounce[id];
// Call the callback
callback();
}, timeout)
};
// Save current data
self._debounce[id] = newData;
}
};
module.exports = Common;
},{"./Overload":31,"./Serialiser":38}],21:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],22:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":31}],23:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
if (sourceType === 'object' && source === null) {
sourceType = 'null';
}
if (testType === 'object' && test === null) {
testType = 'null';
}
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number' || sourceType === 'null' || testType === 'null') {
// Number or null comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
},
/**
*
* @param {Array | Object} docArr An array of objects to run the join
* operation against or a single object.
* @param {Array} joinClause The join clause object array (the array in
* the $join key of a normal join options object).
* @param {Object} joinSource An object containing join source reference
* data or a blank object if you are doing a bespoke join operation.
* @param {Object} options An options object or blank object if no options.
* @returns {Array}
* @private
*/
applyJoin: function (docArr, joinClause, joinSource, options) {
var self = this,
joinSourceIndex,
joinSourceKey,
joinMatch,
joinSourceType,
joinSourceIdentifier,
resultKeyName,
joinSourceInstance,
resultIndex,
joinSearchQuery,
joinMulti,
joinRequire,
joinPrefix,
joinMatchIndex,
joinMatchData,
joinSearchOptions,
joinFindResults,
joinFindResult,
joinItem,
resultRemove = [],
l;
if (!(docArr instanceof Array)) {
// Turn the document into an array
docArr = [docArr];
}
for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) {
for (joinSourceKey in joinClause[joinSourceIndex]) {
if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
// Get the match data for the join
joinMatch = joinClause[joinSourceIndex][joinSourceKey];
// Check if the join is to a collection (default) or a specified source type
// e.g 'view' or 'collection'
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
// Set the key to store the join result in to the collection name by default
// can be overridden by the '$as' clause in the join object
resultKeyName = joinSourceKey;
// Get the join collection instance from the DB
if (joinSource[joinSourceIdentifier]) {
// We have a joinSource for this identifier already (given to us by
// an index when we analysed the query earlier on) and we can use
// that source instead.
joinSourceInstance = joinSource[joinSourceIdentifier];
} else {
// We do not already have a joinSource so grab the instance from the db
if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') {
joinSourceInstance = this._db[joinSourceType](joinSourceKey);
}
}
// Loop our result data array
for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultKeyName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultKeyName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = docArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultIndex);
}
}
}
}
}
return resultRemove;
},
/**
* Takes a query object with dynamic references and converts the references
* into actual values from the references source.
* @param {Object} query The query object with dynamic references.
* @param {Object} item The document to apply the references to.
* @returns {*}
* @private
*/
resolveDynamicQuery: function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
// Check for early exit conditions
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3));
} else {
pathResult = this.sharedPathSolver.value(item, query);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self.resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
},
spliceArrayByIndexList: function (arr, list) {
var i;
for (i = list.length - 1; i >= 0; i--) {
arr.splice(list[i], 1);
}
}
};
module.exports = Matching;
},{}],24:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],25:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* When called in a before phase the newDoc object can be directly altered
* to modify the data in it before the operation is carried out.
* @callback addTriggerCallback
* @param {Object} operation The details about the operation.
* @param {Object} oldDoc The document before the operation.
* @param {Object} newDoc The document after the operation.
*/
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Constants} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Constants} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {addTriggerCallback} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":31}],27:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],28:[function(_dereq_,module,exports){
"use strict";
// Grab the view class
var Shared,
Core,
OldView,
OldViewInit;
Shared = _dereq_('./Shared');
Core = Shared.modules.Core;
OldView = Shared.modules.OldView;
OldViewInit = OldView.prototype.init;
OldView.prototype.init = function () {
var self = this;
this._binds = [];
this._renderStart = 0;
this._renderEnd = 0;
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
_bindInsert: [],
_bindUpdate: [],
_bindRemove: [],
_bindUpsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100,
_bindInsert: 100,
_bindUpdate: 100,
_bindRemove: 100,
_bindUpsert: 100
};
this._deferTime = {
insert: 100,
update: 1,
remove: 1,
upsert: 1,
_bindInsert: 100,
_bindUpdate: 1,
_bindRemove: 1,
_bindUpsert: 1
};
OldViewInit.apply(this, arguments);
// Hook view events to update binds
this.on('insert', function (successArr, failArr) {
self._bindEvent('insert', successArr, failArr);
});
this.on('update', function (successArr, failArr) {
self._bindEvent('update', successArr, failArr);
});
this.on('remove', function (successArr, failArr) {
self._bindEvent('remove', successArr, failArr);
});
this.on('change', self._bindChange);
};
/**
* Binds a selector to the insert, update and delete events of a particular
* view and keeps the selector in sync so that updates are reflected on the
* web page in real-time.
*
* @param {String} selector The jQuery selector string to get target elements.
* @param {Object} options The options object.
*/
OldView.prototype.bind = function (selector, options) {
if (options && options.template) {
this._binds[selector] = options;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot bind data to element, missing options information!');
}
return this;
};
/**
* Un-binds a selector from the view changes.
* @param {String} selector The jQuery selector string to identify the bind to remove.
* @returns {Collection}
*/
OldView.prototype.unBind = function (selector) {
delete this._binds[selector];
return this;
};
/**
* Returns true if the selector is bound to the view.
* @param {String} selector The jQuery selector string to identify the bind to check for.
* @returns {boolean}
*/
OldView.prototype.isBound = function (selector) {
return Boolean(this._binds[selector]);
};
/**
* Sorts items in the DOM based on the bind settings and the passed item array.
* @param {String} selector The jQuery selector of the bind container.
* @param {Array} itemArr The array of items used to determine the order the DOM
* elements should be in based on the order they are in, in the array.
*/
OldView.prototype.bindSortDom = function (selector, itemArr) {
var container = window.jQuery(selector),
arrIndex,
arrItem,
domItem;
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sorting data in DOM...', itemArr);
}
for (arrIndex = 0; arrIndex < itemArr.length; arrIndex++) {
arrItem = itemArr[arrIndex];
// Now we've done our inserts into the DOM, let's ensure
// they are still ordered correctly
domItem = container.find('#' + arrItem[this._primaryKey]);
if (domItem.length) {
if (arrIndex === 0) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index 0...', domItem);
}
container.prepend(domItem);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index ' + arrIndex + '...', domItem);
}
domItem.insertAfter(container.children(':eq(' + (arrIndex - 1) + ')'));
}
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Warning, element for array item not found!', arrItem);
}
}
}
};
OldView.prototype.bindRefresh = function (obj) {
var binds = this._binds,
bindKey,
bind;
if (!obj) {
// Grab current data
obj = {
data: this.find()
};
}
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
bind = binds[bindKey];
if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting DOM...'); }
this.bindSortDom(bindKey, obj.data);
if (bind.afterOperation) {
bind.afterOperation();
}
if (bind.refresh) {
bind.refresh();
}
}
}
};
/**
* Renders a bind view data to the DOM.
* @param {String} bindSelector The jQuery selector string to use to identify
* the bind target. Must match the selector used when defining the original bind.
* @param {Function=} domHandler If specified, this handler method will be called
* with the final HTML for the view instead of the DB handling the DOM insertion.
*/
OldView.prototype.bindRender = function (bindSelector, domHandler) {
// Check the bind exists
var bind = this._binds[bindSelector],
domTarget = window.jQuery(bindSelector),
allData,
dataItem,
itemHtml,
finalHtml = window.jQuery('<ul></ul>'),
bindCallback,
i;
if (bind) {
allData = this._data.find();
bindCallback = function (itemHtml) {
finalHtml.append(itemHtml);
};
// Loop all items and add them to the screen
for (i = 0; i < allData.length; i++) {
dataItem = allData[i];
itemHtml = bind.template(dataItem, bindCallback);
}
if (!domHandler) {
domTarget.append(finalHtml.html());
} else {
domHandler(bindSelector, finalHtml.html());
}
}
};
OldView.prototype.processQueue = function (type, callback) {
var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];
if (queue.length) {
var self = this,
dataArr;
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
this._bindEvent(type, dataArr, []);
}
// Queue another process
setTimeout(function () {
self.processQueue(type, callback);
}, deferTime);
} else {
if (callback) { callback(); }
this.emit('bindQueueComplete');
}
};
OldView.prototype._bindEvent = function (type, successArr, failArr) {
/*var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];*/
var binds = this._binds,
unfilteredDataSet = this.find({}),
filteredDataSet,
bindKey;
// Check if the number of inserts is greater than the defer threshold
/*if (successArr && successArr.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue[type] = queue.concat(successArr);
// Fire off the insert queue handler
this.processQueue(type);
return;
} else {*/
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
if (binds[bindKey].reduce) {
filteredDataSet = this.find(binds[bindKey].reduce.query, binds[bindKey].reduce.options);
} else {
filteredDataSet = unfilteredDataSet;
}
switch (type) {
case 'insert':
this._bindInsert(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'update':
this._bindUpdate(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'remove':
this._bindRemove(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
}
}
}
//}
};
OldView.prototype._bindChange = function (newDataArr) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...', newDataArr);
}
this.bindRefresh(newDataArr);
};
OldView.prototype._bindInsert = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
itemHtml,
makeCallback,
i;
makeCallback = function (itemElem, insertedItem, failArr, all) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.insert) {
options.insert(itemHtml, insertedItem, failArr, all);
} else {
// Handle the insert automatically
// Add the item to the container
if (options.prependInsert) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
if (options.afterInsert) {
options.afterInsert(itemHtml, insertedItem, failArr, all);
}
};
};
// Loop the inserted items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (!itemElem.length) {
itemHtml = options.template(successArr[i], makeCallback(itemElem, successArr[i], failArr, all));
}
}
};
OldView.prototype._bindUpdate = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, itemData) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.update) {
options.update(itemHtml, itemData, all, itemElem.length ? 'update' : 'append');
} else {
if (itemElem.length) {
// An existing item is in the container, replace it with the
// new rendered item from the updated data
itemElem.replaceWith(itemHtml);
} else {
// The item element does not already exist, append it
if (options.prependUpdate) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
}
if (options.afterUpdate) {
options.afterUpdate(itemHtml, itemData, all);
}
};
};
// Loop the updated items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
options.template(successArr[i], makeCallback(itemElem, successArr[i]));
}
};
OldView.prototype._bindRemove = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, data, all) {
return function () {
if (options.remove) {
options.remove(itemElem, data, all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, data, all);
}
}
};
};
// Loop the removed items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (itemElem.length) {
if (options.beforeRemove) {
options.beforeRemove(itemElem, successArr[i], all, makeCallback(itemElem, successArr[i], all));
} else {
if (options.remove) {
options.remove(itemElem, successArr[i], all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, successArr[i], all);
}
}
}
}
}
};
},{"./Shared":39}],29:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
CollectionGroup,
Collection,
CollectionInit,
CollectionGroupInit,
DbInit;
Shared = _dereq_('./Shared');
/**
* The view constructor.
* @param viewName
* @constructor
*/
var OldView = function (viewName) {
this.init.apply(this, arguments);
};
OldView.prototype.init = function (viewName) {
var self = this;
this._name = viewName;
this._listeners = {};
this._query = {
query: {},
options: {}
};
// Register listeners for the CRUD events
this._onFromSetData = function () {
self._onSetData.apply(self, arguments);
};
this._onFromInsert = function () {
self._onInsert.apply(self, arguments);
};
this._onFromUpdate = function () {
self._onUpdate.apply(self, arguments);
};
this._onFromRemove = function () {
self._onRemove.apply(self, arguments);
};
this._onFromChange = function () {
if (self.debug()) { console.log('ForerunnerDB.OldView: Received change'); }
self._onChange.apply(self, arguments);
};
};
Shared.addModule('OldView', OldView);
CollectionGroup = _dereq_('./CollectionGroup');
Collection = _dereq_('./Collection');
CollectionInit = Collection.prototype.init;
CollectionGroupInit = CollectionGroup.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
Shared.mixin(OldView.prototype, 'Mixin.Events');
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
OldView.prototype.drop = function () {
if ((this._db || this._from) && this._name) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Dropping view ' + this._name);
}
this._state = 'dropped';
this.emit('drop', this);
if (this._db && this._db._oldViews) {
delete this._db._oldViews[this._name];
}
if (this._from && this._from._oldViews) {
delete this._from._oldViews[this._name];
}
delete this._listeners;
return true;
}
return false;
};
OldView.prototype.debug = function () {
// TODO: Make this function work
return false;
};
/**
* Gets / sets the DB the view is bound against. Automatically set
* when the db.oldView(viewName) method is called.
* @param db
* @returns {*}
*/
OldView.prototype.db = function (db) {
if (db !== undefined) {
this._db = db;
return this;
}
return this._db;
};
/**
* Gets / sets the collection that the view derives it's data from.
* @param {*} collection A collection instance or the name of a collection
* to use as the data set to derive view data from.
* @returns {*}
*/
OldView.prototype.from = function (collection) {
if (collection !== undefined) {
// Check if this is a collection name or a collection instance
if (typeof(collection) === 'string') {
if (this._db.collectionExists(collection)) {
collection = this._db.collection(collection);
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Invalid collection in view.from() call.');
}
}
// Check if the existing from matches the passed one
if (this._from !== collection) {
// Check if we already have a collection assigned
if (this._from) {
// Remove ourselves from the collection view lookup
this.removeFrom();
}
this.addFrom(collection);
}
return this;
}
return this._from;
};
OldView.prototype.addFrom = function (collection) {
//var self = this;
this._from = collection;
if (this._from) {
this._from.on('setData', this._onFromSetData);
//this._from.on('insert', this._onFromInsert);
//this._from.on('update', this._onFromUpdate);
//this._from.on('remove', this._onFromRemove);
this._from.on('change', this._onFromChange);
// Add this view to the collection's view lookup
this._from._addOldView(this);
this._primaryKey = this._from._primaryKey;
this.refresh();
return this;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot determine collection type in view.from()');
}
};
OldView.prototype.removeFrom = function () {
// Unsubscribe from events on this "from"
this._from.off('setData', this._onFromSetData);
//this._from.off('insert', this._onFromInsert);
//this._from.off('update', this._onFromUpdate);
//this._from.off('remove', this._onFromRemove);
this._from.off('change', this._onFromChange);
this._from._removeOldView(this);
};
/**
* Gets the primary key for this view from the assigned collection.
* @returns {String}
*/
OldView.prototype.primaryKey = function () {
if (this._from) {
return this._from.primaryKey();
}
return undefined;
};
/**
* Gets / sets the query that the view uses to build it's data set.
* @param {Object=} query
* @param {Boolean=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._query.query = query;
}
if (options !== undefined) {
this._query.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryAdd = function (obj, overwrite, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryRemove = function (obj, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Gets / sets the query being used to generate the view data.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._query.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.query;
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._query.options = options;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.options;
};
/**
* Refreshes the view data and diffs between previous and new data to
* determine if any events need to be triggered or DOM binds updated.
*/
OldView.prototype.refresh = function (force) {
if (this._from) {
// Take a copy of the data before updating it, we will use this to
// "diff" between the old and new data and handle DOM bind updates
var oldData = this._data,
oldDataArr,
oldDataItem,
newData,
newDataArr,
query,
primaryKey,
dataItem,
inserted = [],
updated = [],
removed = [],
operated = false,
i;
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refreshing view ' + this._name);
console.log('ForerunnerDB.OldView: Existing data: ' + (typeof(this._data) !== "undefined"));
if (typeof(this._data) !== "undefined") {
console.log('ForerunnerDB.OldView: Current data rows: ' + this._data.find().length);
}
//console.log(OldView.prototype.refresh.caller);
}
// Query the collection and update the data
if (this._query) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has query and options, getting subset...');
}
// Run query against collection
//console.log('refresh with query and options', this._query.options);
this._data = this._from.subset(this._query.query, this._query.options);
//console.log(this._data);
} else {
// No query, return whole collection
if (this._query.options) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has options, getting subset...');
}
this._data = this._from.subset({}, this._query.options);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has no query or options, getting subset...');
}
this._data = this._from.subset({});
}
}
// Check if there was old data
if (!force && oldData) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refresh not forced, old data detected...');
}
// Now determine the difference
newData = this._data;
if (oldData.subsetOf() === newData.subsetOf()) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from same collection...');
}
newDataArr = newData.find();
oldDataArr = oldData.find();
primaryKey = newData._primaryKey;
// The old data and new data were derived from the same parent collection
// so scan the data to determine changes
for (i = 0; i < newDataArr.length; i++) {
dataItem = newDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
oldDataItem = oldData.find(query)[0];
if (!oldDataItem) {
// New item detected
inserted.push(dataItem);
} else {
// Check if an update has occurred
if (JSON.stringify(oldDataItem) !== JSON.stringify(dataItem)) {
// Updated / already included item detected
updated.push(dataItem);
}
}
}
// Now loop the old data and check if any records were removed
for (i = 0; i < oldDataArr.length; i++) {
dataItem = oldDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
if (!newData.find(query)[0]) {
// Removed item detected
removed.push(dataItem);
}
}
if (this.debug()) {
console.log('ForerunnerDB.OldView: Removed ' + removed.length + ' rows');
console.log('ForerunnerDB.OldView: Inserted ' + inserted.length + ' rows');
console.log('ForerunnerDB.OldView: Updated ' + updated.length + ' rows');
}
// Now we have a diff of the two data sets, we need to get the DOM updated
if (inserted.length) {
this._onInsert(inserted, []);
operated = true;
}
if (updated.length) {
this._onUpdate(updated, []);
operated = true;
}
if (removed.length) {
this._onRemove(removed, []);
operated = true;
}
} else {
// The previous data and the new data are derived from different collections
// and can therefore not be compared, all data is therefore effectively "new"
// so first perform a remove of all existing data then do an insert on all new data
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from different collections...');
}
removed = oldData.find();
if (removed.length) {
this._onRemove(removed);
operated = true;
}
inserted = newData.find();
if (inserted.length) {
this._onInsert(inserted);
operated = true;
}
}
} else {
// Force an update as if the view never got created by padding all elements
// to the insert
if (this.debug()) {
console.log('ForerunnerDB.OldView: Forcing data update', newDataArr);
}
this._data = this._from.subset(this._query.query, this._query.options);
newDataArr = this._data.find();
if (this.debug()) {
console.log('ForerunnerDB.OldView: Emitting change event with data', newDataArr);
}
this._onInsert(newDataArr, []);
}
if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change'); }
this.emit('change');
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
OldView.prototype.count = function () {
return this._data && this._data._data ? this._data._data.length : 0;
};
/**
* Queries the view data. See Collection.find() for more information.
* @returns {*}
*/
OldView.prototype.find = function () {
if (this._data) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Finding data in view collection...', this._data);
}
return this._data.find.apply(this._data, arguments);
} else {
return [];
}
};
/**
* Inserts into view data via the view collection. See Collection.insert() for more information.
* @returns {*}
*/
OldView.prototype.insert = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.insert.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Updates into view data via the view collection. See Collection.update() for more information.
* @returns {*}
*/
OldView.prototype.update = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.update.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Removed from view data via the view collection. See Collection.remove() for more information.
* @returns {*}
*/
OldView.prototype.remove = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.remove.apply(this._from, arguments);
} else {
return [];
}
};
OldView.prototype._onSetData = function (newDataArr, oldDataArr) {
this.emit('remove', oldDataArr, []);
this.emit('insert', newDataArr, []);
//this.refresh();
};
OldView.prototype._onInsert = function (successArr, failArr) {
this.emit('insert', successArr, failArr);
//this.refresh();
};
OldView.prototype._onUpdate = function (successArr, failArr) {
this.emit('update', successArr, failArr);
//this.refresh();
};
OldView.prototype._onRemove = function (successArr, failArr) {
this.emit('remove', successArr, failArr);
//this.refresh();
};
OldView.prototype._onChange = function () {
if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing data'); }
this.refresh();
};
// Extend collection with view init
Collection.prototype.init = function () {
this._oldViews = [];
CollectionInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend collection with view init
CollectionGroup.prototype.init = function () {
this._oldViews = [];
CollectionGroupInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._oldViews = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.oldView = function (viewName) {
if (!this._oldViews[viewName]) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Creating view ' + viewName);
}
}
this._oldViews[viewName] = this._oldViews[viewName] || new OldView(viewName).db(this);
return this._oldViews[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.oldViewExists = function (viewName) {
return Boolean(this._oldViews[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.oldViews = function () {
var arr = [],
i;
for (i in this._oldViews) {
if (this._oldViews.hasOwnProperty(i)) {
arr.push({
name: i,
count: this._oldViews[i].count()
});
}
}
return arr;
};
Shared.finishModule('OldView');
module.exports = OldView;
},{"./Collection":5,"./CollectionGroup":6,"./Shared":39}],30:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":33,"./Shared":39}],31:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {String=} name A name to provide this overload to help identify
* it if any errors occur during the resolving phase of the overload. This
* is purely for debug purposes and serves no functional purpose.
* @param {Object} def The overload definition.
* @returns {Function}
* @constructor
*/
var Overload = function (name, def) {
if (!def) {
def = name;
name = undefined;
}
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
overloadName;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload Definition:', def);
throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['array', 'string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],32:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
DbDocument;
Shared = _dereq_('./Shared');
var Overview = function () {
this.init.apply(this, arguments);
};
Overview.prototype.init = function (name) {
var self = this;
this._name = name;
this._data = new DbDocument('__FDB__dc_data_' + this._name);
this._collData = new Collection();
this._sources = [];
this._sourceDroppedWrap = function () {
self._sourceDropped.apply(self, arguments);
};
};
Shared.addModule('Overview', Overview);
Shared.mixin(Overview.prototype, 'Mixin.Common');
Shared.mixin(Overview.prototype, 'Mixin.ChainReactor');
Shared.mixin(Overview.prototype, 'Mixin.Constants');
Shared.mixin(Overview.prototype, 'Mixin.Triggers');
Shared.mixin(Overview.prototype, 'Mixin.Events');
Shared.mixin(Overview.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
DbDocument = _dereq_('./Document');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Overview.prototype, 'state');
Shared.synthesize(Overview.prototype, 'db');
Shared.synthesize(Overview.prototype, 'name');
Shared.synthesize(Overview.prototype, 'query', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'queryOptions', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'reduce', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Overview.prototype.from = function (source) {
if (source !== undefined) {
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
this._setFrom(source);
return this;
}
return this._sources;
};
Overview.prototype.find = function () {
return this._collData.find.apply(this._collData, arguments);
};
/**
* Executes and returns the response from the current reduce method
* assigned to the overview.
* @returns {*}
*/
Overview.prototype.exec = function () {
var reduceFunc = this.reduce();
return reduceFunc ? reduceFunc.apply(this) : undefined;
};
Overview.prototype.count = function () {
return this._collData.count.apply(this._collData, arguments);
};
Overview.prototype._setFrom = function (source) {
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
this._addSource(source);
return this;
};
Overview.prototype._addSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
if (this._sources.indexOf(source) === -1) {
this._sources.push(source);
source.chain(this);
source.on('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._removeSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
var sourceIndex = this._sources.indexOf(source);
if (sourceIndex > -1) {
this._sources.splice(source, 1);
source.unChain(this);
source.off('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._sourceDropped = function (source) {
if (source) {
// Source was dropped, remove from overview
this._removeSource(source);
}
};
Overview.prototype._refresh = function () {
if (!this.isDropped()) {
if (this._sources && this._sources[0]) {
this._collData.primaryKey(this._sources[0].primaryKey());
var tempArr = [],
i;
for (i = 0; i < this._sources.length; i++) {
tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions));
}
this._collData.setData(tempArr);
}
// Now execute the reduce method
if (this._reduce) {
var reducedData = this._reduce.apply(this);
// Update the document with the newly returned data
this._data.setData(reducedData);
}
}
};
Overview.prototype._chainHandler = function (chainPacket) {
switch (chainPacket.type) {
case 'setData':
case 'insert':
case 'update':
case 'remove':
this._refresh();
break;
default:
break;
}
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
Overview.prototype.data = function () {
return this._data;
};
Overview.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
delete this._data;
delete this._collData;
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
delete this._sources;
if (this._db && this._name) {
delete this._db._overview[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._listeners;
}
return true;
};
Db.prototype.overview = function (name) {
var self = this;
if (name) {
// Handle being passed an instance
if (name instanceof Overview) {
return name;
}
if (this._overview && this._overview[name]) {
return this._overview[name];
}
this._overview = this._overview || {};
this._overview[name] = new Overview(name).db(this);
self.emit('create', self._overview[name], 'overview', name);
return this._overview[name];
} else {
// Return an object of collection data
return this._overview || {};
}
};
/**
* Returns an array of overviews the DB currently has.
* @returns {Array} An array of objects containing details of each overview
* the database is currently managing.
*/
Db.prototype.overviews = function () {
var arr = [],
item,
i;
for (i in this._overview) {
if (this._overview.hasOwnProperty(i)) {
item = this._overview[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Overview');
module.exports = Overview;
},{"./Collection":5,"./Document":9,"./Shared":39}],33:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":39}],34:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared = _dereq_('./Shared'),
async = _dereq_('async'),
localforage = _dereq_('localforage'),
FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line
FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line
Db,
Collection,
CollectionDrop,
CollectionGroup,
CollectionInit,
DbInit,
DbDrop,
Persist,
Overload;//,
//DataVersion = '2.0';
/**
* The persistent storage class handles loading and saving data to browser
* storage.
* @constructor
*/
Persist = function () {
this.init.apply(this, arguments);
};
/**
* The local forage library.
*/
Persist.prototype.localforage = localforage;
/**
* The init method that can be overridden or extended.
* @param {Db} db The ForerunnerDB database instance.
*/
Persist.prototype.init = function (db) {
var self = this;
this._encodeSteps = [
function () { return self._encode.apply(self, arguments); }
];
this._decodeSteps = [
function () { return self._decode.apply(self, arguments); }
];
// Check environment
if (db.isClient()) {
if (window.Storage !== undefined) {
this.mode('localforage');
localforage.config({
driver: [
localforage.INDEXEDDB,
localforage.WEBSQL,
localforage.LOCALSTORAGE
],
name: String(db.core().name()),
storeName: 'FDB'
});
}
}
};
Shared.addModule('Persist', Persist);
Shared.mixin(Persist.prototype, 'Mixin.ChainReactor');
Shared.mixin(Persist.prototype, 'Mixin.Common');
Db = Shared.modules.Db;
Collection = _dereq_('./Collection');
CollectionDrop = Collection.prototype.drop;
CollectionGroup = _dereq_('./CollectionGroup');
CollectionInit = Collection.prototype.init;
DbInit = Db.prototype.init;
DbDrop = Db.prototype.drop;
Overload = Shared.overload;
/**
* Gets / sets the auto flag which determines if the persistence module
* will automatically load data for collections the first time they are
* accessed and save data whenever it changes. This is disabled by
* default.
* @param {Boolean} val Set to true to enable, false to disable
* @returns {*}
*/
Shared.synthesize(Persist.prototype, 'auto', function (val) {
var self = this;
if (val !== undefined) {
if (val) {
// Hook db events
this._db.on('create', function () { self._autoLoad.apply(self, arguments); });
this._db.on('change', function () { self._autoSave.apply(self, arguments); });
if (this._db.debug()) {
console.log(this._db.logIdentifier() + ' Automatic load/save enabled');
}
} else {
// Un-hook db events
this._db.off('create', this._autoLoad);
this._db.off('change', this._autoSave);
if (this._db.debug()) {
console.log(this._db.logIdentifier() + ' Automatic load/save disbled');
}
}
}
return this.$super.call(this, val);
});
Persist.prototype._autoLoad = function (obj, objType, name) {
var self = this;
if (typeof obj.load === 'function') {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-loading data for ' + objType + ':', name);
}
obj.load(function (err, data) {
if (err && self._db.debug()) {
console.log(self._db.logIdentifier() + ' Automatic load failed:', err);
}
self.emit('load', err, data);
});
} else {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-load for ' + objType + ':', name, 'no load method, skipping');
}
}
};
Persist.prototype._autoSave = function (obj, objType, name) {
var self = this;
if (typeof obj.save === 'function') {
if (self._db.debug()) {
console.log(self._db.logIdentifier() + ' Auto-saving data for ' + objType + ':', name);
}
obj.save(function (err, data) {
if (err && self._db.debug()) {
console.log(self._db.logIdentifier() + ' Automatic save failed:', err);
}
self.emit('save', err, data);
});
}
};
/**
* Gets / sets the persistent storage mode (the library used
* to persist data to the browser - defaults to localForage).
* @param {String} type The library to use for storage. Defaults
* to localForage.
* @returns {*}
*/
Persist.prototype.mode = function (type) {
if (type !== undefined) {
this._mode = type;
return this;
}
return this._mode;
};
/**
* Gets / sets the driver used when persisting data.
* @param {String} val Specify the driver type (LOCALSTORAGE,
* WEBSQL or INDEXEDDB)
* @returns {*}
*/
Persist.prototype.driver = function (val) {
if (val !== undefined) {
switch (val.toUpperCase()) {
case 'LOCALSTORAGE':
localforage.setDriver(localforage.LOCALSTORAGE);
break;
case 'WEBSQL':
localforage.setDriver(localforage.WEBSQL);
break;
case 'INDEXEDDB':
localforage.setDriver(localforage.INDEXEDDB);
break;
default:
throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!');
}
return this;
}
return localforage.driver();
};
/**
* Starts a decode waterfall process.
* @param {*} val The data to be decoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.decode = function (val, finished) {
async.waterfall([function (callback) {
if (callback) { callback(false, val, {}); }
}].concat(this._decodeSteps), finished);
};
/**
* Starts an encode waterfall process.
* @param {*} val The data to be encoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.encode = function (val, finished) {
async.waterfall([function (callback) {
if (callback) { callback(false, val, {}); }
}].concat(this._encodeSteps), finished);
};
Shared.synthesize(Persist.prototype, 'encodeSteps');
Shared.synthesize(Persist.prototype, 'decodeSteps');
/**
* Adds an encode/decode step to the persistent storage system so
* that you can add custom functionality.
* @param {Function} encode The encode method called with the data from the
* previous encode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the encoder will fail and throw an error.
* @param {Function} decode The decode method called with the data from the
* previous decode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the decoder will fail and throw an error.
* @param {Number=} index Optional index to add the encoder step to. This
* allows you to place a step before or after other existing steps. If not
* provided your step is placed last in the list of steps. For instance if
* you are providing an encryption step it makes sense to place this last
* since all previous steps will then have their data encrypted by your
* final step.
*/
Persist.prototype.addStep = new Overload({
'object': function (obj) {
this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0);
},
'function, function': function (encode, decode) {
this.$main.call(this, encode, decode, 0);
},
'function, function, number': function (encode, decode, index) {
this.$main.call(this, encode, decode, index);
},
$main: function (encode, decode, index) {
if (index === 0 || index === undefined) {
this._encodeSteps.push(encode);
this._decodeSteps.unshift(decode);
} else {
// Place encoder step at index then work out correct
// index to place decoder step
this._encodeSteps.splice(index, 0, encode);
this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode);
}
}
});
Persist.prototype.unwrap = function (dataStr) {
var parts = dataStr.split('::fdb::'),
data;
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
};
/**
* Takes encoded data and decodes it for use as JS native objects and arrays.
* @param {String} val The currently encoded string data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when decoding is
* completed.
* @private
*/
Persist.prototype._decode = function (val, meta, finished) {
var parts,
data;
if (val) {
parts = val.split('::fdb::');
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length || 0;
} else {
meta.foundData = false;
meta.rowCount = 0;
}
if (finished) {
finished(false, data, meta);
}
} else {
meta.foundData = false;
meta.rowCount = 0;
if (finished) {
finished(false, val, meta);
}
}
};
/**
* Takes native JS data and encodes it for for storage as a string.
* @param {Object} val The current un-encoded data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when encoding is
* completed.
* @private
*/
Persist.prototype._encode = function (val, meta, finished) {
var data = val;
if (typeof val === 'object') {
val = 'json::fdb::' + this.jStringify(val);
} else {
val = 'raw::fdb::' + val;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length || 0;
} else {
meta.foundData = false;
meta.rowCount = 0;
}
if (finished) {
finished(false, val, meta);
}
};
/**
* Encodes passed data and then stores it in the browser's persistent
* storage layer.
* @param {String} key The key to store the data under in the persistent
* storage.
* @param {Object} data The data to store under the key.
* @param {Function=} callback The method to call when the save process
* has completed.
*/
Persist.prototype.save = function (key, data, callback) {
switch (this.mode()) {
case 'localforage':
this.encode(data, function (err, data, tableStats) {
localforage.setItem(key, data).then(function (data) {
if (callback) { callback(false, data, tableStats); }
}, function (err) {
if (callback) { callback(err); }
});
});
break;
default:
if (callback) { callback('No data handler.'); }
break;
}
};
/**
* Loads and decodes data from the passed key.
* @param {String} key The key to retrieve data from in the persistent
* storage.
* @param {Function=} callback The method to call when the load process
* has completed.
*/
Persist.prototype.load = function (key, callback) {
var self = this;
switch (this.mode()) {
case 'localforage':
localforage.getItem(key).then(function (val) {
self.decode(val, callback);
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
/**
* Deletes data in persistent storage stored under the passed key.
* @param {String} key The key to drop data for in the storage.
* @param {Function=} callback The method to call when the data is dropped.
*/
Persist.prototype.drop = function (key, callback) {
switch (this.mode()) {
case 'localforage':
localforage.removeItem(key).then(function () {
if (callback) { callback(false); }
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
// Extend the Collection prototype with persist methods
Collection.prototype.drop = new Overload({
/**
* Drop collection and persistent storage.
*/
'': function () {
if (!this.isDropped()) {
this.drop(true);
}
},
/**
* Drop collection and persistent storage with callback.
* @param {Function} callback Callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
this.drop(true, callback);
}
},
/**
* Drop collection and optionally drop persistent storage.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
*/
'boolean': function (removePersistent) {
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name);
this._db.persist.drop(this._db._name + '-' + this._name + '-metaData');
}
} else {
throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
// Call the original method
CollectionDrop.call(this);
}
},
/**
* Drop collections and optionally drop persistent storage with callback.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
* @param {Function} callback Callback method.
*/
'boolean, function': function (removePersistent, callback) {
var self = this;
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name, function () {
self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback);
});
return CollectionDrop.call(this);
} else {
if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); }
}
} else {
// Call the original method
return CollectionDrop.call(this, callback);
}
}
}
});
/**
* Saves an entire collection's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Collection.prototype.save = function (callback) {
var self = this,
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
// Save the collection data
self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) {
if (!err) {
self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) {
if (callback) { callback(err, data, tableStats, metaStats); }
});
} else {
if (callback) { callback(err); }
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) { callback('Cannot save a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot save a collection with no assigned name!'); }
}
};
/**
* Loads an entire collection's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Collection.prototype.load = function (callback) {
var self = this;
if (self._name) {
if (self._db) {
// Load the collection data
self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) {
if (!err) {
if (data) {
// Remove all previous data
self.remove({});
self.insert(data);
//self.setData(data);
}
// Now load the collection's metadata
self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
}
}
if (callback) { callback(err, tableStats, metaStats); }
});
} else {
if (callback) { callback(err); }
}
});
} else {
if (callback) { callback('Cannot load a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot load a collection with no assigned name!'); }
}
};
/**
* Gets the data that represents this collection for easy storage using
* a third-party method / plugin instead of using the standard persistent
* storage system.
* @param {Function} callback The method to call with the data response.
*/
Collection.prototype.saveCustom = function (callback) {
var self = this,
myData = {},
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
self.encode(self._data, function (err, data, tableStats) {
if (!err) {
myData.data = {
name: self._db._name + '-' + self._name,
store: data,
tableStats: tableStats
};
self.encode(self._data, function (err, data, tableStats) {
if (!err) {
myData.metaData = {
name: self._db._name + '-' + self._name + '-metaData',
store: data,
tableStats: tableStats
};
callback(false, myData);
} else {
callback(err);
}
});
} else {
callback(err);
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) { callback('Cannot save a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot save a collection with no assigned name!'); }
}
};
/**
* Loads custom data loaded by a third-party plugin into the collection.
* @param {Object} myData Data object previously saved by using saveCustom()
* @param {Function} callback A callback method to receive notification when
* data has loaded.
*/
Collection.prototype.loadCustom = function (myData, callback) {
var self = this;
if (self._name) {
if (self._db) {
if (myData.data && myData.data.store) {
if (myData.metaData && myData.metaData.store) {
self.decode(myData.data.store, function (err, data, tableStats) {
if (!err) {
if (data) {
// Remove all previous data
self.remove({});
self.insert(data);
self.decode(myData.metaData.store, function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
if (callback) { callback(err, tableStats, metaStats); }
}
} else {
callback(err);
}
});
}
} else {
callback(err);
}
});
} else {
callback('No "metaData" key found in passed object!');
}
} else {
callback('No "data" key found in passed object!');
}
} else {
if (callback) { callback('Cannot load a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot load a collection with no assigned name!'); }
}
};
// Override the DB init to instantiate the plugin
Db.prototype.init = function () {
DbInit.apply(this, arguments);
this.persist = new Persist(this);
};
Db.prototype.load = new Overload({
/**
* Loads an entire database's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
'function': function (callback) {
this.$main.call(this, {}, callback);
},
'object, function': function (myData, callback) {
this.$main.call(this, myData, callback);
},
'$main': function (myData, callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
loadCallback,
index;
loadCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) {
callback(false);
}
}
} else {
if (callback) {
callback(err);
}
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection load method
if (!myData) {
obj[index].load(loadCallback);
} else {
obj[index].loadCustom(myData, loadCallback);
}
}
}
}
});
Db.prototype.save = new Overload({
/**
* Saves an entire database's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
'function': function (callback) {
this.$main.call(this, {}, callback);
},
'object, function': function (options, callback) {
this.$main.call(this, options, callback);
},
'$main': function (options, callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
saveCallback,
index;
saveCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection save method
if (!options.custom) {
obj[index].save(saveCallback);
} else {
obj[index].saveCustom(saveCallback);
}
}
}
}
});
Shared.finishModule('Persist');
module.exports = Persist;
},{"./Collection":5,"./CollectionGroup":6,"./PersistCompress":35,"./PersistCrypto":36,"./Shared":39,"async":41,"localforage":77}],35:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
pako = _dereq_('pako');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
Plugin.prototype.encode = function (val, meta, finished) {
var wrapper = {
data: val,
type: 'fdbCompress',
enabled: false
},
before,
after,
compressedVal;
// Compress the data
before = val.length;
compressedVal = pako.deflate(val, {to: 'string'});
after = compressedVal.length;
// If the compressed version is smaller than the original, use it!
if (after < before) {
wrapper.data = compressedVal;
wrapper.enabled = true;
}
meta.compression = {
enabled: wrapper.enabled,
compressedBytes: after,
uncompressedBytes: before,
effect: Math.round((100 / before) * after) + '%'
};
finished(false, this.jStringify(wrapper), meta);
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var compressionEnabled = false,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
// Check if we need to decompress the string
if (wrapper.enabled) {
data = pako.inflate(wrapper.data, {to: 'string'});
compressionEnabled = true;
} else {
data = wrapper.data;
compressionEnabled = false;
}
meta.compression = {
enabled: compressionEnabled
};
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, data, meta);
}
}
};
// Register this plugin with ForerunnerDB
Shared.plugins.FdbCompress = Plugin;
module.exports = Plugin;
},{"./Shared":39,"pako":78}],36:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
CryptoJS = _dereq_('crypto-js');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
// Ensure at least a password is passed in options
if (!options || !options.pass) {
throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.');
}
this._algo = options.algo || 'AES';
this._pass = options.pass;
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
/**
* Gets / sets the current pass-phrase being used to encrypt / decrypt
* data with the plugin.
*/
Shared.synthesize(Plugin.prototype, 'pass');
Plugin.prototype.stringify = function (cipherParams) {
// create json object with ciphertext
var jsonObj = {
ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64)
};
// optionally add iv and salt
if (cipherParams.iv) {
jsonObj.iv = cipherParams.iv.toString();
}
if (cipherParams.salt) {
jsonObj.s = cipherParams.salt.toString();
}
// stringify json object
return this.jStringify(jsonObj);
};
Plugin.prototype.parse = function (jsonStr) {
// parse json string
var jsonObj = this.jParse(jsonStr);
// extract ciphertext from json object, and create cipher params object
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
});
// optionally extract iv and salt
if (jsonObj.iv) {
cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
}
if (jsonObj.s) {
cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
}
return cipherParams;
};
Plugin.prototype.encode = function (val, meta, finished) {
var self = this,
wrapper = {
type: 'fdbCrypto'
},
encryptedVal;
// Encrypt the data
encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
});
wrapper.data = encryptedVal.toString();
wrapper.enabled = true;
meta.encryption = {
enabled: wrapper.enabled
};
if (finished) {
finished(false, this.jStringify(wrapper), meta);
}
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var self = this,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
}).toString(CryptoJS.enc.Utf8);
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, wrapper, meta);
}
}
};
// Register this plugin with ForerunnerDB
Shared.plugins.FdbCrypto = Plugin;
module.exports = Plugin;
},{"./Shared":39,"crypto-js":50}],37:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":39}],38:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
var self = this;
this._encoder = [];
this._decoder = [];
// Handler for Date() objects
this.registerHandler('$date', function (objInstance) {
if (objInstance instanceof Date) {
// Augment this date object with a new toJSON method
objInstance.toJSON = function () {
return "$date:" + this.toISOString();
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$date:') === 0) {
return self.convert(new Date(data.substr(6)));
}
return undefined;
});
// Handler for RegExp() objects
this.registerHandler('$regexp', function (objInstance) {
if (objInstance instanceof RegExp) {
objInstance.toJSON = function () {
return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '');
/*return {
source: this.source,
params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '')
};*/
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$regexp:') === 0) {
var dataStr = data.substr(8),//±
lengthEnd = dataStr.indexOf(':'),
sourceLength = Number(dataStr.substr(0, lengthEnd)),
source = dataStr.substr(lengthEnd + 1, sourceLength),
params = dataStr.substr(lengthEnd + sourceLength + 2);
return self.convert(new RegExp(source, params));
}
return undefined;
});
};
Serialiser.prototype.registerHandler = function (handles, encoder, decoder) {
if (handles !== undefined) {
// Register encoder
this._encoder.push(encoder);
// Register decoder
this._decoder.push(decoder);
}
};
Serialiser.prototype.convert = function (data) {
// Run through converters and check for match
var arr = this._encoder,
i;
for (i = 0; i < arr.length; i++) {
if (arr[i](data)) {
// The converter we called matched the object and converted it
// so let's return it now.
return data;
}
}
// No converter matched the object, return the unaltered one
return data;
};
Serialiser.prototype.reviver = function () {
var arr = this._decoder;
return function (key, value) {
// Check if we have a decoder method for this key
var decodedData,
i;
for (i = 0; i < arr.length; i++) {
decodedData = arr[i](value);
if (decodedData !== undefined) {
// The decoder we called matched the object and decoded it
// so let's return it now.
return decodedData;
}
}
// No decoder, return basic value
return value;
};
};
module.exports = Serialiser;
},{}],39:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.720',
modules: {},
plugins: {},
index: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
mixin: new Overload({
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {Object} mixinObj The object containing the keys to mix into
* the target object.
*/
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":18,"./Mixin.ChainReactor":19,"./Mixin.Common":20,"./Mixin.Constants":21,"./Mixin.Events":22,"./Mixin.Matching":23,"./Mixin.Sorting":24,"./Mixin.Tags":25,"./Mixin.Triggers":26,"./Mixin.Updating":27,"./Overload":31}],40:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket,
Overload = _dereq_('./Overload'),
Path,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.Matching');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Shared.mixin(View.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
Path = Shared.modules.Path;
sharedPathSolver = new Path();
View.prototype.init = function (name, query, options) {
var self = this;
this.sharedPathSolver = sharedPathSolver;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._data = new Collection(this.name() + '_internal');
};
/**
* This reactor IO node is given data changes from source data and
* then acts as a firewall process between the source and view data.
* Data needs to meet the requirements this IO node imposes before
* the data is passed down the reactor chain (to the view). This
* allows us to intercept data changes from the data source and act
* on them such as applying transforms, checking the data matches
* the view's query, applying joins to the data etc before sending it
* down the reactor chain via the this.chainSend() calls.
*
* Update packets are especially complex to handle because an update
* on the underlying source data could translate into an insert,
* update or remove call on the view. Take a scenario where the view's
* query limits the data see from the source. If the source data is
* updated and the data now falls inside the view's query limitations
* the data is technically now an insert on the view, not an update.
* The same is true in reverse where the update becomes a remove. If
* the updated data already exists in the view and will still exist
* after the update operation then the update can remain an update.
* @param {Object} chainPacket The chain reactor packet representing the
* data operation that has just been processed on the source data.
* @param {View} self The reference to the view we are operating for.
* @private
*/
View.prototype._handleChainIO = function (chainPacket, self) {
var type = chainPacket.type,
hasActiveJoin,
hasActiveQuery,
hasTransformIn,
sharedData;
// NOTE: "self" in this context is the view instance.
// NOTE: "this" in this context is the ReactorIO node sitting in
// between the source (sender) and the destination (listener) and
// in this case the source is the view's "from" data source and the
// destination is the view's _data collection. This means
// that "this.chainSend()" is asking the ReactorIO node to send the
// packet on to the destination listener.
// EARLY EXIT: Check that the packet is not a CRUD operation
if (type !== 'setData' && type !== 'insert' && type !== 'update' && type !== 'remove') {
// This packet is NOT a CRUD operation packet so exit early!
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
// We only need to check packets under three conditions
// 1) We have a limiting query on the view "active query",
// 2) We have a query options with a $join clause on the view "active join"
// 3) We have a transformIn operation registered on the view.
// If none of these conditions exist we can just allow the chain
// packet to proceed as normal
hasActiveJoin = Boolean(self._querySettings.options && self._querySettings.options.$join);
hasActiveQuery = Boolean(self._querySettings.query);
hasTransformIn = self._data._transformIn !== undefined;
// EARLY EXIT: Check for any complex operation flags and if none
// exist, send the packet on and exit early
if (!hasActiveJoin && !hasActiveQuery && !hasTransformIn) {
// We don't have any complex operation flags so exit early!
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
// We have either an active query, active join or a transformIn
// function registered on the view
// We create a shared data object here so that the disparate method
// calls can share data with each other via this object whilst
// still remaining separate methods to keep code relatively clean.
sharedData = {
dataArr: [],
removeArr: []
};
// Check the packet type to get the data arrays to work on
if (chainPacket.type === 'insert') {
// Check if the insert data is an array
if (chainPacket.data.dataSet instanceof Array) {
// Use the insert data array
sharedData.dataArr = chainPacket.data.dataSet;
} else {
// Generate an array from the single insert object
sharedData.dataArr = [chainPacket.data.dataSet];
}
} else if (chainPacket.type === 'update') {
// Use the dataSet array
sharedData.dataArr = chainPacket.data.dataSet;
} else if (chainPacket.type === 'remove') {
if (chainPacket.data.dataSet instanceof Array) {
// Use the remove data array
sharedData.removeArr = chainPacket.data.dataSet;
} else {
// Generate an array from the single remove object
sharedData.removeArr = [chainPacket.data.dataSet];
}
}
// Safety check
if (!(sharedData.dataArr instanceof Array)) {
// This shouldn't happen, let's log it
console.warn('WARNING: dataArr being processed by chain reactor in View class is inconsistent!');
sharedData.dataArr = [];
}
if (!(sharedData.removeArr instanceof Array)) {
// This shouldn't happen, let's log it
console.warn('WARNING: removeArr being processed by chain reactor in View class is inconsistent!');
sharedData.removeArr = [];
}
// We need to operate in this order:
// 1) Check if there is an active join - active joins are operated
// against the SOURCE data. The joined data can potentially be
// utilised by any active query or transformIn so we do this step first.
// 2) Check if there is an active query - this is a query that is run
// against the SOURCE data after any active joins have been resolved
// on the source data. This allows an active query to operate on data
// that would only exist after an active join has been executed.
// If the source data does not fall inside the limiting factors of the
// active query then we add it to a removal array. If it does fall
// inside the limiting factors when we add it to an upsert array. This
// is because data that falls inside the query could end up being
// either new data or updated data after a transformIn operation.
// 3) Check if there is a transformIn function. If a transformIn function
// exist we run it against the data after doing any active join and
// active query.
if (hasActiveJoin) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin');
}
self._handleChainIO_ActiveJoin(chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin');
}
}
if (hasActiveQuery) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery');
}
self._handleChainIO_ActiveQuery(chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery');
}
}
if (hasTransformIn) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_TransformIn');
}
self._handleChainIO_TransformIn(chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_TransformIn');
}
}
// Check if we still have data to operate on and exit
// if there is none left
if (!sharedData.dataArr.length && !sharedData.removeArr.length) {
// There is no more data to operate on, exit without
// sending any data down the chain reactor (return true
// will tell reactor to exit without continuing)!
return true;
}
// Grab the public data collection's primary key
sharedData.pk = self._data.primaryKey();
// We still have data left, let's work out how to handle it
// first let's loop through the removals as these are easy
if (sharedData.removeArr.length) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_RemovePackets');
}
self._handleChainIO_RemovePackets(this, chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_RemovePackets');
}
}
if (sharedData.dataArr.length) {
if (this.debug()) {
console.time(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets');
}
self._handleChainIO_UpsertPackets(this, chainPacket, sharedData);
if (this.debug()) {
console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets');
}
}
// Now return true to tell the chain reactor not to propagate
// the data itself as we have done all that work here
return true;
};
View.prototype._handleChainIO_ActiveJoin = function (chainPacket, sharedData) {
var dataArr = sharedData.dataArr,
removeArr;
// Since we have an active join, all we need to do is operate
// the join clause on each item in the packet's data array.
removeArr = this.applyJoin(dataArr, this._querySettings.options.$join, {}, {});
// Now that we've run our join keep in mind that joins can exclude data
// if there is no matching joined data and the require: true clause in
// the join options is enabled. This means we have to store a removal
// array that tells us which items from the original data we sent to
// join did not match the join data and were set with a require flag.
// Now that we have our array of items to remove, let's run through the
// original data and remove them from there.
this.spliceArrayByIndexList(dataArr, removeArr);
// Make sure we add any items we removed to the shared removeArr
sharedData.removeArr = sharedData.removeArr.concat(removeArr);
};
View.prototype._handleChainIO_ActiveQuery = function (chainPacket, sharedData) {
var self = this,
dataArr = sharedData.dataArr,
i;
// Now we need to run the data against the active query to
// see if the data should be in the final data list or not,
// so we use the _match method.
// Loop backwards so we can safely splice from the array
// while we are looping
for (i = dataArr.length - 1; i >= 0; i--) {
if (!self._match(dataArr[i], self._querySettings.query, self._querySettings.options, 'and', {})) {
// The data didn't match the active query, add it
// to the shared removeArr
sharedData.removeArr.push(dataArr[i]);
// Now remove it from the shared dataArr
dataArr.splice(i, 1);
}
}
};
View.prototype._handleChainIO_TransformIn = function (chainPacket, sharedData) {
var self = this,
dataArr = sharedData.dataArr,
removeArr = sharedData.removeArr,
dataIn = self._data._transformIn,
i;
// At this stage we take the remaining items still left in the data
// array and run our transformIn method on each one, modifying it
// from what it was to what it should be on the view. We also have
// to run this on items we want to remove too because transforms can
// affect primary keys and therefore stop us from identifying the
// correct items to run removal operations on.
// It is important that these are transformed BEFORE they are passed
// to the CRUD methods because we use the CU data to check the position
// of the item in the array and that can only happen if it is already
// pre-transformed. The removal stuff also needs pre-transformed
// because ids can be modified by a transform.
for (i = 0; i < dataArr.length; i++) {
// Assign the new value
dataArr[i] = dataIn(dataArr[i]);
}
for (i = 0; i < removeArr.length; i++) {
// Assign the new value
removeArr[i] = dataIn(removeArr[i]);
}
};
View.prototype._handleChainIO_RemovePackets = function (ioObj, chainPacket, sharedData) {
var $or = [],
pk = sharedData.pk,
removeArr = sharedData.removeArr,
packet = {
dataSet: removeArr,
query: {
$or: $or
}
},
orObj,
i;
for (i = 0; i < removeArr.length; i++) {
orObj = {};
orObj[pk] = removeArr[i][pk];
$or.push(orObj);
}
ioObj.chainSend('remove', packet);
};
View.prototype._handleChainIO_UpsertPackets = function (ioObj, chainPacket, sharedData) {
var data = this._data,
primaryIndex = data._primaryIndex,
primaryCrc = data._primaryCrc,
pk = sharedData.pk,
dataArr = sharedData.dataArr,
arrItem,
insertArr = [],
updateArr = [],
query,
i;
// Let's work out what type of operation this data should
// generate between an insert or an update.
for (i = 0; i < dataArr.length; i++) {
arrItem = dataArr[i];
// Check if the data already exists in the data
if (primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (primaryCrc.get(arrItem[pk]) !== this.hash(arrItem[pk])) {
// The document exists in the data collection but data differs, update required
updateArr.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
insertArr.push(arrItem);
}
}
if (insertArr.length) {
ioObj.chainSend('insert', {
dataSet: insertArr
});
}
if (updateArr.length) {
for (i = 0; i < updateArr.length; i++) {
arrItem = updateArr[i];
query = {};
query[pk] = arrItem[pk];
ioObj.chainSend('update', {
query: query,
update: arrItem,
dataSet: [arrItem]
});
}
}
};
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Queries the view data for a single document.
* @see Collection::findOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findOne = function (query, options) {
return this._data.findOne(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this._data.findById(id, options);
};
/**
* Queries the view data in a sub-array.
* @see Collection::findSub()
* @returns {Array} The result of the find query.
*/
View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._data.findSub(match, path, subDocQuery, subDocOptions);
};
/**
* Queries the view data in a sub-array and returns first match.
* @see Collection::findSubOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this._data.findSubOne(match, path, subDocQuery, subDocOptions);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._data;
};
/**
* Sets the source from which the view will assemble its data.
* @param {Collection|View} source The source to use to assemble view data.
* @param {Function=} callback A callback method.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (source, callback) {
var self = this;
if (source !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
// Remove the current reference to the _from since we
// are about to replace it with a new one
delete this._from;
}
// Check if we have an existing reactor io that links the
// previous _from source to the view's internal data
if (this._io) {
// Drop the io and remove it
this._io.drop();
delete this._io;
}
// Check if we were passed a source name rather than a
// reference to a source object
if (typeof(source) === 'string') {
// We were passed a name, assume it is a collection and
// get the reference to the collection of that name
source = this._db.collection(source);
}
// Check if we were passed a reference to a view rather than
// a collection. Views need to be handled slightly differently
// since their data is stored in an internal data collection
// rather than actually being a direct data source themselves.
if (source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source._data;
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
// Assign the new data source as the view's _from
this._from = source;
// Hook the new data source's drop event so we can unhook
// it as a data source if it gets dropped. This is important
// so that we don't run into problems using a dropped source
// for active data.
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's _from source and determines how they should be interpreted by
// this view. See the _handleChainIO() method which does all the chain packet
// processing for the view.
this._io = new ReactorIO(this._from, this, function (chainPacket) { return self._handleChainIO.call(this, chainPacket, self); });
// Set the view's internal data primary key to the same as the
// current active _from data source
this._data.primaryKey(source.primaryKey());
// Do the initial data lookup and populate the view's internal data
// since at this point we don't actually have any data in the view
// yet.
var collData = source.find(this._querySettings.query, this._querySettings.options);
this._data.setData(collData, {}, callback);
// If we have an active query and that query has an $orderBy clause,
// update our active bucket which allows us to keep track of where
// data should be placed in our internal data array. This is about
// ordering of data and making sure that we maintain an ordered array
// so that if we have data-binding we can place an item in the data-
// bound view at the correct location. Active buckets use quick-sort
// algorithms to quickly determine the position of an item inside an
// existing array based on a sort protocol.
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
updates,
primaryKey,
item,
currentIndex;
if (this.debug()) {
console.log(this.logIdentifier() + ' Received chain reactor data: ' + chainPacket.type);
}
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._data.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
this._data.setData(collData);
// Rebuild active bucket as well
this.rebuildActiveBucket(this._querySettings.options);
break;
case 'insert':
if (this.debug()) {
console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._data.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet);
// Make sure we are working with an array
if (!(chainPacket.data.dataSet instanceof Array)) {
chainPacket.data.dataSet = [chainPacket.data.dataSet];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data.dataSet;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
this._data._insertHandle(arr[index], insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._data._data.length;
this._data._insertHandle(chainPacket.data.dataSet, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._data.name() + '"');
}
primaryKey = this._data.primaryKey();
// Do the update
updates = this._data._handleUpdate(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._data._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._data._updateSpliceMove(this._data._data, currentIndex, insertIndex);
}
}
}
break;
case 'remove':
if (this.debug()) {
console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._data.name() + '"');
}
this._data.remove(chainPacket.data.query, chainPacket.options);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the dataSet and remove the objects from the ActiveBucket
arr = chainPacket.data.dataSet;
count = arr.length;
for (index = 0; index < count; index++) {
this._activeBucket.remove(arr[index]);
}
}
break;
default:
break;
}
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._data.ensureIndex.apply(this._data, arguments);
};
/**
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._data.on.apply(this._data, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._data.off.apply(this._data, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._data.emit.apply(this._data, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::deferEmit()
*/
View.prototype.deferEmit = function () {
return this._data.deferEmit.apply(this._data, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
return this._data.distinct(key, query, options);
};
/**
* Gets the primary key for this view from the assigned collection.
* @see Collection::primaryKey()
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this._data.primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._data) {
this._data.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._chain;
delete this._from;
delete this._data;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
return false;
};
/**
* Gets / sets the query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
* @deprecated Use query(<query>, <options>, <refresh>) instead. Query
* now supports being presented with multiple different variations of
* arguments.
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._data.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._data.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
if (query !== undefined) {
this.emit('queryChange', query);
}
if (options !== undefined) {
this.emit('queryOptionsChange', options);
}
if (query !== undefined || options !== undefined) {
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
if (query !== undefined) {
this.emit('queryChange', query);
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
if (query !== undefined) {
this.emit('queryChange', query);
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = new Overload({
'': function () {
return this._querySettings.query;
},
'object': function (query) {
return this.$main.call(this, query, undefined, true);
},
'*, boolean': function (query, refresh) {
return this.$main.call(this, query, undefined, refresh);
},
'object, object': function (query, options) {
return this.$main.call(this, query, options, true);
},
'*, *, boolean': function (query, options, refresh) {
return this.$main.call(this, query, options, refresh);
},
'$main': function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (query.$findSub && !query.$findSub.$from) {
query.$findSub.$from = this._data.name();
}
if (query.$findSubOne && !query.$findSubOne.$from) {
query.$findSubOne.$from = this._data.name();
}
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
if (query !== undefined) {
this.emit('queryChange', query);
}
if (options !== undefined) {
this.emit('queryOptionsChange', options);
}
if (query !== undefined || options !== undefined) {
return this;
}
return this._querySettings;
}
});
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
// TODO: This could be wasteful if the previous options $orderBy was identical, do a hash and check first!
this.rebuildActiveBucket(options.$orderBy);
}
if (options !== undefined) {
this.emit('queryOptionsChange', options);
}
return this;
}
return this._querySettings.options;
};
/**
* Clears the existing active bucket and builds a new one based
* on the passed orderBy object (if one is passed).
* @param {Object=} orderBy The orderBy object describing how to
* order any data.
*/
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._data._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._data.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
var self = this,
refreshResults,
joinArr,
i, k;
if (this._from) {
// Clear the private data collection which will propagate to the public data
// collection automatically via the chain reactor node between them
this._data.remove();
// Grab all the data from the underlying data source
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
// Insert the underlying data into the private data collection
this._data.insert(refreshResults);
// Store the current cursor data
this._data._data.$cursor = refreshResults.$cursor;
this._data._data.$cursor = refreshResults.$cursor;
}
if (this._querySettings && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) {
// Define the change handler method
self.__joinChange = self.__joinChange || function () {
self._joinChange();
};
// Check for existing join collections
if (this._joinCollections && this._joinCollections.length) {
// Loop the join collections and remove change listeners
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange);
}
}
// Now start hooking any new / existing joins
joinArr = this._querySettings.options.$join;
this._joinCollections = [];
// Loop the joined collections and hook change events
for (i = 0; i < joinArr.length; i++) {
for (k in joinArr[i]) {
if (joinArr[i].hasOwnProperty(k)) {
this._joinCollections.push(k);
}
}
}
if (this._joinCollections.length) {
// Loop the collections and hook change events
for (i = 0; i < this._joinCollections.length; i++) {
this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange);
}
}
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Handles when a change has occurred on a collection that is joined
* by query to this view.
* @param objName
* @param objType
* @private
*/
View.prototype._joinChange = function (objName, objType) {
this.emit('joinChange');
// TODO: This is a really dirty solution because it will require a complete
// TODO: rebuild of the view data. We need to implement an IO handler to
// TODO: selectively update the data of the view based on the joined
// TODO: collection data operation.
// FIXME: This isnt working, major performance killer, invest in some IO from chain reactor to make this a targeted call
this.refresh();
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
return this._data.count.apply(this._data, arguments);
};
// Call underlying
View.prototype.subset = function () {
return this._data.subset.apply(this._data, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn"
* and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
var currentSettings,
newSettings;
currentSettings = this._data.transform();
this._data.transform(obj);
newSettings = this._data.transform();
// Check if transforms are enabled, a dataIn method is set and these
// settings did not match the previous transform settings
if (newSettings.enabled && newSettings.dataIn && (currentSettings.enabled !== newSettings.enabled || currentSettings.dataIn !== newSettings.dataIn)) {
// The data in the view is now stale, refresh it
this.refresh();
}
return newSettings;
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return this._data.filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.data = function () {
return this._data;
};
/**
* @see Collection.indexOf
* @returns {*}
*/
View.prototype.indexOf = function () {
return this._data.indexOf.apply(this._data, arguments);
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @memberof View
* @returns {*}
*/
Shared.synthesize(View.prototype, 'db', function (db) {
if (db) {
this._data.db(db);
// Apply the same debug settings
this.debug(db.debug());
this._data.debug(db.debug());
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} name The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (name) {
var self = this;
// Handle being passed an instance
if (name instanceof View) {
return name;
}
if (this._view[name]) {
return this._view[name];
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating view ' + name);
}
this._view[name] = new View(name).db(this);
self.emit('create', self._view[name], 'view', name);
return this._view[name];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} name The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (name) {
return Boolean(this._view[name]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":2,"./Collection":5,"./CollectionGroup":6,"./Overload":31,"./ReactorIO":37,"./Shared":39}],41:[function(_dereq_,module,exports){
(function (process,global){
/*!
* async
* https://github.com/caolan/async
*
* Copyright 2010-2014 Caolan McMahon
* Released under the MIT license
*/
(function () {
var async = {};
function noop() {}
function identity(v) {
return v;
}
function toBool(v) {
return !!v;
}
function notId(v) {
return !v;
}
// global on the server, window in the browser
var previous_async;
// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
var root = typeof self === 'object' && self.self === self && self ||
typeof global === 'object' && global.global === global && global ||
this;
if (root != null) {
previous_async = root.async;
}
async.noConflict = function () {
root.async = previous_async;
return async;
};
function only_once(fn) {
return function() {
if (fn === null) throw new Error("Callback was already called.");
fn.apply(this, arguments);
fn = null;
};
}
function _once(fn) {
return function() {
if (fn === null) return;
fn.apply(this, arguments);
fn = null;
};
}
//// cross-browser compatiblity functions ////
var _toString = Object.prototype.toString;
var _isArray = Array.isArray || function (obj) {
return _toString.call(obj) === '[object Array]';
};
// Ported from underscore.js isObject
var _isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
function _isArrayLike(arr) {
return _isArray(arr) || (
// has a positive integer length property
typeof arr.length === "number" &&
arr.length >= 0 &&
arr.length % 1 === 0
);
}
function _arrayEach(arr, iterator) {
var index = -1,
length = arr.length;
while (++index < length) {
iterator(arr[index], index, arr);
}
}
function _map(arr, iterator) {
var index = -1,
length = arr.length,
result = Array(length);
while (++index < length) {
result[index] = iterator(arr[index], index, arr);
}
return result;
}
function _range(count) {
return _map(Array(count), function (v, i) { return i; });
}
function _reduce(arr, iterator, memo) {
_arrayEach(arr, function (x, i, a) {
memo = iterator(memo, x, i, a);
});
return memo;
}
function _forEachOf(object, iterator) {
_arrayEach(_keys(object), function (key) {
iterator(object[key], key);
});
}
function _indexOf(arr, item) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) return i;
}
return -1;
}
var _keys = Object.keys || function (obj) {
var keys = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
};
function _keyIterator(coll) {
var i = -1;
var len;
var keys;
if (_isArrayLike(coll)) {
len = coll.length;
return function next() {
i++;
return i < len ? i : null;
};
} else {
keys = _keys(coll);
len = keys.length;
return function next() {
i++;
return i < len ? keys[i] : null;
};
}
}
// Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
// This accumulates the arguments passed into an array, after a given index.
// From underscore.js (https://github.com/jashkenas/underscore/pull/2140).
function _restParam(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function() {
var length = Math.max(arguments.length - startIndex, 0);
var rest = Array(length);
for (var index = 0; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0: return func.call(this, rest);
case 1: return func.call(this, arguments[0], rest);
}
// Currently unused but handle cases outside of the switch statement:
// var args = Array(startIndex + 1);
// for (index = 0; index < startIndex; index++) {
// args[index] = arguments[index];
// }
// args[startIndex] = rest;
// return func.apply(this, args);
};
}
function _withoutIndex(iterator) {
return function (value, index, callback) {
return iterator(value, callback);
};
}
//// exported async module functions ////
//// nextTick implementation with browser-compatible fallback ////
// capture the global reference to guard against fakeTimer mocks
var _setImmediate = typeof setImmediate === 'function' && setImmediate;
var _delay = _setImmediate ? function(fn) {
// not a direct alias for IE10 compatibility
_setImmediate(fn);
} : function(fn) {
setTimeout(fn, 0);
};
if (typeof process === 'object' && typeof process.nextTick === 'function') {
async.nextTick = process.nextTick;
} else {
async.nextTick = _delay;
}
async.setImmediate = _setImmediate ? _delay : async.nextTick;
async.forEach =
async.each = function (arr, iterator, callback) {
return async.eachOf(arr, _withoutIndex(iterator), callback);
};
async.forEachSeries =
async.eachSeries = function (arr, iterator, callback) {
return async.eachOfSeries(arr, _withoutIndex(iterator), callback);
};
async.forEachLimit =
async.eachLimit = function (arr, limit, iterator, callback) {
return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback);
};
async.forEachOf =
async.eachOf = function (object, iterator, callback) {
callback = _once(callback || noop);
object = object || [];
var iter = _keyIterator(object);
var key, completed = 0;
while ((key = iter()) != null) {
completed += 1;
iterator(object[key], key, only_once(done));
}
if (completed === 0) callback(null);
function done(err) {
completed--;
if (err) {
callback(err);
}
// Check key is null in case iterator isn't exhausted
// and done resolved synchronously.
else if (key === null && completed <= 0) {
callback(null);
}
}
};
async.forEachOfSeries =
async.eachOfSeries = function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
var key = nextKey();
function iterate() {
var sync = true;
if (key === null) {
return callback(null);
}
iterator(obj[key], key, only_once(function (err) {
if (err) {
callback(err);
}
else {
key = nextKey();
if (key === null) {
return callback(null);
} else {
if (sync) {
async.setImmediate(iterate);
} else {
iterate();
}
}
}
}));
sync = false;
}
iterate();
};
async.forEachOfLimit =
async.eachOfLimit = function (obj, limit, iterator, callback) {
_eachOfLimit(limit)(obj, iterator, callback);
};
function _eachOfLimit(limit) {
return function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
if (limit <= 0) {
return callback(null);
}
var done = false;
var running = 0;
var errored = false;
(function replenish () {
if (done && running <= 0) {
return callback(null);
}
while (running < limit && !errored) {
var key = nextKey();
if (key === null) {
done = true;
if (running <= 0) {
callback(null);
}
return;
}
running += 1;
iterator(obj[key], key, only_once(function (err) {
running -= 1;
if (err) {
callback(err);
errored = true;
}
else {
replenish();
}
}));
}
})();
};
}
function doParallel(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOf, obj, iterator, callback);
};
}
function doParallelLimit(fn) {
return function (obj, limit, iterator, callback) {
return fn(_eachOfLimit(limit), obj, iterator, callback);
};
}
function doSeries(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOfSeries, obj, iterator, callback);
};
}
function _asyncMap(eachfn, arr, iterator, callback) {
callback = _once(callback || noop);
arr = arr || [];
var results = _isArrayLike(arr) ? [] : {};
eachfn(arr, function (value, index, callback) {
iterator(value, function (err, v) {
results[index] = v;
callback(err);
});
}, function (err) {
callback(err, results);
});
}
async.map = doParallel(_asyncMap);
async.mapSeries = doSeries(_asyncMap);
async.mapLimit = doParallelLimit(_asyncMap);
// reduce only has a series version, as doing reduce in parallel won't
// work in many situations.
async.inject =
async.foldl =
async.reduce = function (arr, memo, iterator, callback) {
async.eachOfSeries(arr, function (x, i, callback) {
iterator(memo, x, function (err, v) {
memo = v;
callback(err);
});
}, function (err) {
callback(err, memo);
});
};
async.foldr =
async.reduceRight = function (arr, memo, iterator, callback) {
var reversed = _map(arr, identity).reverse();
async.reduce(reversed, memo, iterator, callback);
};
async.transform = function (arr, memo, iterator, callback) {
if (arguments.length === 3) {
callback = iterator;
iterator = memo;
memo = _isArray(arr) ? [] : {};
}
async.eachOf(arr, function(v, k, cb) {
iterator(memo, v, k, cb);
}, function(err) {
callback(err, memo);
});
};
function _filter(eachfn, arr, iterator, callback) {
var results = [];
eachfn(arr, function (x, index, callback) {
iterator(x, function (v) {
if (v) {
results.push({index: index, value: x});
}
callback();
});
}, function () {
callback(_map(results.sort(function (a, b) {
return a.index - b.index;
}), function (x) {
return x.value;
}));
});
}
async.select =
async.filter = doParallel(_filter);
async.selectLimit =
async.filterLimit = doParallelLimit(_filter);
async.selectSeries =
async.filterSeries = doSeries(_filter);
function _reject(eachfn, arr, iterator, callback) {
_filter(eachfn, arr, function(value, cb) {
iterator(value, function(v) {
cb(!v);
});
}, callback);
}
async.reject = doParallel(_reject);
async.rejectLimit = doParallelLimit(_reject);
async.rejectSeries = doSeries(_reject);
function _createTester(eachfn, check, getResult) {
return function(arr, limit, iterator, cb) {
function done() {
if (cb) cb(getResult(false, void 0));
}
function iteratee(x, _, callback) {
if (!cb) return callback();
iterator(x, function (v) {
if (cb && check(v)) {
cb(getResult(true, x));
cb = iterator = false;
}
callback();
});
}
if (arguments.length > 3) {
eachfn(arr, limit, iteratee, done);
} else {
cb = iterator;
iterator = limit;
eachfn(arr, iteratee, done);
}
};
}
async.any =
async.some = _createTester(async.eachOf, toBool, identity);
async.someLimit = _createTester(async.eachOfLimit, toBool, identity);
async.all =
async.every = _createTester(async.eachOf, notId, notId);
async.everyLimit = _createTester(async.eachOfLimit, notId, notId);
function _findGetResult(v, x) {
return x;
}
async.detect = _createTester(async.eachOf, identity, _findGetResult);
async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult);
async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult);
async.sortBy = function (arr, iterator, callback) {
async.map(arr, function (x, callback) {
iterator(x, function (err, criteria) {
if (err) {
callback(err);
}
else {
callback(null, {value: x, criteria: criteria});
}
});
}, function (err, results) {
if (err) {
return callback(err);
}
else {
callback(null, _map(results.sort(comparator), function (x) {
return x.value;
}));
}
});
function comparator(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}
};
async.auto = function (tasks, concurrency, callback) {
if (!callback) {
// concurrency is optional, shift the args.
callback = concurrency;
concurrency = null;
}
callback = _once(callback || noop);
var keys = _keys(tasks);
var remainingTasks = keys.length;
if (!remainingTasks) {
return callback(null);
}
if (!concurrency) {
concurrency = remainingTasks;
}
var results = {};
var runningTasks = 0;
var listeners = [];
function addListener(fn) {
listeners.unshift(fn);
}
function removeListener(fn) {
var idx = _indexOf(listeners, fn);
if (idx >= 0) listeners.splice(idx, 1);
}
function taskComplete() {
remainingTasks--;
_arrayEach(listeners.slice(0), function (fn) {
fn();
});
}
addListener(function () {
if (!remainingTasks) {
callback(null, results);
}
});
_arrayEach(keys, function (k) {
var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
var taskCallback = _restParam(function(err, args) {
runningTasks--;
if (args.length <= 1) {
args = args[0];
}
if (err) {
var safeResults = {};
_forEachOf(results, function(val, rkey) {
safeResults[rkey] = val;
});
safeResults[k] = args;
callback(err, safeResults);
}
else {
results[k] = args;
async.setImmediate(taskComplete);
}
});
var requires = task.slice(0, task.length - 1);
// prevent dead-locks
var len = requires.length;
var dep;
while (len--) {
if (!(dep = tasks[requires[len]])) {
throw new Error('Has inexistant dependency');
}
if (_isArray(dep) && _indexOf(dep, k) >= 0) {
throw new Error('Has cyclic dependencies');
}
}
function ready() {
return runningTasks < concurrency && _reduce(requires, function (a, x) {
return (a && results.hasOwnProperty(x));
}, true) && !results.hasOwnProperty(k);
}
if (ready()) {
runningTasks++;
task[task.length - 1](taskCallback, results);
}
else {
addListener(listener);
}
function listener() {
if (ready()) {
runningTasks++;
removeListener(listener);
task[task.length - 1](taskCallback, results);
}
}
});
};
async.retry = function(times, task, callback) {
var DEFAULT_TIMES = 5;
var DEFAULT_INTERVAL = 0;
var attempts = [];
var opts = {
times: DEFAULT_TIMES,
interval: DEFAULT_INTERVAL
};
function parseTimes(acc, t){
if(typeof t === 'number'){
acc.times = parseInt(t, 10) || DEFAULT_TIMES;
} else if(typeof t === 'object'){
acc.times = parseInt(t.times, 10) || DEFAULT_TIMES;
acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL;
} else {
throw new Error('Unsupported argument type for \'times\': ' + typeof t);
}
}
var length = arguments.length;
if (length < 1 || length > 3) {
throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)');
} else if (length <= 2 && typeof times === 'function') {
callback = task;
task = times;
}
if (typeof times !== 'function') {
parseTimes(opts, times);
}
opts.callback = callback;
opts.task = task;
function wrappedTask(wrappedCallback, wrappedResults) {
function retryAttempt(task, finalAttempt) {
return function(seriesCallback) {
task(function(err, result){
seriesCallback(!err || finalAttempt, {err: err, result: result});
}, wrappedResults);
};
}
function retryInterval(interval){
return function(seriesCallback){
setTimeout(function(){
seriesCallback(null);
}, interval);
};
}
while (opts.times) {
var finalAttempt = !(opts.times-=1);
attempts.push(retryAttempt(opts.task, finalAttempt));
if(!finalAttempt && opts.interval > 0){
attempts.push(retryInterval(opts.interval));
}
}
async.series(attempts, function(done, data){
data = data[data.length - 1];
(wrappedCallback || opts.callback)(data.err, data.result);
});
}
// If a callback is passed, run this as a controll flow
return opts.callback ? wrappedTask() : wrappedTask;
};
async.waterfall = function (tasks, callback) {
callback = _once(callback || noop);
if (!_isArray(tasks)) {
var err = new Error('First argument to waterfall must be an array of functions');
return callback(err);
}
if (!tasks.length) {
return callback();
}
function wrapIterator(iterator) {
return _restParam(function (err, args) {
if (err) {
callback.apply(null, [err].concat(args));
}
else {
var next = iterator.next();
if (next) {
args.push(wrapIterator(next));
}
else {
args.push(callback);
}
ensureAsync(iterator).apply(null, args);
}
});
}
wrapIterator(async.iterator(tasks))();
};
function _parallel(eachfn, tasks, callback) {
callback = callback || noop;
var results = _isArrayLike(tasks) ? [] : {};
eachfn(tasks, function (task, key, callback) {
task(_restParam(function (err, args) {
if (args.length <= 1) {
args = args[0];
}
results[key] = args;
callback(err);
}));
}, function (err) {
callback(err, results);
});
}
async.parallel = function (tasks, callback) {
_parallel(async.eachOf, tasks, callback);
};
async.parallelLimit = function(tasks, limit, callback) {
_parallel(_eachOfLimit(limit), tasks, callback);
};
async.series = function(tasks, callback) {
_parallel(async.eachOfSeries, tasks, callback);
};
async.iterator = function (tasks) {
function makeCallback(index) {
function fn() {
if (tasks.length) {
tasks[index].apply(null, arguments);
}
return fn.next();
}
fn.next = function () {
return (index < tasks.length - 1) ? makeCallback(index + 1): null;
};
return fn;
}
return makeCallback(0);
};
async.apply = _restParam(function (fn, args) {
return _restParam(function (callArgs) {
return fn.apply(
null, args.concat(callArgs)
);
});
});
function _concat(eachfn, arr, fn, callback) {
var result = [];
eachfn(arr, function (x, index, cb) {
fn(x, function (err, y) {
result = result.concat(y || []);
cb(err);
});
}, function (err) {
callback(err, result);
});
}
async.concat = doParallel(_concat);
async.concatSeries = doSeries(_concat);
async.whilst = function (test, iterator, callback) {
callback = callback || noop;
if (test()) {
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else if (test.apply(this, args)) {
iterator(next);
} else {
callback(null);
}
});
iterator(next);
} else {
callback(null);
}
};
async.doWhilst = function (iterator, test, callback) {
var calls = 0;
return async.whilst(function() {
return ++calls <= 1 || test.apply(this, arguments);
}, iterator, callback);
};
async.until = function (test, iterator, callback) {
return async.whilst(function() {
return !test.apply(this, arguments);
}, iterator, callback);
};
async.doUntil = function (iterator, test, callback) {
return async.doWhilst(iterator, function() {
return !test.apply(this, arguments);
}, callback);
};
async.during = function (test, iterator, callback) {
callback = callback || noop;
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else {
args.push(check);
test.apply(this, args);
}
});
var check = function(err, truth) {
if (err) {
callback(err);
} else if (truth) {
iterator(next);
} else {
callback(null);
}
};
test(check);
};
async.doDuring = function (iterator, test, callback) {
var calls = 0;
async.during(function(next) {
if (calls++ < 1) {
next(null, true);
} else {
test.apply(this, arguments);
}
}, iterator, callback);
};
function _queue(worker, concurrency, payload) {
if (concurrency == null) {
concurrency = 1;
}
else if(concurrency === 0) {
throw new Error('Concurrency must not be zero');
}
function _insert(q, data, pos, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0 && q.idle()) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
callback: callback || noop
};
if (pos) {
q.tasks.unshift(item);
} else {
q.tasks.push(item);
}
if (q.tasks.length === q.concurrency) {
q.saturated();
}
});
async.setImmediate(q.process);
}
function _next(q, tasks) {
return function(){
workers -= 1;
var removed = false;
var args = arguments;
_arrayEach(tasks, function (task) {
_arrayEach(workersList, function (worker, index) {
if (worker === task && !removed) {
workersList.splice(index, 1);
removed = true;
}
});
task.callback.apply(task, args);
});
if (q.tasks.length + workers === 0) {
q.drain();
}
q.process();
};
}
var workers = 0;
var workersList = [];
var q = {
tasks: [],
concurrency: concurrency,
payload: payload,
saturated: noop,
empty: noop,
drain: noop,
started: false,
paused: false,
push: function (data, callback) {
_insert(q, data, false, callback);
},
kill: function () {
q.drain = noop;
q.tasks = [];
},
unshift: function (data, callback) {
_insert(q, data, true, callback);
},
process: function () {
if (!q.paused && workers < q.concurrency && q.tasks.length) {
while(workers < q.concurrency && q.tasks.length){
var tasks = q.payload ?
q.tasks.splice(0, q.payload) :
q.tasks.splice(0, q.tasks.length);
var data = _map(tasks, function (task) {
return task.data;
});
if (q.tasks.length === 0) {
q.empty();
}
workers += 1;
workersList.push(tasks[0]);
var cb = only_once(_next(q, tasks));
worker(data, cb);
}
}
},
length: function () {
return q.tasks.length;
},
running: function () {
return workers;
},
workersList: function () {
return workersList;
},
idle: function() {
return q.tasks.length + workers === 0;
},
pause: function () {
q.paused = true;
},
resume: function () {
if (q.paused === false) { return; }
q.paused = false;
var resumeCount = Math.min(q.concurrency, q.tasks.length);
// Need to call q.process once per concurrent
// worker to preserve full concurrency after pause
for (var w = 1; w <= resumeCount; w++) {
async.setImmediate(q.process);
}
}
};
return q;
}
async.queue = function (worker, concurrency) {
var q = _queue(function (items, cb) {
worker(items[0], cb);
}, concurrency, 1);
return q;
};
async.priorityQueue = function (worker, concurrency) {
function _compareTasks(a, b){
return a.priority - b.priority;
}
function _binarySearch(sequence, item, compare) {
var beg = -1,
end = sequence.length - 1;
while (beg < end) {
var mid = beg + ((end - beg + 1) >>> 1);
if (compare(item, sequence[mid]) >= 0) {
beg = mid;
} else {
end = mid - 1;
}
}
return beg;
}
function _insert(q, data, priority, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
priority: priority,
callback: typeof callback === 'function' ? callback : noop
};
q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
if (q.tasks.length === q.concurrency) {
q.saturated();
}
async.setImmediate(q.process);
});
}
// Start with a normal queue
var q = async.queue(worker, concurrency);
// Override push to accept second parameter representing priority
q.push = function (data, priority, callback) {
_insert(q, data, priority, callback);
};
// Remove unshift function
delete q.unshift;
return q;
};
async.cargo = function (worker, payload) {
return _queue(worker, 1, payload);
};
function _console_fn(name) {
return _restParam(function (fn, args) {
fn.apply(null, args.concat([_restParam(function (err, args) {
if (typeof console === 'object') {
if (err) {
if (console.error) {
console.error(err);
}
}
else if (console[name]) {
_arrayEach(args, function (x) {
console[name](x);
});
}
}
})]));
});
}
async.log = _console_fn('log');
async.dir = _console_fn('dir');
/*async.info = _console_fn('info');
async.warn = _console_fn('warn');
async.error = _console_fn('error');*/
async.memoize = function (fn, hasher) {
var memo = {};
var queues = {};
hasher = hasher || identity;
var memoized = _restParam(function memoized(args) {
var callback = args.pop();
var key = hasher.apply(null, args);
if (key in memo) {
async.setImmediate(function () {
callback.apply(null, memo[key]);
});
}
else if (key in queues) {
queues[key].push(callback);
}
else {
queues[key] = [callback];
fn.apply(null, args.concat([_restParam(function (args) {
memo[key] = args;
var q = queues[key];
delete queues[key];
for (var i = 0, l = q.length; i < l; i++) {
q[i].apply(null, args);
}
})]));
}
});
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
};
async.unmemoize = function (fn) {
return function () {
return (fn.unmemoized || fn).apply(null, arguments);
};
};
function _times(mapper) {
return function (count, iterator, callback) {
mapper(_range(count), iterator, callback);
};
}
async.times = _times(async.map);
async.timesSeries = _times(async.mapSeries);
async.timesLimit = function (count, limit, iterator, callback) {
return async.mapLimit(_range(count), limit, iterator, callback);
};
async.seq = function (/* functions... */) {
var fns = arguments;
return _restParam(function (args) {
var that = this;
var callback = args[args.length - 1];
if (typeof callback == 'function') {
args.pop();
} else {
callback = noop;
}
async.reduce(fns, args, function (newargs, fn, cb) {
fn.apply(that, newargs.concat([_restParam(function (err, nextargs) {
cb(err, nextargs);
})]));
},
function (err, results) {
callback.apply(that, [err].concat(results));
});
});
};
async.compose = function (/* functions... */) {
return async.seq.apply(null, Array.prototype.reverse.call(arguments));
};
function _applyEach(eachfn) {
return _restParam(function(fns, args) {
var go = _restParam(function(args) {
var that = this;
var callback = args.pop();
return eachfn(fns, function (fn, _, cb) {
fn.apply(that, args.concat([cb]));
},
callback);
});
if (args.length) {
return go.apply(this, args);
}
else {
return go;
}
});
}
async.applyEach = _applyEach(async.eachOf);
async.applyEachSeries = _applyEach(async.eachOfSeries);
async.forever = function (fn, callback) {
var done = only_once(callback || noop);
var task = ensureAsync(fn);
function next(err) {
if (err) {
return done(err);
}
task(next);
}
next();
};
function ensureAsync(fn) {
return _restParam(function (args) {
var callback = args.pop();
args.push(function () {
var innerArgs = arguments;
if (sync) {
async.setImmediate(function () {
callback.apply(null, innerArgs);
});
} else {
callback.apply(null, innerArgs);
}
});
var sync = true;
fn.apply(this, args);
sync = false;
});
}
async.ensureAsync = ensureAsync;
async.constant = _restParam(function(values) {
var args = [null].concat(values);
return function (callback) {
return callback.apply(this, args);
};
});
async.wrapSync =
async.asyncify = function asyncify(func) {
return _restParam(function (args) {
var callback = args.pop();
var result;
try {
result = func.apply(this, args);
} catch (e) {
return callback(e);
}
// if result is Promise object
if (_isObject(result) && typeof result.then === "function") {
result.then(function(value) {
callback(null, value);
})["catch"](function(err) {
callback(err.message ? err : new Error(err));
});
} else {
callback(null, result);
}
});
};
// Node.js
if (typeof module === 'object' && module.exports) {
module.exports = async;
}
// AMD / RequireJS
else if (typeof define === 'function' && define.amd) {
define([], function () {
return async;
});
}
// included directly via <script> tag
else {
root.async = async;
}
}());
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":76}],42:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
var t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
// Mix Rcon
t ^= RCON[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
return CryptoJS.AES;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],43:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
var block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
}
}
return CBC;
}());
/**
* Padding namespace.
*/
var C_pad = C.pad = {};
/**
* PKCS #5/7 padding strategy.
*/
var Pkcs7 = C_pad.Pkcs7 = {
/**
* Pads data using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to pad.
* @param {number} blockSize The multiple that the data should be padded to.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.pad(wordArray, 4);
*/
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Create padding word
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
// Create padding
var paddingWords = [];
for (var i = 0; i < nPaddingBytes; i += 4) {
paddingWords.push(paddingWord);
}
var padding = WordArray.create(paddingWords, nPaddingBytes);
// Add padding
data.concat(padding);
},
/**
* Unpads data that had been padded using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to unpad.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.unpad(wordArray);
*/
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
/**
* Abstract base block cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
*/
var BlockCipher = C_lib.BlockCipher = Cipher.extend({
/**
* Configuration options.
*
* @property {Mode} mode The block mode to use. Default: CBC
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
*/
cfg: Cipher.cfg.extend({
mode: CBC,
padding: Pkcs7
}),
reset: function () {
// Reset cipher
Cipher.reset.call(this);
// Shortcuts
var cfg = this.cfg;
var iv = cfg.iv;
var mode = cfg.mode;
// Reset block mode
if (this._xformMode == this._ENC_XFORM_MODE) {
var modeCreator = mode.createEncryptor;
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
var modeCreator = mode.createDecryptor;
// Keep at least one block in the buffer for unpadding
this._minBufferSize = 1;
}
this._mode = modeCreator.call(mode, this, iv && iv.words);
},
_doProcessBlock: function (words, offset) {
this._mode.processBlock(words, offset);
},
_doFinalize: function () {
// Shortcut
var padding = this.cfg.padding;
// Finalize
if (this._xformMode == this._ENC_XFORM_MODE) {
// Pad data
padding.pad(this._data, this.blockSize);
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
// Unpad data
padding.unpad(finalProcessedBlocks);
}
return finalProcessedBlocks;
},
blockSize: 128/32
});
/**
* A collection of cipher parameters.
*
* @property {WordArray} ciphertext The raw ciphertext.
* @property {WordArray} key The key to this ciphertext.
* @property {WordArray} iv The IV used in the ciphering operation.
* @property {WordArray} salt The salt used with a key derivation function.
* @property {Cipher} algorithm The cipher algorithm.
* @property {Mode} mode The block mode used in the ciphering operation.
* @property {Padding} padding The padding scheme used in the ciphering operation.
* @property {number} blockSize The block size of the cipher.
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
*/
var CipherParams = C_lib.CipherParams = Base.extend({
/**
* Initializes a newly created cipher params object.
*
* @param {Object} cipherParams An object with any of the possible cipher parameters.
*
* @example
*
* var cipherParams = CryptoJS.lib.CipherParams.create({
* ciphertext: ciphertextWordArray,
* key: keyWordArray,
* iv: ivWordArray,
* salt: saltWordArray,
* algorithm: CryptoJS.algo.AES,
* mode: CryptoJS.mode.CBC,
* padding: CryptoJS.pad.PKCS7,
* blockSize: 4,
* formatter: CryptoJS.format.OpenSSL
* });
*/
init: function (cipherParams) {
this.mixIn(cipherParams);
},
/**
* Converts this cipher params object to a string.
*
* @param {Format} formatter (Optional) The formatting strategy to use.
*
* @return {string} The stringified cipher params.
*
* @throws Error If neither the formatter nor the default formatter is set.
*
* @example
*
* var string = cipherParams + '';
* var string = cipherParams.toString();
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
*/
toString: function (formatter) {
return (formatter || this.formatter).stringify(this);
}
});
/**
* Format namespace.
*/
var C_format = C.format = {};
/**
* OpenSSL formatting strategy.
*/
var OpenSSLFormatter = C_format.OpenSSL = {
/**
* Converts a cipher params object to an OpenSSL-compatible string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The OpenSSL-compatible string.
*
* @static
*
* @example
*
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
*/
stringify: function (cipherParams) {
// Shortcuts
var ciphertext = cipherParams.ciphertext;
var salt = cipherParams.salt;
// Format
if (salt) {
var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
} else {
var wordArray = ciphertext;
}
return wordArray.toString(Base64);
},
/**
* Converts an OpenSSL-compatible string to a cipher params object.
*
* @param {string} openSSLStr The OpenSSL-compatible string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
*/
parse: function (openSSLStr) {
// Parse base64
var ciphertext = Base64.parse(openSSLStr);
// Shortcut
var ciphertextWords = ciphertext.words;
// Test for salt
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
// Extract salt
var salt = WordArray.create(ciphertextWords.slice(2, 4));
// Remove salt from ciphertext
ciphertextWords.splice(0, 4);
ciphertext.sigBytes -= 16;
}
return CipherParams.create({ ciphertext: ciphertext, salt: salt });
}
};
/**
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
*/
var SerializableCipher = C_lib.SerializableCipher = Base.extend({
/**
* Configuration options.
*
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
*/
cfg: Base.extend({
format: OpenSSLFormatter
}),
/**
* Encrypts a message.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Encrypt
var encryptor = cipher.createEncryptor(key, cfg);
var ciphertext = encryptor.finalize(message);
// Shortcut
var cipherCfg = encryptor.cfg;
// Create and return serializable cipher params
return CipherParams.create({
ciphertext: ciphertext,
key: key,
iv: cipherCfg.iv,
algorithm: cipher,
mode: cipherCfg.mode,
padding: cipherCfg.padding,
blockSize: cipher.blockSize,
formatter: cfg.format
});
},
/**
* Decrypts serialized ciphertext.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Decrypt
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
return plaintext;
},
/**
* Converts serialized ciphertext to CipherParams,
* else assumed CipherParams already and returns ciphertext unchanged.
*
* @param {CipherParams|string} ciphertext The ciphertext.
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
*
* @return {CipherParams} The unserialized ciphertext.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
*/
_parse: function (ciphertext, format) {
if (typeof ciphertext == 'string') {
return format.parse(ciphertext, this);
} else {
return ciphertext;
}
}
});
/**
* Key derivation function namespace.
*/
var C_kdf = C.kdf = {};
/**
* OpenSSL key derivation function.
*/
var OpenSSLKdf = C_kdf.OpenSSL = {
/**
* Derives a key and IV from a password.
*
* @param {string} password The password to derive from.
* @param {number} keySize The size in words of the key to generate.
* @param {number} ivSize The size in words of the IV to generate.
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
key.sigBytes = keySize * 4;
// Return params
return CipherParams.create({ key: key, iv: iv, salt: salt });
}
};
/**
* A serializable cipher wrapper that derives the key from a password,
* and returns ciphertext as a serializable cipher params object.
*/
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
/**
* Configuration options.
*
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
*/
cfg: SerializableCipher.cfg.extend({
kdf: OpenSSLKdf
}),
/**
* Encrypts a message using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
// Add IV to config
cfg.iv = derivedParams.iv;
// Encrypt
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
// Mix in derived params
ciphertext.mixIn(derivedParams);
return ciphertext;
},
/**
* Decrypts serialized ciphertext using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
// Add IV to config
cfg.iv = derivedParams.iv;
// Decrypt
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
return plaintext;
}
});
}());
}));
},{"./core":44}],44:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory();
}
else if (typeof define === "function" && define.amd) {
// AMD
define([], factory);
}
else {
// Global (browser)
root.CryptoJS = factory();
}
}(this, function () {
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
function F() {}
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
F.prototype = this;
var subtype = new F();
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init')) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else {
// Copy one word at a time
for (var i = 0; i < thatSigBytes; i += 4) {
thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
}
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
var r = (function (m_w) {
var m_w = m_w;
var m_z = 0x3ade68b1;
var mask = 0xffffffff;
return function () {
m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
var result = ((m_z << 0x10) + m_w) & mask;
result /= 0x100000000;
result += 0.5;
return result * (Math.random() > .5 ? 1 : -1);
}
});
for (var i = 0, rcache; i < nBytes; i += 4) {
var _r = r((rcache || Math.random()) * 0x100000000);
rcache = _r() * 0x3ade67b7;
words.push((_r() * 0x100000000) | 0);
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
var processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
return CryptoJS;
}));
},{}],45:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
return CryptoJS.enc.Base64;
}));
},{"./core":44}],46:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* UTF-16 BE encoding strategy.
*/
var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
/**
* Converts a word array to a UTF-16 BE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 BE string.
*
* @static
*
* @example
*
* var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 BE string to a word array.
*
* @param {string} utf16Str The UTF-16 BE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
}
return WordArray.create(words, utf16StrLength * 2);
}
};
/**
* UTF-16 LE encoding strategy.
*/
C_enc.Utf16LE = {
/**
* Converts a word array to a UTF-16 LE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 LE string.
*
* @static
*
* @example
*
* var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 LE string to a word array.
*
* @param {string} utf16Str The UTF-16 LE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
}
return WordArray.create(words, utf16StrLength * 2);
}
};
function swapEndian(word) {
return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
}
}());
return CryptoJS.enc.Utf16;
}));
},{"./core":44}],47:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var MD5 = C_algo.MD5;
/**
* This key derivation function is meant to conform with EVP_BytesToKey.
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
*/
var EvpKDF = C_algo.EvpKDF = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hash algorithm to use. Default: MD5
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: MD5,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.EvpKDF.create();
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init hasher
var hasher = cfg.hasher.create();
// Initial values
var derivedKey = WordArray.create();
// Shortcuts
var derivedKeyWords = derivedKey.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
var block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (var i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.EvpKDF(password, salt);
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
*/
C.EvpKDF = function (password, salt, cfg) {
return EvpKDF.create(cfg).compute(password, salt);
};
}());
return CryptoJS.EvpKDF;
}));
},{"./core":44,"./hmac":49,"./sha1":68}],48:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var CipherParams = C_lib.CipherParams;
var C_enc = C.enc;
var Hex = C_enc.Hex;
var C_format = C.format;
var HexFormatter = C_format.Hex = {
/**
* Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The hexadecimally encoded string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.format.Hex.stringify(cipherParams);
*/
stringify: function (cipherParams) {
return cipherParams.ciphertext.toString(Hex);
},
/**
* Converts a hexadecimally encoded ciphertext string to a cipher params object.
*
* @param {string} input The hexadecimally encoded string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.Hex.parse(hexString);
*/
parse: function (input) {
var ciphertext = Hex.parse(input);
return CipherParams.create({ ciphertext: ciphertext });
}
};
}());
return CryptoJS.format.Hex;
}));
},{"./cipher-core":43,"./core":44}],49:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
/**
* HMAC algorithm.
*/
var HMAC = C_algo.HMAC = Base.extend({
/**
* Initializes a newly created HMAC.
*
* @param {Hasher} hasher The hash algorithm to use.
* @param {WordArray|string} key The secret key.
*
* @example
*
* var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
*/
init: function (hasher, key) {
// Init hasher
hasher = this._hasher = new hasher.init();
// Convert string to WordArray, else assume WordArray already
if (typeof key == 'string') {
key = Utf8.parse(key);
}
// Shortcuts
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
// Allow arbitrary length keys
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
// Clamp excess bits
key.clamp();
// Clone key for inner and outer pads
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
// Shortcuts
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
// XOR keys with pad constants
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 0x5c5c5c5c;
iKeyWords[i] ^= 0x36363636;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
// Set initial values
this.reset();
},
/**
* Resets this HMAC to its initial state.
*
* @example
*
* hmacHasher.reset();
*/
reset: function () {
// Shortcut
var hasher = this._hasher;
// Reset
hasher.reset();
hasher.update(this._iKey);
},
/**
* Updates this HMAC with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {HMAC} This HMAC instance.
*
* @example
*
* hmacHasher.update('message');
* hmacHasher.update(wordArray);
*/
update: function (messageUpdate) {
this._hasher.update(messageUpdate);
// Chainable
return this;
},
/**
* Finalizes the HMAC computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The HMAC.
*
* @example
*
* var hmac = hmacHasher.finalize();
* var hmac = hmacHasher.finalize('message');
* var hmac = hmacHasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Shortcut
var hasher = this._hasher;
// Compute HMAC
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
}());
}));
},{"./core":44}],50:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory);
}
else {
// Global (browser)
root.CryptoJS = factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
return CryptoJS;
}));
},{"./aes":42,"./cipher-core":43,"./core":44,"./enc-base64":45,"./enc-utf16":46,"./evpkdf":47,"./format-hex":48,"./hmac":49,"./lib-typedarrays":51,"./md5":52,"./mode-cfb":53,"./mode-ctr":55,"./mode-ctr-gladman":54,"./mode-ecb":56,"./mode-ofb":57,"./pad-ansix923":58,"./pad-iso10126":59,"./pad-iso97971":60,"./pad-nopadding":61,"./pad-zeropadding":62,"./pbkdf2":63,"./rabbit":65,"./rabbit-legacy":64,"./rc4":66,"./ripemd160":67,"./sha1":68,"./sha224":69,"./sha256":70,"./sha3":71,"./sha384":72,"./sha512":73,"./tripledes":74,"./x64-core":75}],51:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Check if typed arrays are supported
if (typeof ArrayBuffer != 'function') {
return;
}
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
// Reference original init
var superInit = WordArray.init;
// Augment WordArray.init to handle typed arrays
var subInit = WordArray.init = function (typedArray) {
// Convert buffers to uint8
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
}
// Convert other array views to uint8
if (
typedArray instanceof Int8Array ||
(typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
typedArray instanceof Int16Array ||
typedArray instanceof Uint16Array ||
typedArray instanceof Int32Array ||
typedArray instanceof Uint32Array ||
typedArray instanceof Float32Array ||
typedArray instanceof Float64Array
) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
}
// Handle Uint8Array
if (typedArray instanceof Uint8Array) {
// Shortcut
var typedArrayByteLength = typedArray.byteLength;
// Extract bytes
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
}
// Initialize this word array
superInit.call(this, words, typedArrayByteLength);
} else {
// Else call normal init
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
}());
return CryptoJS.lib.WordArray;
}));
},{"./core":44}],52:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476
]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcuts
var H = this._hash.words;
var M_offset_0 = M[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
// Working varialbes
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
// Computation
a = FF(a, b, c, d, M_offset_0, 7, T[0]);
d = FF(d, a, b, c, M_offset_1, 12, T[1]);
c = FF(c, d, a, b, M_offset_2, 17, T[2]);
b = FF(b, c, d, a, M_offset_3, 22, T[3]);
a = FF(a, b, c, d, M_offset_4, 7, T[4]);
d = FF(d, a, b, c, M_offset_5, 12, T[5]);
c = FF(c, d, a, b, M_offset_6, 17, T[6]);
b = FF(b, c, d, a, M_offset_7, 22, T[7]);
a = FF(a, b, c, d, M_offset_8, 7, T[8]);
d = FF(d, a, b, c, M_offset_9, 12, T[9]);
c = FF(c, d, a, b, M_offset_10, 17, T[10]);
b = FF(b, c, d, a, M_offset_11, 22, T[11]);
a = FF(a, b, c, d, M_offset_12, 7, T[12]);
d = FF(d, a, b, c, M_offset_13, 12, T[13]);
c = FF(c, d, a, b, M_offset_14, 17, T[14]);
b = FF(b, c, d, a, M_offset_15, 22, T[15]);
a = GG(a, b, c, d, M_offset_1, 5, T[16]);
d = GG(d, a, b, c, M_offset_6, 9, T[17]);
c = GG(c, d, a, b, M_offset_11, 14, T[18]);
b = GG(b, c, d, a, M_offset_0, 20, T[19]);
a = GG(a, b, c, d, M_offset_5, 5, T[20]);
d = GG(d, a, b, c, M_offset_10, 9, T[21]);
c = GG(c, d, a, b, M_offset_15, 14, T[22]);
b = GG(b, c, d, a, M_offset_4, 20, T[23]);
a = GG(a, b, c, d, M_offset_9, 5, T[24]);
d = GG(d, a, b, c, M_offset_14, 9, T[25]);
c = GG(c, d, a, b, M_offset_3, 14, T[26]);
b = GG(b, c, d, a, M_offset_8, 20, T[27]);
a = GG(a, b, c, d, M_offset_13, 5, T[28]);
d = GG(d, a, b, c, M_offset_2, 9, T[29]);
c = GG(c, d, a, b, M_offset_7, 14, T[30]);
b = GG(b, c, d, a, M_offset_12, 20, T[31]);
a = HH(a, b, c, d, M_offset_5, 4, T[32]);
d = HH(d, a, b, c, M_offset_8, 11, T[33]);
c = HH(c, d, a, b, M_offset_11, 16, T[34]);
b = HH(b, c, d, a, M_offset_14, 23, T[35]);
a = HH(a, b, c, d, M_offset_1, 4, T[36]);
d = HH(d, a, b, c, M_offset_4, 11, T[37]);
c = HH(c, d, a, b, M_offset_7, 16, T[38]);
b = HH(b, c, d, a, M_offset_10, 23, T[39]);
a = HH(a, b, c, d, M_offset_13, 4, T[40]);
d = HH(d, a, b, c, M_offset_0, 11, T[41]);
c = HH(c, d, a, b, M_offset_3, 16, T[42]);
b = HH(b, c, d, a, M_offset_6, 23, T[43]);
a = HH(a, b, c, d, M_offset_9, 4, T[44]);
d = HH(d, a, b, c, M_offset_12, 11, T[45]);
c = HH(c, d, a, b, M_offset_15, 16, T[46]);
b = HH(b, c, d, a, M_offset_2, 23, T[47]);
a = II(a, b, c, d, M_offset_0, 6, T[48]);
d = II(d, a, b, c, M_offset_7, 10, T[49]);
c = II(c, d, a, b, M_offset_14, 15, T[50]);
b = II(b, c, d, a, M_offset_5, 21, T[51]);
a = II(a, b, c, d, M_offset_12, 6, T[52]);
d = II(d, a, b, c, M_offset_3, 10, T[53]);
c = II(c, d, a, b, M_offset_10, 15, T[54]);
b = II(b, c, d, a, M_offset_1, 21, T[55]);
a = II(a, b, c, d, M_offset_8, 6, T[56]);
d = II(d, a, b, c, M_offset_15, 10, T[57]);
c = II(c, d, a, b, M_offset_6, 15, T[58]);
b = II(b, c, d, a, M_offset_13, 21, T[59]);
a = II(a, b, c, d, M_offset_4, 6, T[60]);
d = II(d, a, b, c, M_offset_11, 10, T[61]);
c = II(c, d, a, b, M_offset_2, 15, T[62]);
b = II(b, c, d, a, M_offset_9, 21, T[63]);
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
var nBitsTotalL = nBitsTotal;
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
(((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
(((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
(((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 4; i++) {
// Shortcut
var H_i = H[i];
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a, b, c, d, x, s, t) {
var n = a + ((b & c) | (~b & d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function GG(a, b, c, d, x, s, t) {
var n = a + ((b & d) | (c & ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function HH(a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function II(a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.MD5('message');
* var hash = CryptoJS.MD5(wordArray);
*/
C.MD5 = Hasher._createHelper(MD5);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacMD5(message, key);
*/
C.HmacMD5 = Hasher._createHmacHelper(MD5);
}(Math));
return CryptoJS.MD5;
}));
},{"./core":44}],53:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher Feedback block mode.
*/
CryptoJS.mode.CFB = (function () {
var CFB = CryptoJS.lib.BlockCipherMode.extend();
CFB.Encryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
CFB.Decryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
// Shortcut
var iv = this._iv;
// Generate keystream
if (iv) {
var keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var keystream = this._prevBlock;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
return CFB;
}());
return CryptoJS.mode.CFB;
}));
},{"./cipher-core":43,"./core":44}],54:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby [email protected]
*/
CryptoJS.mode.CTRGladman = (function () {
var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
function incWord(word)
{
if (((word >> 24) & 0xff) === 0xff) { //overflow
var b1 = (word >> 16)&0xff;
var b2 = (word >> 8)&0xff;
var b3 = word & 0xff;
if (b1 === 0xff) // overflow b1
{
b1 = 0;
if (b2 === 0xff)
{
b2 = 0;
if (b3 === 0xff)
{
b3 = 0;
}
else
{
++b3;
}
}
else
{
++b2;
}
}
else
{
++b1;
}
word = 0;
word += (b1 << 16);
word += (b2 << 8);
word += b3;
}
else
{
word += (0x01 << 24);
}
return word;
}
function incCounter(counter)
{
if ((counter[0] = incWord(counter[0])) === 0)
{
// encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
counter[1] = incWord(counter[1]);
}
return counter;
}
var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
incCounter(counter);
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTRGladman.Decryptor = Encryptor;
return CTRGladman;
}());
return CryptoJS.mode.CTRGladman;
}));
},{"./cipher-core":43,"./core":44}],55:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Counter block mode.
*/
CryptoJS.mode.CTR = (function () {
var CTR = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = CTR.Encryptor = CTR.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Increment counter
counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTR.Decryptor = Encryptor;
return CTR;
}());
return CryptoJS.mode.CTR;
}));
},{"./cipher-core":43,"./core":44}],56:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Electronic Codebook block mode.
*/
CryptoJS.mode.ECB = (function () {
var ECB = CryptoJS.lib.BlockCipherMode.extend();
ECB.Encryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
return ECB;
}());
return CryptoJS.mode.ECB;
}));
},{"./cipher-core":43,"./core":44}],57:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Output Feedback block mode.
*/
CryptoJS.mode.OFB = (function () {
var OFB = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = OFB.Encryptor = OFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var keystream = this._keystream;
// Generate keystream
if (iv) {
keystream = this._keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
OFB.Decryptor = Encryptor;
return OFB;
}());
return CryptoJS.mode.OFB;
}));
},{"./cipher-core":43,"./core":44}],58:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ANSI X.923 padding strategy.
*/
CryptoJS.pad.AnsiX923 = {
pad: function (data, blockSize) {
// Shortcuts
var dataSigBytes = data.sigBytes;
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
// Compute last byte position
var lastBytePos = dataSigBytes + nPaddingBytes - 1;
// Pad
data.clamp();
data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
data.sigBytes += nPaddingBytes;
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Ansix923;
}));
},{"./cipher-core":43,"./core":44}],59:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO 10126 padding strategy.
*/
CryptoJS.pad.Iso10126 = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Pad
data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Iso10126;
}));
},{"./cipher-core":43,"./core":44}],60:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO/IEC 9797-1 Padding Method 2.
*/
CryptoJS.pad.Iso97971 = {
pad: function (data, blockSize) {
// Add 0x80 byte
data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
// Zero pad the rest
CryptoJS.pad.ZeroPadding.pad(data, blockSize);
},
unpad: function (data) {
// Remove zero padding
CryptoJS.pad.ZeroPadding.unpad(data);
// Remove one more byte -- the 0x80 byte
data.sigBytes--;
}
};
return CryptoJS.pad.Iso97971;
}));
},{"./cipher-core":43,"./core":44}],61:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* A noop padding strategy.
*/
CryptoJS.pad.NoPadding = {
pad: function () {
},
unpad: function () {
}
};
return CryptoJS.pad.NoPadding;
}));
},{"./cipher-core":43,"./core":44}],62:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Zero padding strategy.
*/
CryptoJS.pad.ZeroPadding = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Pad
data.clamp();
data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
},
unpad: function (data) {
// Shortcut
var dataWords = data.words;
// Unpad
var i = data.sigBytes - 1;
while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
i--;
}
data.sigBytes = i + 1;
}
};
return CryptoJS.pad.ZeroPadding;
}));
},{"./cipher-core":43,"./core":44}],63:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA1 = C_algo.SHA1;
var HMAC = C_algo.HMAC;
/**
* Password-Based Key Derivation Function 2 algorithm.
*/
var PBKDF2 = C_algo.PBKDF2 = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hasher to use. Default: SHA1
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: SHA1,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.PBKDF2.create();
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init HMAC
var hmac = HMAC.create(cfg.hasher, password);
// Initial values
var derivedKey = WordArray.create();
var blockIndex = WordArray.create([0x00000001]);
// Shortcuts
var derivedKeyWords = derivedKey.words;
var blockIndexWords = blockIndex.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
var block = hmac.update(salt).finalize(blockIndex);
hmac.reset();
// Shortcuts
var blockWords = block.words;
var blockWordsLength = blockWords.length;
// Iterations
var intermediate = block;
for (var i = 1; i < iterations; i++) {
intermediate = hmac.finalize(intermediate);
hmac.reset();
// Shortcut
var intermediateWords = intermediate.words;
// XOR intermediate with block
for (var j = 0; j < blockWordsLength; j++) {
blockWords[j] ^= intermediateWords[j];
}
}
derivedKey.concat(block);
blockIndexWords[0]++;
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.PBKDF2(password, salt);
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
*/
C.PBKDF2 = function (password, salt, cfg) {
return PBKDF2.create(cfg).compute(password, salt);
};
}());
return CryptoJS.PBKDF2;
}));
},{"./core":44,"./hmac":49,"./sha1":68}],64:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm.
*
* This is a legacy version that neglected to convert the key to little-endian.
* This error doesn't affect the cipher's security,
* but it does affect its compatibility with other implementations.
*/
var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
*/
C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
}());
return CryptoJS.RabbitLegacy;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],65:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm
*/
var Rabbit = C_algo.Rabbit = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Swap endian
for (var i = 0; i < 4; i++) {
K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
(((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
}
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
* var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
*/
C.Rabbit = StreamCipher._createHelper(Rabbit);
}());
return CryptoJS.Rabbit;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],66:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
/**
* RC4 stream cipher algorithm.
*/
var RC4 = C_algo.RC4 = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySigBytes = key.sigBytes;
// Init sbox
var S = this._S = [];
for (var i = 0; i < 256; i++) {
S[i] = i;
}
// Key setup
for (var i = 0, j = 0; i < 256; i++) {
var keyByteIndex = i % keySigBytes;
var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
j = (j + S[i] + keyByte) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
}
// Counters
this._i = this._j = 0;
},
_doProcessBlock: function (M, offset) {
M[offset] ^= generateKeystreamWord.call(this);
},
keySize: 256/32,
ivSize: 0
});
function generateKeystreamWord() {
// Shortcuts
var S = this._S;
var i = this._i;
var j = this._j;
// Generate keystream word
var keystreamWord = 0;
for (var n = 0; n < 4; n++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
}
// Update counters
this._i = i;
this._j = j;
return keystreamWord;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
*/
C.RC4 = StreamCipher._createHelper(RC4);
/**
* Modified RC4 stream cipher algorithm.
*/
var RC4Drop = C_algo.RC4Drop = RC4.extend({
/**
* Configuration options.
*
* @property {number} drop The number of keystream words to drop. Default 192
*/
cfg: RC4.cfg.extend({
drop: 192
}),
_doReset: function () {
RC4._doReset.call(this);
// Drop
for (var i = this.cfg.drop; i > 0; i--) {
generateKeystreamWord.call(this);
}
}
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
*/
C.RC4Drop = StreamCipher._createHelper(RC4Drop);
}());
return CryptoJS.RC4;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],67:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var _zl = WordArray.create([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]);
var _zr = WordArray.create([
5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]);
var _sl = WordArray.create([
11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]);
var _sr = WordArray.create([
8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]);
var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
/**
* RIPEMD160 hash algorithm.
*/
var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
_doReset: function () {
this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
// Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcut
var H = this._hash.words;
var hl = _hl.words;
var hr = _hr.words;
var zl = _zl.words;
var zr = _zr.words;
var sl = _sl.words;
var sr = _sr.words;
// Working variables
var al, bl, cl, dl, el;
var ar, br, cr, dr, er;
ar = al = H[0];
br = bl = H[1];
cr = cl = H[2];
dr = dl = H[3];
er = el = H[4];
// Computation
var t;
for (var i = 0; i < 80; i += 1) {
t = (al + M[offset+zl[i]])|0;
if (i<16){
t += f1(bl,cl,dl) + hl[0];
} else if (i<32) {
t += f2(bl,cl,dl) + hl[1];
} else if (i<48) {
t += f3(bl,cl,dl) + hl[2];
} else if (i<64) {
t += f4(bl,cl,dl) + hl[3];
} else {// if (i<80) {
t += f5(bl,cl,dl) + hl[4];
}
t = t|0;
t = rotl(t,sl[i]);
t = (t+el)|0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t;
t = (ar + M[offset+zr[i]])|0;
if (i<16){
t += f5(br,cr,dr) + hr[0];
} else if (i<32) {
t += f4(br,cr,dr) + hr[1];
} else if (i<48) {
t += f3(br,cr,dr) + hr[2];
} else if (i<64) {
t += f2(br,cr,dr) + hr[3];
} else {// if (i<80) {
t += f1(br,cr,dr) + hr[4];
}
t = t|0;
t = rotl(t,sr[i]) ;
t = (t+er)|0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t;
}
// Intermediate hash value
t = (H[1] + cl + dr)|0;
H[1] = (H[2] + dl + er)|0;
H[2] = (H[3] + el + ar)|0;
H[3] = (H[4] + al + br)|0;
H[4] = (H[0] + bl + cr)|0;
H[0] = t;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 5; i++) {
// Shortcut
var H_i = H[i];
// Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function f1(x, y, z) {
return ((x) ^ (y) ^ (z));
}
function f2(x, y, z) {
return (((x)&(y)) | ((~x)&(z)));
}
function f3(x, y, z) {
return (((x) | (~(y))) ^ (z));
}
function f4(x, y, z) {
return (((x) & (z)) | ((y)&(~(z))));
}
function f5(x, y, z) {
return ((x) ^ ((y) |(~(z))));
}
function rotl(x,n) {
return (x<<n) | (x>>>(32-n));
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.RIPEMD160('message');
* var hash = CryptoJS.RIPEMD160(wordArray);
*/
C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacRIPEMD160(message, key);
*/
C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
}(Math));
return CryptoJS.RIPEMD160;
}));
},{"./core":44}],68:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
/**
* SHA-1 hash algorithm.
*/
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476,
0xc3d2e1f0
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
// Computation
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = (n << 1) | (n >>> 31);
}
var t = ((a << 5) | (a >>> 27)) + e + W[i];
if (i < 20) {
t += ((b & c) | (~b & d)) + 0x5a827999;
} else if (i < 40) {
t += (b ^ c ^ d) + 0x6ed9eba1;
} else if (i < 60) {
t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
} else /* if (i < 80) */ {
t += (b ^ c ^ d) - 0x359d3e2a;
}
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA1('message');
* var hash = CryptoJS.SHA1(wordArray);
*/
C.SHA1 = Hasher._createHelper(SHA1);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA1(message, key);
*/
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
}());
return CryptoJS.SHA1;
}));
},{"./core":44}],69:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha256"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA256 = C_algo.SHA256;
/**
* SHA-224 hash algorithm.
*/
var SHA224 = C_algo.SHA224 = SHA256.extend({
_doReset: function () {
this._hash = new WordArray.init([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
]);
},
_doFinalize: function () {
var hash = SHA256._doFinalize.call(this);
hash.sigBytes -= 4;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA224('message');
* var hash = CryptoJS.SHA224(wordArray);
*/
C.SHA224 = SHA256._createHelper(SHA224);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA224(message, key);
*/
C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
}());
return CryptoJS.SHA224;
}));
},{"./core":44,"./sha256":70}],70:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return ((n - (n | 0)) * 0x100000000) | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
}());
// Reusable object
var W = [];
/**
* SHA-256 hash algorithm.
*/
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init(H.slice(0));
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
var f = H[5];
var g = H[6];
var h = H[7];
// Computation
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
((gamma0x << 14) | (gamma0x >>> 18)) ^
(gamma0x >>> 3);
var gamma1x = W[i - 2];
var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
((gamma1x << 13) | (gamma1x >>> 19)) ^
(gamma1x >>> 10);
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = (e & f) ^ (~e & g);
var maj = (a & b) ^ (a & c) ^ (b & c);
var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
H[5] = (H[5] + f) | 0;
H[6] = (H[6] + g) | 0;
H[7] = (H[7] + h) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA256('message');
* var hash = CryptoJS.SHA256(wordArray);
*/
C.SHA256 = Hasher._createHelper(SHA256);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA256(message, key);
*/
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
}(Math));
return CryptoJS.SHA256;
}));
},{"./core":44}],71:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var C_algo = C.algo;
// Constants tables
var RHO_OFFSETS = [];
var PI_INDEXES = [];
var ROUND_CONSTANTS = [];
// Compute Constants
(function () {
// Compute rho offset constants
var x = 1, y = 0;
for (var t = 0; t < 24; t++) {
RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
var newX = y % 5;
var newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
// Compute pi index constants
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
}
}
// Compute round constants
var LFSR = 0x01;
for (var i = 0; i < 24; i++) {
var roundConstantMsw = 0;
var roundConstantLsw = 0;
for (var j = 0; j < 7; j++) {
if (LFSR & 0x01) {
var bitPosition = (1 << j) - 1;
if (bitPosition < 32) {
roundConstantLsw ^= 1 << bitPosition;
} else /* if (bitPosition >= 32) */ {
roundConstantMsw ^= 1 << (bitPosition - 32);
}
}
// Compute next LFSR
if (LFSR & 0x80) {
// Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
LFSR = (LFSR << 1) ^ 0x71;
} else {
LFSR <<= 1;
}
}
ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
}
}());
// Reusable objects for temporary values
var T = [];
(function () {
for (var i = 0; i < 25; i++) {
T[i] = X64Word.create();
}
}());
/**
* SHA-3 hash algorithm.
*/
var SHA3 = C_algo.SHA3 = Hasher.extend({
/**
* Configuration options.
*
* @property {number} outputLength
* The desired number of bits in the output hash.
* Only values permitted are: 224, 256, 384, 512.
* Default: 512
*/
cfg: Hasher.cfg.extend({
outputLength: 512
}),
_doReset: function () {
var state = this._state = []
for (var i = 0; i < 25; i++) {
state[i] = new X64Word.init();
}
this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var state = this._state;
var nBlockSizeLanes = this.blockSize / 2;
// Absorb
for (var i = 0; i < nBlockSizeLanes; i++) {
// Shortcuts
var M2i = M[offset + 2 * i];
var M2i1 = M[offset + 2 * i + 1];
// Swap endian
M2i = (
(((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
(((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
);
M2i1 = (
(((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
(((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
);
// Absorb message into state
var lane = state[i];
lane.high ^= M2i1;
lane.low ^= M2i;
}
// Rounds
for (var round = 0; round < 24; round++) {
// Theta
for (var x = 0; x < 5; x++) {
// Mix column lanes
var tMsw = 0, tLsw = 0;
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
tMsw ^= lane.high;
tLsw ^= lane.low;
}
// Temporary values
var Tx = T[x];
Tx.high = tMsw;
Tx.low = tLsw;
}
for (var x = 0; x < 5; x++) {
// Shortcuts
var Tx4 = T[(x + 4) % 5];
var Tx1 = T[(x + 1) % 5];
var Tx1Msw = Tx1.high;
var Tx1Lsw = Tx1.low;
// Mix surrounding columns
var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
lane.high ^= tMsw;
lane.low ^= tLsw;
}
}
// Rho Pi
for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
// Shortcuts
var lane = state[laneIndex];
var laneMsw = lane.high;
var laneLsw = lane.low;
var rhoOffset = RHO_OFFSETS[laneIndex];
// Rotate lanes
if (rhoOffset < 32) {
var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
} else /* if (rhoOffset >= 32) */ {
var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
}
// Transpose lanes
var TPiLane = T[PI_INDEXES[laneIndex]];
TPiLane.high = tMsw;
TPiLane.low = tLsw;
}
// Rho pi at x = y = 0
var T0 = T[0];
var state0 = state[0];
T0.high = state0.high;
T0.low = state0.low;
// Chi
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
// Shortcuts
var laneIndex = x + 5 * y;
var lane = state[laneIndex];
var TLane = T[laneIndex];
var Tx1Lane = T[((x + 1) % 5) + 5 * y];
var Tx2Lane = T[((x + 2) % 5) + 5 * y];
// Mix rows
lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
}
}
// Iota
var lane = state[0];
var roundConstant = ROUND_CONSTANTS[round];
lane.high ^= roundConstant.high;
lane.low ^= roundConstant.low;;
}
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
var blockSizeBits = this.blockSize * 32;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Shortcuts
var state = this._state;
var outputLengthBytes = this.cfg.outputLength / 8;
var outputLengthLanes = outputLengthBytes / 8;
// Squeeze
var hashWords = [];
for (var i = 0; i < outputLengthLanes; i++) {
// Shortcuts
var lane = state[i];
var laneMsw = lane.high;
var laneLsw = lane.low;
// Swap endian
laneMsw = (
(((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
(((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
);
laneLsw = (
(((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
(((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
);
// Squeeze state to retrieve hash
hashWords.push(laneLsw);
hashWords.push(laneMsw);
}
// Return final computed hash
return new WordArray.init(hashWords, outputLengthBytes);
},
clone: function () {
var clone = Hasher.clone.call(this);
var state = clone._state = this._state.slice(0);
for (var i = 0; i < 25; i++) {
state[i] = state[i].clone();
}
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA3('message');
* var hash = CryptoJS.SHA3(wordArray);
*/
C.SHA3 = Hasher._createHelper(SHA3);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA3(message, key);
*/
C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
}(Math));
return CryptoJS.SHA3;
}));
},{"./core":44,"./x64-core":75}],72:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./sha512"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
var SHA512 = C_algo.SHA512;
/**
* SHA-384 hash algorithm.
*/
var SHA384 = C_algo.SHA384 = SHA512.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
]);
},
_doFinalize: function () {
var hash = SHA512._doFinalize.call(this);
hash.sigBytes -= 16;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA384('message');
* var hash = CryptoJS.SHA384(wordArray);
*/
C.SHA384 = SHA512._createHelper(SHA384);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA384(message, key);
*/
C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
}());
return CryptoJS.SHA384;
}));
},{"./core":44,"./sha512":73,"./x64-core":75}],73:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
function X64Word_create() {
return X64Word.create.apply(X64Word, arguments);
}
// Constants
var K = [
X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
];
// Reusable objects
var W = [];
(function () {
for (var i = 0; i < 80; i++) {
W[i] = X64Word_create();
}
}());
/**
* SHA-512 hash algorithm.
*/
var SHA512 = C_algo.SHA512 = Hasher.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
]);
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var H = this._hash.words;
var H0 = H[0];
var H1 = H[1];
var H2 = H[2];
var H3 = H[3];
var H4 = H[4];
var H5 = H[5];
var H6 = H[6];
var H7 = H[7];
var H0h = H0.high;
var H0l = H0.low;
var H1h = H1.high;
var H1l = H1.low;
var H2h = H2.high;
var H2l = H2.low;
var H3h = H3.high;
var H3l = H3.low;
var H4h = H4.high;
var H4l = H4.low;
var H5h = H5.high;
var H5l = H5.low;
var H6h = H6.high;
var H6l = H6.low;
var H7h = H7.high;
var H7l = H7.low;
// Working variables
var ah = H0h;
var al = H0l;
var bh = H1h;
var bl = H1l;
var ch = H2h;
var cl = H2l;
var dh = H3h;
var dl = H3l;
var eh = H4h;
var el = H4l;
var fh = H5h;
var fl = H5l;
var gh = H6h;
var gl = H6l;
var hh = H7h;
var hl = H7l;
// Rounds
for (var i = 0; i < 80; i++) {
// Shortcut
var Wi = W[i];
// Extend message
if (i < 16) {
var Wih = Wi.high = M[offset + i * 2] | 0;
var Wil = Wi.low = M[offset + i * 2 + 1] | 0;
} else {
// Gamma0
var gamma0x = W[i - 15];
var gamma0xh = gamma0x.high;
var gamma0xl = gamma0x.low;
var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
// Gamma1
var gamma1x = W[i - 2];
var gamma1xh = gamma1x.high;
var gamma1xl = gamma1x.low;
var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7 = W[i - 7];
var Wi7h = Wi7.high;
var Wi7l = Wi7.low;
var Wi16 = W[i - 16];
var Wi16h = Wi16.high;
var Wi16l = Wi16.low;
var Wil = gamma0l + Wi7l;
var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
var Wil = Wil + gamma1l;
var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
var Wil = Wil + Wi16l;
var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
Wi.high = Wih;
Wi.low = Wil;
}
var chh = (eh & fh) ^ (~eh & gh);
var chl = (el & fl) ^ (~el & gl);
var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
// t1 = h + sigma1 + ch + K[i] + W[i]
var Ki = K[i];
var Kih = Ki.high;
var Kil = Ki.low;
var t1l = hl + sigma1l;
var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
var t1l = t1l + chl;
var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
var t1l = t1l + Kil;
var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
var t1l = t1l + Wil;
var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
// t2 = sigma0 + maj
var t2l = sigma0l + majl;
var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
// Update working variables
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
el = (dl + t1l) | 0;
eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
al = (t1l + t2l) | 0;
ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
}
// Intermediate hash value
H0l = H0.low = (H0l + al);
H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
H1l = H1.low = (H1l + bl);
H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
H2l = H2.low = (H2l + cl);
H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
H3l = H3.low = (H3l + dl);
H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
H4l = H4.low = (H4l + el);
H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
H5l = H5.low = (H5l + fl);
H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
H6l = H6.low = (H6l + gl);
H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
H7l = H7.low = (H7l + hl);
H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0));
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Convert hash to 32-bit word array before returning
var hash = this._hash.toX32();
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
},
blockSize: 1024/32
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA512('message');
* var hash = CryptoJS.SHA512(wordArray);
*/
C.SHA512 = Hasher._createHelper(SHA512);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA512(message, key);
*/
C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
}());
return CryptoJS.SHA512;
}));
},{"./core":44,"./x64-core":75}],74:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Permuted Choice 1 constants
var PC1 = [
57, 49, 41, 33, 25, 17, 9, 1,
58, 50, 42, 34, 26, 18, 10, 2,
59, 51, 43, 35, 27, 19, 11, 3,
60, 52, 44, 36, 63, 55, 47, 39,
31, 23, 15, 7, 62, 54, 46, 38,
30, 22, 14, 6, 61, 53, 45, 37,
29, 21, 13, 5, 28, 20, 12, 4
];
// Permuted Choice 2 constants
var PC2 = [
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
];
// Cumulative bit shift constants
var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
// SBOXes and round permutation constants
var SBOX_P = [
{
0x0: 0x808200,
0x10000000: 0x8000,
0x20000000: 0x808002,
0x30000000: 0x2,
0x40000000: 0x200,
0x50000000: 0x808202,
0x60000000: 0x800202,
0x70000000: 0x800000,
0x80000000: 0x202,
0x90000000: 0x800200,
0xa0000000: 0x8200,
0xb0000000: 0x808000,
0xc0000000: 0x8002,
0xd0000000: 0x800002,
0xe0000000: 0x0,
0xf0000000: 0x8202,
0x8000000: 0x0,
0x18000000: 0x808202,
0x28000000: 0x8202,
0x38000000: 0x8000,
0x48000000: 0x808200,
0x58000000: 0x200,
0x68000000: 0x808002,
0x78000000: 0x2,
0x88000000: 0x800200,
0x98000000: 0x8200,
0xa8000000: 0x808000,
0xb8000000: 0x800202,
0xc8000000: 0x800002,
0xd8000000: 0x8002,
0xe8000000: 0x202,
0xf8000000: 0x800000,
0x1: 0x8000,
0x10000001: 0x2,
0x20000001: 0x808200,
0x30000001: 0x800000,
0x40000001: 0x808002,
0x50000001: 0x8200,
0x60000001: 0x200,
0x70000001: 0x800202,
0x80000001: 0x808202,
0x90000001: 0x808000,
0xa0000001: 0x800002,
0xb0000001: 0x8202,
0xc0000001: 0x202,
0xd0000001: 0x800200,
0xe0000001: 0x8002,
0xf0000001: 0x0,
0x8000001: 0x808202,
0x18000001: 0x808000,
0x28000001: 0x800000,
0x38000001: 0x200,
0x48000001: 0x8000,
0x58000001: 0x800002,
0x68000001: 0x2,
0x78000001: 0x8202,
0x88000001: 0x8002,
0x98000001: 0x800202,
0xa8000001: 0x202,
0xb8000001: 0x808200,
0xc8000001: 0x800200,
0xd8000001: 0x0,
0xe8000001: 0x8200,
0xf8000001: 0x808002
},
{
0x0: 0x40084010,
0x1000000: 0x4000,
0x2000000: 0x80000,
0x3000000: 0x40080010,
0x4000000: 0x40000010,
0x5000000: 0x40084000,
0x6000000: 0x40004000,
0x7000000: 0x10,
0x8000000: 0x84000,
0x9000000: 0x40004010,
0xa000000: 0x40000000,
0xb000000: 0x84010,
0xc000000: 0x80010,
0xd000000: 0x0,
0xe000000: 0x4010,
0xf000000: 0x40080000,
0x800000: 0x40004000,
0x1800000: 0x84010,
0x2800000: 0x10,
0x3800000: 0x40004010,
0x4800000: 0x40084010,
0x5800000: 0x40000000,
0x6800000: 0x80000,
0x7800000: 0x40080010,
0x8800000: 0x80010,
0x9800000: 0x0,
0xa800000: 0x4000,
0xb800000: 0x40080000,
0xc800000: 0x40000010,
0xd800000: 0x84000,
0xe800000: 0x40084000,
0xf800000: 0x4010,
0x10000000: 0x0,
0x11000000: 0x40080010,
0x12000000: 0x40004010,
0x13000000: 0x40084000,
0x14000000: 0x40080000,
0x15000000: 0x10,
0x16000000: 0x84010,
0x17000000: 0x4000,
0x18000000: 0x4010,
0x19000000: 0x80000,
0x1a000000: 0x80010,
0x1b000000: 0x40000010,
0x1c000000: 0x84000,
0x1d000000: 0x40004000,
0x1e000000: 0x40000000,
0x1f000000: 0x40084010,
0x10800000: 0x84010,
0x11800000: 0x80000,
0x12800000: 0x40080000,
0x13800000: 0x4000,
0x14800000: 0x40004000,
0x15800000: 0x40084010,
0x16800000: 0x10,
0x17800000: 0x40000000,
0x18800000: 0x40084000,
0x19800000: 0x40000010,
0x1a800000: 0x40004010,
0x1b800000: 0x80010,
0x1c800000: 0x0,
0x1d800000: 0x4010,
0x1e800000: 0x40080010,
0x1f800000: 0x84000
},
{
0x0: 0x104,
0x100000: 0x0,
0x200000: 0x4000100,
0x300000: 0x10104,
0x400000: 0x10004,
0x500000: 0x4000004,
0x600000: 0x4010104,
0x700000: 0x4010000,
0x800000: 0x4000000,
0x900000: 0x4010100,
0xa00000: 0x10100,
0xb00000: 0x4010004,
0xc00000: 0x4000104,
0xd00000: 0x10000,
0xe00000: 0x4,
0xf00000: 0x100,
0x80000: 0x4010100,
0x180000: 0x4010004,
0x280000: 0x0,
0x380000: 0x4000100,
0x480000: 0x4000004,
0x580000: 0x10000,
0x680000: 0x10004,
0x780000: 0x104,
0x880000: 0x4,
0x980000: 0x100,
0xa80000: 0x4010000,
0xb80000: 0x10104,
0xc80000: 0x10100,
0xd80000: 0x4000104,
0xe80000: 0x4010104,
0xf80000: 0x4000000,
0x1000000: 0x4010100,
0x1100000: 0x10004,
0x1200000: 0x10000,
0x1300000: 0x4000100,
0x1400000: 0x100,
0x1500000: 0x4010104,
0x1600000: 0x4000004,
0x1700000: 0x0,
0x1800000: 0x4000104,
0x1900000: 0x4000000,
0x1a00000: 0x4,
0x1b00000: 0x10100,
0x1c00000: 0x4010000,
0x1d00000: 0x104,
0x1e00000: 0x10104,
0x1f00000: 0x4010004,
0x1080000: 0x4000000,
0x1180000: 0x104,
0x1280000: 0x4010100,
0x1380000: 0x0,
0x1480000: 0x10004,
0x1580000: 0x4000100,
0x1680000: 0x100,
0x1780000: 0x4010004,
0x1880000: 0x10000,
0x1980000: 0x4010104,
0x1a80000: 0x10104,
0x1b80000: 0x4000004,
0x1c80000: 0x4000104,
0x1d80000: 0x4010000,
0x1e80000: 0x4,
0x1f80000: 0x10100
},
{
0x0: 0x80401000,
0x10000: 0x80001040,
0x20000: 0x401040,
0x30000: 0x80400000,
0x40000: 0x0,
0x50000: 0x401000,
0x60000: 0x80000040,
0x70000: 0x400040,
0x80000: 0x80000000,
0x90000: 0x400000,
0xa0000: 0x40,
0xb0000: 0x80001000,
0xc0000: 0x80400040,
0xd0000: 0x1040,
0xe0000: 0x1000,
0xf0000: 0x80401040,
0x8000: 0x80001040,
0x18000: 0x40,
0x28000: 0x80400040,
0x38000: 0x80001000,
0x48000: 0x401000,
0x58000: 0x80401040,
0x68000: 0x0,
0x78000: 0x80400000,
0x88000: 0x1000,
0x98000: 0x80401000,
0xa8000: 0x400000,
0xb8000: 0x1040,
0xc8000: 0x80000000,
0xd8000: 0x400040,
0xe8000: 0x401040,
0xf8000: 0x80000040,
0x100000: 0x400040,
0x110000: 0x401000,
0x120000: 0x80000040,
0x130000: 0x0,
0x140000: 0x1040,
0x150000: 0x80400040,
0x160000: 0x80401000,
0x170000: 0x80001040,
0x180000: 0x80401040,
0x190000: 0x80000000,
0x1a0000: 0x80400000,
0x1b0000: 0x401040,
0x1c0000: 0x80001000,
0x1d0000: 0x400000,
0x1e0000: 0x40,
0x1f0000: 0x1000,
0x108000: 0x80400000,
0x118000: 0x80401040,
0x128000: 0x0,
0x138000: 0x401000,
0x148000: 0x400040,
0x158000: 0x80000000,
0x168000: 0x80001040,
0x178000: 0x40,
0x188000: 0x80000040,
0x198000: 0x1000,
0x1a8000: 0x80001000,
0x1b8000: 0x80400040,
0x1c8000: 0x1040,
0x1d8000: 0x80401000,
0x1e8000: 0x400000,
0x1f8000: 0x401040
},
{
0x0: 0x80,
0x1000: 0x1040000,
0x2000: 0x40000,
0x3000: 0x20000000,
0x4000: 0x20040080,
0x5000: 0x1000080,
0x6000: 0x21000080,
0x7000: 0x40080,
0x8000: 0x1000000,
0x9000: 0x20040000,
0xa000: 0x20000080,
0xb000: 0x21040080,
0xc000: 0x21040000,
0xd000: 0x0,
0xe000: 0x1040080,
0xf000: 0x21000000,
0x800: 0x1040080,
0x1800: 0x21000080,
0x2800: 0x80,
0x3800: 0x1040000,
0x4800: 0x40000,
0x5800: 0x20040080,
0x6800: 0x21040000,
0x7800: 0x20000000,
0x8800: 0x20040000,
0x9800: 0x0,
0xa800: 0x21040080,
0xb800: 0x1000080,
0xc800: 0x20000080,
0xd800: 0x21000000,
0xe800: 0x1000000,
0xf800: 0x40080,
0x10000: 0x40000,
0x11000: 0x80,
0x12000: 0x20000000,
0x13000: 0x21000080,
0x14000: 0x1000080,
0x15000: 0x21040000,
0x16000: 0x20040080,
0x17000: 0x1000000,
0x18000: 0x21040080,
0x19000: 0x21000000,
0x1a000: 0x1040000,
0x1b000: 0x20040000,
0x1c000: 0x40080,
0x1d000: 0x20000080,
0x1e000: 0x0,
0x1f000: 0x1040080,
0x10800: 0x21000080,
0x11800: 0x1000000,
0x12800: 0x1040000,
0x13800: 0x20040080,
0x14800: 0x20000000,
0x15800: 0x1040080,
0x16800: 0x80,
0x17800: 0x21040000,
0x18800: 0x40080,
0x19800: 0x21040080,
0x1a800: 0x0,
0x1b800: 0x21000000,
0x1c800: 0x1000080,
0x1d800: 0x40000,
0x1e800: 0x20040000,
0x1f800: 0x20000080
},
{
0x0: 0x10000008,
0x100: 0x2000,
0x200: 0x10200000,
0x300: 0x10202008,
0x400: 0x10002000,
0x500: 0x200000,
0x600: 0x200008,
0x700: 0x10000000,
0x800: 0x0,
0x900: 0x10002008,
0xa00: 0x202000,
0xb00: 0x8,
0xc00: 0x10200008,
0xd00: 0x202008,
0xe00: 0x2008,
0xf00: 0x10202000,
0x80: 0x10200000,
0x180: 0x10202008,
0x280: 0x8,
0x380: 0x200000,
0x480: 0x202008,
0x580: 0x10000008,
0x680: 0x10002000,
0x780: 0x2008,
0x880: 0x200008,
0x980: 0x2000,
0xa80: 0x10002008,
0xb80: 0x10200008,
0xc80: 0x0,
0xd80: 0x10202000,
0xe80: 0x202000,
0xf80: 0x10000000,
0x1000: 0x10002000,
0x1100: 0x10200008,
0x1200: 0x10202008,
0x1300: 0x2008,
0x1400: 0x200000,
0x1500: 0x10000000,
0x1600: 0x10000008,
0x1700: 0x202000,
0x1800: 0x202008,
0x1900: 0x0,
0x1a00: 0x8,
0x1b00: 0x10200000,
0x1c00: 0x2000,
0x1d00: 0x10002008,
0x1e00: 0x10202000,
0x1f00: 0x200008,
0x1080: 0x8,
0x1180: 0x202000,
0x1280: 0x200000,
0x1380: 0x10000008,
0x1480: 0x10002000,
0x1580: 0x2008,
0x1680: 0x10202008,
0x1780: 0x10200000,
0x1880: 0x10202000,
0x1980: 0x10200008,
0x1a80: 0x2000,
0x1b80: 0x202008,
0x1c80: 0x200008,
0x1d80: 0x0,
0x1e80: 0x10000000,
0x1f80: 0x10002008
},
{
0x0: 0x100000,
0x10: 0x2000401,
0x20: 0x400,
0x30: 0x100401,
0x40: 0x2100401,
0x50: 0x0,
0x60: 0x1,
0x70: 0x2100001,
0x80: 0x2000400,
0x90: 0x100001,
0xa0: 0x2000001,
0xb0: 0x2100400,
0xc0: 0x2100000,
0xd0: 0x401,
0xe0: 0x100400,
0xf0: 0x2000000,
0x8: 0x2100001,
0x18: 0x0,
0x28: 0x2000401,
0x38: 0x2100400,
0x48: 0x100000,
0x58: 0x2000001,
0x68: 0x2000000,
0x78: 0x401,
0x88: 0x100401,
0x98: 0x2000400,
0xa8: 0x2100000,
0xb8: 0x100001,
0xc8: 0x400,
0xd8: 0x2100401,
0xe8: 0x1,
0xf8: 0x100400,
0x100: 0x2000000,
0x110: 0x100000,
0x120: 0x2000401,
0x130: 0x2100001,
0x140: 0x100001,
0x150: 0x2000400,
0x160: 0x2100400,
0x170: 0x100401,
0x180: 0x401,
0x190: 0x2100401,
0x1a0: 0x100400,
0x1b0: 0x1,
0x1c0: 0x0,
0x1d0: 0x2100000,
0x1e0: 0x2000001,
0x1f0: 0x400,
0x108: 0x100400,
0x118: 0x2000401,
0x128: 0x2100001,
0x138: 0x1,
0x148: 0x2000000,
0x158: 0x100000,
0x168: 0x401,
0x178: 0x2100400,
0x188: 0x2000001,
0x198: 0x2100000,
0x1a8: 0x0,
0x1b8: 0x2100401,
0x1c8: 0x100401,
0x1d8: 0x400,
0x1e8: 0x2000400,
0x1f8: 0x100001
},
{
0x0: 0x8000820,
0x1: 0x20000,
0x2: 0x8000000,
0x3: 0x20,
0x4: 0x20020,
0x5: 0x8020820,
0x6: 0x8020800,
0x7: 0x800,
0x8: 0x8020000,
0x9: 0x8000800,
0xa: 0x20800,
0xb: 0x8020020,
0xc: 0x820,
0xd: 0x0,
0xe: 0x8000020,
0xf: 0x20820,
0x80000000: 0x800,
0x80000001: 0x8020820,
0x80000002: 0x8000820,
0x80000003: 0x8000000,
0x80000004: 0x8020000,
0x80000005: 0x20800,
0x80000006: 0x20820,
0x80000007: 0x20,
0x80000008: 0x8000020,
0x80000009: 0x820,
0x8000000a: 0x20020,
0x8000000b: 0x8020800,
0x8000000c: 0x0,
0x8000000d: 0x8020020,
0x8000000e: 0x8000800,
0x8000000f: 0x20000,
0x10: 0x20820,
0x11: 0x8020800,
0x12: 0x20,
0x13: 0x800,
0x14: 0x8000800,
0x15: 0x8000020,
0x16: 0x8020020,
0x17: 0x20000,
0x18: 0x0,
0x19: 0x20020,
0x1a: 0x8020000,
0x1b: 0x8000820,
0x1c: 0x8020820,
0x1d: 0x20800,
0x1e: 0x820,
0x1f: 0x8000000,
0x80000010: 0x20000,
0x80000011: 0x800,
0x80000012: 0x8020020,
0x80000013: 0x20820,
0x80000014: 0x20,
0x80000015: 0x8020000,
0x80000016: 0x8000000,
0x80000017: 0x8000820,
0x80000018: 0x8020820,
0x80000019: 0x8000020,
0x8000001a: 0x8000800,
0x8000001b: 0x0,
0x8000001c: 0x20800,
0x8000001d: 0x820,
0x8000001e: 0x20020,
0x8000001f: 0x8020800
}
];
// Masks that select the SBOX input
var SBOX_MASK = [
0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
];
/**
* DES block cipher algorithm.
*/
var DES = C_algo.DES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Select 56 bits according to PC1
var keyBits = [];
for (var i = 0; i < 56; i++) {
var keyBitPos = PC1[i] - 1;
keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
}
// Assemble 16 subkeys
var subKeys = this._subKeys = [];
for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
// Create subkey
var subKey = subKeys[nSubKey] = [];
// Shortcut
var bitShift = BIT_SHIFTS[nSubKey];
// Select 48 bits according to PC2
for (var i = 0; i < 24; i++) {
// Select from the left 28 key bits
subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
// Select from the right 28 key bits
subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
}
// Since each subkey is applied to an expanded 32-bit input,
// the subkey can be broken into 8 values scaled to 32-bits,
// which allows the key to be used without expansion
subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
for (var i = 1; i < 7; i++) {
subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
}
subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
}
// Compute inverse subkeys
var invSubKeys = this._invSubKeys = [];
for (var i = 0; i < 16; i++) {
invSubKeys[i] = subKeys[15 - i];
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._subKeys);
},
decryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._invSubKeys);
},
_doCryptBlock: function (M, offset, subKeys) {
// Get input
this._lBlock = M[offset];
this._rBlock = M[offset + 1];
// Initial permutation
exchangeLR.call(this, 4, 0x0f0f0f0f);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeRL.call(this, 2, 0x33333333);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeLR.call(this, 1, 0x55555555);
// Rounds
for (var round = 0; round < 16; round++) {
// Shortcuts
var subKey = subKeys[round];
var lBlock = this._lBlock;
var rBlock = this._rBlock;
// Feistel function
var f = 0;
for (var i = 0; i < 8; i++) {
f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
}
this._lBlock = rBlock;
this._rBlock = lBlock ^ f;
}
// Undo swap from last round
var t = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = t;
// Final permutation
exchangeLR.call(this, 1, 0x55555555);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeRL.call(this, 2, 0x33333333);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeLR.call(this, 4, 0x0f0f0f0f);
// Set output
M[offset] = this._lBlock;
M[offset + 1] = this._rBlock;
},
keySize: 64/32,
ivSize: 64/32,
blockSize: 64/32
});
// Swap bits across the left and right words
function exchangeLR(offset, mask) {
var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
this._rBlock ^= t;
this._lBlock ^= t << offset;
}
function exchangeRL(offset, mask) {
var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
this._lBlock ^= t;
this._rBlock ^= t << offset;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
*/
C.DES = BlockCipher._createHelper(DES);
/**
* Triple-DES block cipher algorithm.
*/
var TripleDES = C_algo.TripleDES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Create DES instances
this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));
},
encryptBlock: function (M, offset) {
this._des1.encryptBlock(M, offset);
this._des2.decryptBlock(M, offset);
this._des3.encryptBlock(M, offset);
},
decryptBlock: function (M, offset) {
this._des3.decryptBlock(M, offset);
this._des2.encryptBlock(M, offset);
this._des1.decryptBlock(M, offset);
},
keySize: 192/32,
ivSize: 64/32,
blockSize: 64/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
*/
C.TripleDES = BlockCipher._createHelper(TripleDES);
}());
return CryptoJS.TripleDES;
}));
},{"./cipher-core":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],75:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var X32WordArray = C_lib.WordArray;
/**
* x64 namespace.
*/
var C_x64 = C.x64 = {};
/**
* A 64-bit word.
*/
var X64Word = C_x64.Word = Base.extend({
/**
* Initializes a newly created 64-bit word.
*
* @param {number} high The high 32 bits.
* @param {number} low The low 32 bits.
*
* @example
*
* var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
*/
init: function (high, low) {
this.high = high;
this.low = low;
}
/**
* Bitwise NOTs this word.
*
* @return {X64Word} A new x64-Word object after negating.
*
* @example
*
* var negated = x64Word.not();
*/
// not: function () {
// var high = ~this.high;
// var low = ~this.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ANDs this word with the passed word.
*
* @param {X64Word} word The x64-Word to AND with this word.
*
* @return {X64Word} A new x64-Word object after ANDing.
*
* @example
*
* var anded = x64Word.and(anotherX64Word);
*/
// and: function (word) {
// var high = this.high & word.high;
// var low = this.low & word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to OR with this word.
*
* @return {X64Word} A new x64-Word object after ORing.
*
* @example
*
* var ored = x64Word.or(anotherX64Word);
*/
// or: function (word) {
// var high = this.high | word.high;
// var low = this.low | word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise XORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to XOR with this word.
*
* @return {X64Word} A new x64-Word object after XORing.
*
* @example
*
* var xored = x64Word.xor(anotherX64Word);
*/
// xor: function (word) {
// var high = this.high ^ word.high;
// var low = this.low ^ word.low;
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the left.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftL(25);
*/
// shiftL: function (n) {
// if (n < 32) {
// var high = (this.high << n) | (this.low >>> (32 - n));
// var low = this.low << n;
// } else {
// var high = this.low << (n - 32);
// var low = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the right.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftR(7);
*/
// shiftR: function (n) {
// if (n < 32) {
// var low = (this.low >>> n) | (this.high << (32 - n));
// var high = this.high >>> n;
// } else {
// var low = this.high >>> (n - 32);
// var high = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Rotates this word n bits to the left.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotL(25);
*/
// rotL: function (n) {
// return this.shiftL(n).or(this.shiftR(64 - n));
// },
/**
* Rotates this word n bits to the right.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotR(7);
*/
// rotR: function (n) {
// return this.shiftR(n).or(this.shiftL(64 - n));
// },
/**
* Adds this word with the passed word.
*
* @param {X64Word} word The x64-Word to add with this word.
*
* @return {X64Word} A new x64-Word object after adding.
*
* @example
*
* var added = x64Word.add(anotherX64Word);
*/
// add: function (word) {
// var low = (this.low + word.low) | 0;
// var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
// var high = (this.high + word.high + carry) | 0;
// return X64Word.create(high, low);
// }
});
/**
* An array of 64-bit words.
*
* @property {Array} words The array of CryptoJS.x64.Word objects.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var X64WordArray = C_x64.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.x64.WordArray.create();
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ]);
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ], 10);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 8;
}
},
/**
* Converts this 64-bit word array to a 32-bit word array.
*
* @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
*
* @example
*
* var x32WordArray = x64WordArray.toX32();
*/
toX32: function () {
// Shortcuts
var x64Words = this.words;
var x64WordsLength = x64Words.length;
// Convert
var x32Words = [];
for (var i = 0; i < x64WordsLength; i++) {
var x64Word = x64Words[i];
x32Words.push(x64Word.high);
x32Words.push(x64Word.low);
}
return X32WordArray.create(x32Words, this.sigBytes);
},
/**
* Creates a copy of this word array.
*
* @return {X64WordArray} The clone.
*
* @example
*
* var clone = x64WordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
// Clone "words" array
var words = clone.words = this.words.slice(0);
// Clone each X64Word object
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
words[i] = words[i].clone();
}
return clone;
}
});
}());
return CryptoJS;
}));
},{"./core":44}],76:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],77:[function(_dereq_,module,exports){
(function (process,global){
/*!
localForage -- Offline Storage, Improved
Version 1.3.0
https://mozilla.github.io/localForage
(c) 2013-2015 Mozilla, Apache License 2.0
*/
(function() {
var define, requireModule, _dereq_, requirejs;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requirejs = _dereq_ = requireModule = function(name) {
requirejs._eak_seen = registry;
if (seen[name]) { return seen[name]; }
seen[name] = {};
if (!registry[name]) {
throw new Error("Could not find module " + name);
}
var mod = registry[name],
deps = mod.deps,
callback = mod.callback,
reified = [],
exports;
for (var i=0, l=deps.length; i<l; i++) {
if (deps[i] === 'exports') {
reified.push(exports = {});
} else {
reified.push(requireModule(resolve(deps[i])));
}
}
var value = callback.apply(this, reified);
return seen[name] = exports || value;
function resolve(child) {
if (child.charAt(0) !== '.') { return child; }
var parts = child.split("/");
var parentBase = name.split("/").slice(0, -1);
for (var i=0, l=parts.length; i<l; i++) {
var part = parts[i];
if (part === '..') { parentBase.pop(); }
else if (part === '.') { continue; }
else { parentBase.push(part); }
}
return parentBase.join("/");
}
};
})();
define("promise/all",
["./utils","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global toString */
var isArray = __dependency1__.isArray;
var isFunction = __dependency1__.isFunction;
/**
Returns a promise that is fulfilled when all the given promises have been
fulfilled, or rejected if any of them become rejected. The return promise
is fulfilled with an array that gives all the values in the order they were
passed in the `promises` array argument.
Example:
```javascript
var promise1 = RSVP.resolve(1);
var promise2 = RSVP.resolve(2);
var promise3 = RSVP.resolve(3);
var promises = [ promise1, promise2, promise3 ];
RSVP.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `RSVP.all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
var promise1 = RSVP.resolve(1);
var promise2 = RSVP.reject(new Error("2"));
var promise3 = RSVP.reject(new Error("3"));
var promises = [ promise1, promise2, promise3 ];
RSVP.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@for RSVP
@param {Array} promises
@param {String} label
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
*/
function all(promises) {
/*jshint validthis:true */
var Promise = this;
if (!isArray(promises)) {
throw new TypeError('You must pass an array to all.');
}
return new Promise(function(resolve, reject) {
var results = [], remaining = promises.length,
promise;
if (remaining === 0) {
resolve([]);
}
function resolver(index) {
return function(value) {
resolveAll(index, value);
};
}
function resolveAll(index, value) {
results[index] = value;
if (--remaining === 0) {
resolve(results);
}
}
for (var i = 0; i < promises.length; i++) {
promise = promises[i];
if (promise && isFunction(promise.then)) {
promise.then(resolver(i), reject);
} else {
resolveAll(i, promise);
}
}
});
}
__exports__.all = all;
});
define("promise/asap",
["exports"],
function(__exports__) {
"use strict";
var browserGlobal = (typeof window !== 'undefined') ? window : {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this);
// node
function useNextTick() {
return function() {
process.nextTick(flush);
};
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function() {
node.data = (iterations = ++iterations % 2);
};
}
function useSetTimeout() {
return function() {
local.setTimeout(flush, 1);
};
}
var queue = [];
function flush() {
for (var i = 0; i < queue.length; i++) {
var tuple = queue[i];
var callback = tuple[0], arg = tuple[1];
callback(arg);
}
queue = [];
}
var scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else {
scheduleFlush = useSetTimeout();
}
function asap(callback, arg) {
var length = queue.push([callback, arg]);
if (length === 1) {
// If length is 1, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
scheduleFlush();
}
}
__exports__.asap = asap;
});
define("promise/config",
["exports"],
function(__exports__) {
"use strict";
var config = {
instrument: false
};
function configure(name, value) {
if (arguments.length === 2) {
config[name] = value;
} else {
return config[name];
}
}
__exports__.config = config;
__exports__.configure = configure;
});
define("promise/polyfill",
["./promise","./utils","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
/*global self*/
var RSVPPromise = __dependency1__.Promise;
var isFunction = __dependency2__.isFunction;
function polyfill() {
var local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof window !== 'undefined' && window.document) {
local = window;
} else {
local = self;
}
var es6PromiseSupport =
"Promise" in local &&
// Some of these methods are missing from
// Firefox/Chrome experimental implementations
"resolve" in local.Promise &&
"reject" in local.Promise &&
"all" in local.Promise &&
"race" in local.Promise &&
// Older version of the spec had a resolver object
// as the arg rather than a function
(function() {
var resolve;
new local.Promise(function(r) { resolve = r; });
return isFunction(resolve);
}());
if (!es6PromiseSupport) {
local.Promise = RSVPPromise;
}
}
__exports__.polyfill = polyfill;
});
define("promise/promise",
["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"],
function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) {
"use strict";
var config = __dependency1__.config;
var configure = __dependency1__.configure;
var objectOrFunction = __dependency2__.objectOrFunction;
var isFunction = __dependency2__.isFunction;
var now = __dependency2__.now;
var all = __dependency3__.all;
var race = __dependency4__.race;
var staticResolve = __dependency5__.resolve;
var staticReject = __dependency6__.reject;
var asap = __dependency7__.asap;
var counter = 0;
config.async = asap; // default async is asap;
function Promise(resolver) {
if (!isFunction(resolver)) {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
if (!(this instanceof Promise)) {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
this._subscribers = [];
invokeResolver(resolver, this);
}
function invokeResolver(resolver, promise) {
function resolvePromise(value) {
resolve(promise, value);
}
function rejectPromise(reason) {
reject(promise, reason);
}
try {
resolver(resolvePromise, rejectPromise);
} catch(e) {
rejectPromise(e);
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
try {
value = callback(detail);
succeeded = true;
} catch(e) {
failed = true;
error = e;
}
} else {
value = detail;
succeeded = true;
}
if (handleThenable(promise, value)) {
return;
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (failed) {
reject(promise, error);
} else if (settled === FULFILLED) {
resolve(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
var PENDING = void 0;
var SEALED = 0;
var FULFILLED = 1;
var REJECTED = 2;
function subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
subscribers[length] = child;
subscribers[length + FULFILLED] = onFulfillment;
subscribers[length + REJECTED] = onRejection;
}
function publish(promise, settled) {
var child, callback, subscribers = promise._subscribers, detail = promise._detail;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
invokeCallback(settled, child, callback, detail);
}
promise._subscribers = null;
}
Promise.prototype = {
constructor: Promise,
_state: undefined,
_detail: undefined,
_subscribers: undefined,
then: function(onFulfillment, onRejection) {
var promise = this;
var thenPromise = new this.constructor(function() {});
if (this._state) {
var callbacks = arguments;
config.async(function invokePromiseCallback() {
invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail);
});
} else {
subscribe(this, thenPromise, onFulfillment, onRejection);
}
return thenPromise;
},
'catch': function(onRejection) {
return this.then(null, onRejection);
}
};
Promise.all = all;
Promise.race = race;
Promise.resolve = staticResolve;
Promise.reject = staticReject;
function handleThenable(promise, value) {
var then = null,
resolved;
try {
if (promise === value) {
throw new TypeError("A promises callback cannot return that same promise.");
}
if (objectOrFunction(value)) {
then = value.then;
if (isFunction(then)) {
then.call(value, function(val) {
if (resolved) { return true; }
resolved = true;
if (value !== val) {
resolve(promise, val);
} else {
fulfill(promise, val);
}
}, function(val) {
if (resolved) { return true; }
resolved = true;
reject(promise, val);
});
return true;
}
}
} catch (error) {
if (resolved) { return true; }
reject(promise, error);
return true;
}
return false;
}
function resolve(promise, value) {
if (promise === value) {
fulfill(promise, value);
} else if (!handleThenable(promise, value)) {
fulfill(promise, value);
}
}
function fulfill(promise, value) {
if (promise._state !== PENDING) { return; }
promise._state = SEALED;
promise._detail = value;
config.async(publishFulfillment, promise);
}
function reject(promise, reason) {
if (promise._state !== PENDING) { return; }
promise._state = SEALED;
promise._detail = reason;
config.async(publishRejection, promise);
}
function publishFulfillment(promise) {
publish(promise, promise._state = FULFILLED);
}
function publishRejection(promise) {
publish(promise, promise._state = REJECTED);
}
__exports__.Promise = Promise;
});
define("promise/race",
["./utils","exports"],
function(__dependency1__, __exports__) {
"use strict";
/* global toString */
var isArray = __dependency1__.isArray;
/**
`RSVP.race` allows you to watch a series of promises and act as soon as the
first promise given to the `promises` argument fulfills or rejects.
Example:
```javascript
var promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 1");
}, 200);
});
var promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 2");
}, 100);
});
RSVP.race([promise1, promise2]).then(function(result){
// result === "promise 2" because it was resolved before promise1
// was resolved.
});
```
`RSVP.race` is deterministic in that only the state of the first completed
promise matters. For example, even if other promises given to the `promises`
array argument are resolved, but the first completed promise has become
rejected before the other promises became fulfilled, the returned promise
will become rejected:
```javascript
var promise1 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
resolve("promise 1");
}, 200);
});
var promise2 = new RSVP.Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error("promise 2"));
}, 100);
});
RSVP.race([promise1, promise2]).then(function(result){
// Code here never runs because there are rejected promises!
}, function(reason){
// reason.message === "promise2" because promise 2 became rejected before
// promise 1 became fulfilled
});
```
@method race
@for RSVP
@param {Array} promises array of promises to observe
@param {String} label optional string for describing the promise returned.
Useful for tooling.
@return {Promise} a promise that becomes fulfilled with the value the first
completed promises is resolved with if the first completed promise was
fulfilled, or rejected with the reason that the first completed promise
was rejected with.
*/
function race(promises) {
/*jshint validthis:true */
var Promise = this;
if (!isArray(promises)) {
throw new TypeError('You must pass an array to race.');
}
return new Promise(function(resolve, reject) {
var results = [], promise;
for (var i = 0; i < promises.length; i++) {
promise = promises[i];
if (promise && typeof promise.then === 'function') {
promise.then(resolve, reject);
} else {
resolve(promise);
}
}
});
}
__exports__.race = race;
});
define("promise/reject",
["exports"],
function(__exports__) {
"use strict";
/**
`RSVP.reject` returns a promise that will become rejected with the passed
`reason`. `RSVP.reject` is essentially shorthand for the following:
```javascript
var promise = new RSVP.Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
var promise = RSVP.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@for RSVP
@param {Any} reason value that the returned promise will be rejected with.
@param {String} label optional string for identifying the returned promise.
Useful for tooling.
@return {Promise} a promise that will become rejected with the given
`reason`.
*/
function reject(reason) {
/*jshint validthis:true */
var Promise = this;
return new Promise(function (resolve, reject) {
reject(reason);
});
}
__exports__.reject = reject;
});
define("promise/resolve",
["exports"],
function(__exports__) {
"use strict";
function resolve(value) {
/*jshint validthis:true */
if (value && typeof value === 'object' && value.constructor === this) {
return value;
}
var Promise = this;
return new Promise(function(resolve) {
resolve(value);
});
}
__exports__.resolve = resolve;
});
define("promise/utils",
["exports"],
function(__exports__) {
"use strict";
function objectOrFunction(x) {
return isFunction(x) || (typeof x === "object" && x !== null);
}
function isFunction(x) {
return typeof x === "function";
}
function isArray(x) {
return Object.prototype.toString.call(x) === "[object Array]";
}
// Date.now is not available in browsers < IE9
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility
var now = Date.now || function() { return new Date().getTime(); };
__exports__.objectOrFunction = objectOrFunction;
__exports__.isFunction = isFunction;
__exports__.isArray = isArray;
__exports__.now = now;
});
requireModule('promise/polyfill').polyfill();
}());(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["localforage"] = factory();
else
root["localforage"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
(function () {
'use strict';
// Custom drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var CustomDrivers = {};
var DriverType = {
INDEXEDDB: 'asyncStorage',
LOCALSTORAGE: 'localStorageWrapper',
WEBSQL: 'webSQLStorage'
};
var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE];
var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'];
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
// Check to see if IndexedDB is available and if it is the latest
// implementation; it's our preferred backend library. We use "_spec_test"
// as the name of the database because it's not the one we'll operate on,
// but it's useful to make sure its using the right spec.
// See: https://github.com/mozilla/localForage/issues/128
var driverSupport = (function (self) {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB;
var result = {};
result[DriverType.WEBSQL] = !!self.openDatabase;
result[DriverType.INDEXEDDB] = !!(function () {
// We mimic PouchDB here; just UA test for Safari (which, as of
// iOS 8/Yosemite, doesn't properly support IndexedDB).
// IndexedDB support is broken and different from Blink's.
// This is faster than the test case (and it's sync), so we just
// do this. *SIGH*
// http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) {
return false;
}
try {
return indexedDB && typeof indexedDB.open === 'function' &&
// Some Samsung/HTC Android 4.0-4.3 devices
// have older IndexedDB specs; if this isn't available
// their IndexedDB is too old for us to use.
// (Replaces the onupgradeneeded test.)
typeof self.IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
})();
result[DriverType.LOCALSTORAGE] = !!(function () {
try {
return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem;
} catch (e) {
return false;
}
})();
return result;
})(this);
var isArray = Array.isArray || function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function () {
var _args = arguments;
return localForageInstance.ready().then(function () {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var key in arg) {
if (arg.hasOwnProperty(key)) {
if (isArray(arg[key])) {
arguments[0][key] = arg[key].slice();
} else {
arguments[0][key] = arg[key];
}
}
}
}
}
return arguments[0];
}
function isLibraryDriver(driverName) {
for (var driver in DriverType) {
if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) {
return true;
}
}
return false;
}
var LocalForage = (function () {
function LocalForage(options) {
_classCallCheck(this, LocalForage);
this.INDEXEDDB = DriverType.INDEXEDDB;
this.LOCALSTORAGE = DriverType.LOCALSTORAGE;
this.WEBSQL = DriverType.WEBSQL;
this._defaultConfig = extend({}, DefaultConfig);
this._config = extend({}, this._defaultConfig, options);
this._driverSet = null;
this._initDriver = null;
this._ready = false;
this._dbInfo = null;
this._wrapLibraryMethodsWithReady();
this.setDriver(this._config.driver);
}
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function config(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if (typeof options === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " + 'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
this.setDriver(this._config.driver);
}
return true;
} else if (typeof options === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
var promise = new Promise(function (resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
var namingError = new Error('Custom driver name already in use: ' + driverObject._driver);
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
if (isLibraryDriver(driverObject._driver)) {
reject(namingError);
return;
}
var customDriverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0; i < customDriverMethods.length; i++) {
var customDriverMethod = customDriverMethods[i];
if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') {
reject(complianceError);
return;
}
}
var supportPromise = Promise.resolve(true);
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
supportPromise = driverObject._support();
} else {
supportPromise = Promise.resolve(!!driverObject._support);
}
}
supportPromise.then(function (supportResult) {
driverSupport[driverName] = supportResult;
CustomDrivers[driverName] = driverObject;
resolve();
}, reject);
} catch (e) {
reject(e);
}
});
promise.then(callback, errorCallback);
return promise;
};
LocalForage.prototype.driver = function driver() {
return this._driver || null;
};
LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
var self = this;
var getDriverPromise = (function () {
if (isLibraryDriver(driverName)) {
switch (driverName) {
case self.INDEXEDDB:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(1));
});
case self.LOCALSTORAGE:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(2));
});
case self.WEBSQL:
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(4));
});
}
} else if (CustomDrivers[driverName]) {
return Promise.resolve(CustomDrivers[driverName]);
}
return Promise.reject(new Error('Driver not found.'));
})();
getDriverPromise.then(callback, errorCallback);
return getDriverPromise;
};
LocalForage.prototype.getSerializer = function getSerializer(callback) {
var serializerPromise = new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
});
if (callback && typeof callback === 'function') {
serializerPromise.then(function (result) {
callback(result);
});
}
return serializerPromise;
};
LocalForage.prototype.ready = function ready(callback) {
var self = this;
var promise = self._driverSet.then(function () {
if (self._ready === null) {
self._ready = self._initDriver();
}
return self._ready;
});
promise.then(callback, callback);
return promise;
};
LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
var self = this;
if (!isArray(drivers)) {
drivers = [drivers];
}
var supportedDrivers = this._getSupportedDrivers(drivers);
function setDriverToConfig() {
self._config.driver = self.driver();
}
function initDriver(supportedDrivers) {
return function () {
var currentDriverIndex = 0;
function driverPromiseLoop() {
while (currentDriverIndex < supportedDrivers.length) {
var driverName = supportedDrivers[currentDriverIndex];
currentDriverIndex++;
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function (driver) {
self._extend(driver);
setDriverToConfig();
self._ready = self._initStorage(self._config);
return self._ready;
})['catch'](driverPromiseLoop);
}
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise.reject(error);
return self._driverSet;
}
return driverPromiseLoop();
};
}
// There might be a driver initialization in progress
// so wait for it to finish in order to avoid a possible
// race condition to set _dbInfo
var oldDriverSetDone = this._driverSet !== null ? this._driverSet['catch'](function () {
return Promise.resolve();
}) : Promise.resolve();
this._driverSet = oldDriverSetDone.then(function () {
var driverName = supportedDrivers[0];
self._dbInfo = null;
self._ready = null;
return self.getDriver(driverName).then(function (driver) {
self._driver = driver._driver;
setDriverToConfig();
self._wrapLibraryMethodsWithReady();
self._initDriver = initDriver(supportedDrivers);
});
})['catch'](function () {
setDriverToConfig();
var error = new Error('No available storage method found.');
self._driverSet = Promise.reject(error);
return self._driverSet;
});
this._driverSet.then(callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function supports(driverName) {
return !!driverSupport[driverName];
};
LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
var supportedDrivers = [];
for (var i = 0, len = drivers.length; i < len; i++) {
var driverName = drivers[i];
if (this.supports(driverName)) {
supportedDrivers.push(driverName);
}
}
return supportedDrivers;
};
LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0; i < LibraryMethods.length; i++) {
callWhenReady(this, LibraryMethods[i]);
}
};
LocalForage.prototype.createInstance = function createInstance(options) {
return new LocalForage(options);
};
return LocalForage;
})();
var localForage = new LocalForage();
exports['default'] = localForage;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 1 */
/***/ function(module, exports) {
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
'use strict';
exports.__esModule = true;
(function () {
'use strict';
var globalObject = this;
// Initialize IndexedDB; fall back to vendor-prefixed versions if needed.
var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB;
// If IndexedDB isn't available, we get outta here!
if (!indexedDB) {
return;
}
var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs;
var dbContexts;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
// Fetch a blob using ajax. This reveals bugs in Chrome < 43.
// For details on all this junk:
// https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme
function _blobAjax(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
return resolve({
response: xhr.response,
type: xhr.getResponseHeader('Content-Type')
});
}
reject({ status: xhr.status, response: xhr.response });
};
xhr.send();
});
}
//
// Detect blob support. Chrome didn't support it until version 38.
// In version 37 they had a broken version where PNGs (and possibly
// other binary types) aren't stored correctly, because when you fetch
// them, the content type is always null.
//
// Furthermore, they have some outstanding bugs where blobs occasionally
// are read by FileReader as null, or by ajax as 404s.
//
// Sadly we use the 404 bug to detect the FileReader bug, so if they
// get fixed independently and released in different versions of Chrome,
// then the bug could come back. So it's worthwhile to watch these issues:
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise(function (resolve, reject) {
var blob = _createBlob([''], { type: 'image/png' });
var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.oncomplete = function () {
// have to do it in a separate transaction, else the correct
// content type is always returned
var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
var getBlobReq = blobTxn.objectStore(DETECT_BLOB_SUPPORT_STORE).get('key');
getBlobReq.onerror = reject;
getBlobReq.onsuccess = function (e) {
var storedBlob = e.target.result;
var url = URL.createObjectURL(storedBlob);
_blobAjax(url).then(function (res) {
resolve(!!(res && res.type === 'image/png'));
}, function () {
resolve(false);
}).then(function () {
URL.revokeObjectURL(url);
});
};
};
})['catch'](function () {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return Promise.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function (value) {
supportsBlobs = value;
return supportsBlobs;
});
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function (e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return _createBlob([arrayBuff], { type: encodedBlob.type });
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
// Initialize a singleton container for all running localForages.
if (!dbContexts) {
dbContexts = {};
}
// Get the current context of the database;
var dbContext = dbContexts[dbInfo.name];
// ...or create a new context.
if (!dbContext) {
dbContext = {
// Running localForages sharing a database.
forages: [],
// Shared database.
db: null
};
// Register the new context in the global container.
dbContexts[dbInfo.name] = dbContext;
}
// Register itself as a running localForage in the current context.
dbContext.forages.push(this);
// Create an array of readiness of the related localForages.
var readyPromises = [];
function ignoreErrors() {
// Don't handle errors here,
// just makes sure related localForages aren't pending.
return Promise.resolve();
}
for (var j = 0; j < dbContext.forages.length; j++) {
var forage = dbContext.forages[j];
if (forage !== this) {
// Don't wait for itself...
readyPromises.push(forage.ready()['catch'](ignoreErrors));
}
}
// Take a snapshot of the related localForages.
var forages = dbContext.forages.slice(0);
// Initialize the connection process only when
// all the related localForages aren't pending.
return Promise.all(readyPromises).then(function () {
dbInfo.db = dbContext.db;
// Get the connection or open a new one without upgrade.
return _getOriginalConnection(dbInfo);
}).then(function (db) {
dbInfo.db = db;
if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
// Reopen the database for upgrading.
return _getUpgradedConnection(dbInfo);
}
return db;
}).then(function (db) {
dbInfo.db = dbContext.db = db;
self._dbInfo = dbInfo;
// Share the final connection amongst related localForages.
for (var k in forages) {
var forage = forages[k];
if (forage !== self) {
// Self is already up-to-date.
forage._dbInfo.db = dbInfo.db;
forage._dbInfo.version = dbInfo.version;
}
}
});
}
function _getOriginalConnection(dbInfo) {
return _getConnection(dbInfo, false);
}
function _getUpgradedConnection(dbInfo) {
return _getConnection(dbInfo, true);
}
function _getConnection(dbInfo, upgradeNeeded) {
return new Promise(function (resolve, reject) {
if (dbInfo.db) {
if (upgradeNeeded) {
dbInfo.db.close();
} else {
return resolve(dbInfo.db);
}
}
var dbArgs = [dbInfo.name];
if (upgradeNeeded) {
dbArgs.push(dbInfo.version);
}
var openreq = indexedDB.open.apply(indexedDB, dbArgs);
if (upgradeNeeded) {
openreq.onupgradeneeded = function (e) {
var db = openreq.result;
try {
db.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// Added when support for blob shims was added
db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
} catch (ex) {
if (ex.name === 'ConstraintError') {
globalObject.console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
} else {
throw ex;
}
}
};
}
openreq.onerror = function () {
reject(openreq.error);
};
openreq.onsuccess = function () {
resolve(openreq.result);
};
});
}
function _isUpgradeNeeded(dbInfo, defaultVersion) {
if (!dbInfo.db) {
return true;
}
var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
var isDowngrade = dbInfo.version < dbInfo.db.version;
var isUpgrade = dbInfo.version > dbInfo.db.version;
if (isDowngrade) {
// If the version is not the default one
// then warn for impossible downgrade.
if (dbInfo.version !== defaultVersion) {
globalObject.console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
}
// Align the versions to prevent errors.
dbInfo.version = dbInfo.db.version;
}
if (isUpgrade || isNewStore) {
// If the store is new then increment the version (if needed).
// This will trigger an "upgradeneeded" event which is required
// for creating a store.
if (isNewStore) {
var incVersion = dbInfo.db.version + 1;
if (incVersion > dbInfo.version) {
dbInfo.version = incVersion;
}
}
return true;
}
return false;
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function () {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function () {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
if (result !== void 0) {
resolve(result);
} else {
cursor['continue']();
}
} else {
resolve();
}
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
var dbInfo;
self.ready().then(function () {
dbInfo = self._dbInfo;
return _checkBlobSupport(dbInfo.db);
}).then(function (blobSupport) {
if (!blobSupport && value instanceof Blob) {
return _encodeBlob(value);
}
return value;
}).then(function (value) {
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
transaction.oncomplete = function () {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `['delete']()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store['delete'](key);
transaction.oncomplete = function () {
resolve();
};
transaction.onerror = function () {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function () {
resolve();
};
transaction.onabort = transaction.onerror = function () {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.count();
req.onsuccess = function () {
resolve(req.result);
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var advanced = false;
var req = store.openCursor();
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
var req = store.openCursor();
var keys = [];
req.onsuccess = function () {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor['continue']();
};
req.onerror = function () {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
exports['default'] = asyncStorage;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).
'use strict';
exports.__esModule = true;
(function () {
'use strict';
var globalObject = this;
var localStorage = null;
// If the app is running inside a Google Chrome packaged webapp, or some
// other context where localStorage isn't available, we don't use
// localStorage. This feature detection is preferred over the old
// `if (window.chrome && window.chrome.runtime)` code.
// See: https://github.com/mozilla/localForage/issues/68
try {
// If localStorage isn't available, we get outta here!
// This should be inside a try catch
if (!this.localStorage || !('setItem' in this.localStorage)) {
return;
}
// Initialize localStorage and create a variable to use throughout
// the code.
localStorage = this.localStorage;
} catch (e) {
return;
}
// Config the localStorage backend, using options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = dbInfo.name + '/';
if (dbInfo.storeName !== self._defaultConfig.storeName) {
dbInfo.keyPrefix += dbInfo.storeName + '/';
}
self._dbInfo = dbInfo;
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
}).then(function (lib) {
dbInfo.serializer = lib;
return Promise.resolve();
});
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear(callback) {
var self = this;
var promise = self.ready().then(function () {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate(iterator, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var keyPrefix = dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
// We use a dedicated iterator instead of the `i` variable below
// so other keys we fetch in localStorage aren't counted in
// the `iterationNumber` argument passed to the `iterate()`
// callback.
//
// See: github.com/mozilla/localForage/pull/435#discussion_r38061530
var iterationNumber = 1;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) !== 0) {
continue;
}
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = dbInfo.serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
if (value !== void 0) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key(n, callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) {
keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length(callback) {
var self = this;
var promise = self.keys().then(function (keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function () {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function () {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise(function (resolve, reject) {
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
try {
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage,
// Default API, from Gaia/localStorage.
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
exports['default'] = localStorageWrapper;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 3 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
(function () {
'use strict';
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
// Get out of our habit of using `window` inline, at least.
var globalObject = this;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (err) {
if (err.name !== 'TypeError') {
throw err;
}
var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueString = '';
if (value) {
valueString = value.toString();
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueString === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueString === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueString === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueString === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueString === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueString === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueString === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueString === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueString === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueString === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function () {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ", value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return _createBlob([buffer], { type: blobType });
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i += 4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
/*jslint bitwise: true */
bytes[p++] = encoded1 << 2 | encoded2 >> 4;
bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if (bytes.length % 3 === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
exports['default'] = localforageSerializer;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
'use strict';
exports.__esModule = true;
(function () {
'use strict';
var globalObject = this;
var openDatabase = this.openDatabase;
// If WebSQL methods aren't available, we can stop now.
if (!openDatabase) {
return;
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
}
}
var dbInfoPromise = new Promise(function (resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
} catch (e) {
return self.setDriver(self.LOCALSTORAGE).then(function () {
return self._initStorage(options);
}).then(resolve)['catch'](reject);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function (t) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () {
self._dbInfo = dbInfo;
resolve();
}, function (t, error) {
reject(error);
});
});
});
return new Promise(function (resolve, reject) {
resolve(__webpack_require__(3));
}).then(function (lib) {
dbInfo.serializer = lib;
return dbInfoPromise;
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
var result = results.rows.length ? results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
resolve(result);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = dbInfo.serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void 0) {
resolve(result);
return;
}
}
resolve();
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
var dbInfo = self._dbInfo;
dbInfo.serializer.serialize(value, function (value, error) {
if (error) {
reject(error);
} else {
dbInfo.db.transaction(function (t) {
t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () {
resolve(originalValue);
}, function (t, error) {
reject(error);
});
}, function (sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// TODO: Try to re-run the transaction.
reject(sqlError);
}
});
}
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
globalObject.console.warn(key + ' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () {
resolve();
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
// Ahhh, SQL makes this one soooooo easy.
t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key(n, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
var result = results.rows.length ? results.rows.item(0).key : null;
resolve(result);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.ready().then(function () {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function (t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function (t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function (result) {
callback(null, result);
}, function (error) {
callback(error);
});
}
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
exports['default'] = webSQLStorage;
}).call(typeof window !== 'undefined' ? window : self);
module.exports = exports['default'];
/***/ }
/******/ ])
});
;
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":76}],78:[function(_dereq_,module,exports){
// Top level file is just a mixin of submodules & constants
'use strict';
var assign = _dereq_('./lib/utils/common').assign;
var deflate = _dereq_('./lib/deflate');
var inflate = _dereq_('./lib/inflate');
var constants = _dereq_('./lib/zlib/constants');
var pako = {};
assign(pako, deflate, inflate, constants);
module.exports = pako;
},{"./lib/deflate":79,"./lib/inflate":80,"./lib/utils/common":81,"./lib/zlib/constants":84}],79:[function(_dereq_,module,exports){
'use strict';
var zlib_deflate = _dereq_('./zlib/deflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH = 0;
var Z_FINISH = 4;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_SYNC_FLUSH = 2;
var Z_DEFAULT_COMPRESSION = -1;
var Z_DEFAULT_STRATEGY = 0;
var Z_DEFLATED = 8;
/* ===========================================================================*/
/**
* class Deflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[deflate]],
* [[deflateRaw]] and [[gzip]].
**/
/* internal
* Deflate.chunks -> Array
*
* Chunks of output data, if [[Deflate#onData]] not overriden.
**/
/**
* Deflate.result -> Uint8Array|Array
*
* Compressed result, generated by default [[Deflate#onData]]
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Deflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Deflate.err -> Number
*
* Error code after deflate finished. 0 (Z_OK) on success.
* You will not need it in real life, because deflate errors
* are possible only on wrong options or bad `onData` / `onEnd`
* custom handlers.
**/
/**
* Deflate.msg -> String
*
* Error message, if [[Deflate.err]] != 0
**/
/**
* new Deflate(options)
* - options (Object): zlib deflate options.
*
* Creates new deflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `level`
* - `windowBits`
* - `memLevel`
* - `strategy`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw deflate
* - `gzip` (Boolean) - create gzip wrapper
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
* - `header` (Object) - custom header for gzip
* - `text` (Boolean) - true if compressed data believed to be text
* - `time` (Number) - modification time, unix timestamp
* - `os` (Number) - operation system code
* - `extra` (Array) - array of bytes with extra data (max 65536)
* - `name` (String) - file name (binary string)
* - `comment` (String) - comment (binary string)
* - `hcrc` (Boolean) - true if header crc should be added
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var deflate = new pako.Deflate({ level: 3});
*
* deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk
*
* if (deflate.err) { throw new Error(deflate.err); }
*
* console.log(deflate.result);
* ```
**/
var Deflate = function(options) {
this.options = utils.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY,
to: ''
}, options || {});
var opt = this.options;
if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits;
}
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2(
this.strm,
opt.level,
opt.method,
opt.windowBits,
opt.memLevel,
opt.strategy
);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
if (opt.header) {
zlib_deflate.deflateSetHeader(this.strm, opt.header);
}
};
/**
* Deflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
* converted to utf8 byte sequence.
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
* new compressed chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the compression context.
*
* On fail call [[Deflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* array format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Deflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
// Finalize on the last chunk.
if (_mode === Z_FINISH) {
status = zlib_deflate.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === Z_SYNC_FLUSH) {
this.onEnd(Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Deflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Deflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Deflate#onEnd(status) -> Void
* - status (Number): deflate status. 0 (Z_OK) on success,
* other if not.
*
* Called once after you tell deflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Deflate.prototype.onEnd = function(status) {
// On success - join
if (status === Z_OK) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* deflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* Compress `data` with deflate alrorythm and `options`.
*
* Supported options are:
*
* - level
* - windowBits
* - memLevel
* - strategy
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
*
* console.log(pako.deflate(data));
* ```
**/
function deflate(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (deflator.err) { throw deflator.msg; }
return deflator.result;
}
/**
* deflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate(input, options);
}
/**
* gzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but create gzip wrapper instead of
* deflate one.
**/
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate(input, options);
}
exports.Deflate = Deflate;
exports.deflate = deflate;
exports.deflateRaw = deflateRaw;
exports.gzip = gzip;
},{"./utils/common":81,"./utils/strings":82,"./zlib/deflate.js":86,"./zlib/messages":91,"./zlib/zstream":93}],80:[function(_dereq_,module,exports){
'use strict';
var zlib_inflate = _dereq_('./zlib/inflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var c = _dereq_('./zlib/constants');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var gzheader = _dereq_('./zlib/gzheader');
var toString = Object.prototype.toString;
/**
* class Inflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[inflate]]
* and [[inflateRaw]].
**/
/* internal
* inflate.chunks -> Array
*
* Chunks of output data, if [[Inflate#onData]] not overriden.
**/
/**
* Inflate.result -> Uint8Array|Array|String
*
* Uncompressed result, generated by default [[Inflate#onData]]
* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Inflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Inflate.err -> Number
*
* Error code after inflate finished. 0 (Z_OK) on success.
* Should be checked if broken data possible.
**/
/**
* Inflate.msg -> String
*
* Error message, if [[Inflate.err]] != 0
**/
/**
* new Inflate(options)
* - options (Object): zlib inflate options.
*
* Creates new inflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `windowBits`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw inflate
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
* By default, when no options set, autodetect deflate/gzip data format via
* wrapper header.
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var inflate = new pako.Inflate({ level: 3});
*
* inflate.push(chunk1, false);
* inflate.push(chunk2, true); // true -> last chunk
*
* if (inflate.err) { throw new Error(inflate.err); }
*
* console.log(inflate.result);
* ```
**/
var Inflate = function(options) {
this.options = utils.assign({
chunkSize: 16384,
windowBits: 0,
to: ''
}, options || {});
var opt = this.options;
// Force window size for `raw` data, if not set directly,
// because we have no header for autodetect.
if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) { opt.windowBits = -15; }
}
// If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
!(options && options.windowBits)) {
opt.windowBits += 32;
}
// Gzip header has no info about windows size, we can do autodetect only
// for deflate. So, if window size not set, force it to max when gzip possible
if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
// bit 3 (16) -> gzipped data
// bit 4 (32) -> autodetect gzip/deflate
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_inflate.inflateInit2(
this.strm,
opt.windowBits
);
if (status !== c.Z_OK) {
throw new Error(msg[status]);
}
this.header = new gzheader();
zlib_inflate.inflateGetHeader(this.strm, this.header);
};
/**
* Inflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
* new output chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the decompression context.
*
* On fail call [[Inflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Inflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
var next_out_utf8, tail, utf8str;
// Flag to properly process Z_BUF_ERROR on testing inflate call
// when we check that all output data was flushed.
var allowBufError = false;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// Only binary strings can be decompressed on practice
strm.input = strings.binstring2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
if (status === c.Z_BUF_ERROR && allowBufError === true) {
status = c.Z_OK;
allowBufError = false;
}
if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.next_out) {
if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
tail = strm.next_out - next_out_utf8;
utf8str = strings.buf2string(strm.output, next_out_utf8);
// move tail
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
this.onData(utf8str);
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
}
// When no more input data, we should check that internal inflate buffers
// are flushed. The only way to do it when avail_out = 0 - run one more
// inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
// Here we set flag to process this error properly.
//
// NOTE. Deflate does not return error in this case and does not needs such
// logic.
if (strm.avail_in === 0 && strm.avail_out === 0) {
allowBufError = true;
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
if (status === c.Z_STREAM_END) {
_mode = c.Z_FINISH;
}
// Finalize on the last chunk.
if (_mode === c.Z_FINISH) {
status = zlib_inflate.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === c.Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === c.Z_SYNC_FLUSH) {
this.onEnd(c.Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Inflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Inflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Inflate#onEnd(status) -> Void
* - status (Number): inflate status. 0 (Z_OK) on success,
* other if not.
*
* Called either after you tell inflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Inflate.prototype.onEnd = function(status) {
// On success - join
if (status === c.Z_OK) {
if (this.options.to === 'string') {
// Glue & convert here, until we teach pako to send
// utf8 alligned strings to onData
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* inflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Decompress `data` with inflate/ungzip and `options`. Autodetect
* format via wrapper header by default. That's why we don't provide
* separate `ungzip` method.
*
* Supported options are:
*
* - windowBits
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , input = pako.deflate([1,2,3,4,5,6,7,8,9])
* , output;
*
* try {
* output = pako.inflate(input);
* } catch (err)
* console.log(err);
* }
* ```
**/
function inflate(input, options) {
var inflator = new Inflate(options);
inflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (inflator.err) { throw inflator.msg; }
return inflator.result;
}
/**
* inflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* The same as [[inflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function inflateRaw(input, options) {
options = options || {};
options.raw = true;
return inflate(input, options);
}
/**
* ungzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Just shortcut to [[inflate]], because it autodetects format
* by header.content. Done for convenience.
**/
exports.Inflate = Inflate;
exports.inflate = inflate;
exports.inflateRaw = inflateRaw;
exports.ungzip = inflate;
},{"./utils/common":81,"./utils/strings":82,"./zlib/constants":84,"./zlib/gzheader":87,"./zlib/inflate.js":89,"./zlib/messages":91,"./zlib/zstream":93}],81:[function(_dereq_,module,exports){
'use strict';
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
(typeof Uint16Array !== 'undefined') &&
(typeof Int32Array !== 'undefined');
exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue; }
if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (source.hasOwnProperty(p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
return;
}
// Fallback to ordinary array
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i=0, l=chunks.length; i<l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i=0, l=chunks.length; i<l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
return [].concat.apply([], chunks);
}
};
// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
},{}],82:[function(_dereq_,module,exports){
// String encode/decode helpers
'use strict';
var utils = _dereq_('./common');
// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safary
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;
try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new utils.Buf8(256);
for (var q=0; q<256; q++) {
_utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
// convert string to array (typed, when possible)
exports.string2buf = function (str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
buf = new utils.Buf8(buf_len);
// convert
for (i=0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Helper (used in 2 places)
function buf2binstring(buf, len) {
// use fallback for big arrays to avoid stack overflow
if (len < 65537) {
if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
}
}
var result = '';
for (var i=0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
}
// Convert byte array to binary string
exports.buf2binstring = function(buf) {
return buf2binstring(buf, buf.length);
};
// Convert binary string (typed, when possible)
exports.binstring2buf = function(str) {
var buf = new utils.Buf8(str.length);
for (var i=0, len=buf.length; i < len; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
};
// convert array to string
exports.buf2string = function (buf, max) {
var i, out, c, c_len;
var len = max || buf.length;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len*2);
for (out=0, i=0; i<len;) {
c = buf[i++];
// quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; }
c_len = _utf8len[c];
// skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
return buf2binstring(utf16buf, out);
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
exports.utf8border = function(buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
pos = max-1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Fuckup - very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means vuffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
},{"./common":81}],83:[function(_dereq_,module,exports){
'use strict';
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.
function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}
module.exports = adler32;
},{}],84:[function(_dereq_,module,exports){
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
},{}],85:[function(_dereq_,module,exports){
'use strict';
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for (var n =0; n < 256; n++) {
c = n;
for (var k =0; k < 8; k++) {
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable,
end = pos + len;
crc = crc ^ (-1);
for (var i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
},{}],86:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var trees = _dereq_('./trees');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var msg = _dereq_('./messages');
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
//var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
//var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
//var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* compression levels */
//var Z_NO_COMPRESSION = 0;
//var Z_BEST_SPEED = 1;
//var Z_BEST_COMPRESSION = 9;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY = 0;
//var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/* The deflate compression method */
var Z_DEFLATED = 8;
/*============================================================================*/
var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
var PRESET_DICT = 0x20;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
function err(strm, errorCode) {
strm.msg = msg[errorCode];
return errorCode;
}
function rank(f) {
return ((f) << 1) - ((f) > 4 ? 9 : 0);
}
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()).
*/
function flush_pending(strm) {
var s = strm.state;
//_tr_flush_bits(s);
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) { return; }
utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
}
function flush_block_only (s, last) {
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
}
function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
function putShortMSB(s, b) {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) { len = size; }
if (len === 0) { return 0; }
strm.avail_in -= len;
utils.arraySet(buf, strm.input, strm.next_in, len, start);
if (strm.state.wrap === 1) {
strm.adler = adler32(strm.adler, buf, len, start);
}
else if (strm.state.wrap === 2) {
strm.adler = crc32(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
}
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
function longest_match(s, cur_match) {
var chain_length = s.max_chain_length; /* max hash chain length */
var scan = s.strstart; /* current string */
var match; /* matched string */
var len; /* length of current match */
var best_len = s.prev_length; /* best match length so far */
var nice_match = s.nice_match; /* stop if match long enough */
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
var _win = s.window; // shortcut
var wmask = s.w_mask;
var prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end ||
_win[match + best_len - 1] !== scan_end1 ||
_win[match] !== _win[scan] ||
_win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++;
// Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
scan < strend);
// Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
}
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart;
// JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = (m >= _w_size ? m - _w_size : 0);
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = (m >= _w_size ? m - _w_size : 0);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// var curr = s.strstart + s.lookahead;
// var init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of window, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->window + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of window, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->window + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
}
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf.
*/
function deflate_stored(s, flush) {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
var max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the window as much as possible: */
if (s.lookahead <= 1) {
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
// s->block_start >= (long)s->w_size, "slide too late");
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
// s.block_start >= s.w_size)) {
// throw new Error("slide too late");
// }
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
//Assert(s->block_start >= 0L, "block gone");
// if (s.block_start < 0) throw new Error("block gone");
s.strstart += s.lookahead;
s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_NEED_MORE;
}
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
function deflate_fast(s, flush) {
var hash_head; /* head of the hash chain */
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break; /* flush the current block */
}
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
s.match_length--; /* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else
{
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
function deflate_slow(s, flush) {
var hash_head; /* head of hash chain */
var bflush; /* set if current block must be flushed */
var max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH-1;
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 &&
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH-1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length-1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH-1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
//Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
function deflate_rle(s, flush) {
var bflush; /* set if current block must be flushed */
var prev; /* byte at distance one to match */
var scan, strend; /* scan goes up to strend for length of run */
var _win = s.window;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
scan < strend);
s.match_length = MAX_MATCH - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
//Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break; /* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0;
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
};
var configuration_table;
configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
function lm_init(s) {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
function DeflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.status = 0; /* as the name implies */
this.pending_buf = null; /* output still pending */
this.pending_buf_size = 0; /* size of pending_buf */
this.pending_out = 0; /* next pending byte to output to the stream */
this.pending = 0; /* nb of bytes in the pending buffer */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null; /* gzip header information to write */
this.gzindex = 0; /* where in extra, name, or comment */
this.method = Z_DEFLATED; /* can only be DEFLATED */
this.last_flush = -1; /* value of flush param for previous deflate call */
this.w_size = 0; /* LZ77 window size (32K by default) */
this.w_bits = 0; /* log2(w_size) (8..16) */
this.w_mask = 0; /* w_size - 1 */
this.window = null;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
this.head = null; /* Heads of the hash chains or NIL. */
this.ins_h = 0; /* hash index of string to be inserted */
this.hash_size = 0; /* number of elements in hash table */
this.hash_bits = 0; /* log2(hash_size) */
this.hash_mask = 0; /* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
this.match_length = 0; /* length of best match */
this.prev_match = 0; /* previous match */
this.match_available = 0; /* set if previous match exists */
this.strstart = 0; /* start of string to insert */
this.match_start = 0; /* start of matching string */
this.lookahead = 0; /* number of valid bytes ahead in window */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0; /* compression level (1..9) */
this.strategy = 0; /* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null; /* desc. for literal tree */
this.d_desc = null; /* desc. for distance tree */
this.bl_desc = null; /* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new utils.Buf16(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
zero(this.heap);
this.heap_len = 0; /* number of elements in the heap */
this.heap_max = 0; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
zero(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.l_buf = 0; /* buffer index for literals or lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.last_lit = 0; /* running index in l_buf */
this.d_buf = 0;
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
this.opt_len = 0; /* bit length of current block with optimal trees */
this.static_len = 0; /* bit length of current block with static trees */
this.matches = 0; /* number of string matches in current block */
this.insert = 0; /* bytes at end of window left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for window memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
function deflateResetKeep(strm) {
var s;
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
strm.adler = (s.wrap === 2) ?
0 // crc32(0, Z_NULL, 0)
:
1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH;
trees._tr_init(s);
return Z_OK;
}
function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
}
function deflateSetHeader(strm, head) {
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
strm.state.gzhead = head;
return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) { // === Z_NULL
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte window bug fixed */
var s = new DeflateState();
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.window = new utils.Buf8(s.w_size * 2);
s.head = new utils.Buf16(s.hash_size);
s.prev = new utils.Buf16(s.w_size);
// Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->window yet */
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new utils.Buf8(s.pending_buf_size);
s.d_buf = s.lit_bufsize >> 1;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
}
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
var old_flush, s;
var beg, val; // for gzip header write only
if (!strm || !strm.state ||
flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
s = strm.state;
if (!strm.output ||
(!strm.input && strm.avail_in !== 0) ||
(s.status === FINISH_STATE && flush !== Z_FINISH)) {
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm; /* just in case */
old_flush = s.last_flush;
s.last_flush = flush;
/* Write the header */
if (s.status === INIT_STATE) {
if (s.wrap === 2) { // GZIP header
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) { // s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
}
else {
put_byte(s, (s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(!s.gzhead.extra ? 0 : 4) +
(!s.gzhead.name ? 0 : 8) +
(!s.gzhead.comment ? 0 : 16)
);
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, (s.gzhead.time >> 8) & 0xff);
put_byte(s, (s.gzhead.time >> 16) & 0xff);
put_byte(s, (s.gzhead.time >> 24) & 0xff);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
}
else // DEFLATE header
{
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= (level_flags << 6);
if (s.strstart !== 0) { header |= PRESET_DICT; }
header += 31 - (header % 31);
s.status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
}
}
//#ifdef GZIP
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
}
else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
}
else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
}
else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
}
}
else {
s.status = BUSY_STATE;
}
}
//#endif
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
(s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush));
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s);
}
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
trees._tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH) {
/*** CLEAR_HASH(s); ***/ /* forget history */
zero(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
}
//Assert(strm->avail_out > 0, "bug2");
//if (strm.avail_out <= 0) { throw new Error("bug2");}
if (flush !== Z_FINISH) { return Z_OK; }
if (s.wrap <= 0) { return Z_STREAM_END; }
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
put_byte(s, (strm.adler >> 16) & 0xff);
put_byte(s, (strm.adler >> 24) & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, (strm.total_in >> 8) & 0xff);
put_byte(s, (strm.total_in >> 16) & 0xff);
put_byte(s, (strm.total_in >> 24) & 0xff);
}
else
{
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
var status;
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR;
}
status = strm.state.status;
if (status !== INIT_STATE &&
status !== EXTRA_STATE &&
status !== NAME_STATE &&
status !== COMMENT_STATE &&
status !== HCRC_STATE &&
status !== BUSY_STATE &&
status !== FINISH_STATE
) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
/* =========================================================================
* Copy the source state to the destination state
*/
//function deflateCopy(dest, source) {
//
//}
exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/
},{"../utils/common":81,"./adler32":83,"./crc32":85,"./messages":91,"./trees":92}],87:[function(_dereq_,module,exports){
'use strict';
function GZheader() {
/* true if compressed data believed to be text */
this.text = 0;
/* modification time */
this.time = 0;
/* extra flags (not used when writing a gzip file) */
this.xflags = 0;
/* operating system */
this.os = 0;
/* pointer to extra field or Z_NULL if none */
this.extra = null;
/* extra field length (valid if extra != Z_NULL) */
this.extra_len = 0; // Actually, we don't need it in JS,
// but leave for few code modifications
//
// Setup limits is not necessary because in js we should not preallocate memory
// for inflate use constant limit in 65536 bytes
//
/* space at extra (only when reading header) */
// this.extra_max = 0;
/* pointer to zero-terminated file name or Z_NULL */
this.name = '';
/* space at name (only when reading header) */
// this.name_max = 0;
/* pointer to zero-terminated comment or Z_NULL */
this.comment = '';
/* space at comment (only when reading header) */
// this.comm_max = 0;
/* true if there was or will be a header crc */
this.hcrc = 0;
/* true when done reading gzip header (not used when writing a gzip file) */
this.done = false;
}
module.exports = GZheader;
},{}],88:[function(_dereq_,module,exports){
'use strict';
// See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
module.exports = function inflate_fast(strm, start) {
var state;
var _in; /* local strm.input */
var last; /* have enough input while in < last */
var _out; /* local strm.output */
var beg; /* inflate()'s initial strm.output */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */
//#endif
var wsize; /* window size or zero if not using window */
var whave; /* valid bytes in the window */
var wnext; /* window write index */
// Use `s_window` instead `window`, avoid conflict with instrumentation tools
var s_window; /* allocated sliding window, if wsize != 0 */
var hold; /* local strm.hold */
var bits; /* local strm.bits */
var lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
var len; /* match length, unused bytes */
var dist; /* match distance */
var from; /* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
s_window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = s_window;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};
},{}],89:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var inflate_fast = _dereq_('./inffast');
var inflate_table = _dereq_('./inftrees');
var CODES = 0;
var LENS = 1;
var DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;
function ZSWAP32(q) {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
}
function InflateState() {
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib) */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding window */
this.wbits = 0; /* log base 2 of requested window size */
this.wsize = 0; /* window size or zero if not using window */
this.whave = 0; /* valid bytes in the window */
this.wnext = 0; /* window write index */
this.window = null; /* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
this.work = new utils.Buf16(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
/* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.window = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
var sym;
lenfix = new utils.Buf32(512);
distfix = new utils.Buf32(32);
/* literal/length table */
sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new utils.Buf8(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->window + state->wnext, end - copy, dist);
utils.arraySet(state.window,src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
utils.arraySet(state.window,src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS
var order = /* permutation of code lengths */
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
if (!strm || !strm.state || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
state.flags = 0; /* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
else if (len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD;
break;
}
state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more conveniend processing later
state.head.extra = new Array(state.head.extra_len);
}
utils.arraySet(
state.head.extra,
input,
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
copy,
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = ZSWAP32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
utils.arraySet(output, input, next, copy, put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = {bits: state.lenbits};
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = {bits: state.lenbits};
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = {bits: state.distbits};
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inflate_fast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.window;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' insdead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
/* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK;
}
exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/
},{"../utils/common":81,"./adler32":83,"./crc32":85,"./inffast":88,"./inftrees":90}],90:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];
var lext = [ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];
var dbase = [ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
];
var dext = [ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
];
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
var bits = opts.bits;
//here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */
var fill; /* index for replicating entries */
var low; /* low bits for current root entry */
var mask; /* mask for low root bits */
var next; /* next available space in table */
var base = null; /* base value table to use */
var base_index = 0;
// var shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */
var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work; /* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else { /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
var i=0;
/* process all codes and make table entries */
for (;;) {
i++;
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
},{"../utils/common":81}],91:[function(_dereq_,module,exports){
'use strict';
module.exports = {
'2': 'need dictionary', /* Z_NEED_DICT 2 */
'1': 'stream end', /* Z_STREAM_END 1 */
'0': '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
},{}],92:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
/* Public constants ==========================================================*/
/* ===========================================================================*/
//var Z_FILTERED = 1;
//var Z_HUFFMAN_ONLY = 2;
//var Z_RLE = 3;
var Z_FIXED = 4;
//var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY = 0;
var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/*============================================================================*/
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
/* The three kinds of block type */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256;
/* end of block literal code */
var REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
var extra_lbits = /* extra bits for each length code */
[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
var extra_dbits = /* extra bits for each distance code */
[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
var extra_blbits = /* extra bits for each bit length code */
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
var bl_order =
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES+2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree; /* static tree or NULL */
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
this.extra_base = extra_base; /* base index for extra_bits */
this.elems = elems; /* max number of elements in the tree */
this.max_length = max_length; /* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
};
var static_l_desc;
var static_d_desc;
var static_bl_desc;
var TreeDesc = function(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree; /* the dynamic tree */
this.max_code = 0; /* largest code with non zero frequency */
this.stat_desc = stat_desc; /* the corresponding static tree */
};
function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
function put_short (s, w) {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
function send_bits(s, value, length) {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length;
}
}
function send_code(s, c, tree) {
send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
function gen_bitlen(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h; /* heap index */
var n, m; /* iterate over the tree elements */
var bits; /* bit length */
var xbits; /* extra bits */
var f; /* frequency */
var overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n*2 + 1]/*.Len*/ = bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) { continue; } /* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n-base];
}
f = tree[n * 2]/*.Freq*/;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
}
}
if (overflow === 0) { return; }
// Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s.bl_count[bits] === 0) { bits--; }
s.bl_count[bits]--; /* move one leaf down the tree */
s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) { continue; }
if (tree[m*2 + 1]/*.Len*/ !== bits) {
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
tree[m*2 + 1]/*.Len*/ = bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
function gen_codes(tree, max_code, bl_count)
// ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
{
var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
var code = 0; /* running code value */
var bits; /* bit index */
var n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
var len = tree[n*2 + 1]/*.Len*/;
if (len === 0) { continue; }
/* Now reverse the bits */
tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
function tr_static_init() {
var n; /* iterates over tree elements */
var bits; /* bit counter */
var length; /* length value */
var code; /* code value */
var dist; /* distance index */
var bl_count = new Array(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
// do check in _tr_init()
//if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif*/
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = code;
}
}
//Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for (; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n*2 + 1]/*.Len*/ = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n*2 + 1]/*.Len*/ = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n*2 + 1]/*.Len*/ = 5;
static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
}
// Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
//static_init_done = true;
}
/* ===========================================================================
* Initialize a new block.
*/
function init_block(s) {
var n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
function bi_windup(s)
{
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf *buf; /* the input data */
//unsigned len; /* its length */
//int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
put_short(s, len);
put_short(s, ~len);
}
// while (len--) {
// put_byte(s, *buf++);
// }
utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
s.pending += len;
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
function smaller(tree, n, m, depth) {
var _n2 = n*2;
var _m2 = m*2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
function pqdownheap(s, tree, k)
// deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
{
var v = s.heap[k];
var j = k << 1; /* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len &&
smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
}
// inlined manually
// var SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
function compress_block(s, ltree, dtree)
// deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
{
var dist; /* distance of matched string */
var lc; /* match length or unmatched char (if dist == 0) */
var lx = 0; /* running index in l_buf */
var code; /* the code to send */
var extra; /* number of extra bits to send */
if (s.last_lit !== 0) {
do {
dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree); /* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
//Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
// "pendingBuf overflow");
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
function build_tree(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m; /* iterate over heap elements */
var max_code = -1; /* largest code with non zero frequency */
var node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2]/*.Freq*/ !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n*2 + 1]/*.Len*/ = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2]/*.Freq*/ = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node*2 + 1]/*.Len*/;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1/*SMALLEST*/];
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1/*SMALLEST*/);
/***/
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
/* and insert the new node in the heap */
s.heap[1/*SMALLEST*/] = node++;
pqdownheap(s, tree, 1/*SMALLEST*/);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
function scan_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]/*.Freq*/ += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
s.bl_tree[REP_3_6*2]/*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
function send_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
//Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count-11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
function build_bl_tree(s) {
var max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3*(max_blindex+1) + 5+5+4;
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
function send_all_trees(s, lcodes, dcodes, blcodes)
// deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
var rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
}
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
function detect_data_type(s) {
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
var black_mask = 0xf3ffc07f;
var n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
return Z_BINARY;
}
}
/* Check for textual ("white-listed") bytes. */
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
}
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
var static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
function _tr_init(s)
{
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Send a stored block
*/
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
copy_block(s, buf, stored_len, true); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
function _tr_align(s) {
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
var max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s.opt_len+3+7) >>> 3;
static_lenb = (s.static_len+3+7) >>> 3;
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->last_lit));
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
}
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
function _tr_tally(s, dist, lc)
// deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
//var out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
s.last_lit++;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc*2]/*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef TRUNCATE_BLOCK
// /* Try to guess if it is profitable to stop the current block here */
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
// /* Compute an upper bound for the compressed length */
// out_length = s.last_lit*8;
// in_length = s.strstart - s.block_start;
//
// for (dcode = 0; dcode < D_CODES; dcode++) {
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
// }
// out_length >>>= 3;
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
// // s->last_lit, in_length, out_length,
// // 100L - out_length*100L/in_length));
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
// return true;
// }
// }
//#endif
return (s.last_lit === s.lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
},{"../utils/common":81}],93:[function(_dereq_,module,exports){
'use strict';
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
},{}]},{},[1]);
|
media/k2/assets/js/jquery-1.5.2.min.js | yakuzmenko/bereg | /*!
* jQuery JavaScript Library v1.5.2
* http://jquery.com/
*
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Thu Mar 31 15:28:23 2011 -0400
*/
(function(a,b){function ci(a){return d.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cf(a){if(!b_[a]){var b=d("<"+a+">").appendTo("body"),c=b.css("display");b.remove();if(c==="none"||c==="")c="block";b_[a]=c}return b_[a]}function ce(a,b){var c={};d.each(cd.concat.apply([],cd.slice(0,b)),function(){c[this]=a});return c}function b$(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function bZ(){try{return new a.XMLHttpRequest}catch(b){}}function bY(){d(a).unload(function(){for(var a in bW)bW[a](0,1)})}function bS(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var e=a.dataTypes,f={},g,h,i=e.length,j,k=e[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h==="string"&&(f[h.toLowerCase()]=a.converters[h]);l=k,k=e[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=f[m]||f["* "+k];if(!n){p=b;for(o in f){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=f[j[1]+" "+k];if(p){o=f[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&d.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function bR(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function bQ(a,b,c,e){if(d.isArray(b)&&b.length)d.each(b,function(b,f){c||bs.test(a)?e(a,f):bQ(a+"["+(typeof f==="object"||d.isArray(f)?b:"")+"]",f,c,e)});else if(c||b==null||typeof b!=="object")e(a,b);else if(d.isArray(b)||d.isEmptyObject(b))e(a,"");else for(var f in b)bQ(a+"["+f+"]",b[f],c,e)}function bP(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bJ,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l==="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bP(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bP(a,c,d,e,"*",g));return l}function bO(a){return function(b,c){typeof b!=="string"&&(c=b,b="*");if(d.isFunction(c)){var e=b.toLowerCase().split(bD),f=0,g=e.length,h,i,j;for(;f<g;f++)h=e[f],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bq(a,b,c){var e=b==="width"?bk:bl,f=b==="width"?a.offsetWidth:a.offsetHeight;if(c==="border")return f;d.each(e,function(){c||(f-=parseFloat(d.css(a,"padding"+this))||0),c==="margin"?f+=parseFloat(d.css(a,"margin"+this))||0:f-=parseFloat(d.css(a,"border"+this+"Width"))||0});return f}function bc(a,b){b.src?d.ajax({url:b.src,async:!1,dataType:"script"}):d.globalEval(b.text||b.textContent||b.innerHTML||""),b.parentNode&&b.parentNode.removeChild(b)}function bb(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function ba(a,b){if(b.nodeType===1){var c=b.nodeName.toLowerCase();b.clearAttributes(),b.mergeAttributes(a);if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(d.expando)}}function _(a,b){if(b.nodeType===1&&d.hasData(a)){var c=d.expando,e=d.data(a),f=d.data(b,e);if(e=e[c]){var g=e.events;f=f[c]=d.extend({},e);if(g){delete f.handle,f.events={};for(var h in g)for(var i=0,j=g[h].length;i<j;i++)d.event.add(b,h+(g[h][i].namespace?".":"")+g[h][i].namespace,g[h][i],g[h][i].data)}}}}function $(a,b){return d.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function Q(a,b,c){if(d.isFunction(b))return d.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return d.grep(a,function(a,d){return a===b===c});if(typeof b==="string"){var e=d.grep(a,function(a){return a.nodeType===1});if(L.test(b))return d.filter(b,e,!c);b=d.filter(b,e)}return d.grep(a,function(a,e){return d.inArray(a,b)>=0===c})}function P(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function H(a,b){return(a&&a!=="*"?a+".":"")+b.replace(t,"`").replace(u,"&")}function G(a){var b,c,e,f,g,h,i,j,k,l,m,n,o,p=[],q=[],s=d._data(this,"events");if(a.liveFired!==this&&s&&s.live&&!a.target.disabled&&(!a.button||a.type!=="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var t=s.live.slice(0);for(i=0;i<t.length;i++)g=t[i],g.origType.replace(r,"")===a.type?q.push(g.selector):t.splice(i--,1);f=d(a.target).closest(q,a.currentTarget);for(j=0,k=f.length;j<k;j++){m=f[j];for(i=0;i<t.length;i++){g=t[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,e=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,e=d(a.relatedTarget).closest(g.selector)[0];(!e||e!==h)&&p.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=p.length;j<k;j++){f=p[j];if(c&&f.level>c)break;a.currentTarget=f.elem,a.data=f.handleObj.data,a.handleObj=f.handleObj,o=f.handleObj.origHandler.apply(f.elem,arguments);if(o===!1||a.isPropagationStopped()){c=f.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}function E(a,c,e){var f=d.extend({},e[0]);f.type=a,f.originalEvent={},f.liveFired=b,d.event.handle.call(c,f),f.isDefaultPrevented()&&e[0].preventDefault()}function y(){return!0}function x(){return!1}function i(a){for(var b in a)if(b!=="toJSON")return!1;return!0}function h(a,c,e){if(e===b&&a.nodeType===1){e=a.getAttribute("data-"+c);if(typeof e==="string"){try{e=e==="true"?!0:e==="false"?!1:e==="null"?null:d.isNaN(e)?g.test(e)?d.parseJSON(e):e:parseFloat(e)}catch(f){}d.data(a,c,e)}else e=b}return e}var c=a.document,d=function(){function G(){if(!d.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(G,1);return}d.ready()}}var d=function(a,b){return new d.fn.init(a,b,g)},e=a.jQuery,f=a.$,g,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,i=/\S/,j=/^\s+/,k=/\s+$/,l=/\d/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=navigator.userAgent,w,x,y,z=Object.prototype.toString,A=Object.prototype.hasOwnProperty,B=Array.prototype.push,C=Array.prototype.slice,D=String.prototype.trim,E=Array.prototype.indexOf,F={};d.fn=d.prototype={constructor:d,init:function(a,e,f){var g,i,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!e&&c.body){this.context=c,this[0]=c.body,this.selector="body",this.length=1;return this}if(typeof a==="string"){g=h.exec(a);if(!g||!g[1]&&e)return!e||e.jquery?(e||f).find(a):this.constructor(e).find(a);if(g[1]){e=e instanceof d?e[0]:e,k=e?e.ownerDocument||e:c,j=m.exec(a),j?d.isPlainObject(e)?(a=[c.createElement(j[1])],d.fn.attr.call(a,e,!0)):a=[k.createElement(j[1])]:(j=d.buildFragment([g[1]],[k]),a=(j.cacheable?d.clone(j.fragment):j.fragment).childNodes);return d.merge(this,a)}i=c.getElementById(g[2]);if(i&&i.parentNode){if(i.id!==g[2])return f.find(a);this.length=1,this[0]=i}this.context=c,this.selector=a;return this}if(d.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return d.makeArray(a,this)},selector:"",jquery:"1.5.2",length:0,size:function(){return this.length},toArray:function(){return C.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var e=this.constructor();d.isArray(a)?B.apply(e,a):d.merge(e,a),e.prevObject=this,e.context=this.context,b==="find"?e.selector=this.selector+(this.selector?" ":"")+c:b&&(e.selector=this.selector+"."+b+"("+c+")");return e},each:function(a,b){return d.each(this,a,b)},ready:function(a){d.bindReady(),x.done(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(C.apply(this,arguments),"slice",C.call(arguments).join(","))},map:function(a){return this.pushStack(d.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:B,sort:[].sort,splice:[].splice},d.fn.init.prototype=d.fn,d.extend=d.fn.extend=function(){var a,c,e,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i==="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!=="object"&&!d.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){e=i[c],f=a[c];if(i===f)continue;l&&f&&(d.isPlainObject(f)||(g=d.isArray(f)))?(g?(g=!1,h=e&&d.isArray(e)?e:[]):h=e&&d.isPlainObject(e)?e:{},i[c]=d.extend(l,h,f)):f!==b&&(i[c]=f)}return i},d.extend({noConflict:function(b){a.$=f,b&&(a.jQuery=e);return d},isReady:!1,readyWait:1,ready:function(a){a===!0&&d.readyWait--;if(!d.readyWait||a!==!0&&!d.isReady){if(!c.body)return setTimeout(d.ready,1);d.isReady=!0;if(a!==!0&&--d.readyWait>0)return;x.resolveWith(c,[d]),d.fn.trigger&&d(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!x){x=d._Deferred();if(c.readyState==="complete")return setTimeout(d.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",y,!1),a.addEventListener("load",d.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",y),a.attachEvent("onload",d.ready);var b=!1;try{b=a.frameElement==null}catch(e){}c.documentElement.doScroll&&b&&G()}}},isFunction:function(a){return d.type(a)==="function"},isArray:Array.isArray||function(a){return d.type(a)==="array"},isWindow:function(a){return a&&typeof a==="object"&&"setInterval"in a},isNaN:function(a){return a==null||!l.test(a)||isNaN(a)},type:function(a){return a==null?String(a):F[z.call(a)]||"object"},isPlainObject:function(a){if(!a||d.type(a)!=="object"||a.nodeType||d.isWindow(a))return!1;if(a.constructor&&!A.call(a,"constructor")&&!A.call(a.constructor.prototype,"isPrototypeOf"))return!1;var c;for(c in a){}return c===b||A.call(a,c)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!=="string"||!b)return null;b=d.trim(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return a.JSON&&a.JSON.parse?a.JSON.parse(b):(new Function("return "+b))();d.error("Invalid JSON: "+b)},parseXML:function(b,c,e){a.DOMParser?(e=new DOMParser,c=e.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b)),e=c.documentElement,(!e||!e.nodeName||e.nodeName==="parsererror")&&d.error("Invalid XML: "+b);return c},noop:function(){},globalEval:function(a){if(a&&i.test(a)){var b=c.head||c.getElementsByTagName("head")[0]||c.documentElement,e=c.createElement("script");d.support.scriptEval()?e.appendChild(c.createTextNode(a)):e.text=a,b.insertBefore(e,b.firstChild),b.removeChild(e)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,e){var f,g=0,h=a.length,i=h===b||d.isFunction(a);if(e){if(i){for(f in a)if(c.apply(a[f],e)===!1)break}else for(;g<h;)if(c.apply(a[g++],e)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(var j=a[0];g<h&&c.call(j,g,j)!==!1;j=a[++g]){}return a},trim:D?function(a){return a==null?"":D.call(a)}:function(a){return a==null?"":(a+"").replace(j,"").replace(k,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var e=d.type(a);a.length==null||e==="string"||e==="function"||e==="regexp"||d.isWindow(a)?B.call(c,a):d.merge(c,a)}return c},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var c=0,d=b.length;c<d;c++)if(b[c]===a)return c;return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length==="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,b,c){var d=[],e;for(var f=0,g=a.length;f<g;f++)e=b(a[f],f,c),e!=null&&(d[d.length]=e);return d.concat.apply([],d)},guid:1,proxy:function(a,c,e){arguments.length===2&&(typeof c==="string"?(e=a,a=e[c],c=b):c&&!d.isFunction(c)&&(e=c,c=b)),!c&&a&&(c=function(){return a.apply(e||this,arguments)}),a&&(c.guid=a.guid=a.guid||c.guid||d.guid++);return c},access:function(a,c,e,f,g,h){var i=a.length;if(typeof c==="object"){for(var j in c)d.access(a,j,c[j],f,g,e);return a}if(e!==b){f=!h&&f&&d.isFunction(e);for(var k=0;k<i;k++)g(a[k],c,f?e.call(a[k],k,g(a[k],c)):e,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}d.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.subclass=this.subclass,a.fn.init=function b(b,c){c&&c instanceof d&&!(c instanceof a)&&(c=a(c));return d.fn.init.call(this,b,c,e)},a.fn.init.prototype=a.fn;var e=a(c);return a},browser:{}}),d.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){F["[object "+b+"]"]=b.toLowerCase()}),w=d.uaMatch(v),w.browser&&(d.browser[w.browser]=!0,d.browser.version=w.version),d.browser.webkit&&(d.browser.safari=!0),E&&(d.inArray=function(a,b){return E.call(b,a)}),i.test(" ")&&(j=/^[\s\xA0]+/,k=/[\s\xA0]+$/),g=d(c),c.addEventListener?y=function(){c.removeEventListener("DOMContentLoaded",y,!1),d.ready()}:c.attachEvent&&(y=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",y),d.ready())});return d}(),e="then done fail isResolved isRejected promise".split(" "),f=[].slice;d.extend({_Deferred:function(){var a=[],b,c,e,f={done:function(){if(!e){var c=arguments,g,h,i,j,k;b&&(k=b,b=0);for(g=0,h=c.length;g<h;g++)i=c[g],j=d.type(i),j==="array"?f.done.apply(f,i):j==="function"&&a.push(i);k&&f.resolveWith(k[0],k[1])}return this},resolveWith:function(d,f){if(!e&&!b&&!c){f=f||[],c=1;try{while(a[0])a.shift().apply(d,f)}finally{b=[d,f],c=0}}return this},resolve:function(){f.resolveWith(this,arguments);return this},isResolved:function(){return c||b},cancel:function(){e=1,a=[];return this}};return f},Deferred:function(a){var b=d._Deferred(),c=d._Deferred(),f;d.extend(b,{then:function(a,c){b.done(a).fail(c);return this},fail:c.done,rejectWith:c.resolveWith,reject:c.resolve,isRejected:c.isResolved,promise:function(a){if(a==null){if(f)return f;f=a={}}var c=e.length;while(c--)a[e[c]]=b[e[c]];return a}}),b.done(c.cancel).fail(b.cancel),delete b.cancel,a&&a.call(b,b);return b},when:function(a){function i(a){return function(c){b[a]=arguments.length>1?f.call(arguments,0):c,--g||h.resolveWith(h,f.call(b,0))}}var b=arguments,c=0,e=b.length,g=e,h=e<=1&&a&&d.isFunction(a.promise)?a:d.Deferred();if(e>1){for(;c<e;c++)b[c]&&d.isFunction(b[c].promise)?b[c].promise().then(i(c),h.reject):--g;g||h.resolveWith(h,b)}else h!==a&&h.resolveWith(h,e?[a]:[]);return h.promise()}}),function(){d.support={};var b=c.createElement("div");b.style.display="none",b.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var e=b.getElementsByTagName("*"),f=b.getElementsByTagName("a")[0],g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=b.getElementsByTagName("input")[0];if(e&&e.length&&f){d.support={leadingWhitespace:b.firstChild.nodeType===3,tbody:!b.getElementsByTagName("tbody").length,htmlSerialize:!!b.getElementsByTagName("link").length,style:/red/.test(f.getAttribute("style")),hrefNormalized:f.getAttribute("href")==="/a",opacity:/^0.55$/.test(f.style.opacity),cssFloat:!!f.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,deleteExpando:!0,optDisabled:!1,checkClone:!1,noCloneEvent:!0,noCloneChecked:!0,boxModel:null,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableHiddenOffsets:!0,reliableMarginRight:!0},i.checked=!0,d.support.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,d.support.optDisabled=!h.disabled;var j=null;d.support.scriptEval=function(){if(j===null){var b=c.documentElement,e=c.createElement("script"),f="script"+d.now();try{e.appendChild(c.createTextNode("window."+f+"=1;"))}catch(g){}b.insertBefore(e,b.firstChild),a[f]?(j=!0,delete a[f]):j=!1,b.removeChild(e)}return j};try{delete b.test}catch(k){d.support.deleteExpando=!1}!b.addEventListener&&b.attachEvent&&b.fireEvent&&(b.attachEvent("onclick",function l(){d.support.noCloneEvent=!1,b.detachEvent("onclick",l)}),b.cloneNode(!0).fireEvent("onclick")),b=c.createElement("div"),b.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";var m=c.createDocumentFragment();m.appendChild(b.firstChild),d.support.checkClone=m.cloneNode(!0).cloneNode(!0).lastChild.checked,d(function(){var a=c.createElement("div"),b=c.getElementsByTagName("body")[0];if(b){a.style.width=a.style.paddingLeft="1px",b.appendChild(a),d.boxModel=d.support.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,d.support.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",d.support.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";var e=a.getElementsByTagName("td");d.support.reliableHiddenOffsets=e[0].offsetHeight===0,e[0].style.display="",e[1].style.display="none",d.support.reliableHiddenOffsets=d.support.reliableHiddenOffsets&&e[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(a.style.width="1px",a.style.marginRight="0",d.support.reliableMarginRight=(parseInt(c.defaultView.getComputedStyle(a,null).marginRight,10)||0)===0),b.removeChild(a).style.display="none",a=e=null}});var n=function(a){var b=c.createElement("div");a="on"+a;if(!b.attachEvent)return!0;var d=a in b;d||(b.setAttribute(a,"return;"),d=typeof b[a]==="function");return d};d.support.submitBubbles=n("submit"),d.support.changeBubbles=n("change"),b=e=f=null}}();var g=/^(?:\{.*\}|\[.*\])$/;d.extend({cache:{},uuid:0,expando:"jQuery"+(d.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?d.cache[a[d.expando]]:a[d.expando];return!!a&&!i(a)},data:function(a,c,e,f){if(d.acceptData(a)){var g=d.expando,h=typeof c==="string",i,j=a.nodeType,k=j?d.cache:a,l=j?a[d.expando]:a[d.expando]&&d.expando;if((!l||f&&l&&!k[l][g])&&h&&e===b)return;l||(j?a[d.expando]=l=++d.uuid:l=d.expando),k[l]||(k[l]={},j||(k[l].toJSON=d.noop));if(typeof c==="object"||typeof c==="function")f?k[l][g]=d.extend(k[l][g],c):k[l]=d.extend(k[l],c);i=k[l],f&&(i[g]||(i[g]={}),i=i[g]),e!==b&&(i[c]=e);if(c==="events"&&!i[c])return i[g]&&i[g].events;return h?i[c]:i}},removeData:function(b,c,e){if(d.acceptData(b)){var f=d.expando,g=b.nodeType,h=g?d.cache:b,j=g?b[d.expando]:d.expando;if(!h[j])return;if(c){var k=e?h[j][f]:h[j];if(k){delete k[c];if(!i(k))return}}if(e){delete h[j][f];if(!i(h[j]))return}var l=h[j][f];d.support.deleteExpando||h!=a?delete h[j]:h[j]=null,l?(h[j]={},g||(h[j].toJSON=d.noop),h[j][f]=l):g&&(d.support.deleteExpando?delete b[d.expando]:b.removeAttribute?b.removeAttribute(d.expando):b[d.expando]=null)}},_data:function(a,b,c){return d.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=d.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),d.fn.extend({data:function(a,c){var e=null;if(typeof a==="undefined"){if(this.length){e=d.data(this[0]);if(this[0].nodeType===1){var f=this[0].attributes,g;for(var i=0,j=f.length;i<j;i++)g=f[i].name,g.indexOf("data-")===0&&(g=g.substr(5),h(this[0],g,e[g]))}}return e}if(typeof a==="object")return this.each(function(){d.data(this,a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(c===b){e=this.triggerHandler("getData"+k[1]+"!",[k[0]]),e===b&&this.length&&(e=d.data(this[0],a),e=h(this[0],a,e));return e===b&&k[1]?this.data(k[0]):e}return this.each(function(){var b=d(this),e=[k[0],c];b.triggerHandler("setData"+k[1]+"!",e),d.data(this,a,c),b.triggerHandler("changeData"+k[1]+"!",e)})},removeData:function(a){return this.each(function(){d.removeData(this,a)})}}),d.extend({queue:function(a,b,c){if(a){b=(b||"fx")+"queue";var e=d._data(a,b);if(!c)return e||[];!e||d.isArray(c)?e=d._data(a,b,d.makeArray(c)):e.push(c);return e}},dequeue:function(a,b){b=b||"fx";var c=d.queue(a,b),e=c.shift();e==="inprogress"&&(e=c.shift()),e&&(b==="fx"&&c.unshift("inprogress"),e.call(a,function(){d.dequeue(a,b)})),c.length||d.removeData(a,b+"queue",!0)}}),d.fn.extend({queue:function(a,c){typeof a!=="string"&&(c=a,a="fx");if(c===b)return d.queue(this[0],a);return this.each(function(b){var e=d.queue(this,a,c);a==="fx"&&e[0]!=="inprogress"&&d.dequeue(this,a)})},dequeue:function(a){return this.each(function(){d.dequeue(this,a)})},delay:function(a,b){a=d.fx?d.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(){var c=this;setTimeout(function(){d.dequeue(c,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var j=/[\n\t\r]/g,k=/\s+/,l=/\r/g,m=/^(?:href|src|style)$/,n=/^(?:button|input)$/i,o=/^(?:button|input|object|select|textarea)$/i,p=/^a(?:rea)?$/i,q=/^(?:radio|checkbox)$/i;d.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"},d.fn.extend({attr:function(a,b){return d.access(this,a,b,!0,d.attr)},removeAttr:function(a,b){return this.each(function(){d.attr(this,a,""),this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.addClass(a.call(this,b,c.attr("class")))});if(a&&typeof a==="string"){var b=(a||"").split(k);for(var c=0,e=this.length;c<e;c++){var f=this[c];if(f.nodeType===1)if(f.className){var g=" "+f.className+" ",h=f.className;for(var i=0,j=b.length;i<j;i++)g.indexOf(" "+b[i]+" ")<0&&(h+=" "+b[i]);f.className=d.trim(h)}else f.className=a}}return this},removeClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.removeClass(a.call(this,b,c.attr("class")))});if(a&&typeof a==="string"||a===b){var c=(a||"").split(k);for(var e=0,f=this.length;e<f;e++){var g=this[e];if(g.nodeType===1&&g.className)if(a){var h=(" "+g.className+" ").replace(j," ");for(var i=0,l=c.length;i<l;i++)h=h.replace(" "+c[i]+" "," ");g.className=d.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,e=typeof b==="boolean";if(d.isFunction(a))return this.each(function(c){var e=d(this);e.toggleClass(a.call(this,c,e.attr("class"),b),b)});return this.each(function(){if(c==="string"){var f,g=0,h=d(this),i=b,j=a.split(k);while(f=j[g++])i=e?i:!h.hasClass(f),h[i?"addClass":"removeClass"](f)}else if(c==="undefined"||c==="boolean")this.className&&d._data(this,"__className__",this.className),this.className=this.className||a===!1?"":d._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ";for(var c=0,d=this.length;c<d;c++)if((" "+this[c].className+" ").replace(j," ").indexOf(b)>-1)return!0;return!1},val:function(a){if(!arguments.length){var c=this[0];if(c){if(d.nodeName(c,"option")){var e=c.attributes.value;return!e||e.specified?c.value:c.text}if(d.nodeName(c,"select")){var f=c.selectedIndex,g=[],h=c.options,i=c.type==="select-one";if(f<0)return null;for(var j=i?f:0,k=i?f+1:h.length;j<k;j++){var m=h[j];if(m.selected&&(d.support.optDisabled?!m.disabled:m.getAttribute("disabled")===null)&&(!m.parentNode.disabled||!d.nodeName(m.parentNode,"optgroup"))){a=d(m).val();if(i)return a;g.push(a)}}if(i&&!g.length&&h.length)return d(h[f]).val();return g}if(q.test(c.type)&&!d.support.checkOn)return c.getAttribute("value")===null?"on":c.value;return(c.value||"").replace(l,"")}return b}var n=d.isFunction(a);return this.each(function(b){var c=d(this),e=a;if(this.nodeType===1){n&&(e=a.call(this,b,c.val())),e==null?e="":typeof e==="number"?e+="":d.isArray(e)&&(e=d.map(e,function(a){return a==null?"":a+""}));if(d.isArray(e)&&q.test(this.type))this.checked=d.inArray(c.val(),e)>=0;else if(d.nodeName(this,"select")){var f=d.makeArray(e);d("option",this).each(function(){this.selected=d.inArray(d(this).val(),f)>=0}),f.length||(this.selectedIndex=-1)}else this.value=e}})}}),d.extend({attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,e,f){if(!a||a.nodeType===3||a.nodeType===8||a.nodeType===2)return b;if(f&&c in d.attrFn)return d(a)[c](e);var g=a.nodeType!==1||!d.isXMLDoc(a),h=e!==b;c=g&&d.props[c]||c;if(a.nodeType===1){var i=m.test(c);if(c==="selected"&&!d.support.optSelected){var j=a.parentNode;j&&(j.selectedIndex,j.parentNode&&j.parentNode.selectedIndex)}if((c in a||a[c]!==b)&&g&&!i){h&&(c==="type"&&n.test(a.nodeName)&&a.parentNode&&d.error("type property can't be changed"),e===null?a.nodeType===1&&a.removeAttribute(c):a[c]=e);if(d.nodeName(a,"form")&&a.getAttributeNode(c))return a.getAttributeNode(c).nodeValue;if(c==="tabIndex"){var k=a.getAttributeNode("tabIndex");return k&&k.specified?k.value:o.test(a.nodeName)||p.test(a.nodeName)&&a.href?0:b}return a[c]}if(!d.support.style&&g&&c==="style"){h&&(a.style.cssText=""+e);return a.style.cssText}h&&a.setAttribute(c,""+e);if(!a.attributes[c]&&(a.hasAttribute&&!a.hasAttribute(c)))return b;var l=!d.support.hrefNormalized&&g&&i?a.getAttribute(c,2):a.getAttribute(c);return l===null?b:l}h&&(a[c]=e);return a[c]}});var r=/\.(.*)$/,s=/^(?:textarea|input|select)$/i,t=/\./g,u=/ /g,v=/[^\w\s.|`]/g,w=function(a){return a.replace(v,"\\$&")};d.event={add:function(c,e,f,g){if(c.nodeType!==3&&c.nodeType!==8){try{d.isWindow(c)&&(c!==a&&!c.frameElement)&&(c=a)}catch(h){}if(f===!1)f=x;else if(!f)return;var i,j;f.handler&&(i=f,f=i.handler),f.guid||(f.guid=d.guid++);var k=d._data(c);if(!k)return;var l=k.events,m=k.handle;l||(k.events=l={}),m||(k.handle=m=function(a){return typeof d!=="undefined"&&d.event.triggered!==a.type?d.event.handle.apply(m.elem,arguments):b}),m.elem=c,e=e.split(" ");var n,o=0,p;while(n=e[o++]){j=i?d.extend({},i):{handler:f,data:g},n.indexOf(".")>-1?(p=n.split("."),n=p.shift(),j.namespace=p.slice(0).sort().join(".")):(p=[],j.namespace=""),j.type=n,j.guid||(j.guid=f.guid);var q=l[n],r=d.event.special[n]||{};if(!q){q=l[n]=[];if(!r.setup||r.setup.call(c,g,p,m)===!1)c.addEventListener?c.addEventListener(n,m,!1):c.attachEvent&&c.attachEvent("on"+n,m)}r.add&&(r.add.call(c,j),j.handler.guid||(j.handler.guid=f.guid)),q.push(j),d.event.global[n]=!0}c=null}},global:{},remove:function(a,c,e,f){if(a.nodeType!==3&&a.nodeType!==8){e===!1&&(e=x);var g,h,i,j,k=0,l,m,n,o,p,q,r,s=d.hasData(a)&&d._data(a),t=s&&s.events;if(!s||!t)return;c&&c.type&&(e=c.handler,c=c.type);if(!c||typeof c==="string"&&c.charAt(0)==="."){c=c||"";for(h in t)d.event.remove(a,h+c);return}c=c.split(" ");while(h=c[k++]){r=h,q=null,l=h.indexOf(".")<0,m=[],l||(m=h.split("."),h=m.shift(),n=new RegExp("(^|\\.)"+d.map(m.slice(0).sort(),w).join("\\.(?:.*\\.)?")+"(\\.|$)")),p=t[h];if(!p)continue;if(!e){for(j=0;j<p.length;j++){q=p[j];if(l||n.test(q.namespace))d.event.remove(a,r,q.handler,j),p.splice(j--,1)}continue}o=d.event.special[h]||{};for(j=f||0;j<p.length;j++){q=p[j];if(e.guid===q.guid){if(l||n.test(q.namespace))f==null&&p.splice(j--,1),o.remove&&o.remove.call(a,q);if(f!=null)break}}if(p.length===0||f!=null&&p.length===1)(!o.teardown||o.teardown.call(a,m)===!1)&&d.removeEvent(a,h,s.handle),g=null,delete t[h]}if(d.isEmptyObject(t)){var u=s.handle;u&&(u.elem=null),delete s.events,delete s.handle,d.isEmptyObject(s)&&d.removeData(a,b,!0)}}},trigger:function(a,c,e){var f=a.type||a,g=arguments[3];if(!g){a=typeof a==="object"?a[d.expando]?a:d.extend(d.Event(f),a):d.Event(f),f.indexOf("!")>=0&&(a.type=f=f.slice(0,-1),a.exclusive=!0),e||(a.stopPropagation(),d.event.global[f]&&d.each(d.cache,function(){var b=d.expando,e=this[b];e&&e.events&&e.events[f]&&d.event.trigger(a,c,e.handle.elem)}));if(!e||e.nodeType===3||e.nodeType===8)return b;a.result=b,a.target=e,c=d.makeArray(c),c.unshift(a)}a.currentTarget=e;var h=d._data(e,"handle");h&&h.apply(e,c);var i=e.parentNode||e.ownerDocument;try{e&&e.nodeName&&d.noData[e.nodeName.toLowerCase()]||e["on"+f]&&e["on"+f].apply(e,c)===!1&&(a.result=!1,a.preventDefault())}catch(j){}if(!a.isPropagationStopped()&&i)d.event.trigger(a,c,i,!0);else if(!a.isDefaultPrevented()){var k,l=a.target,m=f.replace(r,""),n=d.nodeName(l,"a")&&m==="click",o=d.event.special[m]||{};if((!o._default||o._default.call(e,a)===!1)&&!n&&!(l&&l.nodeName&&d.noData[l.nodeName.toLowerCase()])){try{l[m]&&(k=l["on"+m],k&&(l["on"+m]=null),d.event.triggered=a.type,l[m]())}catch(p){}k&&(l["on"+m]=k),d.event.triggered=b}}},handle:function(c){var e,f,g,h,i,j=[],k=d.makeArray(arguments);c=k[0]=d.event.fix(c||a.event),c.currentTarget=this,e=c.type.indexOf(".")<0&&!c.exclusive,e||(g=c.type.split("."),c.type=g.shift(),j=g.slice(0).sort(),h=new RegExp("(^|\\.)"+j.join("\\.(?:.*\\.)?")+"(\\.|$)")),c.namespace=c.namespace||j.join("."),i=d._data(this,"events"),f=(i||{})[c.type];if(i&&f){f=f.slice(0);for(var l=0,m=f.length;l<m;l++){var n=f[l];if(e||h.test(n.namespace)){c.handler=n.handler,c.data=n.data,c.handleObj=n;var o=n.handler.apply(this,k);o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()));if(c.isImmediatePropagationStopped())break}}}return c.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a){if(a[d.expando])return a;var e=a;a=d.Event(e);for(var f=this.props.length,g;f;)g=this.props[--f],a[g]=e[g];a.target||(a.target=a.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),!a.relatedTarget&&a.fromElement&&(a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement);if(a.pageX==null&&a.clientX!=null){var h=c.documentElement,i=c.body;a.pageX=a.clientX+(h&&h.scrollLeft||i&&i.scrollLeft||0)-(h&&h.clientLeft||i&&i.clientLeft||0),a.pageY=a.clientY+(h&&h.scrollTop||i&&i.scrollTop||0)-(h&&h.clientTop||i&&i.clientTop||0)}a.which==null&&(a.charCode!=null||a.keyCode!=null)&&(a.which=a.charCode!=null?a.charCode:a.keyCode),!a.metaKey&&a.ctrlKey&&(a.metaKey=a.ctrlKey),!a.which&&a.button!==b&&(a.which=a.button&1?1:a.button&2?3:a.button&4?2:0);return a},guid:1e8,proxy:d.proxy,special:{ready:{setup:d.bindReady,teardown:d.noop},live:{add:function(a){d.event.add(this,H(a.origType,a.selector),d.extend({},a,{handler:G,guid:a.handler.guid}))},remove:function(a){d.event.remove(this,H(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,c){d.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}}},d.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},d.Event=function(a){if(!this.preventDefault)return new d.Event(a);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?y:x):this.type=a,this.timeStamp=d.now(),this[d.expando]=!0},d.Event.prototype={preventDefault:function(){this.isDefaultPrevented=y;var a=this.originalEvent;a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=y;var a=this.originalEvent;a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=y,this.stopPropagation()},isDefaultPrevented:x,isPropagationStopped:x,isImmediatePropagationStopped:x};var z=function(a){var b=a.relatedTarget;try{if(b&&b!==c&&!b.parentNode)return;while(b&&b!==this)b=b.parentNode;b!==this&&(a.type=a.data,d.event.handle.apply(this,arguments))}catch(e){}},A=function(a){a.type=a.data,d.event.handle.apply(this,arguments)};d.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){d.event.special[a]={setup:function(c){d.event.add(this,b,c&&c.selector?A:z,a)},teardown:function(a){d.event.remove(this,b,a&&a.selector?A:z)}}}),d.support.submitBubbles||(d.event.special.submit={setup:function(a,b){if(this.nodeName&&this.nodeName.toLowerCase()!=="form")d.event.add(this,"click.specialSubmit",function(a){var b=a.target,c=b.type;(c==="submit"||c==="image")&&d(b).closest("form").length&&E("submit",this,arguments)}),d.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=b.type;(c==="text"||c==="password")&&d(b).closest("form").length&&a.keyCode===13&&E("submit",this,arguments)});else return!1},teardown:function(a){d.event.remove(this,".specialSubmit")}});if(!d.support.changeBubbles){var B,C=function(a){var b=a.type,c=a.value;b==="radio"||b==="checkbox"?c=a.checked:b==="select-multiple"?c=a.selectedIndex>-1?d.map(a.options,function(a){return a.selected}).join("-"):"":a.nodeName.toLowerCase()==="select"&&(c=a.selectedIndex);return c},D=function D(a){var c=a.target,e,f;if(s.test(c.nodeName)&&!c.readOnly){e=d._data(c,"_change_data"),f=C(c),(a.type!=="focusout"||c.type!=="radio")&&d._data(c,"_change_data",f);if(e===b||f===e)return;if(e!=null||f)a.type="change",a.liveFired=b,d.event.trigger(a,arguments[1],c)}};d.event.special.change={filters:{focusout:D,beforedeactivate:D,click:function(a){var b=a.target,c=b.type;(c==="radio"||c==="checkbox"||b.nodeName.toLowerCase()==="select")&&D.call(this,a)},keydown:function(a){var b=a.target,c=b.type;(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(c==="checkbox"||c==="radio")||c==="select-multiple")&&D.call(this,a)},beforeactivate:function(a){var b=a.target;d._data(b,"_change_data",C(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in B)d.event.add(this,c+".specialChange",B[c]);return s.test(this.nodeName)},teardown:function(a){d.event.remove(this,".specialChange");return s.test(this.nodeName)}},B=d.event.special.change.filters,B.focus=B.beforeactivate}c.addEventListener&&d.each({focus:"focusin",blur:"focusout"},function(a,b){function f(a){var c=d.event.fix(a);c.type=b,c.originalEvent={},d.event.trigger(c,null,c.target),c.isDefaultPrevented()&&a.preventDefault()}var e=0;d.event.special[b]={setup:function(){e++===0&&c.addEventListener(a,f,!0)},teardown:function(){--e===0&&c.removeEventListener(a,f,!0)}}}),d.each(["bind","one"],function(a,c){d.fn[c]=function(a,e,f){if(typeof a==="object"){for(var g in a)this[c](g,e,a[g],f);return this}if(d.isFunction(e)||e===!1)f=e,e=b;var h=c==="one"?d.proxy(f,function(a){d(this).unbind(a,h);return f.apply(this,arguments)}):f;if(a==="unload"&&c!=="one")this.one(a,e,f);else for(var i=0,j=this.length;i<j;i++)d.event.add(this[i],a,h,e);return this}}),d.fn.extend({unbind:function(a,b){if(typeof a!=="object"||a.preventDefault)for(var e=0,f=this.length;e<f;e++)d.event.remove(this[e],a,b);else for(var c in a)this.unbind(c,a[c]);return this},delegate:function(a,b,c,d){return this.live(b,c,d,a)},undelegate:function(a,b,c){return arguments.length===0?this.unbind("live"):this.die(b,null,c,a)},trigger:function(a,b){return this.each(function(){d.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var c=d.Event(a);c.preventDefault(),c.stopPropagation(),d.event.trigger(c,b,this[0]);return c.result}},toggle:function(a){var b=arguments,c=1;while(c<b.length)d.proxy(a,b[c++]);return this.click(d.proxy(a,function(e){var f=(d._data(this,"lastToggle"+a.guid)||0)%c;d._data(this,"lastToggle"+a.guid,f+1),e.preventDefault();return b[f].apply(this,arguments)||!1}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var F={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};d.each(["live","die"],function(a,c){d.fn[c]=function(a,e,f,g){var h,i=0,j,k,l,m=g||this.selector,n=g?this:d(this.context);if(typeof a==="object"&&!a.preventDefault){for(var o in a)n[c](o,e,a[o],m);return this}d.isFunction(e)&&(f=e,e=b),a=(a||"").split(" ");while((h=a[i++])!=null){j=r.exec(h),k="",j&&(k=j[0],h=h.replace(r,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,h==="focus"||h==="blur"?(a.push(F[h]+k),h=h+k):h=(F[h]||h)+k;if(c==="live")for(var p=0,q=n.length;p<q;p++)d.event.add(n[p],"live."+H(h,m),{data:e,selector:m,handler:f,origType:h,origHandler:f,preType:l});else n.unbind("live."+H(h,m),f)}return this}}),d.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".split(" "),function(a,b){d.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},d.attrFn&&(d.attrFn[b]=!0)}),function(){function u(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}if(i.nodeType===1){f||(i.sizcache=c,i.sizset=g);if(typeof b!=="string"){if(i===b){j=!0;break}}else if(k.filter(b,[i]).length>0){j=i;break}}i=i[a]}d[g]=j}}}function t(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}i.nodeType===1&&!f&&(i.sizcache=c,i.sizset=g);if(i.nodeName.toLowerCase()===b){j=i;break}i=i[a]}d[g]=j}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,g=!1,h=!0,i=/\\/g,j=/\W/;[0,0].sort(function(){h=!1;return 0});var k=function(b,d,e,g){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!=="string")return e;var i,j,n,o,q,r,s,t,u=!0,w=k.isXML(d),x=[],y=b;do{a.exec(""),i=a.exec(y);if(i){y=i[3],x.push(i[1]);if(i[2]){o=i[3];break}}}while(i);if(x.length>1&&m.exec(b))if(x.length===2&&l.relative[x[0]])j=v(x[0]+x[1],d);else{j=l.relative[x[0]]?[d]:k(x.shift(),d);while(x.length)b=x.shift(),l.relative[b]&&(b+=x.shift()),j=v(b,j)}else{!g&&x.length>1&&d.nodeType===9&&!w&&l.match.ID.test(x[0])&&!l.match.ID.test(x[x.length-1])&&(q=k.find(x.shift(),d,w),d=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]);if(d){q=g?{expr:x.pop(),set:p(g)}:k.find(x.pop(),x.length===1&&(x[0]==="~"||x[0]==="+")&&d.parentNode?d.parentNode:d,w),j=q.expr?k.filter(q.expr,q.set):q.set,x.length>0?n=p(j):u=!1;while(x.length)r=x.pop(),s=r,l.relative[r]?s=x.pop():r="",s==null&&(s=d),l.relative[r](n,s,w)}else n=x=[]}n||(n=j),n||k.error(r||b);if(f.call(n)==="[object Array]")if(u)if(d&&d.nodeType===1)for(t=0;n[t]!=null;t++)n[t]&&(n[t]===!0||n[t].nodeType===1&&k.contains(d,n[t]))&&e.push(j[t]);else for(t=0;n[t]!=null;t++)n[t]&&n[t].nodeType===1&&e.push(j[t]);else e.push.apply(e,n);else p(n,e);o&&(k(o,h,e,g),k.uniqueSort(e));return e};k.uniqueSort=function(a){if(r){g=h,a.sort(r);if(g)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},k.matches=function(a,b){return k(a,null,null,b)},k.matchesSelector=function(a,b){return k(b,null,null,[a]).length>0},k.find=function(a,b,c){var d;if(!a)return[];for(var e=0,f=l.order.length;e<f;e++){var g,h=l.order[e];if(g=l.leftMatch[h].exec(a)){var j=g[1];g.splice(1,1);if(j.substr(j.length-1)!=="\\"){g[1]=(g[1]||"").replace(i,""),d=l.find[h](g,b,c);if(d!=null){a=a.replace(l.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!=="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},k.filter=function(a,c,d,e){var f,g,h=a,i=[],j=c,m=c&&c[0]&&k.isXML(c[0]);while(a&&c.length){for(var n in l.filter)if((f=l.leftMatch[n].exec(a))!=null&&f[2]){var o,p,q=l.filter[n],r=f[1];g=!1,f.splice(1,1);if(r.substr(r.length-1)==="\\")continue;j===i&&(i=[]);if(l.preFilter[n]){f=l.preFilter[n](f,j,d,i,e,m);if(f){if(f===!0)continue}else g=o=!0}if(f)for(var s=0;(p=j[s])!=null;s++)if(p){o=q(p,f,s,j);var t=e^!!o;d&&o!=null?t?g=!0:j[s]=!1:t&&(i.push(p),g=!0)}if(o!==b){d||(j=i),a=a.replace(l.match[n],"");if(!g)return[];break}}if(a===h)if(g==null)k.error(a);else break;h=a}return j},k.error=function(a){throw"Syntax error, unrecognized expression: "+a};var l=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b==="string",d=c&&!j.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1){}a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&k.filter(b,a,!0)},">":function(a,b){var c,d=typeof b==="string",e=0,f=a.length;if(d&&!j.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&k.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=u;typeof b==="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=u;typeof b==="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!=="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!=="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!=="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(i,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(i,"")},TAG:function(a,b){return a[1].replace(i,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||k.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&k.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(i,"");!f&&l.attrMap[g]&&(a[1]=l.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(i,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=k(b[3],null,null,c);else{var g=k.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(l.match.POS.test(b[0])||l.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!k(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return"text"===c&&(b===c||b===null)},radio:function(a){return"radio"===a.type},checkbox:function(a){return"checkbox"===a.type},file:function(a){return"file"===a.type},password:function(a){return"password"===a.type},submit:function(a){return"submit"===a.type},image:function(a){return"image"===a.type},reset:function(a){return"reset"===a.type},button:function(a){return"button"===a.type||a.nodeName.toLowerCase()==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=l.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||k.getText([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}k.error(e)},CHILD:function(a,b){var c=b[1],d=a;switch(c){case"only":case"first":while(d=d.previousSibling)if(d.nodeType===1)return!1;if(c==="first")return!0;d=a;case"last":while(d=d.nextSibling)if(d.nodeType===1)return!1;return!0;case"nth":var e=b[2],f=b[3];if(e===1&&f===0)return!0;var g=b[0],h=a.parentNode;if(h&&(h.sizcache!==g||!a.nodeIndex)){var i=0;for(d=h.firstChild;d;d=d.nextSibling)d.nodeType===1&&(d.nodeIndex=++i);h.sizcache=g}var j=a.nodeIndex-f;return e===0?j===0:j%e===0&&j/e>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=l.attrHandle[c]?l.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=l.setFilters[e];if(f)return f(a,c,b,d)}}},m=l.match.POS,n=function(a,b){return"\\"+(b-0+1)};for(var o in l.match)l.match[o]=new RegExp(l.match[o].source+/(?![^\[]*\])(?![^\(]*\))/.source),l.leftMatch[o]=new RegExp(/(^(?:.|\r|\n)*?)/.source+l.match[o].source.replace(/\\(\d+)/g,n));var p=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(q){p=function(a,b){var c=0,d=b||[];if(f.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length==="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var r,s;c.documentElement.compareDocumentPosition?r=function(a,b){if(a===b){g=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(r=function(a,b){var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;if(a===b){g=!0;return 0}if(h===i)return s(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return s(e[k],f[k]);return k===c?s(a,f[k],-1):s(e[k],b,1)},s=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),k.getText=function(a){var b="",c;for(var d=0;a[d];d++)c=a[d],c.nodeType===3||c.nodeType===4?b+=c.nodeValue:c.nodeType!==8&&(b+=k.getText(c.childNodes));return b},function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(l.find.ID=function(a,c,d){if(typeof c.getElementById!=="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!=="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},l.filter.ID=function(a,b){var c=typeof a.getAttributeNode!=="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(l.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!=="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(l.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=k,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){k=function(b,e,f,g){e=e||c;if(!g&&!k.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return p(e.getElementsByTagName(b),f);if(h[2]&&l.find.CLASS&&e.getElementsByClassName)return p(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return p([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return p([],f);if(i.id===h[3])return p([i],f)}try{return p(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var m=e,n=e.getAttribute("id"),o=n||d,q=e.parentNode,r=/^\s*[+~]/.test(b);n?o=o.replace(/'/g,"\\$&"):e.setAttribute("id",o),r&&q&&(e=e.parentNode);try{if(!r||q)return p(e.querySelectorAll("[id='"+o+"'] "+b),f)}catch(s){}finally{n||m.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)k[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}k.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(a))try{if(e||!l.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return k(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;l.order.splice(1,0,"CLASS"),l.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!=="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?k.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?k.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:k.contains=function(){return!1},k.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var v=function(a,b){var c,d=[],e="",f=b.nodeType?[b]:b;while(c=l.match.PSEUDO.exec(a))e+=c[0],a=a.replace(l.match.PSEUDO,"");a=l.relative[a]?a+"*":a;for(var g=0,h=f.length;g<h;g++)k(a,f[g],d);return k.filter(e,d)};d.find=k,d.expr=k.selectors,d.expr[":"]=d.expr.filters,d.unique=k.uniqueSort,d.text=k.getText,d.isXMLDoc=k.isXML,d.contains=k.contains}();var I=/Until$/,J=/^(?:parents|prevUntil|prevAll)/,K=/,/,L=/^.[^:#\[\.,]*$/,M=Array.prototype.slice,N=d.expr.match.POS,O={children:!0,contents:!0,next:!0,prev:!0};d.fn.extend({find:function(a){var b=this.pushStack("","find",a),c=0;for(var e=0,f=this.length;e<f;e++){c=b.length,d.find(a,this[e],b);if(e>0)for(var g=c;g<b.length;g++)for(var h=0;h<c;h++)if(b[h]===b[g]){b.splice(g--,1);break}}return b},has:function(a){var b=d(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(d.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(Q(this,a,!1),"not",a)},filter:function(a){return this.pushStack(Q(this,a,!0),"filter",a)},is:function(a){return!!a&&d.filter(a,this).length>0},closest:function(a,b){var c=[],e,f,g=this[0];if(d.isArray(a)){var h,i,j={},k=1;if(g&&a.length){for(e=0,f=a.length;e<f;e++)i=a[e],j[i]||(j[i]=d.expr.match.POS.test(i)?d(i,b||this.context):i);while(g&&g.ownerDocument&&g!==b){for(i in j)h=j[i],(h.jquery?h.index(g)>-1:d(g).is(h))&&c.push({selector:i,elem:g,level:k});g=g.parentNode,k++}}return c}var l=N.test(a)?d(a,b||this.context):null;for(e=0,f=this.length;e<f;e++){g=this[e];while(g){if(l?l.index(g)>-1:d.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b)break}}c=c.length>1?d.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a||typeof a==="string")return d.inArray(this[0],a?d(a):this.parent().children());return d.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a==="string"?d(a,b):d.makeArray(a),e=d.merge(this.get(),c);return this.pushStack(P(c[0])||P(e[0])?e:d.unique(e))},andSelf:function(){return this.add(this.prevObject)}}),d.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return d.dir(a,"parentNode")},parentsUntil:function(a,b,c){return d.dir(a,"parentNode",c)},next:function(a){return d.nth(a,2,"nextSibling")},prev:function(a){return d.nth(a,2,"previousSibling")},nextAll:function(a){return d.dir(a,"nextSibling")},prevAll:function(a){return d.dir(a,"previousSibling")},nextUntil:function(a,b,c){return d.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return d.dir(a,"previousSibling",c)},siblings:function(a){return d.sibling(a.parentNode.firstChild,a)},children:function(a){return d.sibling(a.firstChild)},contents:function(a){return d.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:d.makeArray(a.childNodes)}},function(a,b){d.fn[a]=function(c,e){var f=d.map(this,b,c),g=M.call(arguments);I.test(a)||(e=c),e&&typeof e==="string"&&(f=d.filter(e,f)),f=this.length>1&&!O[a]?d.unique(f):f,(this.length>1||K.test(e))&&J.test(a)&&(f=f.reverse());return this.pushStack(f,a,g.join(","))}}),d.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?d.find.matchesSelector(b[0],a)?[b[0]]:[]:d.find.matches(a,b)},dir:function(a,c,e){var f=[],g=a[c];while(g&&g.nodeType!==9&&(e===b||g.nodeType!==1||!d(g).is(e)))g.nodeType===1&&f.push(g),g=g[c];return f},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var R=/ jQuery\d+="(?:\d+|null)"/g,S=/^\s+/,T=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,U=/<([\w:]+)/,V=/<tbody/i,W=/<|&#?\w+;/,X=/<(?:script|object|embed|option|style)/i,Y=/checked\s*(?:[^=]|=\s*.checked.)/i,Z={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};Z.optgroup=Z.option,Z.tbody=Z.tfoot=Z.colgroup=Z.caption=Z.thead,Z.th=Z.td,d.support.htmlSerialize||(Z._default=[1,"div<div>","</div>"]),d.fn.extend({text:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.text(a.call(this,b,c.text()))});if(typeof a!=="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return d.text(this)},wrapAll:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapAll(a.call(this,b))});if(this[0]){var b=d(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapInner(a.call(this,b))});return this.each(function(){var b=d(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){d(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){d.nodeName(this,"body")||d(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=d(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,d(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,e;(e=this[c])!=null;c++)if(!a||d.filter(a,[e]).length)!b&&e.nodeType===1&&(d.cleanData(e.getElementsByTagName("*")),d.cleanData([e])),e.parentNode&&e.parentNode.removeChild(e);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&d.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return d.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(R,""):null;if(typeof a!=="string"||X.test(a)||!d.support.leadingWhitespace&&S.test(a)||Z[(U.exec(a)||["",""])[1].toLowerCase()])d.isFunction(a)?this.each(function(b){var c=d(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);else{a=a.replace(T,"<$1></$2>");try{for(var c=0,e=this.length;c<e;c++)this[c].nodeType===1&&(d.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(f){this.empty().append(a)}}return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(d.isFunction(a))return this.each(function(b){var c=d(this),e=c.html();c.replaceWith(a.call(this,b,e))});typeof a!=="string"&&(a=d(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;d(this).remove(),b?d(b).before(a):d(c).append(a)})}return this.length?this.pushStack(d(d.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,e){var f,g,h,i,j=a[0],k=[];if(!d.support.checkClone&&arguments.length===3&&typeof j==="string"&&Y.test(j))return this.each(function(){d(this).domManip(a,c,e,!0)});if(d.isFunction(j))return this.each(function(f){var g=d(this);a[0]=j.call(this,f,c?g.html():b),g.domManip(a,c,e)});if(this[0]){i=j&&j.parentNode,d.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?f={fragment:i}:f=d.buildFragment(a,this,k),h=f.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&d.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)e.call(c?$(this[l],g):this[l],f.cacheable||m>1&&l<n?d.clone(h,!0,!0):h)}k.length&&d.each(k,bc)}return this}}),d.buildFragment=function(a,b,e){var f,g,h,i=b&&b[0]?b[0].ownerDocument||b[0]:c;a.length===1&&typeof a[0]==="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!X.test(a[0])&&(d.support.checkClone||!Y.test(a[0]))&&(g=!0,h=d.fragments[a[0]],h&&(h!==1&&(f=h))),f||(f=i.createDocumentFragment(),d.clean(a,i,f,e)),g&&(d.fragments[a[0]]=h?f:1);return{fragment:f,cacheable:g}},d.fragments={},d.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){d.fn[a]=function(c){var e=[],f=d(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&f.length===1){f[b](this[0]);return this}for(var h=0,i=f.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();d(f[h])[b](j),e=e.concat(j)}return this.pushStack(e,a,f.selector)}}),d.extend({clone:function(a,b,c){var e=a.cloneNode(!0),f,g,h;if((!d.support.noCloneEvent||!d.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!d.isXMLDoc(a)){ba(a,e),f=bb(a),g=bb(e);for(h=0;f[h];++h)ba(f[h],g[h])}if(b){_(a,e);if(c){f=bb(a),g=bb(e);for(h=0;f[h];++h)_(f[h],g[h])}}return e},clean:function(a,b,e,f){b=b||c,typeof b.createElement==="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var g=[];for(var h=0,i;(i=a[h])!=null;h++){typeof i==="number"&&(i+="");if(!i)continue;if(typeof i!=="string"||W.test(i)){if(typeof i==="string"){i=i.replace(T,"<$1></$2>");var j=(U.exec(i)||["",""])[1].toLowerCase(),k=Z[j]||Z._default,l=k[0],m=b.createElement("div");m.innerHTML=k[1]+i+k[2];while(l--)m=m.lastChild;if(!d.support.tbody){var n=V.test(i),o=j==="table"&&!n?m.firstChild&&m.firstChild.childNodes:k[1]==="<table>"&&!n?m.childNodes:[];for(var p=o.length-1;p>=0;--p)d.nodeName(o[p],"tbody")&&!o[p].childNodes.length&&o[p].parentNode.removeChild(o[p])}!d.support.leadingWhitespace&&S.test(i)&&m.insertBefore(b.createTextNode(S.exec(i)[0]),m.firstChild),i=m.childNodes}}else i=b.createTextNode(i);i.nodeType?g.push(i):g=d.merge(g,i)}if(e)for(h=0;g[h];h++)!f||!d.nodeName(g[h],"script")||g[h].type&&g[h].type.toLowerCase()!=="text/javascript"?(g[h].nodeType===1&&g.splice.apply(g,[h+1,0].concat(d.makeArray(g[h].getElementsByTagName("script")))),e.appendChild(g[h])):f.push(g[h].parentNode?g[h].parentNode.removeChild(g[h]):g[h]);return g},cleanData:function(a){var b,c,e=d.cache,f=d.expando,g=d.event.special,h=d.support.deleteExpando;for(var i=0,j;(j=a[i])!=null;i++){if(j.nodeName&&d.noData[j.nodeName.toLowerCase()])continue;c=j[d.expando];if(c){b=e[c]&&e[c][f];if(b&&b.events){for(var k in b.events)g[k]?d.event.remove(j,k):d.removeEvent(j,k,b.handle);b.handle&&(b.handle.elem=null)}h?delete j[d.expando]:j.removeAttribute&&j.removeAttribute(d.expando),delete e[c]}}}});var bd=/alpha\([^)]*\)/i,be=/opacity=([^)]*)/,bf=/-([a-z])/ig,bg=/([A-Z]|^ms)/g,bh=/^-?\d+(?:px)?$/i,bi=/^-?\d/,bj={position:"absolute",visibility:"hidden",display:"block"},bk=["Left","Right"],bl=["Top","Bottom"],bm,bn,bo,bp=function(a,b){return b.toUpperCase()};d.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return d.access(this,a,c,!0,function(a,c,e){return e!==b?d.style(a,c,e):d.css(a,c)})},d.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bm(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{zIndex:!0,fontWeight:!0,opacity:!0,zoom:!0,lineHeight:!0},cssProps:{"float":d.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,e,f){if(a&&a.nodeType!==3&&a.nodeType!==8&&a.style){var g,h=d.camelCase(c),i=a.style,j=d.cssHooks[h];c=d.cssProps[h]||h;if(e===b){if(j&&"get"in j&&(g=j.get(a,!1,f))!==b)return g;return i[c]}if(typeof e==="number"&&isNaN(e)||e==null)return;typeof e==="number"&&!d.cssNumber[h]&&(e+="px");if(!j||!("set"in j)||(e=j.set(a,e))!==b)try{i[c]=e}catch(k){}}},css:function(a,c,e){var f,g=d.camelCase(c),h=d.cssHooks[g];c=d.cssProps[g]||g;if(h&&"get"in h&&(f=h.get(a,!0,e))!==b)return f;if(bm)return bm(a,c,g)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]},camelCase:function(a){return a.replace(bf,bp)}}),d.curCSS=d.css,d.each(["height","width"],function(a,b){d.cssHooks[b]={get:function(a,c,e){var f;if(c){a.offsetWidth!==0?f=bq(a,b,e):d.swap(a,bj,function(){f=bq(a,b,e)});if(f<=0){f=bm(a,b,b),f==="0px"&&bo&&(f=bo(a,b,b));if(f!=null)return f===""||f==="auto"?"0px":f}if(f<0||f==null){f=a.style[b];return f===""||f==="auto"?"0px":f}return typeof f==="string"?f:f+"px"}},set:function(a,b){if(!bh.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),d.support.opacity||(d.cssHooks.opacity={get:function(a,b){return be.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style;c.zoom=1;var e=d.isNaN(b)?"":"alpha(opacity="+b*100+")",f=c.filter||"";c.filter=bd.test(f)?f.replace(bd,e):c.filter+" "+e}}),d(function(){d.support.reliableMarginRight||(d.cssHooks.marginRight={get:function(a,b){var c;d.swap(a,{display:"inline-block"},function(){b?c=bm(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bn=function(a,c,e){var f,g,h;e=e.replace(bg,"-$1").toLowerCase();if(!(g=a.ownerDocument.defaultView))return b;if(h=g.getComputedStyle(a,null))f=h.getPropertyValue(e),f===""&&!d.contains(a.ownerDocument.documentElement,a)&&(f=d.style(a,e));return f}),c.documentElement.currentStyle&&(bo=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bh.test(d)&&bi.test(d)&&(c=f.left,e&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":d||0,d=f.pixelLeft+"px",f.left=c,e&&(a.runtimeStyle.left=e));return d===""?"auto":d}),bm=bn||bo,d.expr&&d.expr.filters&&(d.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!d.support.reliableHiddenOffsets&&(a.style.display||d.css(a,"display"))==="none"},d.expr.filters.visible=function(a){return!d.expr.filters.hidden(a)});var br=/%20/g,bs=/\[\]$/,bt=/\r?\n/g,bu=/#.*$/,bv=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bw=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bx=/^(?:about|app|app\-storage|.+\-extension|file|widget):$/,by=/^(?:GET|HEAD)$/,bz=/^\/\//,bA=/\?/,bB=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bC=/^(?:select|textarea)/i,bD=/\s+/,bE=/([?&])_=[^&]*/,bF=/(^|\-)([a-z])/g,bG=function(a,b,c){return b+c.toUpperCase()},bH=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bI=d.fn.load,bJ={},bK={},bL,bM;try{bL=c.location.href}catch(bN){bL=c.createElement("a"),bL.href="",bL=bL.href}bM=bH.exec(bL.toLowerCase())||[],d.fn.extend({load:function(a,c,e){if(typeof a!=="string"&&bI)return bI.apply(this,arguments);if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var g=a.slice(f,a.length);a=a.slice(0,f)}var h="GET";c&&(d.isFunction(c)?(e=c,c=b):typeof c==="object"&&(c=d.param(c,d.ajaxSettings.traditional),h="POST"));var i=this;d.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?d("<div>").append(c.replace(bB,"")).find(g):c)),e&&i.each(e,[c,b,a])}});return this},serialize:function(){return d.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?d.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bC.test(this.nodeName)||bw.test(this.type))}).map(function(a,b){var c=d(this).val();return c==null?null:d.isArray(c)?d.map(c,function(a,c){return{name:b.name,value:a.replace(bt,"\r\n")}}):{name:b.name,value:c.replace(bt,"\r\n")}}).get()}}),d.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){d.fn[b]=function(a){return this.bind(b,a)}}),d.each(["get","post"],function(a,c){d[c]=function(a,e,f,g){d.isFunction(e)&&(g=g||f,f=e,e=b);return d.ajax({type:c,url:a,data:e,success:f,dataType:g})}}),d.extend({getScript:function(a,c){return d.get(a,b,c,"script")},getJSON:function(a,b,c){return d.get(a,b,c,"json")},ajaxSetup:function(a,b){b?d.extend(!0,a,d.ajaxSettings,b):(b=a,a=d.extend(!0,d.ajaxSettings,b));for(var c in {context:1,url:1})c in b?a[c]=b[c]:c in d.ajaxSettings&&(a[c]=d.ajaxSettings[c]);return a},ajaxSettings:{url:bL,isLocal:bx.test(bM[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":"*/*"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":d.parseJSON,"text xml":d.parseXML}},ajaxPrefilter:bO(bJ),ajaxTransport:bO(bK),ajax:function(a,c){function v(a,c,l,n){if(r!==2){r=2,p&&clearTimeout(p),o=b,m=n||"",u.readyState=a?4:0;var q,t,v,w=l?bR(e,u,l):b,x,y;if(a>=200&&a<300||a===304){if(e.ifModified){if(x=u.getResponseHeader("Last-Modified"))d.lastModified[k]=x;if(y=u.getResponseHeader("Etag"))d.etag[k]=y}if(a===304)c="notmodified",q=!0;else try{t=bS(e,w),c="success",q=!0}catch(z){c="parsererror",v=z}}else{v=c;if(!c||a)c="error",a<0&&(a=0)}u.status=a,u.statusText=c,q?h.resolveWith(f,[t,c,u]):h.rejectWith(f,[u,c,v]),u.statusCode(j),j=b,s&&g.trigger("ajax"+(q?"Success":"Error"),[u,e,q?t:v]),i.resolveWith(f,[u,c]),s&&(g.trigger("ajaxComplete",[u,e]),--d.active||d.event.trigger("ajaxStop"))}}typeof a==="object"&&(c=a,a=b),c=c||{};var e=d.ajaxSetup({},c),f=e.context||e,g=f!==e&&(f.nodeType||f instanceof d)?d(f):d.event,h=d.Deferred(),i=d._Deferred(),j=e.statusCode||{},k,l={},m,n,o,p,q,r=0,s,t,u={readyState:0,setRequestHeader:function(a,b){r||(l[a.toLowerCase().replace(bF,bG)]=b);return this},getAllResponseHeaders:function(){return r===2?m:null},getResponseHeader:function(a){var c;if(r===2){if(!n){n={};while(c=bv.exec(m))n[c[1].toLowerCase()]=c[2]}c=n[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){r||(e.mimeType=a);return this},abort:function(a){a=a||"abort",o&&o.abort(a),v(0,a);return this}};h.promise(u),u.success=u.done,u.error=u.fail,u.complete=i.done,u.statusCode=function(a){if(a){var b;if(r<2)for(b in a)j[b]=[j[b],a[b]];else b=a[u.status],u.then(b,b)}return this},e.url=((a||e.url)+"").replace(bu,"").replace(bz,bM[1]+"//"),e.dataTypes=d.trim(e.dataType||"*").toLowerCase().split(bD),e.crossDomain==null&&(q=bH.exec(e.url.toLowerCase()),e.crossDomain=q&&(q[1]!=bM[1]||q[2]!=bM[2]||(q[3]||(q[1]==="http:"?80:443))!=(bM[3]||(bM[1]==="http:"?80:443)))),e.data&&e.processData&&typeof e.data!=="string"&&(e.data=d.param(e.data,e.traditional)),bP(bJ,e,c,u);if(r===2)return!1;s=e.global,e.type=e.type.toUpperCase(),e.hasContent=!by.test(e.type),s&&d.active++===0&&d.event.trigger("ajaxStart");if(!e.hasContent){e.data&&(e.url+=(bA.test(e.url)?"&":"?")+e.data),k=e.url;if(e.cache===!1){var w=d.now(),x=e.url.replace(bE,"$1_="+w);e.url=x+(x===e.url?(bA.test(e.url)?"&":"?")+"_="+w:"")}}if(e.data&&e.hasContent&&e.contentType!==!1||c.contentType)l["Content-Type"]=e.contentType;e.ifModified&&(k=k||e.url,d.lastModified[k]&&(l["If-Modified-Since"]=d.lastModified[k]),d.etag[k]&&(l["If-None-Match"]=d.etag[k])),l.Accept=e.dataTypes[0]&&e.accepts[e.dataTypes[0]]?e.accepts[e.dataTypes[0]]+(e.dataTypes[0]!=="*"?", */*; q=0.01":""):e.accepts["*"];for(t in e.headers)u.setRequestHeader(t,e.headers[t]);if(e.beforeSend&&(e.beforeSend.call(f,u,e)===!1||r===2)){u.abort();return!1}for(t in {success:1,error:1,complete:1})u[t](e[t]);o=bP(bK,e,c,u);if(o){u.readyState=1,s&&g.trigger("ajaxSend",[u,e]),e.async&&e.timeout>0&&(p=setTimeout(function(){u.abort("timeout")},e.timeout));try{r=1,o.send(l,v)}catch(y){status<2?v(-1,y):d.error(y)}}else v(-1,"No Transport");return u},param:function(a,c){var e=[],f=function(a,b){b=d.isFunction(b)?b():b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=d.ajaxSettings.traditional);if(d.isArray(a)||a.jquery&&!d.isPlainObject(a))d.each(a,function(){f(this.name,this.value)});else for(var g in a)bQ(g,a[g],c,f);return e.join("&").replace(br,"+")}}),d.extend({active:0,lastModified:{},etag:{}});var bT=d.now(),bU=/(\=)\?(&|$)|\?\?/i;d.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return d.expando+"_"+bT++}}),d.ajaxPrefilter("json jsonp",function(b,c,e){var f=typeof b.data==="string";if(b.dataTypes[0]==="jsonp"||c.jsonpCallback||c.jsonp!=null||b.jsonp!==!1&&(bU.test(b.url)||f&&bU.test(b.data))){var g,h=b.jsonpCallback=d.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2",m=function(){a[h]=i,g&&d.isFunction(i)&&a[h](g[0])};b.jsonp!==!1&&(j=j.replace(bU,l),b.url===j&&(f&&(k=k.replace(bU,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},e.then(m,m),b.converters["script json"]=function(){g||d.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),d.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){d.globalEval(a);return a}}}),d.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),d.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var bV=d.now(),bW,bX;d.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&bZ()||b$()}:bZ,bX=d.ajaxSettings.xhr(),d.support.ajax=!!bX,d.support.cors=bX&&"withCredentials"in bX,bX=b,d.support.ajax&&d.ajaxTransport(function(a){if(!a.crossDomain||d.support.cors){var c;return{send:function(e,f){var g=a.xhr(),h,i;a.username?g.open(a.type,a.url,a.async,a.username,a.password):g.open(a.type,a.url,a.async);if(a.xhrFields)for(i in a.xhrFields)g[i]=a.xhrFields[i];a.mimeType&&g.overrideMimeType&&g.overrideMimeType(a.mimeType),!a.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(i in e)g.setRequestHeader(i,e[i])}catch(j){}g.send(a.hasContent&&a.data||null),c=function(e,i){var j,k,l,m,n;try{if(c&&(i||g.readyState===4)){c=b,h&&(g.onreadystatechange=d.noop,delete bW[h]);if(i)g.readyState!==4&&g.abort();else{j=g.status,l=g.getAllResponseHeaders(),m={},n=g.responseXML,n&&n.documentElement&&(m.xml=n),m.text=g.responseText;try{k=g.statusText}catch(o){k=""}j||!a.isLocal||a.crossDomain?j===1223&&(j=204):j=m.text?200:404}}}catch(p){i||f(-1,p)}m&&f(j,k,m,l)},a.async&&g.readyState!==4?(bW||(bW={},bY()),h=bV++,g.onreadystatechange=bW[h]=c):c()},abort:function(){c&&c(0,1)}}}});var b_={},ca=/^(?:toggle|show|hide)$/,cb=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cc,cd=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];d.fn.extend({show:function(a,b,c){var e,f;if(a||a===0)return this.animate(ce("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)e=this[g],f=e.style.display,!d._data(e,"olddisplay")&&f==="none"&&(f=e.style.display=""),f===""&&d.css(e,"display")==="none"&&d._data(e,"olddisplay",cf(e.nodeName));for(g=0;g<h;g++){e=this[g],f=e.style.display;if(f===""||f==="none")e.style.display=d._data(e,"olddisplay")||""}return this},hide:function(a,b,c){if(a||a===0)return this.animate(ce("hide",3),a,b,c);for(var e=0,f=this.length;e<f;e++){var g=d.css(this[e],"display");g!=="none"&&!d._data(this[e],"olddisplay")&&d._data(this[e],"olddisplay",g)}for(e=0;e<f;e++)this[e].style.display="none";return this},_toggle:d.fn.toggle,toggle:function(a,b,c){var e=typeof a==="boolean";d.isFunction(a)&&d.isFunction(b)?this._toggle.apply(this,arguments):a==null||e?this.each(function(){var b=e?a:d(this).is(":hidden");d(this)[b?"show":"hide"]()}):this.animate(ce("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,e){var f=d.speed(b,c,e);if(d.isEmptyObject(a))return this.each(f.complete);return this[f.queue===!1?"each":"queue"](function(){var b=d.extend({},f),c,e=this.nodeType===1,g=e&&d(this).is(":hidden"),h=this;for(c in a){var i=d.camelCase(c);c!==i&&(a[i]=a[c],delete a[c],c=i);if(a[c]==="hide"&&g||a[c]==="show"&&!g)return b.complete.call(this);if(e&&(c==="height"||c==="width")){b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(d.css(this,"display")==="inline"&&d.css(this,"float")==="none")if(d.support.inlineBlockNeedsLayout){var j=cf(this.nodeName);j==="inline"?this.style.display="inline-block":(this.style.display="inline",this.style.zoom=1)}else this.style.display="inline-block"}d.isArray(a[c])&&((b.specialEasing=b.specialEasing||{})[c]=a[c][1],a[c]=a[c][0])}b.overflow!=null&&(this.style.overflow="hidden"),b.curAnim=d.extend({},a),d.each(a,function(c,e){var f=new d.fx(h,b,c);if(ca.test(e))f[e==="toggle"?g?"show":"hide":e](a);else{var i=cb.exec(e),j=f.cur();if(i){var k=parseFloat(i[2]),l=i[3]||(d.cssNumber[c]?"":"px");l!=="px"&&(d.style(h,c,(k||1)+l),j=(k||1)/f.cur()*j,d.style(h,c,j+l)),i[1]&&(k=(i[1]==="-="?-1:1)*k+j),f.custom(j,k,l)}else f.custom(j,e,"")}});return!0})},stop:function(a,b){var c=d.timers;a&&this.queue([]),this.each(function(){for(var a=c.length-1;a>=0;a--)c[a].elem===this&&(b&&c[a](!0),c.splice(a,1))}),b||this.dequeue();return this}}),d.each({slideDown:ce("show",1),slideUp:ce("hide",1),slideToggle:ce("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){d.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),d.extend({speed:function(a,b,c){var e=a&&typeof a==="object"?d.extend({},a):{complete:c||!c&&b||d.isFunction(a)&&a,duration:a,easing:c&&b||b&&!d.isFunction(b)&&b};e.duration=d.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in d.fx.speeds?d.fx.speeds[e.duration]:d.fx.speeds._default,e.old=e.complete,e.complete=function(){e.queue!==!1&&d(this).dequeue(),d.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig||(b.orig={})}}),d.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(d.fx.step[this.prop]||d.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=d.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,b,c){function g(a){return e.step(a)}var e=this,f=d.fx;this.startTime=d.now(),this.start=a,this.end=b,this.unit=c||this.unit||(d.cssNumber[this.prop]?"":"px"),this.now=this.start,this.pos=this.state=0,g.elem=this.elem,g()&&d.timers.push(g)&&!cc&&(cc=setInterval(f.tick,f.interval))},show:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.show=!0,this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),d(this.elem).show()},hide:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b=d.now(),c=!0;if(a||b>=this.options.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),this.options.curAnim[this.prop]=!0;for(var e in this.options.curAnim)this.options.curAnim[e]!==!0&&(c=!1);if(c){if(this.options.overflow!=null&&!d.support.shrinkWrapBlocks){var f=this.elem,g=this.options;d.each(["","X","Y"],function(a,b){f.style["overflow"+b]=g.overflow[a]})}this.options.hide&&d(this.elem).hide();if(this.options.hide||this.options.show)for(var h in this.options.curAnim)d.style(this.elem,h,this.options.orig[h]);this.options.complete.call(this.elem)}return!1}var i=b-this.startTime;this.state=i/this.options.duration;var j=this.options.specialEasing&&this.options.specialEasing[this.prop],k=this.options.easing||(d.easing.swing?"swing":"linear");this.pos=d.easing[j||k](this.state,i,0,1,this.options.duration),this.now=this.start+(this.end-this.start)*this.pos,this.update();return!0}},d.extend(d.fx,{tick:function(){var a=d.timers;for(var b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||d.fx.stop()},interval:13,stop:function(){clearInterval(cc),cc=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){d.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit:a.elem[a.prop]=a.now}}}),d.expr&&d.expr.filters&&(d.expr.filters.animated=function(a){return d.grep(d.timers,function(b){return a===b.elem}).length});var cg=/^t(?:able|d|h)$/i,ch=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?d.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,g=f.documentElement;if(!c||!d.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=f.body,i=ci(f),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||d.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||d.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:d.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);d.offset.initialize();var c,e=b.offsetParent,f=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(d.offset.supportsFixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===e&&(l+=b.offsetTop,m+=b.offsetLeft,d.offset.doesNotAddBorder&&(!d.offset.doesAddBorderForTableAndCells||!cg.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),f=e,e=b.offsetParent),d.offset.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;d.offset.supportsFixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},d.offset={initialize:function(){var a=c.body,b=c.createElement("div"),e,f,g,h,i=parseFloat(d.css(a,"marginTop"))||0,j="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";d.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"}),b.innerHTML=j,a.insertBefore(b,a.firstChild),e=b.firstChild,f=e.firstChild,h=e.nextSibling.firstChild.firstChild,this.doesNotAddBorder=f.offsetTop!==5,this.doesAddBorderForTableAndCells=h.offsetTop===5,f.style.position="fixed",f.style.top="20px",this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15,f.style.position=f.style.top="",e.style.overflow="hidden",e.style.position="relative",this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5,this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i,a.removeChild(b),d.offset.initialize=d.noop},bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;d.offset.initialize(),d.offset.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(d.css(a,"marginTop"))||0,c+=parseFloat(d.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var e=d.css(a,"position");e==="static"&&(a.style.position="relative");var f=d(a),g=f.offset(),h=d.css(a,"top"),i=d.css(a,"left"),j=(e==="absolute"||e==="fixed")&&d.inArray("auto",[h,i])>-1,k={},l={},m,n;j&&(l=f.position()),m=j?l.top:parseInt(h,10)||0,n=j?l.left:parseInt(i,10)||0,d.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):f.css(k)}},d.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),e=ch.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(d.css(a,"marginTop"))||0,c.left-=parseFloat(d.css(a,"marginLeft"))||0,e.top+=parseFloat(d.css(b[0],"borderTopWidth"))||0,e.left+=parseFloat(d.css(b[0],"borderLeftWidth"))||0;return{top:c.top-e.top,left:c.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&(!ch.test(a.nodeName)&&d.css(a,"position")==="static"))a=a.offsetParent;return a})}}),d.each(["Left","Top"],function(a,c){var e="scroll"+c;d.fn[e]=function(c){var f=this[0],g;if(!f)return null;if(c!==b)return this.each(function(){g=ci(this),g?g.scrollTo(a?d(g).scrollLeft():c,a?c:d(g).scrollTop()):this[e]=c});g=ci(f);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:d.support.boxModel&&g.document.documentElement[e]||g.document.body[e]:f[e]}}),d.each(["Height","Width"],function(a,c){var e=c.toLowerCase();d.fn["inner"+c]=function(){return this[0]?parseFloat(d.css(this[0],e,"padding")):null},d.fn["outer"+c]=function(a){return this[0]?parseFloat(d.css(this[0],e,a?"margin":"border")):null},d.fn[e]=function(a){var f=this[0];if(!f)return a==null?null:this;if(d.isFunction(a))return this.each(function(b){var c=d(this);c[e](a.call(this,b,c[e]()))});if(d.isWindow(f)){var g=f.document.documentElement["client"+c];return f.document.compatMode==="CSS1Compat"&&g||f.document.body["client"+c]||g}if(f.nodeType===9)return Math.max(f.documentElement["client"+c],f.body["scroll"+c],f.documentElement["scroll"+c],f.body["offset"+c],f.documentElement["offset"+c]);if(a===b){var h=d.css(f,e),i=parseFloat(h);return d.isNaN(i)?h:i}return this.css(e,typeof a==="string"?a:a+"px")}}),a.jQuery=a.$=d})(window); |
src/svg-icons/editor/insert-invitation.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorInsertInvitation = (props) => (
<SvgIcon {...props}>
<path d="M17 12h-5v5h5v-5zM16 1v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2h-1V1h-2zm3 18H5V8h14v11z"/>
</SvgIcon>
);
EditorInsertInvitation = pure(EditorInsertInvitation);
EditorInsertInvitation.displayName = 'EditorInsertInvitation';
export default EditorInsertInvitation;
|
templates/full/javascript/test/client/util/Wrapper.js | peterjuras/slush-azure-node | import React from 'react';
export default class Wrapper extends React.Component {
render() {
return <div>{this.props.children}</div>;
}
}
|
client/app/containers/Session/components/LoginForm/index.js | sosaucily/r3-go | import React from 'react';
import { Field, reduxForm } from 'redux-form/immutable';
import Button from 'react-toolbox/lib/button/Button';
import { createFormAction } from 'redux-form-saga';
import styled from 'styled-components';
import ReduxFormInput from 'components/ReduxFormInput';
import ErrorField from './ErrorField';
import FieldContainer from './FieldContainer';
import ButtonContainer from './ButtonContainer';
const FormContainer = styled.form`
align-items: center;
display: flex;
flex-direction: column;
padding-bottom: 10px;
`;
function LoginForm(props) {
const { error, handleSubmit, submitActionPrefix, submitting } = props;
const formAction = createFormAction(submitActionPrefix);
return (
<FormContainer onSubmit={handleSubmit(formAction)}>
<FieldContainer>
<Field
name="email"
type="text"
hint="email"
component={ReduxFormInput}
/>
<Field
name="password"
type="text"
hint="password"
component={ReduxFormInput}
/>
</FieldContainer>
{error && !submitting && <ErrorField>{error}</ErrorField>}
<ButtonContainer>
<Button label="Login with Password" disabled={submitting} accent raisedg type="submit" />
</ButtonContainer>
</FormContainer>
);
}
export default reduxForm({
form: 'login',
})(LoginForm);
|
karma-js.conf.js | resalisbury/angular | var sauceConf = require('./sauce.conf');
// Karma configuration
// Generated on Thu Sep 25 2014 11:52:02 GMT-0700 (PDT)
module.exports = function(config) {
config.set({
frameworks: ['jasmine'],
files: [
// Sources and specs.
// Loaded through the System loader, in `test-main.js`.
{pattern: 'dist/js/dev/es5/**', included: false, watched: false},
// zone-microtask must be included first as it contains a Promise monkey patch
'node_modules/zone.js/dist/zone-microtask.js',
'node_modules/zone.js/dist/long-stack-trace-zone.js',
'node_modules/zone.js/dist/jasmine-patch.js',
'node_modules/es6-shim/es6-shim.js',
// Including systemjs because it defines `__eval`, which produces correct stack traces.
'modules/angular2/src/test_lib/shims_for_IE.js',
'node_modules/systemjs/dist/system.src.js',
{pattern: 'node_modules/@reactivex/rxjs/dist/cjs/**', included: false, watched: false, served: true},
'node_modules/reflect-metadata/Reflect.js',
'tools/build/file2modulename.js',
'test-main.js',
{pattern: 'modules/**/test/**/static_assets/**', included: false, watched: false}
],
exclude: ['dist/js/dev/es5/**/e2e_test/**', 'dist/angular1_router.js'],
customLaunchers: sauceConf.customLaunchers,
sauceLabs: {
testName: 'Angular2',
startConnect: false,
recordVideo: false,
recordScreenshots: false,
options: {
'selenium-version': '2.45.0',
'command-timeout': 600,
'idle-timeout': 600,
'max-duration': 5400
}
},
browsers: ['Chrome'],
port: 9876
});
if (process.env.TRAVIS) {
config.sauceLabs.build = 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')';
config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER;
// TODO(mlaval): remove once SauceLabs supports websockets.
// This speeds up the capturing a bit, as browsers don't even try to use websocket.
config.transports = ['xhr-polling'];
}
};
|
files/clappr/0.0.73/clappr.js | garrypolley/jsdelivr | require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (global){
"use strict";
var Player = require('./components/player');
var IframePlayer = require('./components/iframe_player');
var Mediator = require('mediator');
var version = require('../package.json').version;
global.DEBUG = false;
window.Clappr = {
Player: Player,
Mediator: Mediator,
IframePlayer: IframePlayer
};
window.Clappr.version = version;
module.exports = window.Clappr;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../package.json":6,"./components/iframe_player":17,"./components/player":21,"mediator":"mediator"}],2:[function(require,module,exports){
// shim for using process in browser
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');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],3:[function(require,module,exports){
(function (process,global){
(function(global) {
'use strict';
if (global.$traceurRuntime) {
return;
}
var $Object = Object;
var $TypeError = TypeError;
var $create = $Object.create;
var $defineProperties = $Object.defineProperties;
var $defineProperty = $Object.defineProperty;
var $freeze = $Object.freeze;
var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor;
var $getOwnPropertyNames = $Object.getOwnPropertyNames;
var $keys = $Object.keys;
var $hasOwnProperty = $Object.prototype.hasOwnProperty;
var $toString = $Object.prototype.toString;
var $preventExtensions = Object.preventExtensions;
var $seal = Object.seal;
var $isExtensible = Object.isExtensible;
function nonEnum(value) {
return {
configurable: true,
enumerable: false,
value: value,
writable: true
};
}
var types = {
void: function voidType() {},
any: function any() {},
string: function string() {},
number: function number() {},
boolean: function boolean() {}
};
var method = nonEnum;
var counter = 0;
function newUniqueString() {
return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__';
}
var symbolInternalProperty = newUniqueString();
var symbolDescriptionProperty = newUniqueString();
var symbolDataProperty = newUniqueString();
var symbolValues = $create(null);
var privateNames = $create(null);
function createPrivateName() {
var s = newUniqueString();
privateNames[s] = true;
return s;
}
function isSymbol(symbol) {
return typeof symbol === 'object' && symbol instanceof SymbolValue;
}
function typeOf(v) {
if (isSymbol(v))
return 'symbol';
return typeof v;
}
function Symbol(description) {
var value = new SymbolValue(description);
if (!(this instanceof Symbol))
return value;
throw new TypeError('Symbol cannot be new\'ed');
}
$defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol));
$defineProperty(Symbol.prototype, 'toString', method(function() {
var symbolValue = this[symbolDataProperty];
if (!getOption('symbols'))
return symbolValue[symbolInternalProperty];
if (!symbolValue)
throw TypeError('Conversion from symbol to string');
var desc = symbolValue[symbolDescriptionProperty];
if (desc === undefined)
desc = '';
return 'Symbol(' + desc + ')';
}));
$defineProperty(Symbol.prototype, 'valueOf', method(function() {
var symbolValue = this[symbolDataProperty];
if (!symbolValue)
throw TypeError('Conversion from symbol to string');
if (!getOption('symbols'))
return symbolValue[symbolInternalProperty];
return symbolValue;
}));
function SymbolValue(description) {
var key = newUniqueString();
$defineProperty(this, symbolDataProperty, {value: this});
$defineProperty(this, symbolInternalProperty, {value: key});
$defineProperty(this, symbolDescriptionProperty, {value: description});
freeze(this);
symbolValues[key] = this;
}
$defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol));
$defineProperty(SymbolValue.prototype, 'toString', {
value: Symbol.prototype.toString,
enumerable: false
});
$defineProperty(SymbolValue.prototype, 'valueOf', {
value: Symbol.prototype.valueOf,
enumerable: false
});
var hashProperty = createPrivateName();
var hashPropertyDescriptor = {value: undefined};
var hashObjectProperties = {
hash: {value: undefined},
self: {value: undefined}
};
var hashCounter = 0;
function getOwnHashObject(object) {
var hashObject = object[hashProperty];
if (hashObject && hashObject.self === object)
return hashObject;
if ($isExtensible(object)) {
hashObjectProperties.hash.value = hashCounter++;
hashObjectProperties.self.value = object;
hashPropertyDescriptor.value = $create(null, hashObjectProperties);
$defineProperty(object, hashProperty, hashPropertyDescriptor);
return hashPropertyDescriptor.value;
}
return undefined;
}
function freeze(object) {
getOwnHashObject(object);
return $freeze.apply(this, arguments);
}
function preventExtensions(object) {
getOwnHashObject(object);
return $preventExtensions.apply(this, arguments);
}
function seal(object) {
getOwnHashObject(object);
return $seal.apply(this, arguments);
}
Symbol.iterator = Symbol();
freeze(SymbolValue.prototype);
function toProperty(name) {
if (isSymbol(name))
return name[symbolInternalProperty];
return name;
}
function getOwnPropertyNames(object) {
var rv = [];
var names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var name = names[i];
if (!symbolValues[name] && !privateNames[name])
rv.push(name);
}
return rv;
}
function getOwnPropertyDescriptor(object, name) {
return $getOwnPropertyDescriptor(object, toProperty(name));
}
function getOwnPropertySymbols(object) {
var rv = [];
var names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var symbol = symbolValues[names[i]];
if (symbol)
rv.push(symbol);
}
return rv;
}
function hasOwnProperty(name) {
return $hasOwnProperty.call(this, toProperty(name));
}
function getOption(name) {
return global.traceur && global.traceur.options[name];
}
function setProperty(object, name, value) {
var sym,
desc;
if (isSymbol(name)) {
sym = name;
name = name[symbolInternalProperty];
}
object[name] = value;
if (sym && (desc = $getOwnPropertyDescriptor(object, name)))
$defineProperty(object, name, {enumerable: false});
return value;
}
function defineProperty(object, name, descriptor) {
if (isSymbol(name)) {
if (descriptor.enumerable) {
descriptor = $create(descriptor, {enumerable: {value: false}});
}
name = name[symbolInternalProperty];
}
$defineProperty(object, name, descriptor);
return object;
}
function polyfillObject(Object) {
$defineProperty(Object, 'defineProperty', {value: defineProperty});
$defineProperty(Object, 'getOwnPropertyNames', {value: getOwnPropertyNames});
$defineProperty(Object, 'getOwnPropertyDescriptor', {value: getOwnPropertyDescriptor});
$defineProperty(Object.prototype, 'hasOwnProperty', {value: hasOwnProperty});
$defineProperty(Object, 'freeze', {value: freeze});
$defineProperty(Object, 'preventExtensions', {value: preventExtensions});
$defineProperty(Object, 'seal', {value: seal});
Object.getOwnPropertySymbols = getOwnPropertySymbols;
}
function exportStar(object) {
for (var i = 1; i < arguments.length; i++) {
var names = $getOwnPropertyNames(arguments[i]);
for (var j = 0; j < names.length; j++) {
var name = names[j];
if (privateNames[name])
continue;
(function(mod, name) {
$defineProperty(object, name, {
get: function() {
return mod[name];
},
enumerable: true
});
})(arguments[i], names[j]);
}
}
return object;
}
function isObject(x) {
return x != null && (typeof x === 'object' || typeof x === 'function');
}
function toObject(x) {
if (x == null)
throw $TypeError();
return $Object(x);
}
function checkObjectCoercible(argument) {
if (argument == null) {
throw new TypeError('Value cannot be converted to an Object');
}
return argument;
}
function setupGlobals(global) {
global.Symbol = Symbol;
global.Reflect = global.Reflect || {};
global.Reflect.global = global.Reflect.global || global;
polyfillObject(global.Object);
}
setupGlobals(global);
global.$traceurRuntime = {
createPrivateName: createPrivateName,
exportStar: exportStar,
getOwnHashObject: getOwnHashObject,
privateNames: privateNames,
setProperty: setProperty,
setupGlobals: setupGlobals,
toObject: toObject,
isObject: isObject,
toProperty: toProperty,
type: types,
typeof: typeOf,
checkObjectCoercible: checkObjectCoercible,
hasOwnProperty: function(o, p) {
return hasOwnProperty.call(o, p);
},
defineProperties: $defineProperties,
defineProperty: $defineProperty,
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
getOwnPropertyNames: $getOwnPropertyNames,
keys: $keys
};
})(typeof global !== 'undefined' ? global : this);
(function() {
'use strict';
function spread() {
var rv = [],
j = 0,
iterResult;
for (var i = 0; i < arguments.length; i++) {
var valueToSpread = $traceurRuntime.checkObjectCoercible(arguments[i]);
if (typeof valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)] !== 'function') {
throw new TypeError('Cannot spread non-iterable object.');
}
var iter = valueToSpread[$traceurRuntime.toProperty(Symbol.iterator)]();
while (!(iterResult = iter.next()).done) {
rv[j++] = iterResult.value;
}
}
return rv;
}
$traceurRuntime.spread = spread;
})();
(function() {
'use strict';
var $Object = Object;
var $TypeError = TypeError;
var $create = $Object.create;
var $defineProperties = $traceurRuntime.defineProperties;
var $defineProperty = $traceurRuntime.defineProperty;
var $getOwnPropertyDescriptor = $traceurRuntime.getOwnPropertyDescriptor;
var $getOwnPropertyNames = $traceurRuntime.getOwnPropertyNames;
var $getPrototypeOf = Object.getPrototypeOf;
function superDescriptor(homeObject, name) {
var proto = $getPrototypeOf(homeObject);
do {
var result = $getOwnPropertyDescriptor(proto, name);
if (result)
return result;
proto = $getPrototypeOf(proto);
} while (proto);
return undefined;
}
function superCall(self, homeObject, name, args) {
return superGet(self, homeObject, name).apply(self, args);
}
function superGet(self, homeObject, name) {
var descriptor = superDescriptor(homeObject, name);
if (descriptor) {
if (!descriptor.get)
return descriptor.value;
return descriptor.get.call(self);
}
return undefined;
}
function superSet(self, homeObject, name, value) {
var descriptor = superDescriptor(homeObject, name);
if (descriptor && descriptor.set) {
descriptor.set.call(self, value);
return value;
}
throw $TypeError("super has no setter '" + name + "'.");
}
function getDescriptors(object) {
var descriptors = {},
name,
names = $getOwnPropertyNames(object);
for (var i = 0; i < names.length; i++) {
var name = names[i];
descriptors[name] = $getOwnPropertyDescriptor(object, name);
}
return descriptors;
}
function createClass(ctor, object, staticObject, superClass) {
$defineProperty(object, 'constructor', {
value: ctor,
configurable: true,
enumerable: false,
writable: true
});
if (arguments.length > 3) {
if (typeof superClass === 'function')
ctor.__proto__ = superClass;
ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object));
} else {
ctor.prototype = object;
}
$defineProperty(ctor, 'prototype', {
configurable: false,
writable: false
});
return $defineProperties(ctor, getDescriptors(staticObject));
}
function getProtoParent(superClass) {
if (typeof superClass === 'function') {
var prototype = superClass.prototype;
if ($Object(prototype) === prototype || prototype === null)
return superClass.prototype;
throw new $TypeError('super prototype must be an Object or null');
}
if (superClass === null)
return null;
throw new $TypeError(("Super expression must either be null or a function, not " + typeof superClass + "."));
}
function defaultSuperCall(self, homeObject, args) {
if ($getPrototypeOf(homeObject) !== null)
superCall(self, homeObject, 'constructor', args);
}
$traceurRuntime.createClass = createClass;
$traceurRuntime.defaultSuperCall = defaultSuperCall;
$traceurRuntime.superCall = superCall;
$traceurRuntime.superGet = superGet;
$traceurRuntime.superSet = superSet;
})();
(function() {
'use strict';
var createPrivateName = $traceurRuntime.createPrivateName;
var $defineProperties = $traceurRuntime.defineProperties;
var $defineProperty = $traceurRuntime.defineProperty;
var $create = Object.create;
var $TypeError = TypeError;
function nonEnum(value) {
return {
configurable: true,
enumerable: false,
value: value,
writable: true
};
}
var ST_NEWBORN = 0;
var ST_EXECUTING = 1;
var ST_SUSPENDED = 2;
var ST_CLOSED = 3;
var END_STATE = -2;
var RETHROW_STATE = -3;
function getInternalError(state) {
return new Error('Traceur compiler bug: invalid state in state machine: ' + state);
}
function GeneratorContext() {
this.state = 0;
this.GState = ST_NEWBORN;
this.storedException = undefined;
this.finallyFallThrough = undefined;
this.sent_ = undefined;
this.returnValue = undefined;
this.tryStack_ = [];
}
GeneratorContext.prototype = {
pushTry: function(catchState, finallyState) {
if (finallyState !== null) {
var finallyFallThrough = null;
for (var i = this.tryStack_.length - 1; i >= 0; i--) {
if (this.tryStack_[i].catch !== undefined) {
finallyFallThrough = this.tryStack_[i].catch;
break;
}
}
if (finallyFallThrough === null)
finallyFallThrough = RETHROW_STATE;
this.tryStack_.push({
finally: finallyState,
finallyFallThrough: finallyFallThrough
});
}
if (catchState !== null) {
this.tryStack_.push({catch: catchState});
}
},
popTry: function() {
this.tryStack_.pop();
},
get sent() {
this.maybeThrow();
return this.sent_;
},
set sent(v) {
this.sent_ = v;
},
get sentIgnoreThrow() {
return this.sent_;
},
maybeThrow: function() {
if (this.action === 'throw') {
this.action = 'next';
throw this.sent_;
}
},
end: function() {
switch (this.state) {
case END_STATE:
return this;
case RETHROW_STATE:
throw this.storedException;
default:
throw getInternalError(this.state);
}
},
handleException: function(ex) {
this.GState = ST_CLOSED;
this.state = END_STATE;
throw ex;
}
};
function nextOrThrow(ctx, moveNext, action, x) {
switch (ctx.GState) {
case ST_EXECUTING:
throw new Error(("\"" + action + "\" on executing generator"));
case ST_CLOSED:
if (action == 'next') {
return {
value: undefined,
done: true
};
}
throw x;
case ST_NEWBORN:
if (action === 'throw') {
ctx.GState = ST_CLOSED;
throw x;
}
if (x !== undefined)
throw $TypeError('Sent value to newborn generator');
case ST_SUSPENDED:
ctx.GState = ST_EXECUTING;
ctx.action = action;
ctx.sent = x;
var value = moveNext(ctx);
var done = value === ctx;
if (done)
value = ctx.returnValue;
ctx.GState = done ? ST_CLOSED : ST_SUSPENDED;
return {
value: value,
done: done
};
}
}
var ctxName = createPrivateName();
var moveNextName = createPrivateName();
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
GeneratorFunction.prototype = GeneratorFunctionPrototype;
$defineProperty(GeneratorFunctionPrototype, 'constructor', nonEnum(GeneratorFunction));
GeneratorFunctionPrototype.prototype = {
constructor: GeneratorFunctionPrototype,
next: function(v) {
return nextOrThrow(this[ctxName], this[moveNextName], 'next', v);
},
throw: function(v) {
return nextOrThrow(this[ctxName], this[moveNextName], 'throw', v);
}
};
$defineProperties(GeneratorFunctionPrototype.prototype, {
constructor: {enumerable: false},
next: {enumerable: false},
throw: {enumerable: false}
});
Object.defineProperty(GeneratorFunctionPrototype.prototype, Symbol.iterator, nonEnum(function() {
return this;
}));
function createGeneratorInstance(innerFunction, functionObject, self) {
var moveNext = getMoveNext(innerFunction, self);
var ctx = new GeneratorContext();
var object = $create(functionObject.prototype);
object[ctxName] = ctx;
object[moveNextName] = moveNext;
return object;
}
function initGeneratorFunction(functionObject) {
functionObject.prototype = $create(GeneratorFunctionPrototype.prototype);
functionObject.__proto__ = GeneratorFunctionPrototype;
return functionObject;
}
function AsyncFunctionContext() {
GeneratorContext.call(this);
this.err = undefined;
var ctx = this;
ctx.result = new Promise(function(resolve, reject) {
ctx.resolve = resolve;
ctx.reject = reject;
});
}
AsyncFunctionContext.prototype = $create(GeneratorContext.prototype);
AsyncFunctionContext.prototype.end = function() {
switch (this.state) {
case END_STATE:
this.resolve(this.returnValue);
break;
case RETHROW_STATE:
this.reject(this.storedException);
break;
default:
this.reject(getInternalError(this.state));
}
};
AsyncFunctionContext.prototype.handleException = function() {
this.state = RETHROW_STATE;
};
function asyncWrap(innerFunction, self) {
var moveNext = getMoveNext(innerFunction, self);
var ctx = new AsyncFunctionContext();
ctx.createCallback = function(newState) {
return function(value) {
ctx.state = newState;
ctx.value = value;
moveNext(ctx);
};
};
ctx.errback = function(err) {
handleCatch(ctx, err);
moveNext(ctx);
};
moveNext(ctx);
return ctx.result;
}
function getMoveNext(innerFunction, self) {
return function(ctx) {
while (true) {
try {
return innerFunction.call(self, ctx);
} catch (ex) {
handleCatch(ctx, ex);
}
}
};
}
function handleCatch(ctx, ex) {
ctx.storedException = ex;
var last = ctx.tryStack_[ctx.tryStack_.length - 1];
if (!last) {
ctx.handleException(ex);
return;
}
ctx.state = last.catch !== undefined ? last.catch : last.finally;
if (last.finallyFallThrough !== undefined)
ctx.finallyFallThrough = last.finallyFallThrough;
}
$traceurRuntime.asyncWrap = asyncWrap;
$traceurRuntime.initGeneratorFunction = initGeneratorFunction;
$traceurRuntime.createGeneratorInstance = createGeneratorInstance;
})();
(function() {
function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
var out = [];
if (opt_scheme) {
out.push(opt_scheme, ':');
}
if (opt_domain) {
out.push('//');
if (opt_userInfo) {
out.push(opt_userInfo, '@');
}
out.push(opt_domain);
if (opt_port) {
out.push(':', opt_port);
}
}
if (opt_path) {
out.push(opt_path);
}
if (opt_queryData) {
out.push('?', opt_queryData);
}
if (opt_fragment) {
out.push('#', opt_fragment);
}
return out.join('');
}
;
var splitRe = new RegExp('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\?([^#]*))?' + '(?:#(.*))?' + '$');
var ComponentIndex = {
SCHEME: 1,
USER_INFO: 2,
DOMAIN: 3,
PORT: 4,
PATH: 5,
QUERY_DATA: 6,
FRAGMENT: 7
};
function split(uri) {
return (uri.match(splitRe));
}
function removeDotSegments(path) {
if (path === '/')
return '/';
var leadingSlash = path[0] === '/' ? '/' : '';
var trailingSlash = path.slice(-1) === '/' ? '/' : '';
var segments = path.split('/');
var out = [];
var up = 0;
for (var pos = 0; pos < segments.length; pos++) {
var segment = segments[pos];
switch (segment) {
case '':
case '.':
break;
case '..':
if (out.length)
out.pop();
else
up++;
break;
default:
out.push(segment);
}
}
if (!leadingSlash) {
while (up-- > 0) {
out.unshift('..');
}
if (out.length === 0)
out.push('.');
}
return leadingSlash + out.join('/') + trailingSlash;
}
function joinAndCanonicalizePath(parts) {
var path = parts[ComponentIndex.PATH] || '';
path = removeDotSegments(path);
parts[ComponentIndex.PATH] = path;
return buildFromEncodedParts(parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]);
}
function canonicalizeUrl(url) {
var parts = split(url);
return joinAndCanonicalizePath(parts);
}
function resolveUrl(base, url) {
var parts = split(url);
var baseParts = split(base);
if (parts[ComponentIndex.SCHEME]) {
return joinAndCanonicalizePath(parts);
} else {
parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME];
}
for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) {
if (!parts[i]) {
parts[i] = baseParts[i];
}
}
if (parts[ComponentIndex.PATH][0] == '/') {
return joinAndCanonicalizePath(parts);
}
var path = baseParts[ComponentIndex.PATH];
var index = path.lastIndexOf('/');
path = path.slice(0, index + 1) + parts[ComponentIndex.PATH];
parts[ComponentIndex.PATH] = path;
return joinAndCanonicalizePath(parts);
}
function isAbsolute(name) {
if (!name)
return false;
if (name[0] === '/')
return true;
var parts = split(name);
if (parts[ComponentIndex.SCHEME])
return true;
return false;
}
$traceurRuntime.canonicalizeUrl = canonicalizeUrl;
$traceurRuntime.isAbsolute = isAbsolute;
$traceurRuntime.removeDotSegments = removeDotSegments;
$traceurRuntime.resolveUrl = resolveUrl;
})();
(function(global) {
'use strict';
var $__2 = $traceurRuntime,
canonicalizeUrl = $__2.canonicalizeUrl,
resolveUrl = $__2.resolveUrl,
isAbsolute = $__2.isAbsolute;
var moduleInstantiators = Object.create(null);
var baseURL;
if (global.location && global.location.href)
baseURL = resolveUrl(global.location.href, './');
else
baseURL = '';
var UncoatedModuleEntry = function UncoatedModuleEntry(url, uncoatedModule) {
this.url = url;
this.value_ = uncoatedModule;
};
($traceurRuntime.createClass)(UncoatedModuleEntry, {}, {});
var ModuleEvaluationError = function ModuleEvaluationError(erroneousModuleName, cause) {
this.message = this.constructor.name + ': ' + this.stripCause(cause) + ' in ' + erroneousModuleName;
if (!(cause instanceof $ModuleEvaluationError) && cause.stack)
this.stack = this.stripStack(cause.stack);
else
this.stack = '';
};
var $ModuleEvaluationError = ModuleEvaluationError;
($traceurRuntime.createClass)(ModuleEvaluationError, {
stripError: function(message) {
return message.replace(/.*Error:/, this.constructor.name + ':');
},
stripCause: function(cause) {
if (!cause)
return '';
if (!cause.message)
return cause + '';
return this.stripError(cause.message);
},
loadedBy: function(moduleName) {
this.stack += '\n loaded by ' + moduleName;
},
stripStack: function(causeStack) {
var stack = [];
causeStack.split('\n').some((function(frame) {
if (/UncoatedModuleInstantiator/.test(frame))
return true;
stack.push(frame);
}));
stack[0] = this.stripError(stack[0]);
return stack.join('\n');
}
}, {}, Error);
var UncoatedModuleInstantiator = function UncoatedModuleInstantiator(url, func) {
$traceurRuntime.superCall(this, $UncoatedModuleInstantiator.prototype, "constructor", [url, null]);
this.func = func;
};
var $UncoatedModuleInstantiator = UncoatedModuleInstantiator;
($traceurRuntime.createClass)(UncoatedModuleInstantiator, {getUncoatedModule: function() {
if (this.value_)
return this.value_;
try {
return this.value_ = this.func.call(global);
} catch (ex) {
if (ex instanceof ModuleEvaluationError) {
ex.loadedBy(this.url);
throw ex;
}
throw new ModuleEvaluationError(this.url, ex);
}
}}, {}, UncoatedModuleEntry);
function getUncoatedModuleInstantiator(name) {
if (!name)
return;
var url = ModuleStore.normalize(name);
return moduleInstantiators[url];
}
;
var moduleInstances = Object.create(null);
var liveModuleSentinel = {};
function Module(uncoatedModule) {
var isLive = arguments[1];
var coatedModule = Object.create(null);
Object.getOwnPropertyNames(uncoatedModule).forEach((function(name) {
var getter,
value;
if (isLive === liveModuleSentinel) {
var descr = Object.getOwnPropertyDescriptor(uncoatedModule, name);
if (descr.get)
getter = descr.get;
}
if (!getter) {
value = uncoatedModule[name];
getter = function() {
return value;
};
}
Object.defineProperty(coatedModule, name, {
get: getter,
enumerable: true
});
}));
Object.preventExtensions(coatedModule);
return coatedModule;
}
var ModuleStore = {
normalize: function(name, refererName, refererAddress) {
if (typeof name !== "string")
throw new TypeError("module name must be a string, not " + typeof name);
if (isAbsolute(name))
return canonicalizeUrl(name);
if (/[^\.]\/\.\.\//.test(name)) {
throw new Error('module name embeds /../: ' + name);
}
if (name[0] === '.' && refererName)
return resolveUrl(refererName, name);
return canonicalizeUrl(name);
},
get: function(normalizedName) {
var m = getUncoatedModuleInstantiator(normalizedName);
if (!m)
return undefined;
var moduleInstance = moduleInstances[m.url];
if (moduleInstance)
return moduleInstance;
moduleInstance = Module(m.getUncoatedModule(), liveModuleSentinel);
return moduleInstances[m.url] = moduleInstance;
},
set: function(normalizedName, module) {
normalizedName = String(normalizedName);
moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, (function() {
return module;
}));
moduleInstances[normalizedName] = module;
},
get baseURL() {
return baseURL;
},
set baseURL(v) {
baseURL = String(v);
},
registerModule: function(name, func) {
var normalizedName = ModuleStore.normalize(name);
if (moduleInstantiators[normalizedName])
throw new Error('duplicate module named ' + normalizedName);
moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, func);
},
bundleStore: Object.create(null),
register: function(name, deps, func) {
if (!deps || !deps.length && !func.length) {
this.registerModule(name, func);
} else {
this.bundleStore[name] = {
deps: deps,
execute: function() {
var $__0 = arguments;
var depMap = {};
deps.forEach((function(dep, index) {
return depMap[dep] = $__0[index];
}));
var registryEntry = func.call(this, depMap);
registryEntry.execute.call(this);
return registryEntry.exports;
}
};
}
},
getAnonymousModule: function(func) {
return new Module(func.call(global), liveModuleSentinel);
},
getForTesting: function(name) {
var $__0 = this;
if (!this.testingPrefix_) {
Object.keys(moduleInstances).some((function(key) {
var m = /(traceur@[^\/]*\/)/.exec(key);
if (m) {
$__0.testingPrefix_ = m[1];
return true;
}
}));
}
return this.get(this.testingPrefix_ + name);
}
};
ModuleStore.set('@traceur/src/runtime/ModuleStore', new Module({ModuleStore: ModuleStore}));
var setupGlobals = $traceurRuntime.setupGlobals;
$traceurRuntime.setupGlobals = function(global) {
setupGlobals(global);
};
$traceurRuntime.ModuleStore = ModuleStore;
global.System = {
register: ModuleStore.register.bind(ModuleStore),
get: ModuleStore.get,
set: ModuleStore.set,
normalize: ModuleStore.normalize
};
$traceurRuntime.getModuleImpl = function(name) {
var instantiator = getUncoatedModuleInstantiator(name);
return instantiator && instantiator.getUncoatedModule();
};
})(typeof global !== 'undefined' ? global : this);
System.register("[email protected]/src/runtime/polyfills/utils", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/utils";
var $ceil = Math.ceil;
var $floor = Math.floor;
var $isFinite = isFinite;
var $isNaN = isNaN;
var $pow = Math.pow;
var $min = Math.min;
var toObject = $traceurRuntime.toObject;
function toUint32(x) {
return x >>> 0;
}
function isObject(x) {
return x && (typeof x === 'object' || typeof x === 'function');
}
function isCallable(x) {
return typeof x === 'function';
}
function isNumber(x) {
return typeof x === 'number';
}
function toInteger(x) {
x = +x;
if ($isNaN(x))
return 0;
if (x === 0 || !$isFinite(x))
return x;
return x > 0 ? $floor(x) : $ceil(x);
}
var MAX_SAFE_LENGTH = $pow(2, 53) - 1;
function toLength(x) {
var len = toInteger(x);
return len < 0 ? 0 : $min(len, MAX_SAFE_LENGTH);
}
function checkIterable(x) {
return !isObject(x) ? undefined : x[Symbol.iterator];
}
function isConstructor(x) {
return isCallable(x);
}
function createIteratorResultObject(value, done) {
return {
value: value,
done: done
};
}
function maybeDefine(object, name, descr) {
if (!(name in object)) {
Object.defineProperty(object, name, descr);
}
}
function maybeDefineMethod(object, name, value) {
maybeDefine(object, name, {
value: value,
configurable: true,
enumerable: false,
writable: true
});
}
function maybeDefineConst(object, name, value) {
maybeDefine(object, name, {
value: value,
configurable: false,
enumerable: false,
writable: false
});
}
function maybeAddFunctions(object, functions) {
for (var i = 0; i < functions.length; i += 2) {
var name = functions[i];
var value = functions[i + 1];
maybeDefineMethod(object, name, value);
}
}
function maybeAddConsts(object, consts) {
for (var i = 0; i < consts.length; i += 2) {
var name = consts[i];
var value = consts[i + 1];
maybeDefineConst(object, name, value);
}
}
function maybeAddIterator(object, func, Symbol) {
if (!Symbol || !Symbol.iterator || object[Symbol.iterator])
return;
if (object['@@iterator'])
func = object['@@iterator'];
Object.defineProperty(object, Symbol.iterator, {
value: func,
configurable: true,
enumerable: false,
writable: true
});
}
var polyfills = [];
function registerPolyfill(func) {
polyfills.push(func);
}
function polyfillAll(global) {
polyfills.forEach((function(f) {
return f(global);
}));
}
return {
get toObject() {
return toObject;
},
get toUint32() {
return toUint32;
},
get isObject() {
return isObject;
},
get isCallable() {
return isCallable;
},
get isNumber() {
return isNumber;
},
get toInteger() {
return toInteger;
},
get toLength() {
return toLength;
},
get checkIterable() {
return checkIterable;
},
get isConstructor() {
return isConstructor;
},
get createIteratorResultObject() {
return createIteratorResultObject;
},
get maybeDefine() {
return maybeDefine;
},
get maybeDefineMethod() {
return maybeDefineMethod;
},
get maybeDefineConst() {
return maybeDefineConst;
},
get maybeAddFunctions() {
return maybeAddFunctions;
},
get maybeAddConsts() {
return maybeAddConsts;
},
get maybeAddIterator() {
return maybeAddIterator;
},
get registerPolyfill() {
return registerPolyfill;
},
get polyfillAll() {
return polyfillAll;
}
};
});
System.register("[email protected]/src/runtime/polyfills/Map", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Map";
var $__3 = System.get("[email protected]/src/runtime/polyfills/utils"),
isObject = $__3.isObject,
maybeAddIterator = $__3.maybeAddIterator,
registerPolyfill = $__3.registerPolyfill;
var getOwnHashObject = $traceurRuntime.getOwnHashObject;
var $hasOwnProperty = Object.prototype.hasOwnProperty;
var deletedSentinel = {};
function lookupIndex(map, key) {
if (isObject(key)) {
var hashObject = getOwnHashObject(key);
return hashObject && map.objectIndex_[hashObject.hash];
}
if (typeof key === 'string')
return map.stringIndex_[key];
return map.primitiveIndex_[key];
}
function initMap(map) {
map.entries_ = [];
map.objectIndex_ = Object.create(null);
map.stringIndex_ = Object.create(null);
map.primitiveIndex_ = Object.create(null);
map.deletedCount_ = 0;
}
var Map = function Map() {
var iterable = arguments[0];
if (!isObject(this))
throw new TypeError('Map called on incompatible type');
if ($hasOwnProperty.call(this, 'entries_')) {
throw new TypeError('Map can not be reentrantly initialised');
}
initMap(this);
if (iterable !== null && iterable !== undefined) {
for (var $__5 = iterable[Symbol.iterator](),
$__6; !($__6 = $__5.next()).done; ) {
var $__7 = $__6.value,
key = $__7[0],
value = $__7[1];
{
this.set(key, value);
}
}
}
};
($traceurRuntime.createClass)(Map, {
get size() {
return this.entries_.length / 2 - this.deletedCount_;
},
get: function(key) {
var index = lookupIndex(this, key);
if (index !== undefined)
return this.entries_[index + 1];
},
set: function(key, value) {
var objectMode = isObject(key);
var stringMode = typeof key === 'string';
var index = lookupIndex(this, key);
if (index !== undefined) {
this.entries_[index + 1] = value;
} else {
index = this.entries_.length;
this.entries_[index] = key;
this.entries_[index + 1] = value;
if (objectMode) {
var hashObject = getOwnHashObject(key);
var hash = hashObject.hash;
this.objectIndex_[hash] = index;
} else if (stringMode) {
this.stringIndex_[key] = index;
} else {
this.primitiveIndex_[key] = index;
}
}
return this;
},
has: function(key) {
return lookupIndex(this, key) !== undefined;
},
delete: function(key) {
var objectMode = isObject(key);
var stringMode = typeof key === 'string';
var index;
var hash;
if (objectMode) {
var hashObject = getOwnHashObject(key);
if (hashObject) {
index = this.objectIndex_[hash = hashObject.hash];
delete this.objectIndex_[hash];
}
} else if (stringMode) {
index = this.stringIndex_[key];
delete this.stringIndex_[key];
} else {
index = this.primitiveIndex_[key];
delete this.primitiveIndex_[key];
}
if (index !== undefined) {
this.entries_[index] = deletedSentinel;
this.entries_[index + 1] = undefined;
this.deletedCount_++;
return true;
}
return false;
},
clear: function() {
initMap(this);
},
forEach: function(callbackFn) {
var thisArg = arguments[1];
for (var i = 0; i < this.entries_.length; i += 2) {
var key = this.entries_[i];
var value = this.entries_[i + 1];
if (key === deletedSentinel)
continue;
callbackFn.call(thisArg, value, key, this);
}
},
entries: $traceurRuntime.initGeneratorFunction(function $__8() {
var i,
key,
value;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
i = 0;
$ctx.state = 12;
break;
case 12:
$ctx.state = (i < this.entries_.length) ? 8 : -2;
break;
case 4:
i += 2;
$ctx.state = 12;
break;
case 8:
key = this.entries_[i];
value = this.entries_[i + 1];
$ctx.state = 9;
break;
case 9:
$ctx.state = (key === deletedSentinel) ? 4 : 6;
break;
case 6:
$ctx.state = 2;
return [key, value];
case 2:
$ctx.maybeThrow();
$ctx.state = 4;
break;
default:
return $ctx.end();
}
}, $__8, this);
}),
keys: $traceurRuntime.initGeneratorFunction(function $__9() {
var i,
key,
value;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
i = 0;
$ctx.state = 12;
break;
case 12:
$ctx.state = (i < this.entries_.length) ? 8 : -2;
break;
case 4:
i += 2;
$ctx.state = 12;
break;
case 8:
key = this.entries_[i];
value = this.entries_[i + 1];
$ctx.state = 9;
break;
case 9:
$ctx.state = (key === deletedSentinel) ? 4 : 6;
break;
case 6:
$ctx.state = 2;
return key;
case 2:
$ctx.maybeThrow();
$ctx.state = 4;
break;
default:
return $ctx.end();
}
}, $__9, this);
}),
values: $traceurRuntime.initGeneratorFunction(function $__10() {
var i,
key,
value;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
i = 0;
$ctx.state = 12;
break;
case 12:
$ctx.state = (i < this.entries_.length) ? 8 : -2;
break;
case 4:
i += 2;
$ctx.state = 12;
break;
case 8:
key = this.entries_[i];
value = this.entries_[i + 1];
$ctx.state = 9;
break;
case 9:
$ctx.state = (key === deletedSentinel) ? 4 : 6;
break;
case 6:
$ctx.state = 2;
return value;
case 2:
$ctx.maybeThrow();
$ctx.state = 4;
break;
default:
return $ctx.end();
}
}, $__10, this);
})
}, {});
Object.defineProperty(Map.prototype, Symbol.iterator, {
configurable: true,
writable: true,
value: Map.prototype.entries
});
function polyfillMap(global) {
var $__7 = global,
Object = $__7.Object,
Symbol = $__7.Symbol;
if (!global.Map)
global.Map = Map;
var mapPrototype = global.Map.prototype;
if (mapPrototype.entries) {
maybeAddIterator(mapPrototype, mapPrototype.entries, Symbol);
maybeAddIterator(Object.getPrototypeOf(new global.Map().entries()), function() {
return this;
}, Symbol);
}
}
registerPolyfill(polyfillMap);
return {
get Map() {
return Map;
},
get polyfillMap() {
return polyfillMap;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Map" + '');
System.register("[email protected]/src/runtime/polyfills/Set", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Set";
var $__11 = System.get("[email protected]/src/runtime/polyfills/utils"),
isObject = $__11.isObject,
maybeAddIterator = $__11.maybeAddIterator,
registerPolyfill = $__11.registerPolyfill;
var Map = System.get("[email protected]/src/runtime/polyfills/Map").Map;
var getOwnHashObject = $traceurRuntime.getOwnHashObject;
var $hasOwnProperty = Object.prototype.hasOwnProperty;
function initSet(set) {
set.map_ = new Map();
}
var Set = function Set() {
var iterable = arguments[0];
if (!isObject(this))
throw new TypeError('Set called on incompatible type');
if ($hasOwnProperty.call(this, 'map_')) {
throw new TypeError('Set can not be reentrantly initialised');
}
initSet(this);
if (iterable !== null && iterable !== undefined) {
for (var $__15 = iterable[Symbol.iterator](),
$__16; !($__16 = $__15.next()).done; ) {
var item = $__16.value;
{
this.add(item);
}
}
}
};
($traceurRuntime.createClass)(Set, {
get size() {
return this.map_.size;
},
has: function(key) {
return this.map_.has(key);
},
add: function(key) {
this.map_.set(key, key);
return this;
},
delete: function(key) {
return this.map_.delete(key);
},
clear: function() {
return this.map_.clear();
},
forEach: function(callbackFn) {
var thisArg = arguments[1];
var $__13 = this;
return this.map_.forEach((function(value, key) {
callbackFn.call(thisArg, key, key, $__13);
}));
},
values: $traceurRuntime.initGeneratorFunction(function $__18() {
var $__19,
$__20;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
$__19 = this.map_.keys()[Symbol.iterator]();
$ctx.sent = void 0;
$ctx.action = 'next';
$ctx.state = 12;
break;
case 12:
$__20 = $__19[$ctx.action]($ctx.sentIgnoreThrow);
$ctx.state = 9;
break;
case 9:
$ctx.state = ($__20.done) ? 3 : 2;
break;
case 3:
$ctx.sent = $__20.value;
$ctx.state = -2;
break;
case 2:
$ctx.state = 12;
return $__20.value;
default:
return $ctx.end();
}
}, $__18, this);
}),
entries: $traceurRuntime.initGeneratorFunction(function $__21() {
var $__22,
$__23;
return $traceurRuntime.createGeneratorInstance(function($ctx) {
while (true)
switch ($ctx.state) {
case 0:
$__22 = this.map_.entries()[Symbol.iterator]();
$ctx.sent = void 0;
$ctx.action = 'next';
$ctx.state = 12;
break;
case 12:
$__23 = $__22[$ctx.action]($ctx.sentIgnoreThrow);
$ctx.state = 9;
break;
case 9:
$ctx.state = ($__23.done) ? 3 : 2;
break;
case 3:
$ctx.sent = $__23.value;
$ctx.state = -2;
break;
case 2:
$ctx.state = 12;
return $__23.value;
default:
return $ctx.end();
}
}, $__21, this);
})
}, {});
Object.defineProperty(Set.prototype, Symbol.iterator, {
configurable: true,
writable: true,
value: Set.prototype.values
});
Object.defineProperty(Set.prototype, 'keys', {
configurable: true,
writable: true,
value: Set.prototype.values
});
function polyfillSet(global) {
var $__17 = global,
Object = $__17.Object,
Symbol = $__17.Symbol;
if (!global.Set)
global.Set = Set;
var setPrototype = global.Set.prototype;
if (setPrototype.values) {
maybeAddIterator(setPrototype, setPrototype.values, Symbol);
maybeAddIterator(Object.getPrototypeOf(new global.Set().values()), function() {
return this;
}, Symbol);
}
}
registerPolyfill(polyfillSet);
return {
get Set() {
return Set;
},
get polyfillSet() {
return polyfillSet;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Set" + '');
System.register("[email protected]/node_modules/rsvp/lib/rsvp/asap", [], function() {
"use strict";
var __moduleName = "[email protected]/node_modules/rsvp/lib/rsvp/asap";
var len = 0;
function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
scheduleFlush();
}
}
var $__default = asap;
var browserGlobal = (typeof window !== 'undefined') ? window : {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
function useNextTick() {
return function() {
process.nextTick(flush);
};
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, {characterData: true});
return function() {
node.data = (iterations = ++iterations % 2);
};
}
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function() {
channel.port2.postMessage(0);
};
}
function useSetTimeout() {
return function() {
setTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
var scheduleFlush;
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else {
scheduleFlush = useSetTimeout();
}
return {get default() {
return $__default;
}};
});
System.register("[email protected]/src/runtime/polyfills/Promise", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Promise";
var async = System.get("[email protected]/node_modules/rsvp/lib/rsvp/asap").default;
var registerPolyfill = System.get("[email protected]/src/runtime/polyfills/utils").registerPolyfill;
var promiseRaw = {};
function isPromise(x) {
return x && typeof x === 'object' && x.status_ !== undefined;
}
function idResolveHandler(x) {
return x;
}
function idRejectHandler(x) {
throw x;
}
function chain(promise) {
var onResolve = arguments[1] !== (void 0) ? arguments[1] : idResolveHandler;
var onReject = arguments[2] !== (void 0) ? arguments[2] : idRejectHandler;
var deferred = getDeferred(promise.constructor);
switch (promise.status_) {
case undefined:
throw TypeError;
case 0:
promise.onResolve_.push(onResolve, deferred);
promise.onReject_.push(onReject, deferred);
break;
case +1:
promiseEnqueue(promise.value_, [onResolve, deferred]);
break;
case -1:
promiseEnqueue(promise.value_, [onReject, deferred]);
break;
}
return deferred.promise;
}
function getDeferred(C) {
if (this === $Promise) {
var promise = promiseInit(new $Promise(promiseRaw));
return {
promise: promise,
resolve: (function(x) {
promiseResolve(promise, x);
}),
reject: (function(r) {
promiseReject(promise, r);
})
};
} else {
var result = {};
result.promise = new C((function(resolve, reject) {
result.resolve = resolve;
result.reject = reject;
}));
return result;
}
}
function promiseSet(promise, status, value, onResolve, onReject) {
promise.status_ = status;
promise.value_ = value;
promise.onResolve_ = onResolve;
promise.onReject_ = onReject;
return promise;
}
function promiseInit(promise) {
return promiseSet(promise, 0, undefined, [], []);
}
var Promise = function Promise(resolver) {
if (resolver === promiseRaw)
return;
if (typeof resolver !== 'function')
throw new TypeError;
var promise = promiseInit(this);
try {
resolver((function(x) {
promiseResolve(promise, x);
}), (function(r) {
promiseReject(promise, r);
}));
} catch (e) {
promiseReject(promise, e);
}
};
($traceurRuntime.createClass)(Promise, {
catch: function(onReject) {
return this.then(undefined, onReject);
},
then: function(onResolve, onReject) {
if (typeof onResolve !== 'function')
onResolve = idResolveHandler;
if (typeof onReject !== 'function')
onReject = idRejectHandler;
var that = this;
var constructor = this.constructor;
return chain(this, function(x) {
x = promiseCoerce(constructor, x);
return x === that ? onReject(new TypeError) : isPromise(x) ? x.then(onResolve, onReject) : onResolve(x);
}, onReject);
}
}, {
resolve: function(x) {
if (this === $Promise) {
if (isPromise(x)) {
return x;
}
return promiseSet(new $Promise(promiseRaw), +1, x);
} else {
return new this(function(resolve, reject) {
resolve(x);
});
}
},
reject: function(r) {
if (this === $Promise) {
return promiseSet(new $Promise(promiseRaw), -1, r);
} else {
return new this((function(resolve, reject) {
reject(r);
}));
}
},
all: function(values) {
var deferred = getDeferred(this);
var resolutions = [];
try {
var count = values.length;
if (count === 0) {
deferred.resolve(resolutions);
} else {
for (var i = 0; i < values.length; i++) {
this.resolve(values[i]).then(function(i, x) {
resolutions[i] = x;
if (--count === 0)
deferred.resolve(resolutions);
}.bind(undefined, i), (function(r) {
deferred.reject(r);
}));
}
}
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
},
race: function(values) {
var deferred = getDeferred(this);
try {
for (var i = 0; i < values.length; i++) {
this.resolve(values[i]).then((function(x) {
deferred.resolve(x);
}), (function(r) {
deferred.reject(r);
}));
}
} catch (e) {
deferred.reject(e);
}
return deferred.promise;
}
});
var $Promise = Promise;
var $PromiseReject = $Promise.reject;
function promiseResolve(promise, x) {
promiseDone(promise, +1, x, promise.onResolve_);
}
function promiseReject(promise, r) {
promiseDone(promise, -1, r, promise.onReject_);
}
function promiseDone(promise, status, value, reactions) {
if (promise.status_ !== 0)
return;
promiseEnqueue(value, reactions);
promiseSet(promise, status, value);
}
function promiseEnqueue(value, tasks) {
async((function() {
for (var i = 0; i < tasks.length; i += 2) {
promiseHandle(value, tasks[i], tasks[i + 1]);
}
}));
}
function promiseHandle(value, handler, deferred) {
try {
var result = handler(value);
if (result === deferred.promise)
throw new TypeError;
else if (isPromise(result))
chain(result, deferred.resolve, deferred.reject);
else
deferred.resolve(result);
} catch (e) {
try {
deferred.reject(e);
} catch (e) {}
}
}
var thenableSymbol = '@@thenable';
function isObject(x) {
return x && (typeof x === 'object' || typeof x === 'function');
}
function promiseCoerce(constructor, x) {
if (!isPromise(x) && isObject(x)) {
var then;
try {
then = x.then;
} catch (r) {
var promise = $PromiseReject.call(constructor, r);
x[thenableSymbol] = promise;
return promise;
}
if (typeof then === 'function') {
var p = x[thenableSymbol];
if (p) {
return p;
} else {
var deferred = getDeferred(constructor);
x[thenableSymbol] = deferred.promise;
try {
then.call(x, deferred.resolve, deferred.reject);
} catch (r) {
deferred.reject(r);
}
return deferred.promise;
}
}
}
return x;
}
function polyfillPromise(global) {
if (!global.Promise)
global.Promise = Promise;
}
registerPolyfill(polyfillPromise);
return {
get Promise() {
return Promise;
},
get polyfillPromise() {
return polyfillPromise;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Promise" + '');
System.register("[email protected]/src/runtime/polyfills/StringIterator", [], function() {
"use strict";
var $__29;
var __moduleName = "[email protected]/src/runtime/polyfills/StringIterator";
var $__27 = System.get("[email protected]/src/runtime/polyfills/utils"),
createIteratorResultObject = $__27.createIteratorResultObject,
isObject = $__27.isObject;
var $__30 = $traceurRuntime,
hasOwnProperty = $__30.hasOwnProperty,
toProperty = $__30.toProperty;
var iteratedString = Symbol('iteratedString');
var stringIteratorNextIndex = Symbol('stringIteratorNextIndex');
var StringIterator = function StringIterator() {};
($traceurRuntime.createClass)(StringIterator, ($__29 = {}, Object.defineProperty($__29, "next", {
value: function() {
var o = this;
if (!isObject(o) || !hasOwnProperty(o, iteratedString)) {
throw new TypeError('this must be a StringIterator object');
}
var s = o[toProperty(iteratedString)];
if (s === undefined) {
return createIteratorResultObject(undefined, true);
}
var position = o[toProperty(stringIteratorNextIndex)];
var len = s.length;
if (position >= len) {
o[toProperty(iteratedString)] = undefined;
return createIteratorResultObject(undefined, true);
}
var first = s.charCodeAt(position);
var resultString;
if (first < 0xD800 || first > 0xDBFF || position + 1 === len) {
resultString = String.fromCharCode(first);
} else {
var second = s.charCodeAt(position + 1);
if (second < 0xDC00 || second > 0xDFFF) {
resultString = String.fromCharCode(first);
} else {
resultString = String.fromCharCode(first) + String.fromCharCode(second);
}
}
o[toProperty(stringIteratorNextIndex)] = position + resultString.length;
return createIteratorResultObject(resultString, false);
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__29, Symbol.iterator, {
value: function() {
return this;
},
configurable: true,
enumerable: true,
writable: true
}), $__29), {});
function createStringIterator(string) {
var s = String(string);
var iterator = Object.create(StringIterator.prototype);
iterator[toProperty(iteratedString)] = s;
iterator[toProperty(stringIteratorNextIndex)] = 0;
return iterator;
}
return {get createStringIterator() {
return createStringIterator;
}};
});
System.register("[email protected]/src/runtime/polyfills/String", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/String";
var createStringIterator = System.get("[email protected]/src/runtime/polyfills/StringIterator").createStringIterator;
var $__32 = System.get("[email protected]/src/runtime/polyfills/utils"),
maybeAddFunctions = $__32.maybeAddFunctions,
maybeAddIterator = $__32.maybeAddIterator,
registerPolyfill = $__32.registerPolyfill;
var $toString = Object.prototype.toString;
var $indexOf = String.prototype.indexOf;
var $lastIndexOf = String.prototype.lastIndexOf;
function startsWith(search) {
var string = String(this);
if (this == null || $toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
var pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
return $indexOf.call(string, searchString, pos) == start;
}
function endsWith(search) {
var string = String(this);
if (this == null || $toString.call(search) == '[object RegExp]') {
throw TypeError();
}
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var pos = stringLength;
if (arguments.length > 1) {
var position = arguments[1];
if (position !== undefined) {
pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
}
}
var end = Math.min(Math.max(pos, 0), stringLength);
var start = end - searchLength;
if (start < 0) {
return false;
}
return $lastIndexOf.call(string, searchString, start) == start;
}
function contains(search) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var stringLength = string.length;
var searchString = String(search);
var searchLength = searchString.length;
var position = arguments.length > 1 ? arguments[1] : undefined;
var pos = position ? Number(position) : 0;
if (isNaN(pos)) {
pos = 0;
}
var start = Math.min(Math.max(pos, 0), stringLength);
return $indexOf.call(string, searchString, pos) != -1;
}
function repeat(count) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var n = count ? Number(count) : 0;
if (isNaN(n)) {
n = 0;
}
if (n < 0 || n == Infinity) {
throw RangeError();
}
if (n == 0) {
return '';
}
var result = '';
while (n--) {
result += string;
}
return result;
}
function codePointAt(position) {
if (this == null) {
throw TypeError();
}
var string = String(this);
var size = string.length;
var index = position ? Number(position) : 0;
if (isNaN(index)) {
index = 0;
}
if (index < 0 || index >= size) {
return undefined;
}
var first = string.charCodeAt(index);
var second;
if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) {
second = string.charCodeAt(index + 1);
if (second >= 0xDC00 && second <= 0xDFFF) {
return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
}
}
return first;
}
function raw(callsite) {
var raw = callsite.raw;
var len = raw.length >>> 0;
if (len === 0)
return '';
var s = '';
var i = 0;
while (true) {
s += raw[i];
if (i + 1 === len)
return s;
s += arguments[++i];
}
}
function fromCodePoint() {
var codeUnits = [];
var floor = Math.floor;
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
while (++index < length) {
var codePoint = Number(arguments[index]);
if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || floor(codePoint) != codePoint) {
throw RangeError('Invalid code point: ' + codePoint);
}
if (codePoint <= 0xFFFF) {
codeUnits.push(codePoint);
} else {
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = (codePoint % 0x400) + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
}
return String.fromCharCode.apply(null, codeUnits);
}
function stringPrototypeIterator() {
var o = $traceurRuntime.checkObjectCoercible(this);
var s = String(o);
return createStringIterator(s);
}
function polyfillString(global) {
var String = global.String;
maybeAddFunctions(String.prototype, ['codePointAt', codePointAt, 'contains', contains, 'endsWith', endsWith, 'startsWith', startsWith, 'repeat', repeat]);
maybeAddFunctions(String, ['fromCodePoint', fromCodePoint, 'raw', raw]);
maybeAddIterator(String.prototype, stringPrototypeIterator, Symbol);
}
registerPolyfill(polyfillString);
return {
get startsWith() {
return startsWith;
},
get endsWith() {
return endsWith;
},
get contains() {
return contains;
},
get repeat() {
return repeat;
},
get codePointAt() {
return codePointAt;
},
get raw() {
return raw;
},
get fromCodePoint() {
return fromCodePoint;
},
get stringPrototypeIterator() {
return stringPrototypeIterator;
},
get polyfillString() {
return polyfillString;
}
};
});
System.get("[email protected]/src/runtime/polyfills/String" + '');
System.register("[email protected]/src/runtime/polyfills/ArrayIterator", [], function() {
"use strict";
var $__36;
var __moduleName = "[email protected]/src/runtime/polyfills/ArrayIterator";
var $__34 = System.get("[email protected]/src/runtime/polyfills/utils"),
toObject = $__34.toObject,
toUint32 = $__34.toUint32,
createIteratorResultObject = $__34.createIteratorResultObject;
var ARRAY_ITERATOR_KIND_KEYS = 1;
var ARRAY_ITERATOR_KIND_VALUES = 2;
var ARRAY_ITERATOR_KIND_ENTRIES = 3;
var ArrayIterator = function ArrayIterator() {};
($traceurRuntime.createClass)(ArrayIterator, ($__36 = {}, Object.defineProperty($__36, "next", {
value: function() {
var iterator = toObject(this);
var array = iterator.iteratorObject_;
if (!array) {
throw new TypeError('Object is not an ArrayIterator');
}
var index = iterator.arrayIteratorNextIndex_;
var itemKind = iterator.arrayIterationKind_;
var length = toUint32(array.length);
if (index >= length) {
iterator.arrayIteratorNextIndex_ = Infinity;
return createIteratorResultObject(undefined, true);
}
iterator.arrayIteratorNextIndex_ = index + 1;
if (itemKind == ARRAY_ITERATOR_KIND_VALUES)
return createIteratorResultObject(array[index], false);
if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES)
return createIteratorResultObject([index, array[index]], false);
return createIteratorResultObject(index, false);
},
configurable: true,
enumerable: true,
writable: true
}), Object.defineProperty($__36, Symbol.iterator, {
value: function() {
return this;
},
configurable: true,
enumerable: true,
writable: true
}), $__36), {});
function createArrayIterator(array, kind) {
var object = toObject(array);
var iterator = new ArrayIterator;
iterator.iteratorObject_ = object;
iterator.arrayIteratorNextIndex_ = 0;
iterator.arrayIterationKind_ = kind;
return iterator;
}
function entries() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES);
}
function keys() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS);
}
function values() {
return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES);
}
return {
get entries() {
return entries;
},
get keys() {
return keys;
},
get values() {
return values;
}
};
});
System.register("[email protected]/src/runtime/polyfills/Array", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Array";
var $__37 = System.get("[email protected]/src/runtime/polyfills/ArrayIterator"),
entries = $__37.entries,
keys = $__37.keys,
values = $__37.values;
var $__38 = System.get("[email protected]/src/runtime/polyfills/utils"),
checkIterable = $__38.checkIterable,
isCallable = $__38.isCallable,
isConstructor = $__38.isConstructor,
maybeAddFunctions = $__38.maybeAddFunctions,
maybeAddIterator = $__38.maybeAddIterator,
registerPolyfill = $__38.registerPolyfill,
toInteger = $__38.toInteger,
toLength = $__38.toLength,
toObject = $__38.toObject;
function from(arrLike) {
var mapFn = arguments[1];
var thisArg = arguments[2];
var C = this;
var items = toObject(arrLike);
var mapping = mapFn !== undefined;
var k = 0;
var arr,
len;
if (mapping && !isCallable(mapFn)) {
throw TypeError();
}
if (checkIterable(items)) {
arr = isConstructor(C) ? new C() : [];
for (var $__39 = items[Symbol.iterator](),
$__40; !($__40 = $__39.next()).done; ) {
var item = $__40.value;
{
if (mapping) {
arr[k] = mapFn.call(thisArg, item, k);
} else {
arr[k] = item;
}
k++;
}
}
arr.length = k;
return arr;
}
len = toLength(items.length);
arr = isConstructor(C) ? new C(len) : new Array(len);
for (; k < len; k++) {
if (mapping) {
arr[k] = typeof thisArg === 'undefined' ? mapFn(items[k], k) : mapFn.call(thisArg, items[k], k);
} else {
arr[k] = items[k];
}
}
arr.length = len;
return arr;
}
function of() {
for (var items = [],
$__41 = 0; $__41 < arguments.length; $__41++)
items[$__41] = arguments[$__41];
var C = this;
var len = items.length;
var arr = isConstructor(C) ? new C(len) : new Array(len);
for (var k = 0; k < len; k++) {
arr[k] = items[k];
}
arr.length = len;
return arr;
}
function fill(value) {
var start = arguments[1] !== (void 0) ? arguments[1] : 0;
var end = arguments[2];
var object = toObject(this);
var len = toLength(object.length);
var fillStart = toInteger(start);
var fillEnd = end !== undefined ? toInteger(end) : len;
fillStart = fillStart < 0 ? Math.max(len + fillStart, 0) : Math.min(fillStart, len);
fillEnd = fillEnd < 0 ? Math.max(len + fillEnd, 0) : Math.min(fillEnd, len);
while (fillStart < fillEnd) {
object[fillStart] = value;
fillStart++;
}
return object;
}
function find(predicate) {
var thisArg = arguments[1];
return findHelper(this, predicate, thisArg);
}
function findIndex(predicate) {
var thisArg = arguments[1];
return findHelper(this, predicate, thisArg, true);
}
function findHelper(self, predicate) {
var thisArg = arguments[2];
var returnIndex = arguments[3] !== (void 0) ? arguments[3] : false;
var object = toObject(self);
var len = toLength(object.length);
if (!isCallable(predicate)) {
throw TypeError();
}
for (var i = 0; i < len; i++) {
if (i in object) {
var value = object[i];
if (predicate.call(thisArg, value, i, object)) {
return returnIndex ? i : value;
}
}
}
return returnIndex ? -1 : undefined;
}
function polyfillArray(global) {
var $__42 = global,
Array = $__42.Array,
Object = $__42.Object,
Symbol = $__42.Symbol;
maybeAddFunctions(Array.prototype, ['entries', entries, 'keys', keys, 'values', values, 'fill', fill, 'find', find, 'findIndex', findIndex]);
maybeAddFunctions(Array, ['from', from, 'of', of]);
maybeAddIterator(Array.prototype, values, Symbol);
maybeAddIterator(Object.getPrototypeOf([].values()), function() {
return this;
}, Symbol);
}
registerPolyfill(polyfillArray);
return {
get from() {
return from;
},
get of() {
return of;
},
get fill() {
return fill;
},
get find() {
return find;
},
get findIndex() {
return findIndex;
},
get polyfillArray() {
return polyfillArray;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Array" + '');
System.register("[email protected]/src/runtime/polyfills/Object", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Object";
var $__43 = System.get("[email protected]/src/runtime/polyfills/utils"),
maybeAddFunctions = $__43.maybeAddFunctions,
registerPolyfill = $__43.registerPolyfill;
var $__44 = $traceurRuntime,
defineProperty = $__44.defineProperty,
getOwnPropertyDescriptor = $__44.getOwnPropertyDescriptor,
getOwnPropertyNames = $__44.getOwnPropertyNames,
keys = $__44.keys,
privateNames = $__44.privateNames;
function is(left, right) {
if (left === right)
return left !== 0 || 1 / left === 1 / right;
return left !== left && right !== right;
}
function assign(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
var props = keys(source);
var p,
length = props.length;
for (p = 0; p < length; p++) {
var name = props[p];
if (privateNames[name])
continue;
target[name] = source[name];
}
}
return target;
}
function mixin(target, source) {
var props = getOwnPropertyNames(source);
var p,
descriptor,
length = props.length;
for (p = 0; p < length; p++) {
var name = props[p];
if (privateNames[name])
continue;
descriptor = getOwnPropertyDescriptor(source, props[p]);
defineProperty(target, props[p], descriptor);
}
return target;
}
function polyfillObject(global) {
var Object = global.Object;
maybeAddFunctions(Object, ['assign', assign, 'is', is, 'mixin', mixin]);
}
registerPolyfill(polyfillObject);
return {
get is() {
return is;
},
get assign() {
return assign;
},
get mixin() {
return mixin;
},
get polyfillObject() {
return polyfillObject;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Object" + '');
System.register("[email protected]/src/runtime/polyfills/Number", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/Number";
var $__46 = System.get("[email protected]/src/runtime/polyfills/utils"),
isNumber = $__46.isNumber,
maybeAddConsts = $__46.maybeAddConsts,
maybeAddFunctions = $__46.maybeAddFunctions,
registerPolyfill = $__46.registerPolyfill,
toInteger = $__46.toInteger;
var $abs = Math.abs;
var $isFinite = isFinite;
var $isNaN = isNaN;
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
var MIN_SAFE_INTEGER = -Math.pow(2, 53) + 1;
var EPSILON = Math.pow(2, -52);
function NumberIsFinite(number) {
return isNumber(number) && $isFinite(number);
}
;
function isInteger(number) {
return NumberIsFinite(number) && toInteger(number) === number;
}
function NumberIsNaN(number) {
return isNumber(number) && $isNaN(number);
}
;
function isSafeInteger(number) {
if (NumberIsFinite(number)) {
var integral = toInteger(number);
if (integral === number)
return $abs(integral) <= MAX_SAFE_INTEGER;
}
return false;
}
function polyfillNumber(global) {
var Number = global.Number;
maybeAddConsts(Number, ['MAX_SAFE_INTEGER', MAX_SAFE_INTEGER, 'MIN_SAFE_INTEGER', MIN_SAFE_INTEGER, 'EPSILON', EPSILON]);
maybeAddFunctions(Number, ['isFinite', NumberIsFinite, 'isInteger', isInteger, 'isNaN', NumberIsNaN, 'isSafeInteger', isSafeInteger]);
}
registerPolyfill(polyfillNumber);
return {
get MAX_SAFE_INTEGER() {
return MAX_SAFE_INTEGER;
},
get MIN_SAFE_INTEGER() {
return MIN_SAFE_INTEGER;
},
get EPSILON() {
return EPSILON;
},
get isFinite() {
return NumberIsFinite;
},
get isInteger() {
return isInteger;
},
get isNaN() {
return NumberIsNaN;
},
get isSafeInteger() {
return isSafeInteger;
},
get polyfillNumber() {
return polyfillNumber;
}
};
});
System.get("[email protected]/src/runtime/polyfills/Number" + '');
System.register("[email protected]/src/runtime/polyfills/polyfills", [], function() {
"use strict";
var __moduleName = "[email protected]/src/runtime/polyfills/polyfills";
var polyfillAll = System.get("[email protected]/src/runtime/polyfills/utils").polyfillAll;
polyfillAll(this);
var setupGlobals = $traceurRuntime.setupGlobals;
$traceurRuntime.setupGlobals = function(global) {
setupGlobals(global);
polyfillAll(global);
};
return {};
});
System.get("[email protected]/src/runtime/polyfills/polyfills" + '');
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":2}],4:[function(require,module,exports){
/**
* Copyright 2012 Craig Campbell
*
* 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.
*
* Mousetrap is a simple keyboard shortcut library for Javascript with
* no external dependencies
*
* @version 1.1.2
* @url craig.is/killing/mice
*/
/**
* mapping of special keycodes to their corresponding keys
*
* everything in this dictionary cannot use keypress events
* so it has to be here to map to the correct keycodes for
* keyup/keydown events
*
* @type {Object}
*/
var _MAP = {
8: 'backspace',
9: 'tab',
13: 'enter',
16: 'shift',
17: 'ctrl',
18: 'alt',
20: 'capslock',
27: 'esc',
32: 'space',
33: 'pageup',
34: 'pagedown',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
45: 'ins',
46: 'del',
91: 'meta',
93: 'meta',
224: 'meta'
},
/**
* mapping for special characters so they can support
*
* this dictionary is only used incase you want to bind a
* keyup or keydown event to one of these keys
*
* @type {Object}
*/
_KEYCODE_MAP = {
106: '*',
107: '+',
109: '-',
110: '.',
111 : '/',
186: ';',
187: '=',
188: ',',
189: '-',
190: '.',
191: '/',
192: '`',
219: '[',
220: '\\',
221: ']',
222: '\''
},
/**
* this is a mapping of keys that require shift on a US keypad
* back to the non shift equivelents
*
* this is so you can use keyup events with these keys
*
* note that this will only work reliably on US keyboards
*
* @type {Object}
*/
_SHIFT_MAP = {
'~': '`',
'!': '1',
'@': '2',
'#': '3',
'$': '4',
'%': '5',
'^': '6',
'&': '7',
'*': '8',
'(': '9',
')': '0',
'_': '-',
'+': '=',
':': ';',
'\"': '\'',
'<': ',',
'>': '.',
'?': '/',
'|': '\\'
},
/**
* this is a list of special strings you can use to map
* to modifier keys when you specify your keyboard shortcuts
*
* @type {Object}
*/
_SPECIAL_ALIASES = {
'option': 'alt',
'command': 'meta',
'return': 'enter',
'escape': 'esc'
},
/**
* variable to store the flipped version of _MAP from above
* needed to check if we should use keypress or not when no action
* is specified
*
* @type {Object|undefined}
*/
_REVERSE_MAP,
/**
* a list of all the callbacks setup via Mousetrap.bind()
*
* @type {Object}
*/
_callbacks = {},
/**
* direct map of string combinations to callbacks used for trigger()
*
* @type {Object}
*/
_direct_map = {},
/**
* keeps track of what level each sequence is at since multiple
* sequences can start out with the same sequence
*
* @type {Object}
*/
_sequence_levels = {},
/**
* variable to store the setTimeout call
*
* @type {null|number}
*/
_reset_timer,
/**
* temporary state where we will ignore the next keyup
*
* @type {boolean|string}
*/
_ignore_next_keyup = false,
/**
* are we currently inside of a sequence?
* type of action ("keyup" or "keydown" or "keypress") or false
*
* @type {boolean|string}
*/
_inside_sequence = false;
/**
* loop through the f keys, f1 to f19 and add them to the map
* programatically
*/
for (var i = 1; i < 20; ++i) {
_MAP[111 + i] = 'f' + i;
}
/**
* loop through to map numbers on the numeric keypad
*/
for (i = 0; i <= 9; ++i) {
_MAP[i + 96] = i;
}
/**
* cross browser add event method
*
* @param {Element|HTMLDocument} object
* @param {string} type
* @param {Function} callback
* @returns void
*/
function _addEvent(object, type, callback) {
if (object.addEventListener) {
return object.addEventListener(type, callback, false);
}
object.attachEvent('on' + type, callback);
}
/**
* takes the event and returns the key character
*
* @param {Event} e
* @return {string}
*/
function _characterFromEvent(e) {
// for keypress events we should return the character as is
if (e.type == 'keypress') {
return String.fromCharCode(e.which);
}
// for non keypress events the special maps are needed
if (_MAP[e.which]) {
return _MAP[e.which];
}
if (_KEYCODE_MAP[e.which]) {
return _KEYCODE_MAP[e.which];
}
// if it is not in the special map
return String.fromCharCode(e.which).toLowerCase();
}
/**
* should we stop this event before firing off callbacks
*
* @param {Event} e
* @return {boolean}
*/
function _stop(e) {
var element = e.target || e.srcElement,
tag_name = element.tagName;
// if the element has the class "mousetrap" then no need to stop
if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
return false;
}
// stop for input, select, and textarea
return tag_name == 'INPUT' || tag_name == 'SELECT' || tag_name == 'TEXTAREA' || (element.contentEditable && element.contentEditable == 'true');
}
/**
* checks if two arrays are equal
*
* @param {Array} modifiers1
* @param {Array} modifiers2
* @returns {boolean}
*/
function _modifiersMatch(modifiers1, modifiers2) {
return modifiers1.sort().join(',') === modifiers2.sort().join(',');
}
/**
* resets all sequence counters except for the ones passed in
*
* @param {Object} do_not_reset
* @returns void
*/
function _resetSequences(do_not_reset) {
do_not_reset = do_not_reset || {};
var active_sequences = false,
key;
for (key in _sequence_levels) {
if (do_not_reset[key]) {
active_sequences = true;
continue;
}
_sequence_levels[key] = 0;
}
if (!active_sequences) {
_inside_sequence = false;
}
}
/**
* finds all callbacks that match based on the keycode, modifiers,
* and action
*
* @param {string} character
* @param {Array} modifiers
* @param {string} action
* @param {boolean=} remove - should we remove any matches
* @param {string=} combination
* @returns {Array}
*/
function _getMatches(character, modifiers, action, remove, combination) {
var i,
callback,
matches = [];
// if there are no events related to this keycode
if (!_callbacks[character]) {
return [];
}
// if a modifier key is coming up on its own we should allow it
if (action == 'keyup' && _isModifier(character)) {
modifiers = [character];
}
// loop through all callbacks for the key that was pressed
// and see if any of them match
for (i = 0; i < _callbacks[character].length; ++i) {
callback = _callbacks[character][i];
// if this is a sequence but it is not at the right level
// then move onto the next match
if (callback.seq && _sequence_levels[callback.seq] != callback.level) {
continue;
}
// if the action we are looking for doesn't match the action we got
// then we should keep going
if (action != callback.action) {
continue;
}
// if this is a keypress event that means that we need to only
// look at the character, otherwise check the modifiers as
// well
if (action == 'keypress' || _modifiersMatch(modifiers, callback.modifiers)) {
// remove is used so if you change your mind and call bind a
// second time with a new function the first one is overwritten
if (remove && callback.combo == combination) {
_callbacks[character].splice(i, 1);
}
matches.push(callback);
}
}
return matches;
}
/**
* takes a key event and figures out what the modifiers are
*
* @param {Event} e
* @returns {Array}
*/
function _eventModifiers(e) {
var modifiers = [];
if (e.shiftKey) {
modifiers.push('shift');
}
if (e.altKey) {
modifiers.push('alt');
}
if (e.ctrlKey) {
modifiers.push('ctrl');
}
if (e.metaKey) {
modifiers.push('meta');
}
return modifiers;
}
/**
* actually calls the callback function
*
* if your callback function returns false this will use the jquery
* convention - prevent default and stop propogation on the event
*
* @param {Function} callback
* @param {Event} e
* @returns void
*/
function _fireCallback(callback, e) {
if (callback(e) === false) {
if (e.preventDefault) {
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
e.returnValue = false;
e.cancelBubble = true;
}
}
/**
* handles a character key event
*
* @param {string} character
* @param {Event} e
* @returns void
*/
function _handleCharacter(character, e) {
// if this event should not happen stop here
if (_stop(e)) {
return;
}
var callbacks = _getMatches(character, _eventModifiers(e), e.type),
i,
do_not_reset = {},
processed_sequence_callback = false;
// loop through matching callbacks for this key event
for (i = 0; i < callbacks.length; ++i) {
// fire for all sequence callbacks
// this is because if for example you have multiple sequences
// bound such as "g i" and "g t" they both need to fire the
// callback for matching g cause otherwise you can only ever
// match the first one
if (callbacks[i].seq) {
processed_sequence_callback = true;
// keep a list of which sequences were matches for later
do_not_reset[callbacks[i].seq] = 1;
_fireCallback(callbacks[i].callback, e);
continue;
}
// if there were no sequence matches but we are still here
// that means this is a regular match so we should fire that
if (!processed_sequence_callback && !_inside_sequence) {
_fireCallback(callbacks[i].callback, e);
}
}
// if you are inside of a sequence and the key you are pressing
// is not a modifier key then we should reset all sequences
// that were not matched by this key event
if (e.type == _inside_sequence && !_isModifier(character)) {
_resetSequences(do_not_reset);
}
}
/**
* handles a keydown event
*
* @param {Event} e
* @returns void
*/
function _handleKey(e) {
// normalize e.which for key events
// @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
e.which = typeof e.which == "number" ? e.which : e.keyCode;
var character = _characterFromEvent(e);
// no character found then stop
if (!character) {
return;
}
if (e.type == 'keyup' && _ignore_next_keyup == character) {
_ignore_next_keyup = false;
return;
}
_handleCharacter(character, e);
}
/**
* determines if the keycode specified is a modifier key or not
*
* @param {string} key
* @returns {boolean}
*/
function _isModifier(key) {
return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
}
/**
* called to set a 1 second timeout on the specified sequence
*
* this is so after each key press in the sequence you have 1 second
* to press the next key before you have to start over
*
* @returns void
*/
function _resetSequenceTimer() {
clearTimeout(_reset_timer);
_reset_timer = setTimeout(_resetSequences, 1000);
}
/**
* reverses the map lookup so that we can look for specific keys
* to see what can and can't use keypress
*
* @return {Object}
*/
function _getReverseMap() {
if (!_REVERSE_MAP) {
_REVERSE_MAP = {};
for (var key in _MAP) {
// pull out the numeric keypad from here cause keypress should
// be able to detect the keys from the character
if (key > 95 && key < 112) {
continue;
}
if (_MAP.hasOwnProperty(key)) {
_REVERSE_MAP[_MAP[key]] = key;
}
}
}
return _REVERSE_MAP;
}
/**
* picks the best action based on the key combination
*
* @param {string} key - character for key
* @param {Array} modifiers
* @param {string=} action passed in
*/
function _pickBestAction(key, modifiers, action) {
// if no action was picked in we should try to pick the one
// that we think would work best for this key
if (!action) {
action = _getReverseMap()[key] ? 'keydown' : 'keypress';
}
// modifier keys don't work as expected with keypress,
// switch to keydown
if (action == 'keypress' && modifiers.length) {
action = 'keydown';
}
return action;
}
/**
* binds a key sequence to an event
*
* @param {string} combo - combo specified in bind call
* @param {Array} keys
* @param {Function} callback
* @param {string=} action
* @returns void
*/
function _bindSequence(combo, keys, callback, action) {
// start off by adding a sequence level record for this combination
// and setting the level to 0
_sequence_levels[combo] = 0;
// if there is no action pick the best one for the first key
// in the sequence
if (!action) {
action = _pickBestAction(keys[0], []);
}
/**
* callback to increase the sequence level for this sequence and reset
* all other sequences that were active
*
* @param {Event} e
* @returns void
*/
var _increaseSequence = function(e) {
_inside_sequence = action;
++_sequence_levels[combo];
_resetSequenceTimer();
},
/**
* wraps the specified callback inside of another function in order
* to reset all sequence counters as soon as this sequence is done
*
* @param {Event} e
* @returns void
*/
_callbackAndReset = function(e) {
_fireCallback(callback, e);
// we should ignore the next key up if the action is key down
// or keypress. this is so if you finish a sequence and
// release the key the final key will not trigger a keyup
if (action !== 'keyup') {
_ignore_next_keyup = _characterFromEvent(e);
}
// weird race condition if a sequence ends with the key
// another sequence begins with
setTimeout(_resetSequences, 10);
},
i;
// loop through keys one at a time and bind the appropriate callback
// function. for any key leading up to the final one it should
// increase the sequence. after the final, it should reset all sequences
for (i = 0; i < keys.length; ++i) {
_bindSingle(keys[i], i < keys.length - 1 ? _increaseSequence : _callbackAndReset, action, combo, i);
}
}
/**
* binds a single keyboard combination
*
* @param {string} combination
* @param {Function} callback
* @param {string=} action
* @param {string=} sequence_name - name of sequence if part of sequence
* @param {number=} level - what part of the sequence the command is
* @returns void
*/
function _bindSingle(combination, callback, action, sequence_name, level) {
// make sure multiple spaces in a row become a single space
combination = combination.replace(/\s+/g, ' ');
var sequence = combination.split(' '),
i,
key,
keys,
modifiers = [];
// if this pattern is a sequence of keys then run through this method
// to reprocess each pattern one key at a time
if (sequence.length > 1) {
return _bindSequence(combination, sequence, callback, action);
}
// take the keys from this pattern and figure out what the actual
// pattern is all about
keys = combination === '+' ? ['+'] : combination.split('+');
for (i = 0; i < keys.length; ++i) {
key = keys[i];
// normalize key names
if (_SPECIAL_ALIASES[key]) {
key = _SPECIAL_ALIASES[key];
}
// if this is not a keypress event then we should
// be smart about using shift keys
// this will only work for US keyboards however
if (action && action != 'keypress' && _SHIFT_MAP[key]) {
key = _SHIFT_MAP[key];
modifiers.push('shift');
}
// if this key is a modifier then add it to the list of modifiers
if (_isModifier(key)) {
modifiers.push(key);
}
}
// depending on what the key combination is
// we will try to pick the best event for it
action = _pickBestAction(key, modifiers, action);
// make sure to initialize array if this is the first time
// a callback is added for this key
if (!_callbacks[key]) {
_callbacks[key] = [];
}
// remove an existing match if there is one
_getMatches(key, modifiers, action, !sequence_name, combination);
// add this call back to the array
// if it is a sequence put it at the beginning
// if not put it at the end
//
// this is important because the way these are processed expects
// the sequence ones to come first
_callbacks[key][sequence_name ? 'unshift' : 'push']({
callback: callback,
modifiers: modifiers,
action: action,
seq: sequence_name,
level: level,
combo: combination
});
}
/**
* binds multiple combinations to the same callback
*
* @param {Array} combinations
* @param {Function} callback
* @param {string|undefined} action
* @returns void
*/
function _bindMultiple(combinations, callback, action) {
for (var i = 0; i < combinations.length; ++i) {
_bindSingle(combinations[i], callback, action);
}
}
// start!
_addEvent(document, 'keypress', _handleKey);
_addEvent(document, 'keydown', _handleKey);
_addEvent(document, 'keyup', _handleKey);
var mousetrap = {
/**
* binds an event to mousetrap
*
* can be a single key, a combination of keys separated with +,
* a comma separated list of keys, an array of keys, or
* a sequence of keys separated by spaces
*
* be sure to list the modifier keys first to make sure that the
* correct key ends up getting bound (the last key in the pattern)
*
* @param {string|Array} keys
* @param {Function} callback
* @param {string=} action - 'keypress', 'keydown', or 'keyup'
* @returns void
*/
bind: function(keys, callback, action) {
_bindMultiple(keys instanceof Array ? keys : [keys], callback, action);
_direct_map[keys + ':' + action] = callback;
return this;
},
/**
* unbinds an event to mousetrap
*
* the unbinding sets the callback function of the specified key combo
* to an empty function and deletes the corresponding key in the
* _direct_map dict.
*
* the keycombo+action has to be exactly the same as
* it was defined in the bind method
*
* TODO: actually remove this from the _callbacks dictionary instead
* of binding an empty function
*
* @param {string|Array} keys
* @param {string} action
* @returns void
*/
unbind: function(keys, action) {
if (_direct_map[keys + ':' + action]) {
delete _direct_map[keys + ':' + action];
this.bind(keys, function() {}, action);
}
return this;
},
/**
* triggers an event that has already been bound
*
* @param {string} keys
* @param {string=} action
* @returns void
*/
trigger: function(keys, action) {
_direct_map[keys + ':' + action]();
return this;
},
/**
* resets the library back to its initial state. this is useful
* if you want to clear out the current keyboard shortcuts and bind
* new ones - for example if you switch to another page
*
* @returns void
*/
reset: function() {
_callbacks = {};
_direct_map = {};
return this;
}
};
module.exports = mousetrap;
},{}],5:[function(require,module,exports){
(function( factory ) {
if (typeof define !== 'undefined' && define.amd) {
define([], factory);
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = factory();
} else {
window.scrollMonitor = factory();
}
})(function() {
var scrollTop = function() {
return window.pageYOffset ||
(document.documentElement && document.documentElement.scrollTop) ||
document.body.scrollTop;
};
var exports = {};
var watchers = [];
var VISIBILITYCHANGE = 'visibilityChange';
var ENTERVIEWPORT = 'enterViewport';
var FULLYENTERVIEWPORT = 'fullyEnterViewport';
var EXITVIEWPORT = 'exitViewport';
var PARTIALLYEXITVIEWPORT = 'partiallyExitViewport';
var LOCATIONCHANGE = 'locationChange';
var STATECHANGE = 'stateChange';
var eventTypes = [
VISIBILITYCHANGE,
ENTERVIEWPORT,
FULLYENTERVIEWPORT,
EXITVIEWPORT,
PARTIALLYEXITVIEWPORT,
LOCATIONCHANGE,
STATECHANGE
];
var defaultOffsets = {top: 0, bottom: 0};
var getViewportHeight = function() {
return window.innerHeight || document.documentElement.clientHeight;
};
var getDocumentHeight = function() {
// jQuery approach
// whichever is greatest
return Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.documentElement.clientHeight
);
};
exports.viewportTop = null;
exports.viewportBottom = null;
exports.documentHeight = null;
exports.viewportHeight = getViewportHeight();
var previousDocumentHeight;
var latestEvent;
var calculateViewportI;
function calculateViewport() {
exports.viewportTop = scrollTop();
exports.viewportBottom = exports.viewportTop + exports.viewportHeight;
exports.documentHeight = getDocumentHeight();
if (exports.documentHeight !== previousDocumentHeight) {
calculateViewportI = watchers.length;
while( calculateViewportI-- ) {
watchers[calculateViewportI].recalculateLocation();
}
previousDocumentHeight = exports.documentHeight;
}
}
function recalculateWatchLocationsAndTrigger() {
exports.viewportHeight = getViewportHeight();
calculateViewport();
updateAndTriggerWatchers();
}
var recalculateAndTriggerTimer;
function debouncedRecalcuateAndTrigger() {
clearTimeout(recalculateAndTriggerTimer);
recalculateAndTriggerTimer = setTimeout( recalculateWatchLocationsAndTrigger, 100 );
}
var updateAndTriggerWatchersI;
function updateAndTriggerWatchers() {
// update all watchers then trigger the events so one can rely on another being up to date.
updateAndTriggerWatchersI = watchers.length;
while( updateAndTriggerWatchersI-- ) {
watchers[updateAndTriggerWatchersI].update();
}
updateAndTriggerWatchersI = watchers.length;
while( updateAndTriggerWatchersI-- ) {
watchers[updateAndTriggerWatchersI].triggerCallbacks();
}
}
function ElementWatcher( watchItem, offsets ) {
var self = this;
this.watchItem = watchItem;
if (!offsets) {
this.offsets = defaultOffsets;
} else if (offsets === +offsets) {
this.offsets = {top: offsets, bottom: offsets};
} else {
this.offsets = {
top: offsets.top || defaultOffsets.top,
bottom: offsets.bottom || defaultOffsets.bottom
};
}
this.callbacks = {}; // {callback: function, isOne: true }
for (var i = 0, j = eventTypes.length; i < j; i++) {
self.callbacks[eventTypes[i]] = [];
}
this.locked = false;
var wasInViewport;
var wasFullyInViewport;
var wasAboveViewport;
var wasBelowViewport;
var listenerToTriggerListI;
var listener;
function triggerCallbackArray( listeners ) {
if (listeners.length === 0) {
return;
}
listenerToTriggerListI = listeners.length;
while( listenerToTriggerListI-- ) {
listener = listeners[listenerToTriggerListI];
listener.callback.call( self, latestEvent );
if (listener.isOne) {
listeners.splice(listenerToTriggerListI, 1);
}
}
}
this.triggerCallbacks = function triggerCallbacks() {
if (this.isInViewport && !wasInViewport) {
triggerCallbackArray( this.callbacks[ENTERVIEWPORT] );
}
if (this.isFullyInViewport && !wasFullyInViewport) {
triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] );
}
if (this.isAboveViewport !== wasAboveViewport &&
this.isBelowViewport !== wasBelowViewport) {
triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] );
// if you skip completely past this element
if (!wasFullyInViewport && !this.isFullyInViewport) {
triggerCallbackArray( this.callbacks[FULLYENTERVIEWPORT] );
triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] );
}
if (!wasInViewport && !this.isInViewport) {
triggerCallbackArray( this.callbacks[ENTERVIEWPORT] );
triggerCallbackArray( this.callbacks[EXITVIEWPORT] );
}
}
if (!this.isFullyInViewport && wasFullyInViewport) {
triggerCallbackArray( this.callbacks[PARTIALLYEXITVIEWPORT] );
}
if (!this.isInViewport && wasInViewport) {
triggerCallbackArray( this.callbacks[EXITVIEWPORT] );
}
if (this.isInViewport !== wasInViewport) {
triggerCallbackArray( this.callbacks[VISIBILITYCHANGE] );
}
switch( true ) {
case wasInViewport !== this.isInViewport:
case wasFullyInViewport !== this.isFullyInViewport:
case wasAboveViewport !== this.isAboveViewport:
case wasBelowViewport !== this.isBelowViewport:
triggerCallbackArray( this.callbacks[STATECHANGE] );
}
wasInViewport = this.isInViewport;
wasFullyInViewport = this.isFullyInViewport;
wasAboveViewport = this.isAboveViewport;
wasBelowViewport = this.isBelowViewport;
};
this.recalculateLocation = function() {
if (this.locked) {
return;
}
var previousTop = this.top;
var previousBottom = this.bottom;
if (this.watchItem.nodeName) { // a dom element
var cachedDisplay = this.watchItem.style.display;
if (cachedDisplay === 'none') {
this.watchItem.style.display = '';
}
var boundingRect = this.watchItem.getBoundingClientRect();
this.top = boundingRect.top + exports.viewportTop;
this.bottom = boundingRect.bottom + exports.viewportTop;
if (cachedDisplay === 'none') {
this.watchItem.style.display = cachedDisplay;
}
} else if (this.watchItem === +this.watchItem) { // number
if (this.watchItem > 0) {
this.top = this.bottom = this.watchItem;
} else {
this.top = this.bottom = exports.documentHeight - this.watchItem;
}
} else { // an object with a top and bottom property
this.top = this.watchItem.top;
this.bottom = this.watchItem.bottom;
}
this.top -= this.offsets.top;
this.bottom += this.offsets.bottom;
this.height = this.bottom - this.top;
if ( (previousTop !== undefined || previousBottom !== undefined) && (this.top !== previousTop || this.bottom !== previousBottom) ) {
triggerCallbackArray( this.callbacks[LOCATIONCHANGE] );
}
};
this.recalculateLocation();
this.update();
wasInViewport = this.isInViewport;
wasFullyInViewport = this.isFullyInViewport;
wasAboveViewport = this.isAboveViewport;
wasBelowViewport = this.isBelowViewport;
}
ElementWatcher.prototype = {
on: function( event, callback, isOne ) {
// trigger the event if it applies to the element right now.
switch( true ) {
case event === VISIBILITYCHANGE && !this.isInViewport && this.isAboveViewport:
case event === ENTERVIEWPORT && this.isInViewport:
case event === FULLYENTERVIEWPORT && this.isFullyInViewport:
case event === EXITVIEWPORT && this.isAboveViewport && !this.isInViewport:
case event === PARTIALLYEXITVIEWPORT && this.isAboveViewport:
callback.call( this, latestEvent );
if (isOne) {
return;
}
}
if (this.callbacks[event]) {
this.callbacks[event].push({callback: callback, isOne: isOne||false});
} else {
throw new Error('Tried to add a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', '));
}
},
off: function( event, callback ) {
if (this.callbacks[event]) {
for (var i = 0, item; item = this.callbacks[event][i]; i++) {
if (item.callback === callback) {
this.callbacks[event].splice(i, 1);
break;
}
}
} else {
throw new Error('Tried to remove a scroll monitor listener of type '+event+'. Your options are: '+eventTypes.join(', '));
}
},
one: function( event, callback ) {
this.on( event, callback, true);
},
recalculateSize: function() {
this.height = this.watchItem.offsetHeight + this.offsets.top + this.offsets.bottom;
this.bottom = this.top + this.height;
},
update: function() {
this.isAboveViewport = this.top < exports.viewportTop;
this.isBelowViewport = this.bottom > exports.viewportBottom;
this.isInViewport = (this.top <= exports.viewportBottom && this.bottom >= exports.viewportTop);
this.isFullyInViewport = (this.top >= exports.viewportTop && this.bottom <= exports.viewportBottom) ||
(this.isAboveViewport && this.isBelowViewport);
},
destroy: function() {
var index = watchers.indexOf(this),
self = this;
watchers.splice(index, 1);
for (var i = 0, j = eventTypes.length; i < j; i++) {
self.callbacks[eventTypes[i]].length = 0;
}
},
// prevent recalculating the element location
lock: function() {
this.locked = true;
},
unlock: function() {
this.locked = false;
}
};
var eventHandlerFactory = function (type) {
return function( callback, isOne ) {
this.on.call(this, type, callback, isOne);
};
};
for (var i = 0, j = eventTypes.length; i < j; i++) {
var type = eventTypes[i];
ElementWatcher.prototype[type] = eventHandlerFactory(type);
}
try {
calculateViewport();
} catch (e) {
try {
window.$(calculateViewport);
} catch (e) {
throw new Error('If you must put scrollMonitor in the <head>, you must use jQuery.');
}
}
function scrollMonitorListener(event) {
latestEvent = event;
calculateViewport();
updateAndTriggerWatchers();
}
if (window.addEventListener) {
window.addEventListener('scroll', scrollMonitorListener);
window.addEventListener('resize', debouncedRecalcuateAndTrigger);
} else {
// Old IE support
window.attachEvent('onscroll', scrollMonitorListener);
window.attachEvent('onresize', debouncedRecalcuateAndTrigger);
}
exports.beget = exports.create = function( element, offsets ) {
if (typeof element === 'string') {
element = document.querySelector(element);
} else if (element && element.length > 0) {
element = element[0];
}
var watcher = new ElementWatcher( element, offsets );
watchers.push(watcher);
watcher.update();
return watcher;
};
exports.update = function() {
latestEvent = null;
calculateViewport();
updateAndTriggerWatchers();
};
exports.recalculateLocations = function() {
exports.documentHeight = 0;
exports.update();
};
return exports;
});
},{}],6:[function(require,module,exports){
module.exports={
"name": "clappr",
"version": "0.0.73",
"description": "An extensible media player for the web",
"main": "dist/clappr.min.js",
"scripts": {
"test": "./node_modules/.bin/gulp release && ./node_modules/.bin/karma start --single-run --browsers Firefox"
},
"repository": {
"type": "git",
"url": "[email protected]:globocom/clappr.git"
},
"author": "Globo.com",
"license": "ISC",
"bugs": {
"url": "https://github.com/globocom/clappr/issues"
},
"browser": {
"zepto": "clappr-zepto"
},
"homepage": "https://github.com/globocom/clappr",
"devDependencies": {
"browserify": "^7.0.1",
"chai": "1.10.0",
"compass-mixins": "0.12.3",
"dotenv": "^0.4.0",
"es6ify": "~1.4.0",
"exorcist": "^0.1.6",
"express": "^4.6.1",
"express-alias": "0.4.0",
"glob": "^4.0.2",
"gulp": "^3.8.1",
"clappr-zepto": "latest",
"gulp-compressor": "^0.1.0",
"gulp-jshint": "1.9.0",
"gulp-livereload": "^2.1.0",
"gulp-minify-css": "~0.3.5",
"gulp-rename": "^1.2.0",
"gulp-sass": "1.0.0",
"gulp-streamify": "0.0.5",
"gulp-uglify": "^1.0.1",
"gulp-util": "3.0.1",
"karma": "^0.12.17",
"karma-browserify": "^1.0.0",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^0.1.4",
"karma-cli": "0.0.4",
"karma-firefox-launcher": "^0.1.3",
"karma-jasmine": "^0.2.2",
"karma-jquery": "^0.1.0",
"karma-mocha": "^0.1.4",
"karma-safari-launcher": "^0.1.1",
"karma-sinon": "^1.0.3",
"karma-sinon-chai": "^0.2.0",
"mkdirp": "^0.5.0",
"s3": "^4.1.1",
"scp": "0.0.3",
"sinon": "^1.10.2",
"traceur": "0.0.72",
"vinyl-source-stream": "^1.0.0",
"vinyl-transform": "0.0.1",
"watchify": "^2.0.0",
"yargs": "1.3.3"
},
"dependencies": {
"underscore": "1.7.0",
"mousetrap": "0.0.1",
"scrollmonitor": "^1.0.8"
}
}
},{}],7:[function(require,module,exports){
"use strict";
var _ = require('underscore');
module.exports = {
'media_control': _.template('<div class="media-control-background" data-background></div><div class="media-control-layer" data-controls><% var renderBar=function(name) { %><div class="bar-container" data-<%= name %>><div class="bar-background" data-<%= name %>><div class="bar-fill-1" data-<%= name %>></div><div class="bar-fill-2" data-<%= name %>></div><div class="bar-hover" data-<%= name %>></div></div><div class="bar-scrubber" data-<%= name %>><div class="bar-scrubber-icon" data-<%= name %>></div></div></div><% }; %><% var renderSegmentedBar=function(name, segments) { segments=segments || 10; %><div class="bar-container" data-<%= name %>><% for (var i = 0; i < segments; i++) { %><div class="segmented-bar-element" data-<%= name %>></div><% } %></div><% }; %><% var renderDrawer=function(name, renderContent) { %><div class="drawer-container" data-<%= name %>><div class="drawer-icon-container" data-<%= name %>><div class="drawer-icon media-control-icon" data-<%= name %>></div><span class="drawer-text" data-<%= name %>></span></div><% renderContent(name); %></div><% }; %><% var renderIndicator=function(name) { %><div class="media-control-indicator" data-<%= name %>></div><% }; %><% var renderButton=function(name) { %><button class="media-control-button media-control-icon" data-<%= name %>></button><% }; %><% var templates={ bar: renderBar, segmentedBar: renderSegmentedBar, }; var render=function(settingsList) { _.each(settingsList, function(setting) { if(setting === "seekbar") { renderBar(setting); } else if (setting === "volume") { renderDrawer(setting, settings.volumeBarTemplate ? templates[settings.volumeBarTemplate] : function(name) { return renderSegmentedBar(name); }); } else if (setting === "duration" || setting=== "position") { renderIndicator(setting); } else { renderButton(setting); } }); }; %><% if (settings.default && settings.default.length) { %><div class="media-control-center-panel" data-media-control><% render(settings.default); %></div><% } %><% if (settings.left && settings.left.length) { %><div class="media-control-left-panel" data-media-control><% render(settings.left); %></div><% } %><% if (settings.right && settings.right.length) { %><div class="media-control-right-panel" data-media-control><% render(settings.right); %></div><% } %></div>'),
'seek_time': _.template('<span data-seek-time></span>'),
'flash': _.template('<param name="movie" value="<%= swfPath %>"><param name="quality" value="autohigh"><param name="swliveconnect" value="true"><param name="allowScriptAccess" value="always"><param name="bgcolor" value="#001122"><param name="allowFullScreen" value="false"><param name="wmode" value="transparent"><param name="tabindex" value="1"><param name=FlashVars value="playbackId=<%= playbackId %>" /><embed type="application/x-shockwave-flash" disabled tabindex="-1" enablecontextmenu="false" allowScriptAccess="always" quality="autohight" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"></embed>'),
'hls': _.template('<param name="movie" value="<%= swfPath %>?inline=1"><param name="quality" value="autohigh"><param name="swliveconnect" value="true"><param name="allowScriptAccess" value="always"><param name="bgcolor" value="#001122"><param name="allowFullScreen" value="false"><param name="wmode" value="transparent"><param name="tabindex" value="1"><param name=FlashVars value="playbackId=<%= playbackId %>" /><embed type="application/x-shockwave-flash" tabindex="1" enablecontextmenu="false" allowScriptAccess="always" quality="autohigh" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"></embed>'),
'html5_video': _.template('<source src="<%=src%>" type="<%=type%>">'),
'no_op': _.template('<p data-no-op-msg>Something went wrong :(</p>'),
'background_button': _.template('<div class="background-button-wrapper" data-background-button><button class="background-button-icon" data-background-button></button></div>'),
'dvr_controls': _.template('<div class="live-info">LIVE</div><button class="live-button">BACK TO LIVE</button>'),
'poster': _.template('<div class="play-wrapper" data-poster><span class="poster-icon play" data-poster/></div>'),
'spinner_three_bounce': _.template('<div data-bounce1></div><div data-bounce2></div><div data-bounce3></div>'),
'watermark': _.template('<div data-watermark data-watermark-<%=position %>><img src="<%= imageUrl %>"></div>'),
CSS: {
'container': '.container[data-container]{position:absolute;background-color:#000;height:100%;width:100%}.container[data-container].pointer-enabled{cursor:pointer}',
'core': '[data-player]{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);-ms-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0);position:relative;margin:0;padding:0;border:0;height:594px;width:1055px;font-style:normal;font-weight:400;text-align:center;overflow:hidden;font-size:100%;font-family:"lucida grande",tahoma,verdana,arial,sans-serif;text-shadow:0 0 0;box-sizing:border-box}[data-player] a,[data-player] abbr,[data-player] acronym,[data-player] address,[data-player] applet,[data-player] article,[data-player] aside,[data-player] audio,[data-player] b,[data-player] big,[data-player] blockquote,[data-player] canvas,[data-player] caption,[data-player] center,[data-player] cite,[data-player] code,[data-player] dd,[data-player] del,[data-player] details,[data-player] dfn,[data-player] div,[data-player] dl,[data-player] dt,[data-player] em,[data-player] embed,[data-player] fieldset,[data-player] figcaption,[data-player] figure,[data-player] footer,[data-player] form,[data-player] h1,[data-player] h2,[data-player] h3,[data-player] h4,[data-player] h5,[data-player] h6,[data-player] header,[data-player] hgroup,[data-player] i,[data-player] iframe,[data-player] img,[data-player] ins,[data-player] kbd,[data-player] label,[data-player] legend,[data-player] li,[data-player] mark,[data-player] menu,[data-player] nav,[data-player] object,[data-player] ol,[data-player] output,[data-player] p,[data-player] pre,[data-player] q,[data-player] ruby,[data-player] s,[data-player] samp,[data-player] section,[data-player] small,[data-player] span,[data-player] strike,[data-player] strong,[data-player] sub,[data-player] summary,[data-player] sup,[data-player] table,[data-player] tbody,[data-player] td,[data-player] tfoot,[data-player] th,[data-player] thead,[data-player] time,[data-player] tr,[data-player] tt,[data-player] u,[data-player] ul,[data-player] var,[data-player] video{margin:0;padding:0;border:0;font:inherit;font-size:100%;vertical-align:baseline}[data-player] table{border-collapse:collapse;border-spacing:0}[data-player] caption,[data-player] td,[data-player] th{text-align:left;font-weight:400;vertical-align:middle}[data-player] blockquote,[data-player] q{quotes:none}[data-player] blockquote:after,[data-player] blockquote:before,[data-player] q:after,[data-player] q:before{content:"";content:none}[data-player] a img{border:none}[data-player] *{max-width:initial;box-sizing:inherit;float:initial}[data-player].fullscreen{width:100%;height:100%}[data-player].nocursor{cursor:none}[data-player] .clappr-style{display:none!important}@media screen{[data-player]{opacity:.99}}',
'media_control': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.media-control-notransition{-webkit-transition:none!important;-webkit-transition-delay:0s;-moz-transition:none!important;-o-transition:none!important;transition:none!important}.media-control[data-media-control]{position:absolute;width:100%;height:100%;z-index:9999;pointer-events:none}.media-control[data-media-control].dragging{pointer-events:auto;cursor:-webkit-grabbing!important;cursor:grabbing!important}.media-control[data-media-control].dragging *{cursor:-webkit-grabbing!important;cursor:grabbing!important}.media-control[data-media-control] .media-control-background[data-background]{position:absolute;height:40%;width:100%;bottom:0;background-image:-owg(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-webkit(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-moz(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:-o(linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9)));background-image:linear-gradient(rgba(0,0,0,0),rgba(0,0,0,.9));-webkit-transition:opacity .6s;-webkit-transition-delay:ease-out;-moz-transition:opacity .6s ease-out;-o-transition:opacity .6s ease-out;transition:opacity .6s ease-out}.media-control[data-media-control] .media-control-icon{font-family:Player;font-weight:400;font-style:normal;font-size:26px;line-height:32px;letter-spacing:0;speak:none;color:#fff;opacity:.5;vertical-align:middle;text-align:left;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.media-control[data-media-control] .media-control-icon:hover{color:#fff;opacity:.75;text-shadow:rgba(255,255,255,.8) 0 0 5px}.media-control[data-media-control].media-control-hide .media-control-background[data-background]{opacity:0}.media-control[data-media-control].media-control-hide .media-control-layer[data-controls]{bottom:-50px}.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls]{position:absolute;bottom:7px;width:100%;height:32px;vertical-align:middle;pointer-events:auto;-webkit-transition:bottom .4s;-webkit-transition-delay:ease-out;-moz-transition:bottom .4s ease-out;-o-transition:bottom .4s ease-out;transition:bottom .4s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-left-panel[data-media-control]{position:absolute;top:0;left:4px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-center-panel[data-media-control]{height:100%;text-align:center;line-height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-right-panel[data-media-control]{position:absolute;top:0;right:4px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button{background-color:transparent;border:0;margin:0 6px;padding:0;cursor:pointer;display:inline-block}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button:focus{outline:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]{float:right;background-color:transparent;border:0;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]:before{content:"\\e006"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen].shrink:before{content:"\\e007"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]{cursor:default;float:right;background-color:transparent;border:0;height:100%;opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]:before{content:"\\e008"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled:hover{opacity:1;text-shadow:none}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].playing:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].paused:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]{float:left;height:100%;font-size:20px}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].playing:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].stopped:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration],.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{display:inline-block;font-size:10px;color:#fff;cursor:default;line-height:32px;position:relative}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{margin-left:6px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]{color:rgba(255,255,255,.5);margin-right:6px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]:before{content:"|";margin:0 3px}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]{position:absolute;top:-20px;left:0;display:inline-block;vertical-align:middle;width:100%;height:25px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar]{width:100%;height:1px;position:relative;top:12px;background-color:#666}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-1[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#c2c2c2;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#005aff;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:0;position:absolute;top:-3px;width:5px;height:7px;background-color:rgba(255,255,255,.5);-webkit-transition:opacity .1s;-webkit-transition-delay:ease;-moz-transition:opacity .1s ease;-o-transition:opacity .1s ease;transition:opacity .1s ease}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled{cursor:default}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar].seek-disabled:hover .bar-background[data-seekbar] .bar-hover[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{position:absolute;top:2px;left:0;width:20px;height:20px;opacity:1;-webkit-transition:all .1s;-webkit-transition-delay:ease-out;-moz-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] .bar-scrubber-icon[data-seekbar]{position:absolute;left:6px;top:6px;width:8px;height:8px;border-radius:10px;box-shadow:0 0 0 6px rgba(255,255,255,.2);background-color:#fff}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume]{float:right;display:inline-block;height:32px;cursor:pointer;margin:0 6px;box-sizing:border-box}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume]{float:left;bottom:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]{background-color:transparent;border:0;box-sizing:content-box;width:16px;height:32px;margin-right:6px;opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:hover{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:before{content:"\\e004"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted{opacity:.5}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:hover{opacity:.7}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:before{content:"\\e005"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume]{float:left;position:relative;top:6px;width:42px;height:18px;padding:3px 0;overflow:hidden;-webkit-transition:width .2s;-webkit-transition-delay:ease-out;-moz-transition:width .2s ease-out;-o-transition:width .2s ease-out;transition:width .2s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]{float:left;width:4px;padding-left:2px;height:12px;opacity:.5;-webkit-box-shadow:inset 2px 0 0 #fff;-moz-box-shadow:inset 2px 0 0 #fff;-ms-box-shadow:inset 2px 0 0 #fff;-o-box-shadow:inset 2px 0 0 #fff;box-shadow:inset 2px 0 0 #fff;-webkit-transition:-webkit-transform .2s;-webkit-transition-delay:ease-out;-moz-transition:-moz-transform .2s ease-out;-o-transition:-o-transform .2s ease-out;transition:transform .2s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume].fill{-webkit-box-shadow:inset 2px 0 0 #fff;-moz-box-shadow:inset 2px 0 0 #fff;-ms-box-shadow:inset 2px 0 0 #fff;-o-box-shadow:inset 2px 0 0 #fff;box-shadow:inset 2px 0 0 #fff;opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:nth-of-type(1){padding-left:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .segmented-bar-element[data-volume]:hover{-webkit-transform:scaleY(1.5);-moz-transform:scaleY(1.5);-ms-transform:scaleY(1.5);-o-transform:scaleY(1.5);transform:scaleY(1.5)}.media-control[data-media-control].w320 .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume].volume-bar-hide{height:12px;top:9px;padding:0;width:0}',
'seek_time': '.seek-time[data-seek-time]{position:absolute;width:auto;height:20px;line-height:20px;bottom:55px;background-color:rgba(2,2,2,.5);z-index:9999;-webkit-transition:opacity .1s;-webkit-transition-delay:ease;-moz-transition:opacity .1s ease;-o-transition:opacity .1s ease;transition:opacity .1s ease}.seek-time[data-seek-time].hidden[data-seek-time]{opacity:0}.seek-time[data-seek-time] span[data-seek-time]{position:relative;color:#fff;font-size:10px;padding-left:7px;padding-right:7px}',
'flash': '[data-flash]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none}',
'hls': '[data-hls]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none;top:0}',
'html5_video': '[data-html5-video]{position:absolute;height:100%;width:100%;display:block}',
'html_img': '[data-html-img]{max-width:100%;max-height:100%}',
'no_op': '[data-no-op]{z-index:1000;position:absolute;background-color:#222;height:100%;width:100%}[data-no-op] p[data-no-op-msg]{position:relative;font-size:25px;top:50%;color:#fff}',
'background_button': '.background-button[data-background-button]{font-family:Player;position:absolute;height:100%;width:100%;background-color:rgba(0,0,0,.2);pointer-events:none;-webkit-transition:all .4s;-webkit-transition-delay:ease-out;-moz-transition:all .4s ease-out;-o-transition:all .4s ease-out;transition:all .4s ease-out}.background-button[data-background-button].hide{background-color:transparent}.background-button[data-background-button].hide .background-button-wrapper[data-background-button]{opacity:0}.background-button[data-background-button] .background-button-wrapper[data-background-button]{position:absolute;overflow:hidden;width:100%;height:25%;line-height:100%;font-size:25%;top:50%;text-align:center}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button]{cursor:pointer;pointer-events:auto;font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;border:0;outline:0;background-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button]:hover{opacity:1;text-shadow:rgba(255,255,255,.8) 0 0 15px}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playing:before{content:"\\e002"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].notplaying:before{content:"\\e001"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playstop.playing:before{content:"\\e003"}.background-button[data-background-button] .background-button-wrapper[data-background-button] .background-button-icon[data-background-button].playstop.notplaying:before{content:"\\e001"}.media-control.media-control-hide[data-media-control] .background-button[data-background-button]{opacity:0}',
'dvr_controls': '@import url(http://fonts.googleapis.com/css?family=Roboto);.dvr-controls[data-dvr-controls]{display:inline-block;float:left;color:#fff;line-height:32px;font-size:10px;font-weight:700;margin-left:6px}.dvr-controls[data-dvr-controls] .live-info{cursor:default;font-family:Roboto,"Open Sans",Arial,sans-serif}.dvr-controls[data-dvr-controls] .live-info:before{content:"";display:inline-block;position:relative;width:7px;height:7px;border-radius:3.5px;margin-right:3.5px;background-color:#ff0101}.dvr-controls[data-dvr-controls] .live-info.disabled{opacity:.3}.dvr-controls[data-dvr-controls] .live-info.disabled:before{background-color:#fff}.dvr-controls[data-dvr-controls] .live-button{cursor:pointer;outline:0;display:none;border:0;color:#fff;background-color:transparent;height:32px;padding:0;opacity:.7;font-family:Roboto,"Open Sans",Arial,sans-serif;-webkit-transition:all .1s;-webkit-transition-delay:ease;-moz-transition:all .1s ease;-o-transition:all .1s ease;transition:all .1s ease}.dvr-controls[data-dvr-controls] .live-button:before{content:"";display:inline-block;position:relative;width:7px;height:7px;border-radius:3.5px;margin-right:3.5px;background-color:#fff}.dvr-controls[data-dvr-controls] .live-button:hover{opacity:1;text-shadow:rgba(255,255,255,.75) 0 0 5px}.dvr .dvr-controls[data-dvr-controls] .live-info{display:none}.dvr .dvr-controls[data-dvr-controls] .live-button{display:block}.dvr.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{background-color:#005aff}.media-control.live[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{background-color:#ff0101}.seek-time[data-seek-time] span[data-duration]{position:relative;color:rgba(255,255,255,.5);font-size:10px;padding-right:7px}.seek-time[data-seek-time] span[data-duration]:before{content:"|";margin-right:7px}',
'poster': '@font-face{font-family:Player;src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot);src:url(http://cdn.clappr.io/latest/assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.ttf) format("truetype"),url(http://cdn.clappr.io/latest/assets/Player-Regular.svg#player) format("svg")}.player-poster[data-poster]{cursor:pointer;position:absolute;height:100%;width:100%;z-index:998;top:0}.player-poster[data-poster] .poster-background[data-poster]{width:100%;height:100%}.player-poster[data-poster] .play-wrapper[data-poster]{position:absolute;width:100%;height:25%;line-height:100%;font-size:25%;top:50%;text-align:center}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]{font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;color:#fff;opacity:.75;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transition:opacity text-shadow;-webkit-transition-delay:.1s;-moz-transition:opacity text-shadow .1s;-o-transition:opacity text-shadow .1s;transition:opacity text-shadow .1s ease}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster].play[data-poster]:before{content:"\\e001"}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]:hover{opacity:1;text-shadow:rgba(255,255,255,.8) 0 0 15px}',
'spinner_three_bounce': '.spinner-three-bounce[data-spinner]{position:absolute;margin:0 auto;width:70px;text-align:center;z-index:999;top:47%;left:0;right:0}.spinner-three-bounce[data-spinner]>div{width:18px;height:18px;background-color:#FFF;border-radius:100%;display:inline-block;-webkit-animation:bouncedelay 1.4s infinite ease-in-out;-moz-animation:bouncedelay 1.4s infinite ease-in-out;-ms-animation:bouncedelay 1.4s infinite ease-in-out;-o-animation:bouncedelay 1.4s infinite ease-in-out;animation:bouncedelay 1.4s infinite ease-in-out;-webkit-animation-fill-mode:both;-moz-animation-fill-mode:both;-ms-animation-fill-mode:both;-o-animation-fill-mode:both;animation-fill-mode:both}.spinner-three-bounce[data-spinner] [data-bounce1],.spinner-three-bounce[data-spinner] [data-bounce2]{-webkit-animation-delay:-.32s;-moz-animation-delay:-.32s;-ms-animation-delay:-.32s;-o-animation-delay:-.32s;animation-delay:-.32s}@-moz-keyframes bouncedelay{0%,100%,80%{-moz-transform:scale(0);transform:scale(0)}40%{-moz-transform:scale(1);transform:scale(1)}}@-webkit-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);transform:scale(1)}}@-o-keyframes bouncedelay{0%,100%,80%{-o-transform:scale(0);transform:scale(0)}40%{-o-transform:scale(1);transform:scale(1)}}@-ms-keyframes bouncedelay{0%,100%,80%{-ms-transform:scale(0);transform:scale(0)}40%{-ms-transform:scale(1);transform:scale(1)}}@keyframes bouncedelay{0%,100%,80%{transform:scale(0)}40%{transform:scale(1)}}',
'watermark': '[data-watermark]{position:absolute;margin:100px auto 0;width:70px;text-align:center;z-index:10}[data-watermark-bottom-left]{bottom:10px;left:10px}[data-watermark-bottom-right]{bottom:10px;right:42px}[data-watermark-top-left]{top:-95px;left:10px}[data-watermark-top-right]{top:-95px;right:37px}'
}
};
},{"underscore":"underscore"}],8:[function(require,module,exports){
"use strict";
var $ = require('zepto');
var _ = require('underscore');
var JST = require('./jst');
var Styler = {getStyleFor: function(name, options) {
options = options || {};
return $('<style class="clappr-style"></style>').html(_.template(JST.CSS[name])(options))[0];
}};
module.exports = Styler;
},{"./jst":7,"underscore":"underscore","zepto":"zepto"}],9:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var extend = function(protoProps, staticProps) {
var parent = this;
var child;
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function() {
return parent.apply(this, arguments);
};
}
_.extend(child, parent, staticProps);
var Surrogate = function() {
this.constructor = child;
};
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate();
if (protoProps)
_.extend(child.prototype, protoProps);
child.__super__ = parent.prototype;
child.super = function(name) {
return parent.prototype[name];
};
child.prototype.getClass = function() {
return child;
};
return child;
};
var formatTime = function(time) {
time = time * 1000;
time = parseInt(time / 1000);
var seconds = time % 60;
time = parseInt(time / 60);
var minutes = time % 60;
time = parseInt(time / 60);
var hours = time % 24;
var out = "";
if (hours && hours > 0)
out += ("0" + hours).slice(-2) + ":";
out += ("0" + minutes).slice(-2) + ":";
out += ("0" + seconds).slice(-2);
return out.trim();
};
var Fullscreen = {
isFullscreen: function() {
return document.webkitIsFullScreen || document.mozFullScreen || !!document.msFullscreenElement || window.iframeFullScreen;
},
requestFullscreen: function(el) {
if (el.requestFullscreen) {
el.requestFullscreen();
} else if (el.webkitRequestFullscreen) {
el.webkitRequestFullscreen();
} else if (el.mozRequestFullScreen) {
el.mozRequestFullScreen();
} else if (el.msRequestFullscreen) {
el.msRequestFullscreen();
}
},
cancelFullscreen: function() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
}
};
var seekStringToSeconds = function(url) {
var elements = _.rest(_.compact(url.match(/t=([0-9]*)h?([0-9]*)m?([0-9]*)s/))).reverse();
var seconds = 0;
var factor = 1;
_.each(elements, function(el) {
seconds += (parseInt(el) * factor);
factor = factor * 60;
}, this);
return seconds;
};
module.exports = {
extend: extend,
formatTime: formatTime,
Fullscreen: Fullscreen,
seekStringToSeconds: seekStringToSeconds
};
},{"underscore":"underscore"}],10:[function(require,module,exports){
"use strict";
var UIObject = require('ui_object');
var Styler = require('../../base/styler');
var _ = require('underscore');
var Events = require('events');
var Container = function Container(options) {
$traceurRuntime.superCall(this, $Container.prototype, "constructor", [options]);
this.playback = options.playback;
this.settings = this.playback.settings;
this.isReady = false;
this.mediaControlDisabled = false;
this.plugins = [this.playback];
this.bindEvents();
};
var $Container = Container;
($traceurRuntime.createClass)(Container, {
get name() {
return 'Container';
},
get attributes() {
return {
class: 'container',
'data-container': ''
};
},
get events() {
return {'click': 'clicked'};
},
bindEvents: function() {
this.listenTo(this.playback, Events.PLAYBACK_PROGRESS, this.progress);
this.listenTo(this.playback, Events.PLAYBACK_TIMEUPDATE, this.timeUpdated);
this.listenTo(this.playback, Events.PLAYBACK_READY, this.ready);
this.listenTo(this.playback, Events.PLAYBACK_BUFFERING, this.buffering);
this.listenTo(this.playback, Events.PLAYBACK_BUFFERFULL, this.bufferfull);
this.listenTo(this.playback, Events.PLAYBACK_SETTINGSUPDATE, this.settingsUpdate);
this.listenTo(this.playback, Events.PLAYBACK_LOADEDMETADATA, this.loadedMetadata);
this.listenTo(this.playback, Events.PLAYBACK_HIGHDEFINITIONUPDATE, this.highDefinitionUpdate);
this.listenTo(this.playback, Events.PLAYBACK_BITRATE, this.updateBitrate);
this.listenTo(this.playback, Events.PLAYBACK_PLAYBACKSTATE, this.playbackStateChanged);
this.listenTo(this.playback, Events.PLAYBACK_DVR, this.playbackDvrStateChanged);
this.listenTo(this.playback, Events.PLAYBACK_MEDIACONTROL_DISABLE, this.disableMediaControl);
this.listenTo(this.playback, Events.PLAYBACK_MEDIACONTROL_ENABLE, this.enableMediaControl);
this.listenTo(this.playback, Events.PLAYBACK_ENDED, this.ended);
this.listenTo(this.playback, Events.PLAYBACK_PLAY, this.playing);
this.listenTo(this.playback, Events.PLAYBACK_ERROR, this.error);
},
with: function(klass) {
_.extend(this, klass);
return this;
},
playbackStateChanged: function() {
this.trigger(Events.CONTAINER_PLAYBACKSTATE);
},
playbackDvrStateChanged: function(dvrInUse) {
this.settings = this.playback.settings;
this.dvrInUse = dvrInUse;
this.trigger(Events.CONTAINER_PLAYBACKDVRSTATECHANGED, dvrInUse);
},
updateBitrate: function(newBitrate) {
this.trigger(Events.CONTAINER_BITRATE, newBitrate);
},
statsReport: function(metrics) {
this.trigger(Events.CONTAINER_STATS_REPORT, metrics);
},
getPlaybackType: function() {
return this.playback.getPlaybackType();
},
isDvrEnabled: function() {
return !!this.playback.dvrEnabled;
},
isDvrInUse: function() {
return !!this.dvrInUse;
},
destroy: function() {
this.trigger(Events.CONTAINER_DESTROYED, this, this.name);
this.playback.destroy();
_(this.plugins).each((function(plugin) {
return plugin.destroy();
}));
this.$el.remove();
},
setStyle: function(style) {
this.$el.css(style);
},
animate: function(style, duration) {
return this.$el.animate(style, duration).promise();
},
ready: function() {
this.isReady = true;
this.trigger(Events.CONTAINER_READY, this.name);
},
isPlaying: function() {
return this.playback.isPlaying();
},
getDuration: function() {
return this.playback.getDuration();
},
error: function(errorObj) {
this.$el.append(errorObj.render().el);
this.trigger(Events.CONTAINER_ERROR, {
error: errorObj,
container: this
}, this.name);
},
loadedMetadata: function(duration) {
this.trigger(Events.CONTAINER_LOADEDMETADATA, duration);
},
timeUpdated: function(position, duration) {
this.trigger(Events.CONTAINER_TIMEUPDATE, position, duration, this.name);
},
progress: function(startPosition, endPosition, duration) {
this.trigger(Events.CONTAINER_PROGRESS, startPosition, endPosition, duration, this.name);
},
playing: function() {
this.trigger(Events.CONTAINER_PLAY, this.name);
},
play: function() {
this.playback.play();
},
stop: function() {
this.trigger(Events.CONTAINER_STOP, this.name);
this.playback.stop();
},
pause: function() {
this.trigger(Events.CONTAINER_PAUSE, this.name);
this.playback.pause();
},
ended: function() {
this.trigger(Events.CONTAINER_ENDED, this, this.name);
},
clicked: function() {
this.trigger(Events.CONTAINER_CLICK, this, this.name);
},
setCurrentTime: function(time) {
this.trigger(Events.CONTAINER_SEEK, time, this.name);
this.playback.seek(time);
},
setVolume: function(value) {
this.trigger(Events.CONTAINER_VOLUME, value, this.name);
this.playback.volume(value);
},
fullscreen: function() {
this.trigger(Events.CONTAINER_FULLSCREEN, this.name);
},
buffering: function() {
this.trigger(Events.CONTAINER_STATE_BUFFERING, this.name);
},
bufferfull: function() {
this.trigger(Events.CONTAINER_STATE_BUFFERFULL, this.name);
},
addPlugin: function(plugin) {
this.plugins.push(plugin);
},
hasPlugin: function(name) {
return !!this.getPlugin(name);
},
getPlugin: function(name) {
return _(this.plugins).find(function(plugin) {
return plugin.name === name;
});
},
settingsUpdate: function() {
this.settings = this.playback.settings;
this.trigger(Events.CONTAINER_SETTINGSUPDATE);
},
highDefinitionUpdate: function() {
this.trigger(Events.CONTAINER_HIGHDEFINITIONUPDATE);
},
isHighDefinitionInUse: function() {
return this.playback.isHighDefinitionInUse();
},
disableMediaControl: function() {
this.mediaControlDisabled = true;
this.trigger(Events.CONTAINER_MEDIACONTROL_DISABLE);
},
enableMediaControl: function() {
this.mediaControlDisabled = false;
this.trigger(Events.CONTAINER_MEDIACONTROL_ENABLE);
},
render: function() {
var style = Styler.getStyleFor('container');
this.$el.append(style);
this.$el.append(this.playback.render().el);
return this;
}
}, {}, UIObject);
module.exports = Container;
},{"../../base/styler":8,"events":"events","ui_object":"ui_object","underscore":"underscore"}],11:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var BaseObject = require('base_object');
var Container = require('container');
var $ = require('zepto');
var Events = require('events');
var ContainerFactory = function ContainerFactory(options, loader) {
$traceurRuntime.superCall(this, $ContainerFactory.prototype, "constructor", [options]);
this.options = options;
this.loader = loader;
};
var $ContainerFactory = ContainerFactory;
($traceurRuntime.createClass)(ContainerFactory, {
createContainers: function() {
var $__0 = this;
return $.Deferred((function(promise) {
promise.resolve(_.map($__0.options.sources, (function(source) {
return $__0.createContainer(source);
}), $__0));
}));
},
findPlaybackPlugin: function(source) {
return _.find(this.loader.playbackPlugins, (function(p) {
return p.canPlay(source.toString());
}), this);
},
createContainer: function(source) {
var playbackPlugin = this.findPlaybackPlugin(source);
var options = _.extend({}, this.options, {
src: source,
autoPlay: !!this.options.autoPlay
});
var playback = new playbackPlugin(options);
var container = new Container({playback: playback});
var defer = $.Deferred();
defer.promise(container);
this.addContainerPlugins(container, source);
this.listenToOnce(container, Events.CONTAINER_READY, (function() {
return defer.resolve(container);
}));
return container;
},
addContainerPlugins: function(container, source) {
_.each(this.loader.containerPlugins, function(Plugin) {
var options = _.extend(this.options, {
container: container,
src: source
});
container.addPlugin(new Plugin(options));
}, this);
}
}, {}, BaseObject);
module.exports = ContainerFactory;
},{"base_object":"base_object","container":"container","events":"events","underscore":"underscore","zepto":"zepto"}],12:[function(require,module,exports){
"use strict";
module.exports = require('./container_factory');
},{"./container_factory":11}],13:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var $ = require('zepto');
var UIObject = require('ui_object');
var ContainerFactory = require('../container_factory');
var Fullscreen = require('../../base/utils').Fullscreen;
var Styler = require('../../base/styler');
var MediaControl = require('media_control');
var PlayerInfo = require('player_info');
var Mediator = require('mediator');
var Events = require('events');
var Core = function Core(options) {
var $__0 = this;
$traceurRuntime.superCall(this, $Core.prototype, "constructor", [options]);
PlayerInfo.options = options;
this.options = options;
this.plugins = [];
this.containers = [];
this.createContainers(options);
$(document).bind('fullscreenchange', (function() {
return $__0.exit();
}));
$(document).bind('MSFullscreenChange', (function() {
return $__0.exit();
}));
$(document).bind('mozfullscreenchange', (function() {
return $__0.exit();
}));
};
var $Core = Core;
($traceurRuntime.createClass)(Core, {
get events() {
return {
'webkitfullscreenchange': 'exit',
'mousemove': 'showMediaControl',
'mouseleave': 'hideMediaControl'
};
},
get attributes() {
return {'data-player': ''};
},
createContainers: function(options) {
var $__0 = this;
this.defer = $.Deferred();
this.defer.promise(this);
this.containerFactory = new ContainerFactory(options, options.loader);
this.containerFactory.createContainers().then((function(containers) {
return $__0.setupContainers(containers);
})).then((function(containers) {
return $__0.resolveOnContainersReady(containers);
}));
},
updateSize: function() {
if (Fullscreen.isFullscreen()) {
this.setFullscreen();
} else {
this.setPlayerSize();
}
Mediator.trigger(Events.PLAYER_RESIZE);
},
setFullscreen: function() {
this.$el.addClass('fullscreen');
this.$el.removeAttr('style');
PlayerInfo.previousSize = PlayerInfo.currentSize;
PlayerInfo.currentSize = {
width: $(window).width(),
height: $(window).height()
};
},
setPlayerSize: function() {
this.$el.removeClass('fullscreen');
PlayerInfo.currentSize = PlayerInfo.previousSize;
PlayerInfo.previousSize = {
width: $(window).width(),
height: $(window).height()
};
this.resize(PlayerInfo.currentSize);
},
resize: function(options) {
var size = _.pick(options, 'width', 'height');
this.$el.css(size);
PlayerInfo.previousSize = PlayerInfo.currentSize;
PlayerInfo.currentSize = size;
Mediator.trigger(Events.PLAYER_RESIZE);
},
resolveOnContainersReady: function(containers) {
var $__0 = this;
$.when.apply($, containers).done((function() {
return $__0.defer.resolve($__0);
}));
},
addPlugin: function(plugin) {
this.plugins.push(plugin);
},
hasPlugin: function(name) {
return !!this.getPlugin(name);
},
getPlugin: function(name) {
return _(this.plugins).find((function(plugin) {
return plugin.name === name;
}));
},
load: function(sources) {
var $__0 = this;
sources = _.isArray(sources) ? sources : [sources.toString()];
_(this.containers).each((function(container) {
return container.destroy();
}));
this.containerFactory.options = _(this.options).extend({sources: sources});
this.containerFactory.createContainers().then((function(containers) {
$__0.setupContainers(containers);
}));
},
destroy: function() {
_(this.containers).each((function(container) {
return container.destroy();
}));
_(this.plugins).each((function(plugin) {
return plugin.destroy();
}));
this.$el.remove();
this.mediaControl.destroy();
$(document).unbind('fullscreenchange');
$(document).unbind('MSFullscreenChange');
$(document).unbind('mozfullscreenchange');
},
exit: function() {
this.updateSize();
this.mediaControl.show();
},
setMediaControlContainer: function(container) {
this.mediaControl.setContainer(container);
this.mediaControl.render();
},
disableMediaControl: function() {
this.mediaControl.disable();
this.$el.removeClass('nocursor');
},
enableMediaControl: function() {
this.mediaControl.enable();
},
removeContainer: function(container) {
this.stopListening(container);
this.containers = _.without(this.containers, container);
},
appendContainer: function(container) {
this.listenTo(container, Events.CONTAINER_DESTROYED, this.removeContainer);
this.el.appendChild(container.render().el);
this.containers.push(container);
},
setupContainers: function(containers) {
_.map(containers, this.appendContainer, this);
this.setupMediaControl(this.getCurrentContainer());
this.render();
this.$el.appendTo(this.options.parentElement);
return containers;
},
createContainer: function(source) {
var container = this.containerFactory.createContainer(source);
this.appendContainer(container);
return container;
},
setupMediaControl: function(container) {
if (this.mediaControl) {
this.mediaControl.setContainer(container);
} else {
this.mediaControl = this.createMediaControl(_.extend({container: container}, this.options));
this.listenTo(this.mediaControl, Events.MEDIACONTROL_FULLSCREEN, this.toggleFullscreen);
this.listenTo(this.mediaControl, Events.MEDIACONTROL_SHOW, this.onMediaControlShow.bind(this, true));
this.listenTo(this.mediaControl, Events.MEDIACONTROL_HIDE, this.onMediaControlShow.bind(this, false));
}
},
createMediaControl: function(options) {
if (options.mediacontrol && options.mediacontrol.external) {
return new options.mediacontrol.external(options);
} else {
return new MediaControl(options);
}
},
getCurrentContainer: function() {
return this.containers[0];
},
toggleFullscreen: function() {
if (!Fullscreen.isFullscreen()) {
Fullscreen.requestFullscreen(this.el);
this.$el.addClass('fullscreen');
} else {
Fullscreen.cancelFullscreen();
this.$el.removeClass('fullscreen nocursor');
}
this.mediaControl.show();
},
showMediaControl: function(event) {
this.mediaControl.show(event);
},
hideMediaControl: function(event) {
this.mediaControl.hide(event);
},
onMediaControlShow: function(showing) {
if (showing)
this.$el.removeClass('nocursor');
else if (Fullscreen.isFullscreen())
this.$el.addClass('nocursor');
},
render: function() {
var style = Styler.getStyleFor('core');
this.$el.append(style);
this.$el.append(this.mediaControl.render().el);
this.options.width = this.options.width || this.$el.width();
this.options.height = this.options.height || this.$el.height();
PlayerInfo.previousSize = PlayerInfo.currentSize = _.pick(this.options, 'width', 'height');
this.updateSize();
return this;
}
}, {}, UIObject);
module.exports = Core;
},{"../../base/styler":8,"../../base/utils":9,"../container_factory":12,"events":"events","media_control":"media_control","mediator":"mediator","player_info":"player_info","ui_object":"ui_object","underscore":"underscore","zepto":"zepto"}],14:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var BaseObject = require('base_object');
var Core = require('core');
var CoreFactory = function CoreFactory(player, loader) {
this.player = player;
this.options = player.options;
this.loader = loader;
this.options.loader = this.loader;
};
($traceurRuntime.createClass)(CoreFactory, {
create: function() {
this.core = new Core(this.options);
this.core.then(this.addCorePlugins.bind(this));
return this.core;
},
addCorePlugins: function() {
_.each(this.loader.corePlugins, function(Plugin) {
var plugin = new Plugin(this.core);
this.core.addPlugin(plugin);
this.setupExternalInterface(plugin);
}, this);
return this.core;
},
setupExternalInterface: function(plugin) {
_.each(plugin.getExternalInterface(), function(value, key) {
this.player[key] = value.bind(plugin);
}, this);
}
}, {}, BaseObject);
module.exports = CoreFactory;
},{"base_object":"base_object","core":"core","underscore":"underscore"}],15:[function(require,module,exports){
"use strict";
module.exports = require('./core_factory');
},{"./core_factory":14}],16:[function(require,module,exports){
"use strict";
var BaseObject = require('base_object');
var $ = require('zepto');
var Player = require('../player');
var IframePlayer = function IframePlayer(options) {
$traceurRuntime.superCall(this, $IframePlayer.prototype, "constructor", [options]);
this.options = options;
this.createIframe();
};
var $IframePlayer = IframePlayer;
($traceurRuntime.createClass)(IframePlayer, {
createIframe: function() {
this.iframe = document.createElement("iframe");
this.iframe.setAttribute("frameborder", 0);
this.iframe.setAttribute("id", this.uniqueId);
this.iframe.setAttribute("allowfullscreen", true);
this.iframe.setAttribute("scrolling", "no");
this.iframe.setAttribute("src", "http://cdn.clappr.io/latest/assets/iframe.htm" + this.buildQueryString());
this.iframe.setAttribute('width', this.options.width);
this.iframe.setAttribute('height', this.options.height);
},
attachTo: function(element) {
element.appendChild(this.iframe);
},
addEventListeners: function() {
var $__0 = this;
this.iframe.contentWindow.addEventListener("fullscreenchange", (function() {
return $__0.updateSize();
}));
this.iframe.contentWindow.addEventListener("webkitfullscreenchange", (function() {
return $__0.updateSize();
}));
this.iframe.contentWindow.addEventListener("mozfullscreenchange", (function() {
return $__0.updateSize();
}));
},
buildQueryString: function() {
var result = "";
for (var param in this.options) {
result += !!result ? "&" : "?";
result += encodeURIComponent(param) + "=" + encodeURIComponent(this.options[param]);
}
return result;
}
}, {}, BaseObject);
module.exports = IframePlayer;
},{"../player":21,"base_object":"base_object","zepto":"zepto"}],17:[function(require,module,exports){
"use strict";
module.exports = require('./iframe_player');
},{"./iframe_player":16}],18:[function(require,module,exports){
"use strict";
module.exports = require('./loader');
},{"./loader":19}],19:[function(require,module,exports){
"use strict";
var BaseObject = require('base_object');
var _ = require('underscore');
var PlayerInfo = require('player_info');
var HTML5VideoPlayback = require('html5_video');
var FlashVideoPlayback = require('flash');
var HTML5AudioPlayback = require('html5_audio');
var HLSVideoPlayback = require('hls');
var HTMLImgPlayback = require('html_img');
var NoOp = require('../../playbacks/no_op');
var SpinnerThreeBouncePlugin = require('../../plugins/spinner_three_bounce');
var StatsPlugin = require('../../plugins/stats');
var WaterMarkPlugin = require('../../plugins/watermark');
var PosterPlugin = require('poster');
var GoogleAnalyticsPlugin = require('../../plugins/google_analytics');
var ClickToPausePlugin = require('../../plugins/click_to_pause');
var BackgroundButton = require('../../plugins/background_button');
var DVRControls = require('../../plugins/dvr_controls');
var Loader = function Loader(externalPlugins) {
$traceurRuntime.superCall(this, $Loader.prototype, "constructor", []);
this.playbackPlugins = [FlashVideoPlayback, HTML5VideoPlayback, HTML5AudioPlayback, HLSVideoPlayback, HTMLImgPlayback, NoOp];
this.containerPlugins = [SpinnerThreeBouncePlugin, WaterMarkPlugin, PosterPlugin, StatsPlugin, GoogleAnalyticsPlugin, ClickToPausePlugin];
this.corePlugins = [BackgroundButton, DVRControls];
if (externalPlugins) {
this.addExternalPlugins(externalPlugins);
}
};
var $Loader = Loader;
($traceurRuntime.createClass)(Loader, {
addExternalPlugins: function(plugins) {
var pluginName = function(plugin) {
return plugin.prototype.name;
};
if (plugins.playback) {
this.playbackPlugins = _.uniq(plugins.playback.concat(this.playbackPlugins), pluginName);
}
if (plugins.container) {
this.containerPlugins = _.uniq(plugins.container.concat(this.containerPlugins), pluginName);
}
if (plugins.core) {
this.corePlugins = _.uniq(plugins.core.concat(this.corePlugins), pluginName);
}
PlayerInfo.playbackPlugins = this.playbackPlugins;
},
getPlugin: function(name) {
var allPlugins = _.union(this.containerPlugins, this.playbackPlugins, this.corePlugins);
return _.find(allPlugins, function(plugin) {
return plugin.prototype.name === name;
});
}
}, {}, BaseObject);
module.exports = Loader;
},{"../../playbacks/no_op":29,"../../plugins/background_button":32,"../../plugins/click_to_pause":34,"../../plugins/dvr_controls":36,"../../plugins/google_analytics":38,"../../plugins/spinner_three_bounce":42,"../../plugins/stats":44,"../../plugins/watermark":46,"base_object":"base_object","flash":"flash","hls":"hls","html5_audio":"html5_audio","html5_video":"html5_video","html_img":"html_img","player_info":"player_info","poster":"poster","underscore":"underscore"}],20:[function(require,module,exports){
"use strict";
var _ = require('underscore');
var $ = require('zepto');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var UIObject = require('ui_object');
var Utils = require('../../base/utils');
var Mousetrap = require('mousetrap');
var SeekTime = require('../seek_time');
var Mediator = require('mediator');
var PlayerInfo = require('player_info');
var Events = require('events');
var MediaControl = function MediaControl(options) {
var $__0 = this;
$traceurRuntime.superCall(this, $MediaControl.prototype, "constructor", [options]);
this.seekTime = new SeekTime(this);
this.options = options;
this.mute = this.options.mute;
this.currentVolume = this.options.mute ? 0 : 100;
this.container = options.container;
this.container.setVolume(this.currentVolume);
this.keepVisible = false;
this.addEventListeners();
this.settings = {
left: ['play', 'stop', 'pause'],
right: ['volume'],
default: ['position', 'seekbar', 'duration']
};
this.settings = _.isEmpty(this.container.settings) ? this.settings : this.container.settings;
this.disabled = false;
if (this.container.mediaControlDisabled || this.options.chromeless) {
this.disable();
}
$(document).bind('mouseup', (function(event) {
return $__0.stopDrag(event);
}));
$(document).bind('mousemove', (function(event) {
return $__0.updateDrag(event);
}));
Mediator.on(Events.PLAYER_RESIZE, (function() {
return $__0.playerResize();
}));
};
var $MediaControl = MediaControl;
($traceurRuntime.createClass)(MediaControl, {
get name() {
return 'MediaControl';
},
get attributes() {
return {
class: 'media-control',
'data-media-control': ''
};
},
get events() {
return {
'click [data-play]': 'play',
'click [data-pause]': 'pause',
'click [data-playpause]': 'togglePlayPause',
'click [data-stop]': 'stop',
'click [data-playstop]': 'togglePlayStop',
'click [data-fullscreen]': 'toggleFullscreen',
'click .bar-container[data-seekbar]': 'seek',
'click .bar-container[data-volume]': 'volume',
'click .drawer-icon[data-volume]': 'toggleMute',
'mouseenter .drawer-container[data-volume]': 'showVolumeBar',
'mouseleave .drawer-container[data-volume]': 'hideVolumeBar',
'mousedown .bar-scrubber[data-volume]': 'startVolumeDrag',
'mousedown .bar-scrubber[data-seekbar]': 'startSeekDrag',
'mousemove .bar-container[data-seekbar]': 'mousemoveOnSeekBar',
'mouseleave .bar-container[data-seekbar]': 'mouseleaveOnSeekBar',
'mouseenter .media-control-layer[data-controls]': 'setKeepVisible',
'mouseleave .media-control-layer[data-controls]': 'resetKeepVisible'
};
},
get template() {
return JST.media_control;
},
addEventListeners: function() {
this.listenTo(this.container, Events.CONTAINER_PLAY, this.changeTogglePlay);
this.listenTo(this.container, Events.CONTAINER_TIMEUPDATE, this.updateSeekBar);
this.listenTo(this.container, Events.CONTAINER_PROGRESS, this.updateProgressBar);
this.listenTo(this.container, Events.CONTAINER_SETTINGSUPDATE, this.settingsUpdate);
this.listenTo(this.container, Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.settingsUpdate);
this.listenTo(this.container, Events.CONTAINER_HIGHDEFINITIONUPDATE, this.highDefinitionUpdate);
this.listenTo(this.container, Events.CONTAINER_MEDIACONTROL_DISABLE, this.disable);
this.listenTo(this.container, Events.CONTAINER_MEDIACONTROL_ENABLE, this.enable);
this.listenTo(this.container, Events.CONTAINER_ENDED, this.ended);
},
disable: function() {
this.disabled = true;
this.hide();
this.$el.hide();
},
enable: function() {
if (this.options.chromeless)
return;
this.disabled = false;
this.show();
},
play: function() {
this.container.play();
},
pause: function() {
this.container.pause();
},
stop: function() {
this.container.stop();
},
changeTogglePlay: function() {
if (this.container.isPlaying()) {
this.$playPauseToggle.removeClass('paused').addClass('playing');
this.$playStopToggle.removeClass('stopped').addClass('playing');
this.trigger(Events.MEDIACONTROL_PLAYING);
} else {
this.$playPauseToggle.removeClass('playing').addClass('paused');
this.$playStopToggle.removeClass('playing').addClass('stopped');
this.trigger(Events.MEDIACONTROL_NOTPLAYING);
}
},
mousemoveOnSeekBar: function(event) {
if (this.container.settings.seekEnabled) {
var offsetX = event.pageX - this.$seekBarContainer.offset().left - (this.$seekBarHover.width() / 2);
this.$seekBarHover.css({left: offsetX});
}
this.trigger(Events.MEDIACONTROL_MOUSEMOVE_SEEKBAR, event);
},
mouseleaveOnSeekBar: function(event) {
this.trigger(Events.MEDIACONTROL_MOUSELEAVE_SEEKBAR, event);
},
playerResize: function() {
if (Utils.Fullscreen.isFullscreen()) {
this.$fullscreenToggle.addClass('shrink');
} else {
this.$fullscreenToggle.removeClass('shrink');
}
this.$el.removeClass('w320');
if (PlayerInfo.currentSize.width <= 320) {
this.$el.addClass('w320');
}
},
togglePlayPause: function() {
if (this.container.isPlaying()) {
this.container.pause();
} else {
this.container.play();
}
this.changeTogglePlay();
},
togglePlayStop: function() {
if (this.container.isPlaying()) {
this.container.stop();
} else {
this.container.play();
}
this.changeTogglePlay();
},
startSeekDrag: function(event) {
if (!this.container.settings.seekEnabled)
return;
this.draggingSeekBar = true;
this.$el.addClass('dragging');
this.$seekBarLoaded.addClass('media-control-notransition');
this.$seekBarPosition.addClass('media-control-notransition');
this.$seekBarScrubber.addClass('media-control-notransition');
if (event) {
event.preventDefault();
}
},
startVolumeDrag: function(event) {
this.draggingVolumeBar = true;
this.$el.addClass('dragging');
if (event) {
event.preventDefault();
}
},
stopDrag: function(event) {
if (this.draggingSeekBar) {
this.seek(event);
}
this.$el.removeClass('dragging');
this.$seekBarLoaded.removeClass('media-control-notransition');
this.$seekBarPosition.removeClass('media-control-notransition');
this.$seekBarScrubber.removeClass('media-control-notransition dragging');
this.draggingSeekBar = false;
this.draggingVolumeBar = false;
},
updateDrag: function(event) {
if (event) {
event.preventDefault();
}
if (this.draggingSeekBar) {
var offsetX = event.pageX - this.$seekBarContainer.offset().left;
var pos = offsetX / this.$seekBarContainer.width() * 100;
pos = Math.min(100, Math.max(pos, 0));
this.setSeekPercentage(pos);
} else if (this.draggingVolumeBar) {
this.volume(event);
}
},
volume: function(event) {
var offsetY = event.pageX - this.$volumeBarContainer.offset().left;
this.currentVolume = (offsetY / this.$volumeBarContainer.width()) * 100;
this.currentVolume = Math.min(100, Math.max(this.currentVolume, 0));
this.container.setVolume(this.currentVolume);
this.setVolumeLevel(this.currentVolume);
},
toggleMute: function() {
if (this.mute) {
if (this.currentVolume <= 0) {
this.currentVolume = 100;
}
this.setVolume(this.currentVolume);
} else {
this.setVolume(0);
}
},
setVolume: function(value) {
this.container.setVolume(value);
this.setVolumeLevel(value);
if (value === 0) {
this.mute = true;
} else {
this.mute = false;
}
},
toggleFullscreen: function() {
this.trigger(Events.MEDIACONTROL_FULLSCREEN, this.name);
this.container.fullscreen();
this.resetKeepVisible();
},
setContainer: function(container) {
this.stopListening(this.container);
this.container = container;
this.changeTogglePlay();
this.addEventListeners();
this.settingsUpdate();
this.container.trigger(Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.container.isDvrInUse());
this.container.setVolume(this.currentVolume);
if (this.container.mediaControlDisabled) {
this.disable();
}
this.trigger(Events.MEDIACONTROL_CONTAINERCHANGED);
},
showVolumeBar: function() {
if (this.hideVolumeId) {
clearTimeout(this.hideVolumeId);
}
this.$volumeBarContainer.removeClass('volume-bar-hide');
},
hideVolumeBar: function() {
var $__0 = this;
var timeout = 400;
if (!this.$volumeBarContainer)
return;
if (this.draggingVolumeBar) {
this.hideVolumeId = setTimeout((function() {
return $__0.hideVolumeBar();
}), timeout);
} else {
if (this.hideVolumeId) {
clearTimeout(this.hideVolumeId);
}
this.hideVolumeId = setTimeout((function() {
return $__0.$volumeBarContainer.addClass('volume-bar-hide');
}), timeout);
}
},
ended: function() {
this.changeTogglePlay();
},
updateProgressBar: function(startPosition, endPosition, duration) {
var loadedStart = startPosition / duration * 100;
var loadedEnd = endPosition / duration * 100;
this.$seekBarLoaded.css({
left: loadedStart + '%',
width: (loadedEnd - loadedStart) + '%'
});
},
updateSeekBar: function(position, duration) {
if (this.draggingSeekBar)
return;
if (position < 0)
position = duration;
this.$seekBarPosition.removeClass('media-control-notransition');
this.$seekBarScrubber.removeClass('media-control-notransition');
var seekbarValue = (100 / duration) * position;
this.setSeekPercentage(seekbarValue);
this.$('[data-position]').html(Utils.formatTime(position));
this.$('[data-duration]').html(Utils.formatTime(duration));
},
seek: function(event) {
if (!this.container.settings.seekEnabled)
return;
var offsetX = event.pageX - this.$seekBarContainer.offset().left;
var pos = offsetX / this.$seekBarContainer.width() * 100;
pos = Math.min(100, Math.max(pos, 0));
this.container.setCurrentTime(pos);
this.setSeekPercentage(pos);
return false;
},
setKeepVisible: function() {
this.keepVisible = true;
},
resetKeepVisible: function() {
this.keepVisible = false;
},
isVisible: function() {
return !this.$el.hasClass('media-control-hide');
},
show: function(event) {
var $__0 = this;
if (this.disabled || this.container.getPlaybackType() === null)
return;
var timeout = 2000;
if (!event || (event.clientX !== this.lastMouseX && event.clientY !== this.lastMouseY) || navigator.userAgent.match(/firefox/i)) {
clearTimeout(this.hideId);
this.$el.show();
this.trigger(Events.MEDIACONTROL_SHOW, this.name);
this.$el.removeClass('media-control-hide');
this.hideId = setTimeout((function() {
return $__0.hide();
}), timeout);
if (event) {
this.lastMouseX = event.clientX;
this.lastMouseY = event.clientY;
}
}
},
hide: function() {
var $__0 = this;
var timeout = 2000;
clearTimeout(this.hideId);
if (!this.isVisible() || this.options.hideMediaControl === false)
return;
if (this.keepVisible || this.draggingSeekBar || this.draggingVolumeBar) {
this.hideId = setTimeout((function() {
return $__0.hide();
}), timeout);
} else {
this.trigger(Events.MEDIACONTROL_HIDE, this.name);
this.$el.addClass('media-control-hide');
this.hideVolumeBar();
}
},
settingsUpdate: function() {
if (this.container.getPlaybackType() !== null && !_.isEmpty(this.container.settings)) {
this.settings = this.container.settings;
this.render();
this.enable();
} else {
this.disable();
}
},
highDefinitionUpdate: function() {
if (this.container.isHighDefinitionInUse()) {
this.$el.find('button[data-hd-indicator]').addClass("enabled");
} else {
this.$el.find('button[data-hd-indicator]').removeClass("enabled");
}
},
createCachedElements: function() {
this.$playPauseToggle = this.$el.find('button.media-control-button[data-playpause]');
this.$playStopToggle = this.$el.find('button.media-control-button[data-playstop]');
this.$fullscreenToggle = this.$el.find('button.media-control-button[data-fullscreen]');
this.$seekBarContainer = this.$el.find('.bar-container[data-seekbar]');
this.$seekBarLoaded = this.$el.find('.bar-fill-1[data-seekbar]');
this.$seekBarPosition = this.$el.find('.bar-fill-2[data-seekbar]');
this.$seekBarScrubber = this.$el.find('.bar-scrubber[data-seekbar]');
this.$seekBarHover = this.$el.find('.bar-hover[data-seekbar]');
this.$volumeBarContainer = this.$el.find('.bar-container[data-volume]');
this.$volumeIcon = this.$el.find('.drawer-icon[data-volume]');
},
setVolumeLevel: function(value) {
var $__0 = this;
if (!this.container.isReady) {
this.listenToOnce(this.container, Events.CONTAINER_READY, (function() {
return $__0.setVolumeLevel(value);
}));
} else {
this.$volumeBarContainer.find('.segmented-bar-element').removeClass('fill');
var item = Math.ceil(value / 10.0);
this.$volumeBarContainer.find('.segmented-bar-element').slice(0, item).addClass('fill');
if (value > 0) {
this.$volumeIcon.removeClass('muted');
} else {
this.$volumeIcon.addClass('muted');
}
}
},
setSeekPercentage: function(value) {
if (value > 100)
return;
var pos = this.$seekBarContainer.width() * value / 100.0 - (this.$seekBarScrubber.width() / 2.0);
this.currentSeekPercentage = value;
this.$seekBarPosition.css({width: value + '%'});
this.$seekBarScrubber.css({left: pos});
},
bindKeyEvents: function() {
var $__0 = this;
Mousetrap.bind(['space'], (function() {
return $__0.togglePlayPause();
}));
},
unbindKeyEvents: function() {
Mousetrap.unbind('space');
},
parseColors: function() {
if (this.options.mediacontrol) {
var buttonsColor = this.options.mediacontrol.buttons;
var seekbarColor = this.options.mediacontrol.seekbar;
this.$el.find('.bar-fill-2[data-seekbar]').css('background-color', seekbarColor);
this.$el.find('[data-media-control] > .media-control-icon, .drawer-icon').css('color', buttonsColor);
this.$el.find('.segmented-bar-element[data-volume]').css('boxShadow', "inset 2px 0 0 " + buttonsColor);
}
},
render: function() {
var $__0 = this;
var timeout = 1000;
var style = Styler.getStyleFor('media_control');
this.$el.html(this.template({settings: this.settings}));
this.$el.append(style);
this.createCachedElements();
this.$playPauseToggle.addClass('paused');
this.$playStopToggle.addClass('stopped');
this.changeTogglePlay();
this.hideId = setTimeout((function() {
return $__0.hide();
}), timeout);
if (this.disabled) {
this.hide();
}
this.$seekBarPosition.addClass('media-control-notransition');
this.$seekBarScrubber.addClass('media-control-notransition');
if (!this.currentSeekPercentage) {
this.currentSeekPercentage = 0;
}
this.setSeekPercentage(this.currentSeekPercentage);
this.$el.ready((function() {
if (!$__0.container.settings.seekEnabled) {
$__0.$seekBarContainer.addClass('seek-disabled');
}
$__0.setVolumeLevel($__0.currentVolume);
$__0.bindKeyEvents();
$__0.hideVolumeBar();
}));
this.parseColors();
this.seekTime.render();
this.trigger(Events.MEDIACONTROL_RENDERED);
return this;
},
destroy: function() {
$(document).unbind('mouseup');
$(document).unbind('mousemove');
this.unbindKeyEvents();
}
}, {}, UIObject);
module.exports = MediaControl;
},{"../../base/jst":7,"../../base/styler":8,"../../base/utils":9,"../seek_time":22,"events":"events","mediator":"mediator","mousetrap":4,"player_info":"player_info","ui_object":"ui_object","underscore":"underscore","zepto":"zepto"}],21:[function(require,module,exports){
"use strict";
var BaseObject = require('base_object');
var CoreFactory = require('./core_factory');
var Loader = require('./loader');
var _ = require('underscore');
var ScrollMonitor = require('scrollmonitor');
var PlayerInfo = require('player_info');
var Player = function Player(options) {
$traceurRuntime.superCall(this, $Player.prototype, "constructor", [options]);
window.p = this;
this.options = options;
this.options.sources = this.normalizeSources(options);
this.loader = new Loader(this.options.plugins || []);
this.coreFactory = new CoreFactory(this, this.loader);
options.height || (options.height = 360);
options.width || (options.width = 640);
PlayerInfo.currentSize = {
width: options.width,
height: options.height
};
if (this.options.parentId) {
var el = document.querySelector(this.options.parentId);
if (el) {
this.attachTo(el);
}
}
};
var $Player = Player;
($traceurRuntime.createClass)(Player, {
attachTo: function(element) {
this.options.parentElement = element;
this.core = this.coreFactory.create();
if (this.options.autoPlayVisible) {
this.bindAutoPlayVisible(this.options.autoPlayVisible);
}
},
bindAutoPlayVisible: function(option) {
var $__0 = this;
this.elementWatcher = ScrollMonitor.create(this.core.$el);
if (option === 'full') {
this.elementWatcher.fullyEnterViewport((function() {
return $__0.enterViewport();
}));
} else if (option === 'partial') {
this.elementWatcher.enterViewport((function() {
return $__0.enterViewport();
}));
}
},
enterViewport: function() {
if (this.elementWatcher.top !== 0 && !this.isPlaying()) {
this.play();
}
},
normalizeSources: function(options) {
return _.compact(_.flatten([options.source, options.sources]));
},
resize: function(size) {
this.core.resize(size);
},
load: function(sources) {
this.core.load(sources);
},
destroy: function() {
this.core.destroy();
},
play: function() {
this.core.mediaControl.container.play();
},
pause: function() {
this.core.mediaControl.container.pause();
},
stop: function() {
this.core.mediaControl.container.stop();
},
seek: function(time) {
this.core.mediaControl.container.setCurrentTime(time);
},
setVolume: function(volume) {
this.core.mediaControl.container.setVolume(volume);
},
mute: function() {
this.core.mediaControl.container.setVolume(0);
},
unmute: function() {
this.core.mediaControl.container.setVolume(100);
},
isPlaying: function() {
return this.core.mediaControl.container.isPlaying();
}
}, {}, BaseObject);
module.exports = Player;
},{"./core_factory":15,"./loader":18,"base_object":"base_object","player_info":"player_info","scrollmonitor":5,"underscore":"underscore"}],22:[function(require,module,exports){
"use strict";
module.exports = require('./seek_time');
},{"./seek_time":23}],23:[function(require,module,exports){
"use strict";
var UIObject = require('ui_object');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var formatTime = require('../../base/utils').formatTime;
var Events = require('events');
var SeekTime = function SeekTime(mediaControl) {
$traceurRuntime.superCall(this, $SeekTime.prototype, "constructor", []);
this.mediaControl = mediaControl;
this.addEventListeners();
};
var $SeekTime = SeekTime;
($traceurRuntime.createClass)(SeekTime, {
get name() {
return 'seek_time';
},
get template() {
return JST.seek_time;
},
get attributes() {
return {
'class': 'seek-time hidden',
'data-seek-time': ''
};
},
addEventListeners: function() {
this.listenTo(this.mediaControl, Events.MEDIACONTROL_MOUSEMOVE_SEEKBAR, this.showTime);
this.listenTo(this.mediaControl, Events.MEDIACONTROL_MOUSELEAVE_SEEKBAR, this.hideTime);
},
showTime: function(event) {
var offset = event.pageX - this.mediaControl.$seekBarContainer.offset().left;
var timePosition = Math.min(100, Math.max((offset) / this.mediaControl.$seekBarContainer.width() * 100, 0));
var pointerPosition = event.pageX - this.mediaControl.$el.offset().left - (this.$el.width() / 2);
pointerPosition = Math.min(Math.max(0, pointerPosition), this.mediaControl.$el.width() - this.$el.width());
var currentTime = timePosition * this.mediaControl.container.getDuration() / 100;
var options = {
timestamp: currentTime,
formattedTime: formatTime(currentTime),
pointerPosition: pointerPosition
};
this.update(options);
},
hideTime: function() {
this.$el.addClass('hidden');
this.$el.css('left', '-100%');
},
update: function(options) {
if (this.mediaControl.container.getPlaybackType() === 'vod' || this.mediaControl.container.isDvrInUse()) {
this.$el.find('[data-seek-time]').text(options.formattedTime);
this.$el.css('left', options.pointerPosition);
this.$el.removeClass('hidden');
}
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
this.mediaControl.$el.append(this.el);
}
}, {}, UIObject);
module.exports = SeekTime;
},{"../../base/jst":7,"../../base/styler":8,"../../base/utils":9,"events":"events","ui_object":"ui_object"}],24:[function(require,module,exports){
"use strict";
var Playback = require('playback');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Mediator = require('mediator');
var _ = require('underscore');
var $ = require('zepto');
var Browser = require('browser');
var Mousetrap = require('mousetrap');
var seekStringToSeconds = require('../../base/utils').seekStringToSeconds;
var Events = require('events');
var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-flash-vod=""><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="gpu"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>';
var Flash = function Flash(options) {
$traceurRuntime.superCall(this, $Flash.prototype, "constructor", [options]);
this.src = options.src;
this.isRTMP = (this.src.indexOf("rtmp") > -1);
this.defaultBaseSwfPath = "http://cdn.clappr.io/" + Clappr.version + "/assets/";
this.swfPath = (options.swfBasePath || this.defaultBaseSwfPath) + "Player.swf";
this.autoPlay = options.autoPlay;
this.settings = {default: ['seekbar']};
if (this.isRTMP) {
this.settings.left = ["playstop"];
this.settings.right = ["fullscreen", "volume"];
} else {
this.settings.left = ["playpause", "position", "duration"];
this.settings.right = ["fullscreen", "volume"];
this.settings.seekEnabled = true;
}
this.isReady = false;
this.addListeners();
};
var $Flash = Flash;
($traceurRuntime.createClass)(Flash, {
get name() {
return 'flash';
},
get tagName() {
return 'object';
},
get template() {
return JST.flash;
},
bootstrap: function() {
this.el.width = "100%";
this.el.height = "100%";
this.isReady = true;
if (this.currentState === 'PLAYING') {
this.firstPlay();
} else {
this.currentState = "IDLE";
this.autoPlay && this.play();
}
$('<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" />').insertAfter(this.$el);
this.trigger(Events.PLAYBACK_READY, this.name);
},
getPlaybackType: function() {
return this.isRTMP ? 'live' : 'vod';
},
setupFirefox: function() {
var $el = this.$('embed');
$el.attr('data-flash', '');
this.setElement($el[0]);
},
isHighDefinitionInUse: function() {
return false;
},
updateTime: function() {
this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.getPosition(), this.el.getDuration(), this.name);
},
addListeners: function() {
Mediator.on(this.uniqueId + ':progress', this.progress, this);
Mediator.on(this.uniqueId + ':timeupdate', this.updateTime, this);
Mediator.on(this.uniqueId + ':statechanged', this.checkState, this);
Mediator.on(this.uniqueId + ':flashready', this.bootstrap, this);
_.each(_.range(1, 10), function(i) {
var $__0 = this;
Mousetrap.bind([i.toString()], (function() {
return $__0.seek(i * 10);
}));
}.bind(this));
},
stopListening: function() {
$traceurRuntime.superCall(this, $Flash.prototype, "stopListening", []);
Mediator.off(this.uniqueId + ':progress');
Mediator.off(this.uniqueId + ':timeupdate');
Mediator.off(this.uniqueId + ':statechanged');
Mediator.off(this.uniqueId + ':flashready');
_.each(_.range(1, 10), function(i) {
var $__0 = this;
Mousetrap.unbind([i.toString()], (function() {
return $__0.seek(i * 10);
}));
}.bind(this));
},
checkState: function() {
if (this.currentState === "PAUSED") {
return;
} else if (this.currentState !== "PLAYING_BUFFERING" && this.el.getState() === "PLAYING_BUFFERING") {
this.trigger(Events.PLAYBACK_BUFFERING, this.name);
this.currentState = "PLAYING_BUFFERING";
} else if (this.currentState === "PLAYING_BUFFERING" && this.el.getState() === "PLAYING") {
this.trigger(Events.PLAYBACK_BUFFERFULL, this.name);
this.currentState = "PLAYING";
} else if (this.el.getState() === "IDLE") {
this.currentState = "IDLE";
} else if (this.el.getState() === "ENDED") {
this.trigger(Events.PLAYBACK_ENDED, this.name);
this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.el.getDuration(), this.name);
this.currentState = "ENDED";
}
},
progress: function() {
if (this.currentState !== "IDLE" && this.currentState !== "ENDED") {
this.trigger(Events.PLAYBACK_PROGRESS, 0, this.el.getBytesLoaded(), this.el.getBytesTotal(), this.name);
}
},
firstPlay: function() {
var $__0 = this;
this.currentState = "PLAYING";
if (_.isFunction(this.el.playerPlay)) {
this.el.playerPlay(this.src);
this.listenToOnce(this, Events.PLAYBACK_BUFFERFULL, (function() {
return $__0.checkInitialSeek();
}));
}
},
checkInitialSeek: function() {
var seekTime = seekStringToSeconds(window.location.href);
this.seekSeconds(seekTime);
},
play: function() {
if (this.el.getState() === 'PAUSED' || this.el.getState() === 'PLAYING_BUFFERING') {
this.currentState = "PLAYING";
this.el.playerResume();
} else if (this.el.getState() !== 'PLAYING') {
this.firstPlay();
}
this.trigger(Events.PLAYBACK_PLAY, this.name);
},
volume: function(value) {
var $__0 = this;
if (this.isReady) {
this.el.playerVolume(value);
} else {
this.listenToOnce(this, Events.PLAYBACK_BUFFERFULL, (function() {
return $__0.volume(value);
}));
}
},
pause: function() {
this.currentState = "PAUSED";
this.el.playerPause();
},
stop: function() {
this.el.playerStop();
this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.name);
},
isPlaying: function() {
return !!(this.isReady && this.currentState === "PLAYING");
},
getDuration: function() {
return this.el.getDuration();
},
seek: function(seekBarValue) {
var seekTo = this.el.getDuration() * (seekBarValue / 100);
this.seekSeconds(seekTo);
},
seekSeconds: function(seekTo) {
this.el.playerSeek(seekTo);
this.trigger(Events.PLAYBACK_TIMEUPDATE, seekTo, this.el.getDuration(), this.name);
if (this.currentState === "PAUSED") {
this.el.playerPause();
}
},
destroy: function() {
clearInterval(this.bootstrapId);
this.stopListening();
this.$el.remove();
},
setupIE: function() {
this.setElement($(_.template(objectIE)({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
})));
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
}));
if (Browser.isFirefox) {
this.setupFirefox();
} else if (Browser.isLegacyIE) {
this.setupIE();
}
this.$el.append(style);
return this;
}
}, {}, Playback);
Flash.canPlay = function(resource) {
if (resource.indexOf('rtmp') > -1) {
return true;
} else if ((!Browser.isMobile && Browser.isFirefox) || Browser.isLegacyIE) {
return _.isString(resource) && !!resource.match(/(.*)\.(mp4|mov|f4v|3gpp|3gp)/);
} else {
return _.isString(resource) && !!resource.match(/(.*)\.(mov|f4v|3gpp|3gp)/);
}
};
module.exports = Flash;
},{"../../base/jst":7,"../../base/styler":8,"../../base/utils":9,"browser":"browser","events":"events","mediator":"mediator","mousetrap":4,"playback":"playback","underscore":"underscore","zepto":"zepto"}],25:[function(require,module,exports){
"use strict";
var Playback = require('playback');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var _ = require("underscore");
var Mediator = require('mediator');
var Browser = require('browser');
var Events = require('events');
var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" class="hls-playback" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-hls="" width="100%" height="100%"><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> </object>';
var HLS = function HLS(options) {
$traceurRuntime.superCall(this, $HLS.prototype, "constructor", [options]);
this.src = options.src;
this.defaultBaseSwfPath = "http://cdn.clappr.io/" + Clappr.version + "/assets/";
this.swfPath = (options.swfBasePath || this.defaultBaseSwfPath) + "HLSPlayer.swf";
this.flushLiveURLCache = (options.flushLiveURLCache === undefined) ? true : options.flushLiveURLCache;
this.capLevelToStage = (options.capLevelToStage === undefined) ? false : options.capLevelToStage;
this.highDefinition = false;
this.autoPlay = options.autoPlay;
this.defaultSettings = {
left: ["playstop"],
default: ['seekbar'],
right: ["fullscreen", "volume", "hd-indicator"],
seekEnabled: false
};
this.settings = _.extend({}, this.defaultSettings);
this.playbackType = 'live';
this.addListeners();
};
var $HLS = HLS;
($traceurRuntime.createClass)(HLS, {
get name() {
return 'hls';
},
get tagName() {
return 'object';
},
get template() {
return JST.hls;
},
get attributes() {
return {
'class': 'hls-playback',
'data-hls': '',
'type': 'application/x-shockwave-flash'
};
},
addListeners: function() {
var $__0 = this;
Mediator.on(this.uniqueId + ':flashready', (function() {
return $__0.bootstrap();
}));
Mediator.on(this.uniqueId + ':timeupdate', (function() {
return $__0.updateTime();
}));
Mediator.on(this.uniqueId + ':playbackstate', (function(state) {
return $__0.setPlaybackState(state);
}));
Mediator.on(this.uniqueId + ':highdefinition', (function(isHD) {
return $__0.updateHighDefinition(isHD);
}));
Mediator.on(this.uniqueId + ':playbackerror', (function() {
return $__0.flashPlaybackError();
}));
},
stopListening: function() {
$traceurRuntime.superCall(this, $HLS.prototype, "stopListening", []);
Mediator.off(this.uniqueId + ':flashready');
Mediator.off(this.uniqueId + ':timeupdate');
Mediator.off(this.uniqueId + ':playbackstate');
Mediator.off(this.uniqueId + ':highdefinition');
Mediator.off(this.uniqueId + ':playbackerror');
},
bootstrap: function() {
this.el.width = "100%";
this.el.height = "100%";
this.isReady = true;
this.trigger(Events.PLAYBACK_READY, this.name);
this.currentState = "IDLE";
this.setFlashSettings();
this.autoPlay && this.play();
},
setFlashSettings: function() {
this.el.globoPlayerSetflushLiveURLCache(this.flushLiveURLCache);
this.el.globoPlayerCapLeveltoStage(this.capLevelToStage);
this.el.globoPlayerSetmaxBufferLength(0);
},
updateHighDefinition: function(isHD) {
this.highDefinition = (isHD === "true");
this.trigger(Events.PLAYBACK_HIGHDEFINITIONUPDATE);
this.trigger(Events.PLAYBACK_BITRATE, {'bitrate': this.getCurrentBitrate()});
},
updateTime: function() {
var duration = this.getDuration();
var position = Math.min(Math.max(this.el.globoGetPosition(), 0), duration);
var previousDVRStatus = this.dvrEnabled;
var livePlayback = (this.playbackType === 'live');
this.dvrEnabled = (livePlayback && duration > 240);
if (duration === 100 || livePlayback === undefined) {
return;
}
if (this.dvrEnabled !== previousDVRStatus) {
this.updateSettings();
this.trigger(Events.PLAYBACK_SETTINGSUPDATE, this.name);
}
if (livePlayback && (!this.dvrEnabled || !this.dvrInUse)) {
position = duration;
}
this.trigger(Events.PLAYBACK_TIMEUPDATE, position, duration, this.name);
},
play: function() {
if (this.currentState === 'PAUSED') {
this.el.globoPlayerResume();
} else if (this.currentState !== "PLAYING") {
this.firstPlay();
}
this.trigger(Events.PLAYBACK_PLAY, this.name);
},
getPlaybackType: function() {
return this.playbackType ? this.playbackType : null;
},
getCurrentBitrate: function() {
var currentLevel = this.getLevels()[this.el.globoGetLevel()];
return currentLevel.bitrate;
},
getLastProgramDate: function() {
var programDate = this.el.globoGetLastProgramDate();
return programDate - 1.08e+7;
},
isHighDefinitionInUse: function() {
return this.highDefinition;
},
getLevels: function() {
if (!this.levels || this.levels.length === 0) {
this.levels = this.el.globoGetLevels();
}
return this.levels;
},
setPlaybackState: function(state) {
var bufferLength = this.el.globoGetbufferLength();
if (state === "PLAYING_BUFFERING" && bufferLength < 1) {
this.trigger(Events.PLAYBACK_BUFFERING, this.name);
this.updateCurrentState(state);
} else if (state === "PLAYING") {
if (_.contains(["PLAYING_BUFFERING", "PAUSED", "IDLE"], this.currentState)) {
this.trigger(Events.PLAYBACK_BUFFERFULL, this.name);
this.updateCurrentState(state);
}
} else if (state === "PAUSED") {
this.updateCurrentState(state);
} else if (state === "IDLE") {
this.trigger(Events.PLAYBACK_ENDED, this.name);
this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.el.globoGetDuration(), this.name);
this.updateCurrentState(state);
}
this.lastBufferLength = bufferLength;
},
updateCurrentState: function(state) {
this.currentState = state;
this.updatePlaybackType();
},
updatePlaybackType: function() {
this.playbackType = this.el.globoGetType();
if (this.playbackType) {
this.playbackType = this.playbackType.toLowerCase();
if (this.playbackType === 'vod') {
this.startReportingProgress();
} else {
this.stopReportingProgress();
}
}
this.trigger(Events.PLAYBACK_PLAYBACKSTATE);
},
startReportingProgress: function() {
if (!this.reportingProgress) {
this.reportingProgress = true;
Mediator.on(this.uniqueId + ':fragmentloaded', this.onFragmentLoaded);
}
},
stopReportingProgress: function() {
Mediator.off(this.uniqueId + ':fragmentloaded', this.onFragmentLoaded, this);
},
onFragmentLoaded: function() {
var buffered = this.el.globoGetPosition() + this.el.globoGetbufferLength();
this.trigger(Events.PLAYBACK_PROGRESS, this.el.globoGetPosition(), buffered, this.getDuration(), this.name);
},
firstPlay: function() {
this.el.globoPlayerLoad(this.src);
this.el.globoPlayerPlay();
},
volume: function(value) {
var $__0 = this;
if (this.isReady) {
this.el.globoPlayerVolume(value);
} else {
this.listenToOnce(this, Events.PLAYBACK_BUFFERFULL, (function() {
return $__0.volume(value);
}));
}
},
pause: function() {
if (this.playbackType !== 'live' || this.dvrEnabled) {
this.el.globoPlayerPause();
if (this.playbackType === 'live' && this.dvrEnabled) {
this.updateDvr(true);
}
}
},
stop: function() {
this.el.globoPlayerStop();
this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.name);
},
isPlaying: function() {
if (this.currentState) {
return !!(this.currentState.match(/playing/i));
}
return false;
},
getDuration: function() {
var duration = this.el.globoGetDuration();
if (this.playbackType === 'live') {
duration = duration - 10;
}
return duration;
},
seek: function(time) {
var duration = this.getDuration();
if (time > 0) {
time = duration * time / 100;
}
if (this.playbackType === 'live') {
var dvrInUse = (time >= 0 && duration - time > 5);
if (!dvrInUse) {
time = -1;
}
this.updateDvr(dvrInUse);
}
this.el.globoPlayerSeek(time);
this.trigger(Events.PLAYBACK_TIMEUPDATE, time, duration, this.name);
},
updateDvr: function(dvrInUse) {
var previousDvrInUse = !!this.dvrInUse;
this.dvrInUse = dvrInUse;
if (this.dvrInUse !== previousDvrInUse) {
this.updateSettings();
this.trigger(Events.PLAYBACK_DVR, this.dvrInUse);
this.trigger(Events.PLAYBACK_STATS_ADD, {'dvr': this.dvrInUse});
}
},
flashPlaybackError: function() {
this.trigger(Events.PLAYBACK_STOP);
},
timeUpdate: function(time, duration) {
this.trigger(Events.PLAYBACK_TIMEUPDATE, time, duration, this.name);
},
destroy: function() {
this.stopListening();
this.$el.remove();
},
setupFirefox: function() {
var $el = this.$('embed');
$el.attr('data-hls', '');
this.setElement($el);
},
setupIE: function() {
this.setElement($(_.template(objectIE)({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
})));
},
updateSettings: function() {
this.settings = _.extend({}, this.defaultSettings);
if (this.playbackType === "vod" || this.dvrInUse) {
this.settings.left = ["playpause", "position", "duration"];
this.settings.seekEnabled = true;
} else if (this.dvrEnabled) {
this.settings.left = ["playpause"];
this.settings.seekEnabled = true;
} else {
this.settings.seekEnabled = false;
}
},
setElement: function(element) {
this.$el = element;
this.el = element[0];
},
render: function() {
var style = Styler.getStyleFor(this.name);
if (Browser.isLegacyIE) {
this.setupIE();
} else {
this.$el.html(this.template({
cid: this.cid,
swfPath: this.swfPath,
playbackId: this.uniqueId
}));
if (Browser.isFirefox) {
this.setupFirefox();
} else if (Browser.isIE) {
this.$('embed').remove();
}
}
this.el.id = this.cid;
this.$el.append(style);
return this;
}
}, {}, Playback);
HLS.canPlay = function(resource) {
return !!resource.match(/^http(.*).m3u8?/);
};
module.exports = HLS;
},{"../../base/jst":7,"../../base/styler":8,"browser":"browser","events":"events","mediator":"mediator","playback":"playback","underscore":"underscore"}],26:[function(require,module,exports){
"use strict";
var Playback = require('playback');
var Events = require('events');
var HTML5Audio = function HTML5Audio(params) {
$traceurRuntime.superCall(this, $HTML5Audio.prototype, "constructor", [params]);
this.el.src = params.src;
this.settings = {
left: ['playpause', 'position', 'duration'],
right: ['fullscreen', 'volume'],
default: ['seekbar']
};
this.render();
params.autoPlay && this.play();
};
var $HTML5Audio = HTML5Audio;
($traceurRuntime.createClass)(HTML5Audio, {
get name() {
return 'html5_audio';
},
get tagName() {
return 'audio';
},
get events() {
return {
'timeupdate': 'timeUpdated',
'ended': 'ended'
};
},
bindEvents: function() {
this.listenTo(this.container, Events.CONTAINER_PLAY, this.play);
this.listenTo(this.container, Events.CONTAINER_PAUSE, this.pause);
this.listenTo(this.container, Events.CONTAINER_SEEK, this.seek);
this.listenTo(this.container, Events.CONTAINER_VOLUME, this.volume);
this.listenTo(this.container, Events.CONTAINER_STOP, this.stop);
},
getPlaybackType: function() {
return "aod";
},
play: function() {
this.el.play();
this.trigger(Events.PLAYBACK_PLAY);
},
pause: function() {
this.el.pause();
},
stop: function() {
this.pause();
this.el.currentTime = 0;
},
volume: function(value) {
this.el.volume = value / 100;
},
mute: function() {
this.el.volume = 0;
},
unmute: function() {
this.el.volume = 1;
},
isMuted: function() {
return !!this.el.volume;
},
ended: function() {
this.trigger(Events.CONTAINER_TIMEUPDATE, 0);
},
seek: function(seekBarValue) {
var time = this.el.duration * (seekBarValue / 100);
this.el.currentTime = time;
},
getCurrentTime: function() {
return this.el.currentTime;
},
getDuration: function() {
return this.el.duration;
},
isPlaying: function() {
return !this.el.paused && !this.el.ended;
},
timeUpdated: function() {
this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.currentTime, this.el.duration, this.name);
},
render: function() {
return this;
}
}, {}, Playback);
HTML5Audio.canPlay = function(resource) {
return !!resource.match(/(.*).mp3/);
};
module.exports = HTML5Audio;
},{"events":"events","playback":"playback"}],27:[function(require,module,exports){
(function (process){
"use strict";
var Playback = require('playback');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var Browser = require('browser');
var Mousetrap = require('mousetrap');
var seekStringToSeconds = require('../../base/utils').seekStringToSeconds;
var Events = require('events');
var _ = require('underscore');
var HTML5Video = function HTML5Video(options) {
$traceurRuntime.superCall(this, $HTML5Video.prototype, "constructor", [options]);
this.options = options;
this.src = options.src;
this.el.src = options.src;
this.el.loop = options.loop;
this.firstBuffer = true;
this.isHLS = (this.src.indexOf('m3u8') > -1);
this.settings = {default: ['seekbar']};
if (this.isHLS) {
this.el.preload = options.preload ? options.preload : 'none';
this.settings.left = ["playstop"];
this.settings.right = ["fullscreen", "volume"];
} else {
this.el.preload = options.preload ? options.preload : 'metadata';
this.settings.left = ["playpause", "position", "duration"];
this.settings.right = ["fullscreen", "volume"];
this.settings.seekEnabled = true;
}
this.bindEvents();
};
var $HTML5Video = HTML5Video;
($traceurRuntime.createClass)(HTML5Video, {
get name() {
return 'html5_video';
},
get tagName() {
return 'video';
},
get template() {
return JST.html5_video;
},
get attributes() {
return {'data-html5-video': ''};
},
get events() {
return {
'timeupdate': 'timeUpdated',
'progress': 'progress',
'ended': 'ended',
'stalled': 'stalled',
'waiting': 'waiting',
'canplaythrough': 'bufferFull',
'loadedmetadata': 'loadedMetadata'
};
},
bindEvents: function() {
_.each(_.range(1, 10), function(i) {
var $__0 = this;
Mousetrap.bind([i.toString()], (function() {
return $__0.seek(i * 10);
}));
}.bind(this));
},
loadedMetadata: function(e) {
this.trigger(Events.PLAYBACK_LOADEDMETADATA, e.target.duration);
this.trigger(Events.PLAYBACK_SETTINGSUPDATE);
this.checkInitialSeek();
},
getPlaybackType: function() {
return this.isHLS && _.contains([0, undefined, Infinity], this.el.duration) ? 'live' : 'vod';
},
isHighDefinitionInUse: function() {
return false;
},
play: function() {
this.el.play();
this.trigger(Events.PLAYBACK_PLAY);
if (this.isHLS) {
this.trigger(Events.PLAYBACK_TIMEUPDATE, 1, 1, this.name);
}
},
pause: function() {
this.el.pause();
},
stop: function() {
this.pause();
if (this.el.readyState !== 0) {
this.el.currentTime = 0;
}
},
volume: function(value) {
this.el.volume = value / 100;
},
mute: function() {
this.el.volume = 0;
},
unmute: function() {
this.el.volume = 1;
},
isMuted: function() {
return !!this.el.volume;
},
isPlaying: function() {
return !this.el.paused && !this.el.ended;
},
ended: function() {
this.trigger(Events.PLAYBACK_ENDED, this.name);
this.trigger(Events.PLAYBACK_TIMEUPDATE, 0, this.el.duration, this.name);
},
stalled: function() {
if (this.getPlaybackType() === 'vod' && this.el.readyState < this.el.HAVE_FUTURE_DATA) {
this.trigger(Events.PLAYBACK_BUFFERING, this.name);
}
},
waiting: function() {
if (this.el.readyState < this.el.HAVE_FUTURE_DATA) {
this.trigger(Events.PLAYBACK_BUFFERING, this.name);
}
},
bufferFull: function() {
if (this.options.poster && this.firstBuffer) {
this.firstBuffer = false;
this.el.poster = this.options.poster;
} else {
this.el.poster = '';
}
this.trigger(Events.PLAYBACK_BUFFERFULL, this.name);
},
destroy: function() {
this.stop();
this.el.src = '';
this.$el.remove();
},
seek: function(seekBarValue) {
var time = this.el.duration * (seekBarValue / 100);
this.seekSeconds(time);
},
seekSeconds: function(time) {
this.el.currentTime = time;
},
checkInitialSeek: function() {
var seekTime = seekStringToSeconds(window.location.href);
this.seekSeconds(seekTime);
},
getCurrentTime: function() {
return this.el.currentTime;
},
getDuration: function() {
return this.el.duration;
},
timeUpdated: function() {
if (this.getPlaybackType() !== 'live') {
this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.currentTime, this.el.duration, this.name);
}
},
progress: function() {
if (!this.el.buffered.length)
return;
var bufferedPos = 0;
for (var i = 0; i < this.el.buffered.length; i++) {
if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) {
bufferedPos = i;
break;
}
}
this.trigger(Events.PLAYBACK_PROGRESS, this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name);
},
typeFor: function(src) {
return (src.indexOf('.m3u8') > 0) ? 'application/vnd.apple.mpegurl' : 'video/mp4';
},
render: function() {
var $__0 = this;
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template({
src: this.src,
type: this.typeFor(this.src)
}));
this.$el.append(style);
this.trigger(Events.PLAYBACK_READY, this.name);
process.nextTick((function() {
return $__0.options.autoPlay && $__0.play();
}));
return this;
}
}, {}, Playback);
HTML5Video.canPlay = function(resource) {
var mimetypes = {
'mp4': _.map(["avc1.42E01E", "avc1.58A01E", "avc1.4D401E", "avc1.64001E", "mp4v.20.8", "mp4v.20.240"], function(codec) {
return 'video/mp4; codecs=' + codec + ', mp4a.40.2';
}),
'ogg': ['video/ogg; codecs="theora, vorbis"', 'video/ogg; codecs="dirac"', 'video/ogg; codecs="theora, speex"'],
'3gpp': ['video/3gpp; codecs="mp4v.20.8, samr"'],
'webm': ['video/webm; codecs="vp8, vorbis"'],
'mkv': ['video/x-matroska; codecs="theora, vorbis"'],
'm3u8': ['application/x-mpegURL']
};
mimetypes['ogv'] = mimetypes['ogg'];
mimetypes['3gp'] = mimetypes['3gpp'];
var extension = resource.split('?')[0].match(/.*\.(.*)$/)[1];
if (_.has(mimetypes, extension)) {
var v = document.createElement('video');
return !!_.find(mimetypes[extension], function(ext) {
return !!v.canPlayType(ext).replace(/no/, '');
});
}
return false;
};
module.exports = HTML5Video;
}).call(this,require('_process'))
},{"../../base/jst":7,"../../base/styler":8,"../../base/utils":9,"_process":2,"browser":"browser","events":"events","mousetrap":4,"playback":"playback","underscore":"underscore"}],28:[function(require,module,exports){
"use strict";
var Playback = require('playback');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Events = require('events');
var HTMLImg = function HTMLImg(params) {
$traceurRuntime.superCall(this, $HTMLImg.prototype, "constructor", [params]);
this.el.src = params.src;
setTimeout(function() {
this.trigger(Events.PLAYBACK_BUFFERFULL, this.name);
}.bind(this), 1);
};
var $HTMLImg = HTMLImg;
($traceurRuntime.createClass)(HTMLImg, {
get name() {
return 'html_img';
},
get tagName() {
return 'img';
},
get attributes() {
return {'data-html-img': ''};
},
getPlaybackType: function() {
return null;
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.append(style);
return this;
}
}, {}, Playback);
HTMLImg.canPlay = function(resource) {
return !!resource.match(/(.*).(png|jpg|jpeg|gif|bmp)/);
};
module.exports = HTMLImg;
},{"../../base/jst":7,"../../base/styler":8,"events":"events","playback":"playback"}],29:[function(require,module,exports){
"use strict";
module.exports = require('./no_op');
},{"./no_op":30}],30:[function(require,module,exports){
"use strict";
var Playback = require('playback');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var NoOp = function NoOp(options) {
$traceurRuntime.superCall(this, $NoOp.prototype, "constructor", [options]);
};
var $NoOp = NoOp;
($traceurRuntime.createClass)(NoOp, {
get name() {
return 'no_op';
},
get template() {
return JST.no_op;
},
get attributes() {
return {'data-no-op': ''};
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
return this;
}
}, {}, Playback);
NoOp.canPlay = (function(source) {
return true;
});
module.exports = NoOp;
},{"../../base/jst":7,"../../base/styler":8,"playback":"playback"}],31:[function(require,module,exports){
(function (process){
"use strict";
var UICorePlugin = require('ui_core_plugin');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var Events = require('events');
var Browser = require('browser');
var Mediator = require('mediator');
var PlayerInfo = require('player_info');
var BackgroundButton = function BackgroundButton(core) {
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "constructor", [core]);
this.core = core;
this.settingsUpdate();
};
var $BackgroundButton = BackgroundButton;
($traceurRuntime.createClass)(BackgroundButton, {
get template() {
return JST.background_button;
},
get name() {
return 'background_button';
},
get attributes() {
return {
'class': 'background-button',
'data-background-button': ''
};
},
get events() {
return {'click .background-button-icon': 'click'};
},
bindEvents: function() {
this.listenTo(this.core.mediaControl.container, Events.CONTAINER_STATE_BUFFERING, this.hide);
this.listenTo(this.core.mediaControl.container, Events.CONTAINER_STATE_BUFFERFULL, this.show);
this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_RENDERED, this.settingsUpdate);
this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_SHOW, this.updateSize);
this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_PLAYING, this.playing);
this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_NOTPLAYING, this.notplaying);
Mediator.on(Events.PLAYER_RESIZE, this.updateSize, this);
},
stopListening: function() {
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "stopListening", []);
Mediator.off(Events.PLAYER_RESIZE, this.updateSize, this);
},
settingsUpdate: function() {
this.stopListening();
if (this.shouldRender()) {
this.render();
this.bindEvents();
if (this.core.mediaControl.container.isPlaying()) {
this.playing();
} else {
this.notplaying();
}
} else {
this.$el.remove();
this.$playPauseButton.show();
this.$playStopButton.show();
this.listenTo(this.core.mediaControl.container, Events.CONTAINER_SETTINGSUPDATE, this.settingsUpdate);
this.listenTo(this.core.mediaControl.container, Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.settingsUpdate);
this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_CONTAINERCHANGED, this.settingsUpdate);
}
},
shouldRender: function() {
var useBackgroundButton = (this.core.options.useBackgroundButton === undefined && Browser.isMobile) || !!this.core.options.useBackgroundButton;
return useBackgroundButton && (this.core.mediaControl.$el.find('[data-playstop]').length > 0 || this.core.mediaControl.$el.find('[data-playpause]').length > 0);
},
click: function() {
this.core.mediaControl.show();
if (this.shouldStop) {
this.core.mediaControl.togglePlayStop();
} else {
this.core.mediaControl.togglePlayPause();
}
},
show: function() {
this.$el.removeClass('hide');
},
hide: function() {
this.$el.addClass('hide');
},
enable: function() {
this.stopListening();
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "enable", []);
this.settingsUpdate();
},
disable: function() {
$traceurRuntime.superCall(this, $BackgroundButton.prototype, "disable", []);
this.$playPauseButton.show();
this.$playStopButton.show();
},
playing: function() {
this.$buttonIcon.removeClass('notplaying').addClass('playing');
},
notplaying: function() {
this.$buttonIcon.removeClass('playing').addClass('notplaying');
},
getExternalInterface: function() {},
updateSize: function() {
if (!this.$el)
return;
var height = PlayerInfo.currentSize ? PlayerInfo.currentSize.height : this.$el.height();
this.$el.css({fontSize: height});
this.$buttonWrapper.css({marginTop: -(this.$buttonWrapper.height() / 2)});
},
render: function() {
var $__0 = this;
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
this.$playPauseButton = this.core.mediaControl.$el.find('[data-playpause]');
this.$playStopButton = this.core.mediaControl.$el.find('[data-playstop]');
this.$buttonWrapper = this.$el.find('.background-button-wrapper[data-background-button]');
this.$buttonIcon = this.$el.find('.background-button-icon[data-background-button]');
this.shouldStop = this.$playStopButton.length > 0;
this.$el.insertBefore(this.core.mediaControl.$el.find('.media-control-layer[data-controls]'));
this.$el.click((function() {
return $__0.click($__0.$el);
}));
process.nextTick((function() {
return $__0.updateSize();
}));
if (this.core.options.useBackgroundButton) {
this.$playPauseButton.hide();
this.$playStopButton.hide();
}
if (this.shouldStop) {
this.$buttonIcon.addClass('playstop');
}
if (this.core.mediaControl.isVisible()) {
this.show();
}
return this;
}
}, {}, UICorePlugin);
module.exports = BackgroundButton;
}).call(this,require('_process'))
},{"../../base/jst":7,"../../base/styler":8,"_process":2,"browser":"browser","events":"events","mediator":"mediator","player_info":"player_info","ui_core_plugin":"ui_core_plugin"}],32:[function(require,module,exports){
"use strict";
module.exports = require('./background_button');
},{"./background_button":31}],33:[function(require,module,exports){
"use strict";
var ContainerPlugin = require('container_plugin');
var Events = require('events');
var ClickToPausePlugin = function ClickToPausePlugin() {
$traceurRuntime.defaultSuperCall(this, $ClickToPausePlugin.prototype, arguments);
};
var $ClickToPausePlugin = ClickToPausePlugin;
($traceurRuntime.createClass)(ClickToPausePlugin, {
get name() {
return 'click_to_pause';
},
bindEvents: function() {
this.listenTo(this.container, Events.CONTAINER_CLICK, this.click);
this.listenTo(this.container, Events.CONTAINER_SETTINGSUPDATE, this.settingsUpdate);
},
click: function() {
if (this.container.getPlaybackType() !== 'live' || this.container.isDvrEnabled()) {
if (this.container.isPlaying()) {
this.container.pause();
} else {
this.container.play();
}
}
},
settingsUpdate: function() {
this.container.$el.removeClass('pointer-enabled');
if (this.container.getPlaybackType() !== 'live' || this.container.isDvrEnabled()) {
this.container.$el.addClass('pointer-enabled');
}
}
}, {}, ContainerPlugin);
module.exports = ClickToPausePlugin;
},{"container_plugin":"container_plugin","events":"events"}],34:[function(require,module,exports){
"use strict";
module.exports = require('./click_to_pause');
},{"./click_to_pause":33}],35:[function(require,module,exports){
"use strict";
var UICorePlugin = require('ui_core_plugin');
var JST = require('../../base/jst');
var Styler = require('../../base/styler');
var Events = require('events');
var DVRControls = function DVRControls(core) {
$traceurRuntime.superCall(this, $DVRControls.prototype, "constructor", [core]);
this.core = core;
this.settingsUpdate();
};
var $DVRControls = DVRControls;
($traceurRuntime.createClass)(DVRControls, {
get template() {
return JST.dvr_controls;
},
get name() {
return 'dvr_controls';
},
get events() {
return {'click .live-button': 'click'};
},
get attributes() {
return {
'class': 'dvr-controls',
'data-dvr-controls': ''
};
},
bindEvents: function() {
this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_RENDERED, this.settingsUpdate);
this.listenTo(this.core.mediaControl.container, Events.CONTAINER_PLAYBACKDVRSTATECHANGED, this.dvrChanged);
},
dvrChanged: function(dvrEnabled) {
this.settingsUpdate();
this.core.mediaControl.$el.addClass('live');
if (dvrEnabled) {
this.core.mediaControl.$el.addClass('dvr');
this.core.mediaControl.$el.find('.media-control-indicator[data-position], .media-control-indicator[data-duration]').hide();
} else {
this.core.mediaControl.$el.removeClass('dvr');
}
},
click: function() {
if (!this.core.mediaControl.container.isPlaying()) {
this.core.mediaControl.container.play();
}
if (this.core.mediaControl.$el.hasClass('dvr')) {
this.core.mediaControl.container.setCurrentTime(-1);
}
},
settingsUpdate: function() {
var $__0 = this;
this.stopListening();
if (this.shouldRender()) {
this.render();
this.$el.click((function() {
return $__0.click();
}));
}
this.bindEvents();
},
shouldRender: function() {
var useDvrControls = this.core.options.useDvrControls === undefined || !!this.core.options.useDvrControls;
return useDvrControls && this.core.mediaControl.container.getPlaybackType() === 'live';
},
render: function() {
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
if (this.shouldRender()) {
this.core.mediaControl.$el.addClass('live');
this.core.mediaControl.$('.media-control-left-panel[data-media-control]').append(this.$el);
if (this.$duration) {
this.$duration.remove();
}
this.$duration = $('<span data-duration></span>');
this.core.mediaControl.seekTime.$el.append(this.$duration);
}
return this;
}
}, {}, UICorePlugin);
module.exports = DVRControls;
},{"../../base/jst":7,"../../base/styler":8,"events":"events","ui_core_plugin":"ui_core_plugin"}],36:[function(require,module,exports){
"use strict";
module.exports = require('./dvr_controls');
},{"./dvr_controls":35}],37:[function(require,module,exports){
"use strict";
var ContainerPlugin = require('container_plugin');
var Events = require('events');
var GoogleAnalytics = function GoogleAnalytics(options) {
$traceurRuntime.superCall(this, $GoogleAnalytics.prototype, "constructor", [options]);
if (options.gaAccount) {
this.embedScript();
this.account = options.gaAccount;
this.trackerName = options.gaTrackerName + "." || 'Clappr.';
this.currentHDState = undefined;
}
};
var $GoogleAnalytics = GoogleAnalytics;
($traceurRuntime.createClass)(GoogleAnalytics, {
get name() {
return 'google_analytics';
},
embedScript: function() {
var $__0 = this;
if (!window._gat) {
var script = document.createElement('script');
script.setAttribute("type", "text/javascript");
script.setAttribute("async", "async");
script.setAttribute("src", "http://www.google-analytics.com/ga.js");
script.onload = (function() {
return $__0.addEventListeners();
});
document.body.appendChild(script);
} else {
this.addEventListeners();
}
},
addEventListeners: function() {
var $__0 = this;
this.listenTo(this.container, Events.CONTAINER_PLAY, this.onPlay);
this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop);
this.listenTo(this.container, Events.CONTAINER_PAUSE, this.onPause);
this.listenTo(this.container, Events.CONTAINER_ENDED, this.onEnded);
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering);
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferFull);
this.listenTo(this.container, Events.CONTAINER_ENDED, this.onEnded);
this.listenTo(this.container, Events.CONTAINER_ERROR, this.onError);
this.listenTo(this.container, Events.CONTAINER_PLAYBACKSTATE, this.onPlaybackChanged);
this.listenTo(this.container, Events.CONTAINER_VOLUME, (function(event) {
return $__0.onVolumeChanged(event);
}));
this.listenTo(this.container, Events.CONTAINER_SEEK, (function(event) {
return $__0.onSeek(event);
}));
this.listenTo(this.container, Events.CONTAINER_FULL_SCREEN, this.onFullscreen);
this.listenTo(this.container, Events.CONTAINER_HIGHDEFINITIONUPDATE, this.onHD);
this.listenTo(this.container.playback, Events.PLAYBACK_DVR, this.onDVR);
_gaq.push([this.trackerName + '_setAccount', this.account]);
},
onPlay: function() {
this.push(["Video", "Play", this.container.playback.src]);
},
onStop: function() {
this.push(["Video", "Stop", this.container.playback.src]);
},
onEnded: function() {
this.push(["Video", "Ended", this.container.playback.src]);
},
onBuffering: function() {
this.push(["Video", "Buffering", this.container.playback.src]);
},
onBufferFull: function() {
this.push(["Video", "Bufferfull", this.container.playback.src]);
},
onError: function() {
this.push(["Video", "Error", this.container.playback.src]);
},
onHD: function() {
var status = this.container.isHighDefinitionInUse() ? "ON" : "OFF";
if (status !== this.currentHDState) {
this.currentHDState = status;
this.push(["Video", "HD - " + status, this.container.playback.src]);
}
},
onPlaybackChanged: function() {
var type = this.container.getPlaybackType();
if (type !== null) {
this.push(["Video", "Playback Type - " + type, this.container.playback.src]);
}
},
onDVR: function() {
var status = this.container.isHighDefinitionInUse();
this.push(["Interaction", "DVR - " + status, this.container.playback.src]);
},
onPause: function() {
this.push(["Video", "Pause", this.container.playback.src]);
},
onSeek: function() {
this.push(["Video", "Seek", this.container.playback.src]);
},
onVolumeChanged: function() {
this.push(["Interaction", "Volume", this.container.playback.src]);
},
onFullscreen: function() {
this.push(["Interaction", "Fullscreen", this.container.playback.src]);
},
push: function(array) {
var res = [this.trackerName + "_trackEvent"].concat(array);
_gaq.push(res);
}
}, {}, ContainerPlugin);
module.exports = GoogleAnalytics;
},{"container_plugin":"container_plugin","events":"events"}],38:[function(require,module,exports){
"use strict";
module.exports = require('./google_analytics');
},{"./google_analytics":37}],39:[function(require,module,exports){
"use strict";
module.exports = require('./log');
},{"./log":40}],40:[function(require,module,exports){
"use strict";
var Mousetrap = require('mousetrap');
var _ = require('underscore');
var Log = function Log() {
var $__0 = this;
Mousetrap.bind(['ctrl+shift+d'], (function() {
return $__0.onOff();
}));
this.BLACKLIST = ['playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress'];
};
($traceurRuntime.createClass)(Log, {
info: function(klass, message) {
this.log(klass, 'info', message);
},
warn: function(klass, message) {
this.log(klass, 'warn', message);
},
debug: function(klass, message) {
this.log(klass, 'debug', message);
},
onOff: function() {
window.DEBUG = !window.DEBUG;
if (window.DEBUG) {
console.log('log enabled');
} else {
console.log('log disabled');
}
},
log: function(klass, level, message) {
if (!window.DEBUG || _.contains(this.BLACKLIST, message))
return;
var color;
if (level === 'warn') {
color = '#FF8000';
} else if (level === 'info') {
color = '#006600';
} else if (level === 'error') {
color = '#FF0000';
}
console.log("%c [" + klass + "] [" + level + "] " + message, 'color: ' + color);
}
}, {});
Log.getInstance = function() {
if (this._instance === undefined) {
this._instance = new this();
}
return this._instance;
};
module.exports = Log;
},{"mousetrap":4,"underscore":"underscore"}],41:[function(require,module,exports){
(function (process){
"use strict";
var UIContainerPlugin = require('ui_container_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Events = require('events');
var Mediator = require('mediator');
var PlayerInfo = require('player_info');
var $ = require('zepto');
var _ = require('underscore');
var PosterPlugin = function PosterPlugin(options) {
$traceurRuntime.superCall(this, $PosterPlugin.prototype, "constructor", [options]);
this.options = options;
_.defaults(this.options, {disableControlsOnPoster: true});
if (this.options.disableControlsOnPoster) {
this.container.disableMediaControl();
}
this.render();
};
var $PosterPlugin = PosterPlugin;
($traceurRuntime.createClass)(PosterPlugin, {
get name() {
return 'poster';
},
get template() {
return JST.poster;
},
get attributes() {
return {
'class': 'player-poster',
'data-poster': ''
};
},
get events() {
return {'click': 'clicked'};
},
bindEvents: function() {
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering);
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferfull);
this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop);
this.listenTo(this.container, Events.CONTAINER_ENDED, this.onStop);
Mediator.on(Events.PLAYER_RESIZE, this.updateSize, this);
},
stopListening: function() {
$traceurRuntime.superCall(this, $PosterPlugin.prototype, "stopListening", []);
Mediator.off(Events.PLAYER_RESIZE, this.updateSize, this);
},
onBuffering: function() {
this.hidePlayButton();
},
onBufferfull: function() {
this.$el.hide();
if (this.options.disableControlsOnPoster) {
this.container.enableMediaControl();
}
},
onStop: function() {
this.$el.show();
if (this.options.disableControlsOnPoster) {
this.container.disableMediaControl();
}
if (!this.options.hidePlayButton) {
this.showPlayButton();
}
},
hidePlayButton: function() {
this.$playButton.hide();
},
showPlayButton: function() {
this.$playButton.show();
this.updateSize();
},
clicked: function() {
this.container.play();
return false;
},
updateSize: function() {
if (!this.$el)
return;
var height = PlayerInfo.currentSize ? PlayerInfo.currentSize.height : this.$el.height();
this.$el.css({fontSize: height});
if (this.$playWrapper.is(':visible')) {
this.$playWrapper.css({marginTop: -(this.$playWrapper.height() / 2)});
if (!this.options.hidePlayButton) {
this.$playButton.show();
}
} else {
this.$playButton.hide();
}
},
render: function() {
var $__0 = this;
var style = Styler.getStyleFor(this.name);
this.$el.html(this.template());
this.$el.append(style);
this.$playButton = this.$el.find('.poster-icon');
this.$playWrapper = this.$el.find('.play-wrapper');
if (this.options.poster !== undefined) {
var imgEl = $('<img data-poster class="poster-background"></img>');
imgEl.attr('src', this.options.poster);
this.$el.prepend(imgEl);
}
this.container.$el.append(this.el);
if (!!this.options.hidePlayButton) {
this.hidePlayButton();
}
process.nextTick((function() {
return $__0.updateSize();
}));
return this;
}
}, {}, UIContainerPlugin);
module.exports = PosterPlugin;
}).call(this,require('_process'))
},{"../../base/jst":7,"../../base/styler":8,"_process":2,"events":"events","mediator":"mediator","player_info":"player_info","ui_container_plugin":"ui_container_plugin","underscore":"underscore","zepto":"zepto"}],42:[function(require,module,exports){
"use strict";
module.exports = require('./spinner_three_bounce');
},{"./spinner_three_bounce":43}],43:[function(require,module,exports){
"use strict";
var UIContainerPlugin = require('ui_container_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Events = require('events');
var SpinnerThreeBouncePlugin = function SpinnerThreeBouncePlugin(options) {
$traceurRuntime.superCall(this, $SpinnerThreeBouncePlugin.prototype, "constructor", [options]);
this.template = JST.spinner_three_bounce;
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering);
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferFull);
this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop);
this.render();
};
var $SpinnerThreeBouncePlugin = SpinnerThreeBouncePlugin;
($traceurRuntime.createClass)(SpinnerThreeBouncePlugin, {
get name() {
return 'spinner';
},
get attributes() {
return {
'data-spinner': '',
'class': 'spinner-three-bounce'
};
},
onBuffering: function() {
this.$el.show();
},
onBufferFull: function() {
this.$el.hide();
},
onStop: function() {
this.$el.hide();
},
render: function() {
this.$el.html(this.template());
var style = Styler.getStyleFor('spinner_three_bounce');
this.container.$el.append(style);
this.container.$el.append(this.$el);
this.$el.hide();
return this;
}
}, {}, UIContainerPlugin);
module.exports = SpinnerThreeBouncePlugin;
},{"../../base/jst":7,"../../base/styler":8,"events":"events","ui_container_plugin":"ui_container_plugin"}],44:[function(require,module,exports){
"use strict";
module.exports = require('./stats');
},{"./stats":45}],45:[function(require,module,exports){
"use strict";
var ContainerPlugin = require('container_plugin');
var $ = require("zepto");
var Events = require('events');
var StatsPlugin = function StatsPlugin(options) {
$traceurRuntime.superCall(this, $StatsPlugin.prototype, "constructor", [options]);
this.setInitialAttrs();
this.reportInterval = options.reportInterval || 5000;
this.state = "IDLE";
};
var $StatsPlugin = StatsPlugin;
($traceurRuntime.createClass)(StatsPlugin, {
get name() {
return 'stats';
},
bindEvents: function() {
this.listenTo(this.container.playback, Events.PLAYBACK_PLAY, this.onPlay);
this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop);
this.listenTo(this.container, Events.CONTAINER_DESTROYED, this.onStop);
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERING, this.onBuffering);
this.listenTo(this.container, Events.CONTAINER_STATE_BUFFERFULL, this.onBufferFull);
this.listenTo(this.container, Events.CONTAINER_STATS_ADD, this.onStatsAdd);
this.listenTo(this.container, Events.CONTAINER_BITRATE, this.onStatsAdd);
this.listenTo(this.container.playback, Events.PLAYBACK_STATS_ADD, this.onStatsAdd);
},
setInitialAttrs: function() {
this.firstPlay = true;
this.startupTime = 0;
this.rebufferingTime = 0;
this.watchingTime = 0;
this.rebuffers = 0;
this.externalMetrics = {};
},
onPlay: function() {
this.state = "PLAYING";
this.watchingTimeInit = Date.now();
if (!this.intervalId) {
this.intervalId = setInterval(this.report.bind(this), this.reportInterval);
}
},
onStop: function() {
clearInterval(this.intervalId);
this.intervalId = undefined;
this.state = "STOPPED";
},
onBuffering: function() {
if (this.firstPlay) {
this.startupTimeInit = Date.now();
} else {
this.rebufferingTimeInit = Date.now();
}
this.state = "BUFFERING";
this.rebuffers++;
},
onBufferFull: function() {
if (this.firstPlay && !!this.startupTimeInit) {
this.firstPlay = false;
this.startupTime = Date.now() - this.startupTimeInit;
this.watchingTimeInit = Date.now();
} else if (!!this.rebufferingTimeInit) {
this.rebufferingTime += this.getRebufferingTime();
}
this.rebufferingTimeInit = undefined;
this.state = "PLAYING";
},
getRebufferingTime: function() {
return Date.now() - this.rebufferingTimeInit;
},
getWatchingTime: function() {
var totalTime = (Date.now() - this.watchingTimeInit);
return totalTime - this.rebufferingTime;
},
isRebuffering: function() {
return !!this.rebufferingTimeInit;
},
onStatsAdd: function(metric) {
$.extend(this.externalMetrics, metric);
},
getStats: function() {
var metrics = {
startupTime: this.startupTime,
rebuffers: this.rebuffers,
rebufferingTime: this.isRebuffering() ? this.rebufferingTime + this.getRebufferingTime() : this.rebufferingTime,
watchingTime: this.isRebuffering() ? this.getWatchingTime() - this.getRebufferingTime() : this.getWatchingTime()
};
$.extend(metrics, this.externalMetrics);
return metrics;
},
report: function() {
this.container.statsReport(this.getStats());
}
}, {}, ContainerPlugin);
module.exports = StatsPlugin;
},{"container_plugin":"container_plugin","events":"events","zepto":"zepto"}],46:[function(require,module,exports){
"use strict";
module.exports = require('./watermark');
},{"./watermark":47}],47:[function(require,module,exports){
"use strict";
var UIContainerPlugin = require('ui_container_plugin');
var Styler = require('../../base/styler');
var JST = require('../../base/jst');
var Events = require('events');
var WaterMarkPlugin = function WaterMarkPlugin(options) {
$traceurRuntime.superCall(this, $WaterMarkPlugin.prototype, "constructor", [options]);
this.template = JST[this.name];
this.position = options.position || "bottom-right";
if (options.watermark) {
this.imageUrl = options.watermark;
this.render();
} else {
this.$el.remove();
}
};
var $WaterMarkPlugin = WaterMarkPlugin;
($traceurRuntime.createClass)(WaterMarkPlugin, {
get name() {
return 'watermark';
},
bindEvents: function() {
this.listenTo(this.container, Events.CONTAINER_PLAY, this.onPlay);
this.listenTo(this.container, Events.CONTAINER_STOP, this.onStop);
},
onPlay: function() {
if (!this.hidden)
this.$el.show();
},
onStop: function() {
this.$el.hide();
},
render: function() {
this.$el.hide();
var templateOptions = {
position: this.position,
imageUrl: this.imageUrl
};
this.$el.html(this.template(templateOptions));
var style = Styler.getStyleFor(this.name);
this.container.$el.append(style);
this.container.$el.append(this.$el);
return this;
}
}, {}, UIContainerPlugin);
module.exports = WaterMarkPlugin;
},{"../../base/jst":7,"../../base/styler":8,"events":"events","ui_container_plugin":"ui_container_plugin"}],"base_object":[function(require,module,exports){
"use strict";
var _ = require('underscore');
var extend = require('./utils').extend;
var Events = require('events');
var pluginOptions = ['container'];
var BaseObject = function BaseObject(options) {
this.uniqueId = _.uniqueId('o');
options || (options = {});
_.extend(this, _.pick(options, pluginOptions));
};
($traceurRuntime.createClass)(BaseObject, {}, {}, Events);
BaseObject.extend = extend;
module.exports = BaseObject;
},{"./utils":9,"events":"events","underscore":"underscore"}],"browser":[function(require,module,exports){
"use strict";
var Browser = function Browser() {};
($traceurRuntime.createClass)(Browser, {}, {});
Browser.isSafari = (!!navigator.userAgent.match(/safari/i) && navigator.userAgent.indexOf('Chrome') === -1);
Browser.isChrome = !!(navigator.userAgent.match(/chrome/i));
Browser.isFirefox = !!(navigator.userAgent.match(/firefox/i));
Browser.isLegacyIE = !!(window.ActiveXObject);
Browser.isIE = Browser.isLegacyIE || !!(navigator.userAgent.match(/trident.*rv:1\d/i));
Browser.isIE11 = !!(navigator.userAgent.match(/trident.*rv:11/i));
Browser.isMobile = !!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone|IEMobile|Opera Mini/i.test(navigator.userAgent));
Browser.isWin8App = !!(/MSAppHost/i.test(navigator.userAgent));
Browser.isWiiU = !!(/WiiU/i.test(navigator.userAgent));
Browser.isPS4 = !!(/PlayStation 4/i.test(navigator.userAgent));
module.exports = Browser;
},{}],"container_plugin":[function(require,module,exports){
"use strict";
var BaseObject = require('base_object');
var ContainerPlugin = function ContainerPlugin(options) {
$traceurRuntime.superCall(this, $ContainerPlugin.prototype, "constructor", [options]);
this.bindEvents();
};
var $ContainerPlugin = ContainerPlugin;
($traceurRuntime.createClass)(ContainerPlugin, {
enable: function() {
this.bindEvents();
},
disable: function() {
this.stopListening();
},
bindEvents: function() {},
destroy: function() {
this.stopListening();
}
}, {}, BaseObject);
module.exports = ContainerPlugin;
},{"base_object":"base_object"}],"container":[function(require,module,exports){
"use strict";
module.exports = require('./container');
},{"./container":10}],"core_plugin":[function(require,module,exports){
"use strict";
var BaseObject = require('base_object');
var CorePlugin = function CorePlugin(core) {
$traceurRuntime.superCall(this, $CorePlugin.prototype, "constructor", [core]);
this.core = core;
};
var $CorePlugin = CorePlugin;
($traceurRuntime.createClass)(CorePlugin, {
getExternalInterface: function() {
return {};
},
destroy: function() {}
}, {}, BaseObject);
module.exports = CorePlugin;
},{"base_object":"base_object"}],"core":[function(require,module,exports){
"use strict";
module.exports = require('./core');
},{"./core":13}],"events":[function(require,module,exports){
"use strict";
var _ = require('underscore');
var Log = require('../plugins/log').getInstance();
var slice = Array.prototype.slice;
var Events = function Events() {};
($traceurRuntime.createClass)(Events, {
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback)
return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({
callback: callback,
context: context,
ctx: context || this
});
return this;
},
once: function(name, callback, context) {
if (!eventsApi(this, 'once', name, [callback, context]) || !callback)
return this;
var self = this;
var once = _.once(function() {
self.off(name, once);
callback.apply(this, arguments);
});
once._callback = callback;
return this.on(name, once, context);
},
off: function(name, callback, context) {
var retain,
ev,
events,
names,
i,
l,
j,
k;
if (!this._events || !eventsApi(this, 'off', name, [callback, context]))
return this;
if (!name && !callback && !context) {
this._events = void 0;
return this;
}
names = name ? [name] : _.keys(this._events);
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
events = this._events[name];
if (events) {
this._events[name] = retain = [];
if (callback || context) {
for (j = 0, k = events.length; j < k; j++) {
ev = events[j];
if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) {
retain.push(ev);
}
}
}
if (!retain.length)
delete this._events[name];
}
}
return this;
},
trigger: function(name) {
var klass = arguments[arguments.length - 1];
Log.info(klass, name);
if (!this._events)
return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args))
return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events)
triggerEvents(events, args);
if (allEvents)
triggerEvents(allEvents, arguments);
return this;
},
stopListening: function(obj, name, callback) {
var listeningTo = this._listeningTo;
if (!listeningTo)
return this;
var remove = !name && !callback;
if (!callback && typeof name === 'object')
callback = this;
if (obj)
(listeningTo = {})[obj._listenId] = obj;
for (var id in listeningTo) {
obj = listeningTo[id];
obj.off(name, callback, this);
if (remove || _.isEmpty(obj._events))
delete this._listeningTo[id];
}
return this;
}
}, {});
var eventSplitter = /\s+/;
var eventsApi = function(obj, action, name, rest) {
if (!name)
return true;
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
return false;
}
if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0,
l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
return false;
}
return true;
};
var triggerEvents = function(events, args) {
var ev,
i = -1,
l = events.length,
a1 = args[0],
a2 = args[1],
a3 = args[2];
switch (args.length) {
case 0:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx);
return;
case 1:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, a1);
return;
case 2:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, a1, a2);
return;
case 3:
while (++i < l)
(ev = events[i]).callback.call(ev.ctx, a1, a2, a3);
return;
default:
while (++i < l)
(ev = events[i]).callback.apply(ev.ctx, args);
return;
}
};
var listenMethods = {
listenTo: 'on',
listenToOnce: 'once'
};
_.each(listenMethods, function(implementation, method) {
Events.prototype[method] = function(obj, name, callback) {
var listeningTo = this._listeningTo || (this._listeningTo = {});
var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
listeningTo[id] = obj;
if (!callback && typeof name === 'object')
callback = this;
obj[implementation](name, callback, this);
return this;
};
});
Events.PLAYER_RESIZE = 'player:resize';
Events.PLAYBACK_PROGRESS = 'playback:progress';
Events.PLAYBACK_TIMEUPDATE = 'playback:timeupdate';
Events.PLAYBACK_READY = 'playback:ready';
Events.PLAYBACK_BUFFERING = 'playback:buffering';
Events.PLAYBACK_BUFFERFULL = 'playback:bufferfull';
Events.PLAYBACK_SETTINGSUPDATE = 'playback:settingsupdate';
Events.PLAYBACK_LOADEDMETADATA = 'playback:loadedmetadata';
Events.PLAYBACK_HIGHDEFINITIONUPDATE = 'playback:highdefinitionupdate';
Events.PLAYBACK_BITRATE = 'playback:bitrate';
Events.PLAYBACK_PLAYBACKSTATE = 'playback:playbackstate';
Events.PLAYBACK_DVR = 'playback:dvr';
Events.PLAYBACK_MEDIACONTROL_DISABLE = 'playback:mediacontrol:disable';
Events.PLAYBACK_MEDIACONTROL_ENABLE = 'playback:mediacontrol:enable';
Events.PLAYBACK_ENDED = 'playback:ended';
Events.PLAYBACK_PLAY = 'playback:play';
Events.PLAYBACK_ERROR = 'playback:error';
Events.PLAYBACK_STATS_ADD = 'playback:stats:add';
Events.CONTAINER_PLAYBACKSTATE = 'container:playbackstate';
Events.CONTAINER_PLAYBACKDVRSTATECHANGED = 'container:dvr';
Events.CONTAINER_BITRATE = 'container:bitrate';
Events.CONTAINER_STATS_REPORT = 'container:stats:report';
Events.CONTAINER_DESTROYED = 'container:destroyed';
Events.CONTAINER_READY = 'container:ready';
Events.CONTAINER_ERROR = 'container:error';
Events.CONTAINER_LOADEDMETADATA = 'container:loadedmetadata';
Events.CONTAINER_TIMEUPDATE = 'container:timeupdate';
Events.CONTAINER_PROGRESS = 'container:progress';
Events.CONTAINER_PLAY = 'container:play';
Events.CONTAINER_STOP = 'container:stop';
Events.CONTAINER_PAUSE = 'container:pause';
Events.CONTAINER_ENDED = 'container:ended';
Events.CONTAINER_CLICK = 'container:click';
Events.CONTAINER_SEEK = 'container:seek';
Events.CONTAINER_VOLUME = 'container:volume';
Events.CONTAINER_FULLSCREEN = 'container:fullscreen';
Events.CONTAINER_STATE_BUFFERING = 'container:state:buffering';
Events.CONTAINER_STATE_BUFFERFULL = 'container:state:bufferfull';
Events.CONTAINER_SETTINGSUPDATE = 'container:settingsupdate';
Events.CONTAINER_HIGHDEFINITIONUPDATE = 'container:highdefinitionupdate';
Events.CONTAINER_MEDIACONTROL_DISABLE = 'container:mediacontrol:disable';
Events.CONTAINER_MEDIACONTROL_ENABLE = 'container:mediacontrol:enable';
Events.CONTAINER_STATS_ADD = 'container:stats:add';
Events.MEDIACONTROL_RENDERED = 'mediacontrol:rendered';
Events.MEDIACONTROL_FULLSCREEN = 'mediacontrol:fullscreen';
Events.MEDIACONTROL_SHOW = 'mediacontrol:show';
Events.MEDIACONTROL_HIDE = 'mediacontrol:hide';
Events.MEDIACONTROL_MOUSEMOVE_SEEKBAR = 'mediacontrol:mousemove:seekbar';
Events.MEDIACONTROL_MOUSELEAVE_SEEKBAR = 'mediacontrol:mouseleave:seekbar';
Events.MEDIACONTROL_PLAYING = 'mediacontrol:playing';
Events.MEDIACONTROL_NOTPLAYING = 'mediacontrol:notplaying';
Events.MEDIACONTROL_CONTAINERCHANGED = 'mediacontrol:containerchanged';
module.exports = Events;
},{"../plugins/log":39,"underscore":"underscore"}],"flash":[function(require,module,exports){
"use strict";
module.exports = require('./flash');
},{"./flash":24}],"hls":[function(require,module,exports){
"use strict";
module.exports = require('./hls');
},{"./hls":25}],"html5_audio":[function(require,module,exports){
"use strict";
module.exports = require('./html5_audio');
},{"./html5_audio":26}],"html5_video":[function(require,module,exports){
"use strict";
module.exports = require('./html5_video');
},{"./html5_video":27}],"html_img":[function(require,module,exports){
"use strict";
module.exports = require('./html_img');
},{"./html_img":28}],"media_control":[function(require,module,exports){
"use strict";
module.exports = require('./media_control');
},{"./media_control":20}],"mediator":[function(require,module,exports){
"use strict";
var Events = require('events');
var events = new Events();
var Mediator = function Mediator() {};
($traceurRuntime.createClass)(Mediator, {}, {});
Mediator.on = function(name, callback, context) {
events.on(name, callback, context);
return;
};
Mediator.once = function(name, callback, context) {
events.once(name, callback, context);
return;
};
Mediator.off = function(name, callback, context) {
events.off(name, callback, context);
return;
};
Mediator.trigger = function(name, opts) {
events.trigger(name, opts);
return;
};
Mediator.stopListening = function(obj, name, callback) {
events.stopListening(obj, name, callback);
return;
};
module.exports = Mediator;
},{"events":"events"}],"playback":[function(require,module,exports){
"use strict";
var UIObject = require('ui_object');
var Playback = function Playback(options) {
$traceurRuntime.superCall(this, $Playback.prototype, "constructor", [options]);
this.settings = {};
};
var $Playback = Playback;
($traceurRuntime.createClass)(Playback, {
play: function() {},
pause: function() {},
stop: function() {},
seek: function(time) {},
getDuration: function() {
return 0;
},
isPlaying: function() {
return false;
},
getPlaybackType: function() {
return 'no_op';
},
isHighDefinitionInUse: function() {
return false;
},
volume: function(value) {},
destroy: function() {
this.$el.remove();
}
}, {}, UIObject);
Playback.canPlay = (function(source) {
return false;
});
module.exports = Playback;
},{"ui_object":"ui_object"}],"player_info":[function(require,module,exports){
"use strict";
var PlayerInfo = {
options: {},
playbackPlugins: [],
currentSize: {
width: 0,
height: 0
}
};
module.exports = PlayerInfo;
},{}],"poster":[function(require,module,exports){
"use strict";
module.exports = require('./poster');
},{"./poster":41}],"ui_container_plugin":[function(require,module,exports){
"use strict";
var UIObject = require('ui_object');
var UIContainerPlugin = function UIContainerPlugin(options) {
$traceurRuntime.superCall(this, $UIContainerPlugin.prototype, "constructor", [options]);
this.enabled = true;
this.bindEvents();
};
var $UIContainerPlugin = UIContainerPlugin;
($traceurRuntime.createClass)(UIContainerPlugin, {
enable: function() {
this.bindEvents();
this.$el.show();
this.enabled = true;
},
disable: function() {
this.stopListening();
this.$el.hide();
this.enabled = false;
},
bindEvents: function() {},
destroy: function() {
this.remove();
}
}, {}, UIObject);
module.exports = UIContainerPlugin;
},{"ui_object":"ui_object"}],"ui_core_plugin":[function(require,module,exports){
"use strict";
var UIObject = require('ui_object');
var UICorePlugin = function UICorePlugin(core) {
$traceurRuntime.superCall(this, $UICorePlugin.prototype, "constructor", [core]);
this.core = core;
this.enabled = true;
this.bindEvents();
this.render();
};
var $UICorePlugin = UICorePlugin;
($traceurRuntime.createClass)(UICorePlugin, {
bindEvents: function() {},
getExternalInterface: function() {
return {};
},
enable: function() {
this.bindEvents();
this.$el.show();
this.enabled = true;
},
disable: function() {
this.stopListening();
this.$el.hide();
this.enabled = false;
},
destroy: function() {
this.remove();
},
render: function() {
this.$el.html(this.template());
this.$el.append(this.styler.getStyleFor(this.name));
this.core.$el.append(this.el);
return this;
}
}, {}, UIObject);
module.exports = UICorePlugin;
},{"ui_object":"ui_object"}],"ui_object":[function(require,module,exports){
"use strict";
var $ = require('zepto');
var _ = require('underscore');
var extend = require('./utils').extend;
var BaseObject = require('base_object');
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
var UIObject = function UIObject(options) {
$traceurRuntime.superCall(this, $UIObject.prototype, "constructor", [options]);
this.cid = _.uniqueId('c');
this._ensureElement();
this.delegateEvents();
};
var $UIObject = UIObject;
($traceurRuntime.createClass)(UIObject, {
get tagName() {
return 'div';
},
$: function(selector) {
return this.$el.find(selector);
},
render: function() {
return this;
},
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
setElement: function(element, delegate) {
if (this.$el)
this.undelegateEvents();
this.$el = element instanceof $ ? element : $(element);
this.el = this.$el[0];
if (delegate !== false)
this.delegateEvents();
return this;
},
delegateEvents: function(events) {
if (!(events || (events = _.result(this, 'events'))))
return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method))
method = this[events[key]];
if (!method)
continue;
var match = key.match(delegateEventSplitter);
var eventName = match[1],
selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.on(eventName, method);
} else {
this.$el.on(eventName, selector, method);
}
}
return this;
},
undelegateEvents: function() {
this.$el.off('.delegateEvents' + this.cid);
return this;
},
_ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id)
attrs.id = _.result(this, 'id');
if (this.className)
attrs['class'] = _.result(this, 'className');
var $el = $('<' + _.result(this, 'tagName') + '>').attr(attrs);
this.setElement($el, false);
} else {
this.setElement(_.result(this, 'el'), false);
}
}
}, {}, BaseObject);
UIObject.extend = extend;
module.exports = UIObject;
},{"./utils":9,"base_object":"base_object","underscore":"underscore","zepto":"zepto"}],"underscore":[function(require,module,exports){
// Underscore.js 1.7.0
// http://underscorejs.org
// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var
push = ArrayProto.push,
slice = ArrayProto.slice,
concat = ArrayProto.concat,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.7.0';
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
var createCallback = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
case 2: return function(value, other) {
return func.call(context, value, other);
};
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
// A mostly-internal function to generate callbacks that can be applied
// to each element in a collection, returning the desired result — either
// identity, an arbitrary callback, a property matcher, or a property accessor.
_.iteratee = function(value, context, argCount) {
if (value == null) return _.identity;
if (_.isFunction(value)) return createCallback(value, context, argCount);
if (_.isObject(value)) return _.matches(value);
return _.property(value);
};
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles raw objects in addition to array-likes. Treats all
// sparse array-likes as if they were dense.
_.each = _.forEach = function(obj, iteratee, context) {
if (obj == null) return obj;
iteratee = createCallback(iteratee, context);
var i, length = obj.length;
if (length === +length) {
for (i = 0; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
// Return the results of applying the iteratee to each element.
_.map = _.collect = function(obj, iteratee, context) {
if (obj == null) return [];
iteratee = _.iteratee(iteratee, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
results = Array(length),
currentKey;
for (var index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
results[index] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
var reduceError = 'Reduce of empty array with no initial value';
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`.
_.reduce = _.foldl = _.inject = function(obj, iteratee, memo, context) {
if (obj == null) obj = [];
iteratee = createCallback(iteratee, context, 4);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index = 0, currentKey;
if (arguments.length < 3) {
if (!length) throw new TypeError(reduceError);
memo = obj[keys ? keys[index++] : index++];
}
for (; index < length; index++) {
currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
_.reduceRight = _.foldr = function(obj, iteratee, memo, context) {
if (obj == null) obj = [];
iteratee = createCallback(iteratee, context, 4);
var keys = obj.length !== + obj.length && _.keys(obj),
index = (keys || obj).length,
currentKey;
if (arguments.length < 3) {
if (!index) throw new TypeError(reduceError);
memo = obj[keys ? keys[--index] : --index];
}
while (index--) {
currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, predicate, context) {
var result;
predicate = _.iteratee(predicate, context);
_.some(obj, function(value, index, list) {
if (predicate(value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Aliased as `select`.
_.filter = _.select = function(obj, predicate, context) {
var results = [];
if (obj == null) return results;
predicate = _.iteratee(predicate, context);
_.each(obj, function(value, index, list) {
if (predicate(value, index, list)) results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, predicate, context) {
return _.filter(obj, _.negate(_.iteratee(predicate)), context);
};
// Determine whether all of the elements match a truth test.
// Aliased as `all`.
_.every = _.all = function(obj, predicate, context) {
if (obj == null) return true;
predicate = _.iteratee(predicate, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index, currentKey;
for (index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
if (!predicate(obj[currentKey], currentKey, obj)) return false;
}
return true;
};
// Determine if at least one element in the object matches a truth test.
// Aliased as `any`.
_.some = _.any = function(obj, predicate, context) {
if (obj == null) return false;
predicate = _.iteratee(predicate, context);
var keys = obj.length !== +obj.length && _.keys(obj),
length = (keys || obj).length,
index, currentKey;
for (index = 0; index < length; index++) {
currentKey = keys ? keys[index] : index;
if (predicate(obj[currentKey], currentKey, obj)) return true;
}
return false;
};
// Determine if the array or object contains a given value (using `===`).
// Aliased as `include`.
_.contains = _.include = function(obj, target) {
if (obj == null) return false;
if (obj.length !== +obj.length) obj = _.values(obj);
return _.indexOf(obj, target) >= 0;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
return (isFunc ? method : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, _.property(key));
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
return _.filter(obj, _.matches(attrs));
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.find(obj, _.matches(attrs));
};
// Return the maximum element (or element-based computation).
_.max = function(obj, iteratee, context) {
var result = -Infinity, lastComputed = -Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = obj.length === +obj.length ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value > result) {
result = value;
}
}
} else {
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iteratee, context) {
var result = Infinity, lastComputed = Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = obj.length === +obj.length ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value < result) {
result = value;
}
}
} else {
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed < lastComputed || computed === Infinity && result === Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Shuffle a collection, using the modern version of the
// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
_.shuffle = function(obj) {
var set = obj && obj.length === +obj.length ? obj : _.values(obj);
var length = set.length;
var shuffled = Array(length);
for (var index = 0, rand; index < length; index++) {
rand = _.random(0, index);
if (rand !== index) shuffled[index] = shuffled[rand];
shuffled[rand] = set[index];
}
return shuffled;
};
// Sample **n** random values from a collection.
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (n == null || guard) {
if (obj.length !== +obj.length) obj = _.values(obj);
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};
// Sort the object's values by a criterion produced by an iteratee.
_.sortBy = function(obj, iteratee, context) {
iteratee = _.iteratee(iteratee, context);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iteratee(value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(behavior) {
return function(obj, iteratee, context) {
var result = {};
iteratee = _.iteratee(iteratee, context);
_.each(obj, function(value, index) {
var key = iteratee(value, index, obj);
behavior(result, value, key);
});
return result;
};
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = group(function(result, value, key) {
if (_.has(result, key)) result[key].push(value); else result[key] = [value];
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
_.indexBy = group(function(result, value, key) {
result[key] = value;
});
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = group(function(result, value, key) {
if (_.has(result, key)) result[key]++; else result[key] = 1;
});
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iteratee, context) {
iteratee = _.iteratee(iteratee, context, 1);
var value = iteratee(obj);
var low = 0, high = array.length;
while (low < high) {
var mid = low + high >>> 1;
if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
}
return low;
};
// Safely create a real, live array from anything iterable.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (obj.length === +obj.length) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return obj.length === +obj.length ? obj.length : _.keys(obj).length;
};
// Split a collection into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
_.partition = function(obj, predicate, context) {
predicate = _.iteratee(predicate, context);
var pass = [], fail = [];
_.each(obj, function(value, key, obj) {
(predicate(value, key, obj) ? pass : fail).push(value);
});
return [pass, fail];
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[0];
if (n < 0) return [];
return slice.call(array, 0, n);
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[array.length - 1];
return slice.call(array, Math.max(array.length - n, 0));
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, n == null || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, strict, output) {
if (shallow && _.every(input, _.isArray)) {
return concat.apply(output, input);
}
for (var i = 0, length = input.length; i < length; i++) {
var value = input[i];
if (!_.isArray(value) && !_.isArguments(value)) {
if (!strict) output.push(value);
} else if (shallow) {
push.apply(output, value);
} else {
flatten(value, shallow, strict, output);
}
}
return output;
};
// Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, false, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iteratee, context) {
if (array == null) return [];
if (!_.isBoolean(isSorted)) {
context = iteratee;
iteratee = isSorted;
isSorted = false;
}
if (iteratee != null) iteratee = _.iteratee(iteratee, context);
var result = [];
var seen = [];
for (var i = 0, length = array.length; i < length; i++) {
var value = array[i];
if (isSorted) {
if (!i || seen !== value) result.push(value);
seen = value;
} else if (iteratee) {
var computed = iteratee(value, i, array);
if (_.indexOf(seen, computed) < 0) {
seen.push(computed);
result.push(value);
}
} else if (_.indexOf(result, value) < 0) {
result.push(value);
}
}
return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(flatten(arguments, true, true, []));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
if (array == null) return [];
var result = [];
var argsLength = arguments.length;
for (var i = 0, length = array.length; i < length; i++) {
var item = array[i];
if (_.contains(result, item)) continue;
for (var j = 1; j < argsLength; j++) {
if (!_.contains(arguments[j], item)) break;
}
if (j === argsLength) result.push(item);
}
return result;
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = flatten(slice.call(arguments, 1), true, true, []);
return _.filter(array, function(value){
return !_.contains(rest, value);
});
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function(array) {
if (array == null) return [];
var length = _.max(arguments, 'length').length;
var results = Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(arguments, i);
}
return results;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
if (list == null) return {};
var result = {};
for (var i = 0, length = list.length; i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// Return the position of the first occurrence of an item in an array,
// or -1 if the item is not included in the array.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, length = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted;
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
for (; i < length; i++) if (array[i] === item) return i;
return -1;
};
_.lastIndexOf = function(array, item, from) {
if (array == null) return -1;
var idx = array.length;
if (typeof from == 'number') {
idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1);
}
while (--idx >= 0) if (array[idx] === item) return idx;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = step || 1;
var length = Math.max(Math.ceil((stop - start) / step), 0);
var range = Array(length);
for (var idx = 0; idx < length; idx++, start += step) {
range[idx] = start;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Reusable constructor function for prototype setting.
var Ctor = function(){};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
var args, bound;
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
args = slice.call(arguments, 2);
bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
Ctor.prototype = func.prototype;
var self = new Ctor;
Ctor.prototype = null;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (_.isObject(result)) return result;
return self;
};
return bound;
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. _ acts
// as a placeholder, allowing any combination of arguments to be pre-filled.
_.partial = function(func) {
var boundArgs = slice.call(arguments, 1);
return function() {
var position = 0;
var args = boundArgs.slice();
for (var i = 0, length = args.length; i < length; i++) {
if (args[i] === _) args[i] = arguments[position++];
}
while (position < arguments.length) args.push(arguments[position++]);
return func.apply(this, args);
};
};
// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
_.bindAll = function(obj) {
var i, length = arguments.length, key;
if (length <= 1) throw new Error('bindAll must be passed function names');
for (i = 1; i < length; i++) {
key = arguments[i];
obj[key] = _.bind(obj[key], obj);
}
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memoize = function(key) {
var cache = memoize.cache;
var address = hasher ? hasher.apply(this, arguments) : key;
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
return cache[address];
};
memoize.cache = {};
return memoize;
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){
return func.apply(null, args);
}, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = _.now() - timestamp;
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return _.partial(wrapper, func);
};
// Returns a negated version of the passed-in predicate.
_.negate = function(predicate) {
return function() {
return !predicate.apply(this, arguments);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var args = arguments;
var start = args.length - 1;
return function() {
var i = start;
var result = args[start].apply(this, arguments);
while (i--) result = args[i].call(this, result);
return result;
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Returns a function that will only be executed before being called N times.
_.before = function(times, func) {
var memo;
return function() {
if (--times > 0) {
memo = func.apply(this, arguments);
} else {
func = null;
}
return memo;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = _.partial(_.before, 2);
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var values = Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var pairs = Array(length);
for (var i = 0; i < length; i++) {
pairs[i] = [keys[i], obj[keys[i]]];
}
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
if (!_.isObject(obj)) return obj;
var source, prop;
for (var i = 1, length = arguments.length; i < length; i++) {
source = arguments[i];
for (prop in source) {
if (hasOwnProperty.call(source, prop)) {
obj[prop] = source[prop];
}
}
}
return obj;
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj, iteratee, context) {
var result = {}, key;
if (obj == null) return result;
if (_.isFunction(iteratee)) {
iteratee = createCallback(iteratee, context);
for (key in obj) {
var value = obj[key];
if (iteratee(value, key, obj)) result[key] = value;
}
} else {
var keys = concat.apply([], slice.call(arguments, 1));
obj = new Object(obj);
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
if (key in obj) result[key] = obj[key];
}
}
return result;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj, iteratee, context) {
if (_.isFunction(iteratee)) {
iteratee = _.negate(iteratee);
} else {
var keys = _.map(concat.apply([], slice.call(arguments, 1)), String);
iteratee = function(value, key) {
return !_.contains(keys, key);
};
}
return _.pick(obj, iteratee, context);
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
if (!_.isObject(obj)) return obj;
for (var i = 1, length = arguments.length; i < length; i++) {
var source = arguments[i];
for (var prop in source) {
if (obj[prop] === void 0) obj[prop] = source[prop];
}
}
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a === 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className !== toString.call(b)) return false;
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case '[object RegExp]':
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return '' + a === '' + b;
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) return +b !== +b;
// An `egal` comparison is performed for other numeric values.
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a === +b;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) return bStack[length] === b;
}
// Objects with different constructors are not equivalent, but `Object`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (
aCtor !== bCtor &&
// Handle Object.create(x) cases
'constructor' in a && 'constructor' in b &&
!(_.isFunction(aCtor) && aCtor instanceof aCtor &&
_.isFunction(bCtor) && bCtor instanceof bCtor)
) {
return false;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size, result;
// Recursively compare objects and arrays.
if (className === '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size === b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
}
}
} else {
// Deep compare objects.
var keys = _.keys(a), key;
size = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
result = _.keys(b).length === size;
if (result) {
while (size--) {
// Deep compare each member
key = keys[size];
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, [], []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (_.isArray(obj) || _.isString(obj) || _.isArguments(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) === '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return _.has(obj, 'callee');
};
}
// Optimize `isFunction` if appropriate. Work around an IE 11 bug.
if (typeof /./ !== 'function') {
_.isFunction = function(obj) {
return typeof obj == 'function' || false;
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj !== +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return obj != null && hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iteratees.
_.identity = function(value) {
return value;
};
_.constant = function(value) {
return function() {
return value;
};
};
_.noop = function(){};
_.property = function(key) {
return function(obj) {
return obj[key];
};
};
// Returns a predicate for checking whether an object has a given set of `key:value` pairs.
_.matches = function(attrs) {
var pairs = _.pairs(attrs), length = pairs.length;
return function(obj) {
if (obj == null) return !length;
obj = new Object(obj);
for (var i = 0; i < length; i++) {
var pair = pairs[i], key = pair[0];
if (pair[1] !== obj[key] || !(key in obj)) return false;
}
return true;
};
};
// Run a function **n** times.
_.times = function(n, iteratee, context) {
var accum = Array(Math.max(0, n));
iteratee = createCallback(iteratee, context, 1);
for (var i = 0; i < n; i++) accum[i] = iteratee(i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// A (possibly faster) way to get the current timestamp as an integer.
_.now = Date.now || function() {
return new Date().getTime();
};
// List of HTML entities for escaping.
var escapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`'
};
var unescapeMap = _.invert(escapeMap);
// Functions for escaping and unescaping strings to/from HTML interpolation.
var createEscaper = function(map) {
var escaper = function(match) {
return map[match];
};
// Regexes for identifying a key that needs to be escaped
var source = '(?:' + _.keys(map).join('|') + ')';
var testRegexp = RegExp(source);
var replaceRegexp = RegExp(source, 'g');
return function(string) {
string = string == null ? '' : '' + string;
return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
};
};
_.escape = createEscaper(escapeMap);
_.unescape = createEscaper(unescapeMap);
// If the value of the named `property` is a function then invoke it with the
// `object` as context; otherwise, return it.
_.result = function(object, property) {
if (object == null) return void 0;
var value = object[property];
return _.isFunction(value) ? object[property]() : value;
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
var escapeChar = function(match) {
return '\\' + escapes[match];
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
_.template = function(text, settings, oldSettings) {
if (!settings && oldSettings) settings = oldSettings;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset).replace(escaper, escapeChar);
index = offset + match.length;
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
} else if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
} else if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
// Adobe VMs need the match returned to produce the correct offest.
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + 'return __p;\n';
try {
var render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled source as a convenience for precompilation.
var argument = settings.variable || 'obj';
template.source = 'function(' + argument + '){\n' + source + '}';
return template;
};
// Add a "chain" function. Start chaining a wrapped Underscore object.
_.chain = function(obj) {
var instance = _(obj);
instance._chain = true;
return instance;
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(obj) {
return this._chain ? _(obj).chain() : obj;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
_.each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result.call(this, func.apply(_, args));
};
});
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
_.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
return result.call(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
_.each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result.call(this, method.apply(this._wrapped, arguments));
};
});
// Extracts the result from a wrapped and chained object.
_.prototype.value = function() {
return this._wrapped;
};
// AMD registration happens at the end for compatibility with AMD loaders
// that may not enforce next-turn semantics on modules. Even though general
// practice for AMD registration is to be anonymous, underscore registers
// as a named module because, like jQuery, it is a base library that is
// popular enough to be bundled in a third party lib, but not be part of
// an AMD load request. Those cases could generate an error when an
// anonymous define() is called outside of a loader request.
if (typeof define === 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}
}.call(this));
},{}],"zepto":[function(require,module,exports){
/* Zepto v1.1.4-67-g76e4233 - zepto deferred detect ajax touch selector event callbacks - zeptojs.com/license */
var Zepto=function(){function k(t){return null==t?String(t):S[j.call(t)]||"object"}function D(t){return"function"==k(t)}function L(t){return null!=t&&t==t.window}function Z(t){return null!=t&&t.nodeType==t.DOCUMENT_NODE}function F(t){return"object"==k(t)}function $(t){return F(t)&&!L(t)&&Object.getPrototypeOf(t)==Object.prototype}function R(t){return"number"==typeof t.length}function _(t){return s.call(t,function(t){return null!=t})}function q(t){return t.length>0?n.fn.concat.apply([],t):t}function W(t){return t.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function B(t){return t in c?c[t]:c[t]=new RegExp("(^|\\s)"+t+"(\\s|$)")}function I(t,e){return"number"!=typeof e||l[W(t)]?e:e+"px"}function z(t){var e,n;return f[t]||(e=u.createElement(t),u.body.appendChild(e),n=getComputedStyle(e,"").getPropertyValue("display"),e.parentNode.removeChild(e),"none"==n&&(n="block"),f[t]=n),f[t]}function H(t){return"children"in t?a.call(t.children):n.map(t.childNodes,function(t){return 1==t.nodeType?t:void 0})}function V(t,e){var n,i=t?t.length:0;for(n=0;i>n;n++)this[n]=t[n];this.length=i,this.selector=e||""}function U(n,i,r){for(e in i)r&&($(i[e])||A(i[e]))?($(i[e])&&!$(n[e])&&(n[e]={}),A(i[e])&&!A(n[e])&&(n[e]=[]),U(n[e],i[e],r)):i[e]!==t&&(n[e]=i[e])}function X(t,e){return null==e?n(t):n(t).filter(e)}function Y(t,e,n,i){return D(e)?e.call(t,n,i):e}function J(t,e,n){null==n?t.removeAttribute(e):t.setAttribute(e,n)}function G(e,n){var i=e.className||"",r=i&&i.baseVal!==t;return n===t?r?i.baseVal:i:void(r?i.baseVal=n:e.className=n)}function K(t){try{return t?"true"==t||("false"==t?!1:"null"==t?null:+t+""==t?+t:/^[\[\{]/.test(t)?n.parseJSON(t):t):t}catch(e){return t}}function Q(t,e){e(t);for(var n=0,i=t.childNodes.length;i>n;n++)Q(t.childNodes[n],e)}var t,e,n,i,P,N,r=[],o=r.concat,s=r.filter,a=r.slice,u=window.document,f={},c={},l={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},h=/^\s*<(\w+|!)[^>]*>/,p=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,d=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,m=/^(?:body|html)$/i,g=/([A-Z])/g,v=["val","css","html","text","data","width","height","offset"],y=["after","prepend","before","append"],w=u.createElement("table"),b=u.createElement("tr"),x={tr:u.createElement("tbody"),tbody:w,thead:w,tfoot:w,td:b,th:b,"*":u.createElement("div")},T=/complete|loaded|interactive/,E=/^[\w-]*$/,S={},j=S.toString,C={},O=u.createElement("div"),M={tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},A=Array.isArray||function(t){return t instanceof Array};return C.matches=function(t,e){if(!e||!t||1!==t.nodeType)return!1;var n=t.webkitMatchesSelector||t.mozMatchesSelector||t.oMatchesSelector||t.matchesSelector;if(n)return n.call(t,e);var i,r=t.parentNode,o=!r;return o&&(r=O).appendChild(t),i=~C.qsa(r,e).indexOf(t),o&&O.removeChild(t),i},P=function(t){return t.replace(/-+(.)?/g,function(t,e){return e?e.toUpperCase():""})},N=function(t){return s.call(t,function(e,n){return t.indexOf(e)==n})},C.fragment=function(e,i,r){var o,s,f;return p.test(e)&&(o=n(u.createElement(RegExp.$1))),o||(e.replace&&(e=e.replace(d,"<$1></$2>")),i===t&&(i=h.test(e)&&RegExp.$1),i in x||(i="*"),f=x[i],f.innerHTML=""+e,o=n.each(a.call(f.childNodes),function(){f.removeChild(this)})),$(r)&&(s=n(o),n.each(r,function(t,e){v.indexOf(t)>-1?s[t](e):s.attr(t,e)})),o},C.Z=function(t,e){return new V(t,e)},C.isZ=function(t){return t instanceof C.Z},C.init=function(e,i){var r;if(!e)return C.Z();if("string"==typeof e)if(e=e.trim(),"<"==e[0]&&h.test(e))r=C.fragment(e,RegExp.$1,i),e=null;else{if(i!==t)return n(i).find(e);r=C.qsa(u,e)}else{if(D(e))return n(u).ready(e);if(C.isZ(e))return e;if(A(e))r=_(e);else if(F(e))r=[e],e=null;else if(h.test(e))r=C.fragment(e.trim(),RegExp.$1,i),e=null;else{if(i!==t)return n(i).find(e);r=C.qsa(u,e)}}return C.Z(r,e)},n=function(t,e){return C.init(t,e)},n.extend=function(t){var e,n=a.call(arguments,1);return"boolean"==typeof t&&(e=t,t=n.shift()),n.forEach(function(n){U(t,n,e)}),t},C.qsa=function(t,e){var n,i="#"==e[0],r=!i&&"."==e[0],o=i||r?e.slice(1):e,s=E.test(o);return t.getElementById&&s&&i?(n=t.getElementById(o))?[n]:[]:1!==t.nodeType&&9!==t.nodeType&&11!==t.nodeType?[]:a.call(s&&!i&&t.getElementsByClassName?r?t.getElementsByClassName(o):t.getElementsByTagName(e):t.querySelectorAll(e))},n.contains=u.documentElement.contains?function(t,e){return t!==e&&t.contains(e)}:function(t,e){for(;e&&(e=e.parentNode);)if(e===t)return!0;return!1},n.type=k,n.isFunction=D,n.isWindow=L,n.isArray=A,n.isPlainObject=$,n.isEmptyObject=function(t){var e;for(e in t)return!1;return!0},n.inArray=function(t,e,n){return r.indexOf.call(e,t,n)},n.camelCase=P,n.trim=function(t){return null==t?"":String.prototype.trim.call(t)},n.uuid=0,n.support={},n.expr={},n.noop=function(){},n.map=function(t,e){var n,r,o,i=[];if(R(t))for(r=0;r<t.length;r++)n=e(t[r],r),null!=n&&i.push(n);else for(o in t)n=e(t[o],o),null!=n&&i.push(n);return q(i)},n.each=function(t,e){var n,i;if(R(t)){for(n=0;n<t.length;n++)if(e.call(t[n],n,t[n])===!1)return t}else for(i in t)if(e.call(t[i],i,t[i])===!1)return t;return t},n.grep=function(t,e){return s.call(t,e)},window.JSON&&(n.parseJSON=JSON.parse),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(t,e){S["[object "+e+"]"]=e.toLowerCase()}),n.fn={constructor:C.Z,length:0,forEach:r.forEach,reduce:r.reduce,push:r.push,sort:r.sort,splice:r.splice,indexOf:r.indexOf,concat:function(){var t,e,n=[];for(t=0;t<arguments.length;t++)e=arguments[t],n[t]=C.isZ(e)?e.toArray():e;return o.apply(C.isZ(this)?this.toArray():this,n)},map:function(t){return n(n.map(this,function(e,n){return t.call(e,n,e)}))},slice:function(){return n(a.apply(this,arguments))},ready:function(t){return T.test(u.readyState)&&u.body?t(n):u.addEventListener("DOMContentLoaded",function(){t(n)},!1),this},get:function(e){return e===t?a.call(this):this[e>=0?e:e+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){null!=this.parentNode&&this.parentNode.removeChild(this)})},each:function(t){return r.every.call(this,function(e,n){return t.call(e,n,e)!==!1}),this},filter:function(t){return D(t)?this.not(this.not(t)):n(s.call(this,function(e){return C.matches(e,t)}))},add:function(t,e){return n(N(this.concat(n(t,e))))},is:function(t){return this.length>0&&C.matches(this[0],t)},not:function(e){var i=[];if(D(e)&&e.call!==t)this.each(function(t){e.call(this,t)||i.push(this)});else{var r="string"==typeof e?this.filter(e):R(e)&&D(e.item)?a.call(e):n(e);this.forEach(function(t){r.indexOf(t)<0&&i.push(t)})}return n(i)},has:function(t){return this.filter(function(){return F(t)?n.contains(this,t):n(this).find(t).size()})},eq:function(t){return-1===t?this.slice(t):this.slice(t,+t+1)},first:function(){var t=this[0];return t&&!F(t)?t:n(t)},last:function(){var t=this[this.length-1];return t&&!F(t)?t:n(t)},find:function(t){var e,i=this;return e=t?"object"==typeof t?n(t).filter(function(){var t=this;return r.some.call(i,function(e){return n.contains(e,t)})}):1==this.length?n(C.qsa(this[0],t)):this.map(function(){return C.qsa(this,t)}):n()},closest:function(t,e){var i=this[0],r=!1;for("object"==typeof t&&(r=n(t));i&&!(r?r.indexOf(i)>=0:C.matches(i,t));)i=i!==e&&!Z(i)&&i.parentNode;return n(i)},parents:function(t){for(var e=[],i=this;i.length>0;)i=n.map(i,function(t){return(t=t.parentNode)&&!Z(t)&&e.indexOf(t)<0?(e.push(t),t):void 0});return X(e,t)},parent:function(t){return X(N(this.pluck("parentNode")),t)},children:function(t){return X(this.map(function(){return H(this)}),t)},contents:function(){return this.map(function(){return a.call(this.childNodes)})},siblings:function(t){return X(this.map(function(t,e){return s.call(H(e.parentNode),function(t){return t!==e})}),t)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(t){return n.map(this,function(e){return e[t]})},show:function(){return this.each(function(){"none"==this.style.display&&(this.style.display=""),"none"==getComputedStyle(this,"").getPropertyValue("display")&&(this.style.display=z(this.nodeName))})},replaceWith:function(t){return this.before(t).remove()},wrap:function(t){var e=D(t);if(this[0]&&!e)var i=n(t).get(0),r=i.parentNode||this.length>1;return this.each(function(o){n(this).wrapAll(e?t.call(this,o):r?i.cloneNode(!0):i)})},wrapAll:function(t){if(this[0]){n(this[0]).before(t=n(t));for(var e;(e=t.children()).length;)t=e.first();n(t).append(this)}return this},wrapInner:function(t){var e=D(t);return this.each(function(i){var r=n(this),o=r.contents(),s=e?t.call(this,i):t;o.length?o.wrapAll(s):r.append(s)})},unwrap:function(){return this.parent().each(function(){n(this).replaceWith(n(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(e){return this.each(function(){var i=n(this);(e===t?"none"==i.css("display"):e)?i.show():i.hide()})},prev:function(t){return n(this.pluck("previousElementSibling")).filter(t||"*")},next:function(t){return n(this.pluck("nextElementSibling")).filter(t||"*")},html:function(t){return 0 in arguments?this.each(function(e){var i=this.innerHTML;n(this).empty().append(Y(this,t,e,i))}):0 in this?this[0].innerHTML:null},text:function(t){return 0 in arguments?this.each(function(e){var n=Y(this,t,e,this.textContent);this.textContent=null==n?"":""+n}):0 in this?this[0].textContent:null},attr:function(n,i){var r;return"string"!=typeof n||1 in arguments?this.each(function(t){if(1===this.nodeType)if(F(n))for(e in n)J(this,e,n[e]);else J(this,n,Y(this,i,t,this.getAttribute(n)))}):this.length&&1===this[0].nodeType?!(r=this[0].getAttribute(n))&&n in this[0]?this[0][n]:r:t},removeAttr:function(t){return this.each(function(){1===this.nodeType&&t.split(" ").forEach(function(t){J(this,t)},this)})},prop:function(t,e){return t=M[t]||t,1 in arguments?this.each(function(n){this[t]=Y(this,e,n,this[t])}):this[0]&&this[0][t]},data:function(e,n){var i="data-"+e.replace(g,"-$1").toLowerCase(),r=1 in arguments?this.attr(i,n):this.attr(i);return null!==r?K(r):t},val:function(t){return 0 in arguments?this.each(function(e){this.value=Y(this,t,e,this.value)}):this[0]&&(this[0].multiple?n(this[0]).find("option").filter(function(){return this.selected}).pluck("value"):this[0].value)},offset:function(t){if(t)return this.each(function(e){var i=n(this),r=Y(this,t,e,i.offset()),o=i.offsetParent().offset(),s={top:r.top-o.top,left:r.left-o.left};"static"==i.css("position")&&(s.position="relative"),i.css(s)});if(!this.length)return null;var e=this[0].getBoundingClientRect();return{left:e.left+window.pageXOffset,top:e.top+window.pageYOffset,width:Math.round(e.width),height:Math.round(e.height)}},css:function(t,i){if(arguments.length<2){var r,o=this[0];if(!o)return;if(r=getComputedStyle(o,""),"string"==typeof t)return o.style[P(t)]||r.getPropertyValue(t);if(A(t)){var s={};return n.each(t,function(t,e){s[e]=o.style[P(e)]||r.getPropertyValue(e)}),s}}var a="";if("string"==k(t))i||0===i?a=W(t)+":"+I(t,i):this.each(function(){this.style.removeProperty(W(t))});else for(e in t)t[e]||0===t[e]?a+=W(e)+":"+I(e,t[e])+";":this.each(function(){this.style.removeProperty(W(e))});return this.each(function(){this.style.cssText+=";"+a})},index:function(t){return t?this.indexOf(n(t)[0]):this.parent().children().indexOf(this[0])},hasClass:function(t){return t?r.some.call(this,function(t){return this.test(G(t))},B(t)):!1},addClass:function(t){return t?this.each(function(e){if("className"in this){i=[];var r=G(this),o=Y(this,t,e,r);o.split(/\s+/g).forEach(function(t){n(this).hasClass(t)||i.push(t)},this),i.length&&G(this,r+(r?" ":"")+i.join(" "))}}):this},removeClass:function(e){return this.each(function(n){if("className"in this){if(e===t)return G(this,"");i=G(this),Y(this,e,n,i).split(/\s+/g).forEach(function(t){i=i.replace(B(t)," ")}),G(this,i.trim())}})},toggleClass:function(e,i){return e?this.each(function(r){var o=n(this),s=Y(this,e,r,G(this));s.split(/\s+/g).forEach(function(e){(i===t?!o.hasClass(e):i)?o.addClass(e):o.removeClass(e)})}):this},scrollTop:function(e){if(this.length){var n="scrollTop"in this[0];return e===t?n?this[0].scrollTop:this[0].pageYOffset:this.each(n?function(){this.scrollTop=e}:function(){this.scrollTo(this.scrollX,e)})}},scrollLeft:function(e){if(this.length){var n="scrollLeft"in this[0];return e===t?n?this[0].scrollLeft:this[0].pageXOffset:this.each(n?function(){this.scrollLeft=e}:function(){this.scrollTo(e,this.scrollY)})}},position:function(){if(this.length){var t=this[0],e=this.offsetParent(),i=this.offset(),r=m.test(e[0].nodeName)?{top:0,left:0}:e.offset();return i.top-=parseFloat(n(t).css("margin-top"))||0,i.left-=parseFloat(n(t).css("margin-left"))||0,r.top+=parseFloat(n(e[0]).css("border-top-width"))||0,r.left+=parseFloat(n(e[0]).css("border-left-width"))||0,{top:i.top-r.top,left:i.left-r.left}}},offsetParent:function(){return this.map(function(){for(var t=this.offsetParent||u.body;t&&!m.test(t.nodeName)&&"static"==n(t).css("position");)t=t.offsetParent;return t})}},n.fn.detach=n.fn.remove,["width","height"].forEach(function(e){var i=e.replace(/./,function(t){return t[0].toUpperCase()});n.fn[e]=function(r){var o,s=this[0];return r===t?L(s)?s["inner"+i]:Z(s)?s.documentElement["scroll"+i]:(o=this.offset())&&o[e]:this.each(function(t){s=n(this),s.css(e,Y(this,r,t,s[e]()))})}}),y.forEach(function(t,e){var i=e%2;n.fn[t]=function(){var t,o,r=n.map(arguments,function(e){return t=k(e),"object"==t||"array"==t||null==e?e:C.fragment(e)}),s=this.length>1;return r.length<1?this:this.each(function(t,a){o=i?a:a.parentNode,a=0==e?a.nextSibling:1==e?a.firstChild:2==e?a:null;var f=n.contains(u.documentElement,o);r.forEach(function(t){if(s)t=t.cloneNode(!0);else if(!o)return n(t).remove();o.insertBefore(t,a),f&&Q(t,function(t){null==t.nodeName||"SCRIPT"!==t.nodeName.toUpperCase()||t.type&&"text/javascript"!==t.type||t.src||window.eval.call(window,t.innerHTML)})})})},n.fn[i?t+"To":"insert"+(e?"Before":"After")]=function(e){return n(e)[t](this),this}}),C.Z.prototype=V.prototype=n.fn,C.uniq=N,C.deserializeValue=K,n.zepto=C,n}();window.Zepto=Zepto,void 0===window.$&&(window.$=Zepto),function(t){function n(e){var i=[["resolve","done",t.Callbacks({once:1,memory:1}),"resolved"],["reject","fail",t.Callbacks({once:1,memory:1}),"rejected"],["notify","progress",t.Callbacks({memory:1})]],r="pending",o={state:function(){return r},always:function(){return s.done(arguments).fail(arguments),this},then:function(){var e=arguments;return n(function(n){t.each(i,function(i,r){var a=t.isFunction(e[i])&&e[i];s[r[1]](function(){var e=a&&a.apply(this,arguments);if(e&&t.isFunction(e.promise))e.promise().done(n.resolve).fail(n.reject).progress(n.notify);else{var i=this===o?n.promise():this,s=a?[e]:arguments;n[r[0]+"With"](i,s)}})}),e=null}).promise()},promise:function(e){return null!=e?t.extend(e,o):o}},s={};return t.each(i,function(t,e){var n=e[2],a=e[3];o[e[1]]=n.add,a&&n.add(function(){r=a},i[1^t][2].disable,i[2][2].lock),s[e[0]]=function(){return s[e[0]+"With"](this===s?o:this,arguments),this},s[e[0]+"With"]=n.fireWith}),o.promise(s),e&&e.call(s,s),s}var e=Array.prototype.slice;t.when=function(i){var f,c,l,r=e.call(arguments),o=r.length,s=0,a=1!==o||i&&t.isFunction(i.promise)?o:0,u=1===a?i:n(),h=function(t,n,i){return function(r){n[t]=this,i[t]=arguments.length>1?e.call(arguments):r,i===f?u.notifyWith(n,i):--a||u.resolveWith(n,i)}};if(o>1)for(f=new Array(o),c=new Array(o),l=new Array(o);o>s;++s)r[s]&&t.isFunction(r[s].promise)?r[s].promise().done(h(s,l,r)).fail(u.reject).progress(h(s,c,f)):--a;return a||u.resolveWith(l,r),u.promise()},t.Deferred=n}(Zepto),function(t){function e(t,e){var n=this.os={},i=this.browser={},r=t.match(/Web[kK]it[\/]{0,1}([\d.]+)/),o=t.match(/(Android);?[\s\/]+([\d.]+)?/),s=!!t.match(/\(Macintosh\; Intel /),a=t.match(/(iPad).*OS\s([\d_]+)/),u=t.match(/(iPod)(.*OS\s([\d_]+))?/),f=!a&&t.match(/(iPhone\sOS)\s([\d_]+)/),c=t.match(/(webOS|hpwOS)[\s\/]([\d.]+)/),l=/Win\d{2}|Windows/.test(e),h=t.match(/Windows Phone ([\d.]+)/),p=c&&t.match(/TouchPad/),d=t.match(/Kindle\/([\d.]+)/),m=t.match(/Silk\/([\d._]+)/),g=t.match(/(BlackBerry).*Version\/([\d.]+)/),v=t.match(/(BB10).*Version\/([\d.]+)/),y=t.match(/(RIM\sTablet\sOS)\s([\d.]+)/),w=t.match(/PlayBook/),b=t.match(/Chrome\/([\d.]+)/)||t.match(/CriOS\/([\d.]+)/),x=t.match(/Firefox\/([\d.]+)/),T=t.match(/\((?:Mobile|Tablet); rv:([\d.]+)\).*Firefox\/[\d.]+/),E=t.match(/MSIE\s([\d.]+)/)||t.match(/Trident\/[\d](?=[^\?]+).*rv:([0-9.].)/),S=!b&&t.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/),j=S||t.match(/Version\/([\d.]+)([^S](Safari)|[^M]*(Mobile)[^S]*(Safari))/);(i.webkit=!!r)&&(i.version=r[1]),o&&(n.android=!0,n.version=o[2]),f&&!u&&(n.ios=n.iphone=!0,n.version=f[2].replace(/_/g,".")),a&&(n.ios=n.ipad=!0,n.version=a[2].replace(/_/g,".")),u&&(n.ios=n.ipod=!0,n.version=u[3]?u[3].replace(/_/g,"."):null),h&&(n.wp=!0,n.version=h[1]),c&&(n.webos=!0,n.version=c[2]),p&&(n.touchpad=!0),g&&(n.blackberry=!0,n.version=g[2]),v&&(n.bb10=!0,n.version=v[2]),y&&(n.rimtabletos=!0,n.version=y[2]),w&&(i.playbook=!0),d&&(n.kindle=!0,n.version=d[1]),m&&(i.silk=!0,i.version=m[1]),!m&&n.android&&t.match(/Kindle Fire/)&&(i.silk=!0),b&&(i.chrome=!0,i.version=b[1]),x&&(i.firefox=!0,i.version=x[1]),T&&(n.firefoxos=!0,n.version=T[1]),E&&(i.ie=!0,i.version=E[1]),j&&(s||n.ios||l)&&(i.safari=!0,n.ios||(i.version=j[1])),S&&(i.webview=!0),n.tablet=!!(a||w||o&&!t.match(/Mobile/)||x&&t.match(/Tablet/)||E&&!t.match(/Phone/)&&t.match(/Touch/)),n.phone=!(n.tablet||n.ipod||!(o||f||c||g||v||b&&t.match(/Android/)||b&&t.match(/CriOS\/([\d.]+)/)||x&&t.match(/Mobile/)||E&&t.match(/Touch/)))}e.call(t,navigator.userAgent,navigator.platform),t.__detect=e}(Zepto),function(t){function h(e,n,i){var r=t.Event(n);return t(e).trigger(r,i),!r.isDefaultPrevented()}function p(t,e,i,r){return t.global?h(e||n,i,r):void 0}function d(e){e.global&&0===t.active++&&p(e,null,"ajaxStart")}function m(e){e.global&&!--t.active&&p(e,null,"ajaxStop")}function g(t,e){var n=e.context;return e.beforeSend.call(n,t,e)===!1||p(e,n,"ajaxBeforeSend",[t,e])===!1?!1:void p(e,n,"ajaxSend",[t,e])}function v(t,e,n,i){var r=n.context,o="success";n.success.call(r,t,o,e),i&&i.resolveWith(r,[t,o,e]),p(n,r,"ajaxSuccess",[e,n,t]),w(o,e,n)}function y(t,e,n,i,r){var o=i.context;i.error.call(o,n,e,t),r&&r.rejectWith(o,[n,e,t]),p(i,o,"ajaxError",[n,i,t||e]),w(e,n,i)}function w(t,e,n){var i=n.context;n.complete.call(i,e,t),p(n,i,"ajaxComplete",[e,n]),m(n)}function b(){}function x(t){return t&&(t=t.split(";",2)[0]),t&&(t==f?"html":t==u?"json":s.test(t)?"script":a.test(t)&&"xml")||"text"}function T(t,e){return""==e?t:(t+"&"+e).replace(/[&?]{1,2}/,"?")}function E(e){e.processData&&e.data&&"string"!=t.type(e.data)&&(e.data=t.param(e.data,e.traditional)),!e.data||e.type&&"GET"!=e.type.toUpperCase()||(e.url=T(e.url,e.data),e.data=void 0)}function S(e,n,i,r){return t.isFunction(n)&&(r=i,i=n,n=void 0),t.isFunction(i)||(r=i,i=void 0),{url:e,data:n,success:i,dataType:r}}function C(e,n,i,r){var o,s=t.isArray(n),a=t.isPlainObject(n);t.each(n,function(n,u){o=t.type(u),r&&(n=i?r:r+"["+(a||"object"==o||"array"==o?n:"")+"]"),!r&&s?e.add(u.name,u.value):"array"==o||!i&&"object"==o?C(e,u,i,n):e.add(n,u)})}var i,r,e=0,n=window.document,o=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,s=/^(?:text|application)\/javascript/i,a=/^(?:text|application)\/xml/i,u="application/json",f="text/html",c=/^\s*$/,l=n.createElement("a");l.href=window.location.href,t.active=0,t.ajaxJSONP=function(i,r){if(!("type"in i))return t.ajax(i);var f,h,o=i.jsonpCallback,s=(t.isFunction(o)?o():o)||"jsonp"+ ++e,a=n.createElement("script"),u=window[s],c=function(e){t(a).triggerHandler("error",e||"abort")},l={abort:c};return r&&r.promise(l),t(a).on("load error",function(e,n){clearTimeout(h),t(a).off().remove(),"error"!=e.type&&f?v(f[0],l,i,r):y(null,n||"error",l,i,r),window[s]=u,f&&t.isFunction(u)&&u(f[0]),u=f=void 0}),g(l,i)===!1?(c("abort"),l):(window[s]=function(){f=arguments},a.src=i.url.replace(/\?(.+)=\?/,"?$1="+s),n.head.appendChild(a),i.timeout>0&&(h=setTimeout(function(){c("timeout")},i.timeout)),l)},t.ajaxSettings={type:"GET",beforeSend:b,success:b,error:b,complete:b,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:u,xml:"application/xml, text/xml",html:f,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},t.ajax=function(e){var a,o=t.extend({},e||{}),s=t.Deferred&&t.Deferred();for(i in t.ajaxSettings)void 0===o[i]&&(o[i]=t.ajaxSettings[i]);d(o),o.crossDomain||(a=n.createElement("a"),a.href=o.url,a.href=a.href,o.crossDomain=l.protocol+"//"+l.host!=a.protocol+"//"+a.host),o.url||(o.url=window.location.toString()),E(o);var u=o.dataType,f=/\?.+=\?/.test(o.url);if(f&&(u="jsonp"),o.cache!==!1&&(e&&e.cache===!0||"script"!=u&&"jsonp"!=u)||(o.url=T(o.url,"_="+Date.now())),"jsonp"==u)return f||(o.url=T(o.url,o.jsonp?o.jsonp+"=?":o.jsonp===!1?"":"callback=?")),t.ajaxJSONP(o,s);var C,h=o.accepts[u],p={},m=function(t,e){p[t.toLowerCase()]=[t,e]},w=/^([\w-]+:)\/\//.test(o.url)?RegExp.$1:window.location.protocol,S=o.xhr(),j=S.setRequestHeader;if(s&&s.promise(S),o.crossDomain||m("X-Requested-With","XMLHttpRequest"),m("Accept",h||"*/*"),(h=o.mimeType||h)&&(h.indexOf(",")>-1&&(h=h.split(",",2)[0]),S.overrideMimeType&&S.overrideMimeType(h)),(o.contentType||o.contentType!==!1&&o.data&&"GET"!=o.type.toUpperCase())&&m("Content-Type",o.contentType||"application/x-www-form-urlencoded"),o.headers)for(r in o.headers)m(r,o.headers[r]);if(S.setRequestHeader=m,S.onreadystatechange=function(){if(4==S.readyState){S.onreadystatechange=b,clearTimeout(C);var e,n=!1;if(S.status>=200&&S.status<300||304==S.status||0==S.status&&"file:"==w){u=u||x(o.mimeType||S.getResponseHeader("content-type")),e=S.responseText;try{"script"==u?(1,eval)(e):"xml"==u?e=S.responseXML:"json"==u&&(e=c.test(e)?null:t.parseJSON(e))}catch(i){n=i}n?y(n,"parsererror",S,o,s):v(e,S,o,s)}else y(S.statusText||null,S.status?"error":"abort",S,o,s)}},g(S,o)===!1)return S.abort(),y(null,"abort",S,o,s),S;if(o.xhrFields)for(r in o.xhrFields)S[r]=o.xhrFields[r];var P="async"in o?o.async:!0;S.open(o.type,o.url,P,o.username,o.password);for(r in p)j.apply(S,p[r]);return o.timeout>0&&(C=setTimeout(function(){S.onreadystatechange=b,S.abort(),y(null,"timeout",S,o,s)},o.timeout)),S.send(o.data?o.data:null),S},t.get=function(){return t.ajax(S.apply(null,arguments))},t.post=function(){var e=S.apply(null,arguments);return e.type="POST",t.ajax(e)},t.getJSON=function(){var e=S.apply(null,arguments);return e.dataType="json",t.ajax(e)},t.fn.load=function(e,n,i){if(!this.length)return this;var a,r=this,s=e.split(/\s/),u=S(e,n,i),f=u.success;return s.length>1&&(u.url=s[0],a=s[1]),u.success=function(e){r.html(a?t("<div>").html(e.replace(o,"")).find(a):e),f&&f.apply(r,arguments)},t.ajax(u),this};var j=encodeURIComponent;t.param=function(e,n){var i=[];return i.add=function(e,n){t.isFunction(n)&&(n=n()),null==n&&(n=""),this.push(j(e)+"="+j(n))},C(i,e,n),i.join("&").replace(/%20/g,"+")}}(Zepto),function(t){function u(t,e,n,i){return Math.abs(t-e)>=Math.abs(n-i)?t-e>0?"Left":"Right":n-i>0?"Up":"Down"}function f(){o=null,e.last&&(e.el.trigger("longTap"),e={})}function c(){o&&clearTimeout(o),o=null}function l(){n&&clearTimeout(n),i&&clearTimeout(i),r&&clearTimeout(r),o&&clearTimeout(o),n=i=r=o=null,e={}}function h(t){return("touch"==t.pointerType||t.pointerType==t.MSPOINTER_TYPE_TOUCH)&&t.isPrimary}function p(t,e){return t.type=="pointer"+e||t.type.toLowerCase()=="mspointer"+e}var n,i,r,o,a,e={},s=750;t(document).ready(function(){var d,m,y,w,g=0,v=0;"MSGesture"in window&&(a=new MSGesture,a.target=document.body),t(document).bind("MSGestureEnd",function(t){var n=t.velocityX>1?"Right":t.velocityX<-1?"Left":t.velocityY>1?"Down":t.velocityY<-1?"Up":null;n&&(e.el.trigger("swipe"),e.el.trigger("swipe"+n))}).on("touchstart MSPointerDown pointerdown",function(i){(!(w=p(i,"down"))||h(i))&&(y=w?i:i.touches[0],i.touches&&1===i.touches.length&&e.x2&&(e.x2=void 0,e.y2=void 0),d=Date.now(),m=d-(e.last||d),e.el=t("tagName"in y.target?y.target:y.target.parentNode),n&&clearTimeout(n),e.x1=y.pageX,e.y1=y.pageY,m>0&&250>=m&&(e.isDoubleTap=!0),e.last=d,o=setTimeout(f,s),a&&w&&a.addPointer(i.pointerId))}).on("touchmove MSPointerMove pointermove",function(t){(!(w=p(t,"move"))||h(t))&&(y=w?t:t.touches[0],c(),e.x2=y.pageX,e.y2=y.pageY,g+=Math.abs(e.x1-e.x2),v+=Math.abs(e.y1-e.y2))}).on("touchend MSPointerUp pointerup",function(o){(!(w=p(o,"up"))||h(o))&&(c(),e.x2&&Math.abs(e.x1-e.x2)>30||e.y2&&Math.abs(e.y1-e.y2)>30?r=setTimeout(function(){e.el.trigger("swipe"),e.el.trigger("swipe"+u(e.x1,e.x2,e.y1,e.y2)),e={}},0):"last"in e&&(30>g&&30>v?i=setTimeout(function(){var i=t.Event("tap");i.cancelTouch=l,e.el.trigger(i),e.isDoubleTap?(e.el&&e.el.trigger("doubleTap"),e={}):n=setTimeout(function(){n=null,e.el&&e.el.trigger("singleTap"),e={}},250)},0):e={}),g=v=0)}).on("touchcancel MSPointerCancel pointercancel",l),t(window).on("scroll",l)}),["swipe","swipeLeft","swipeRight","swipeUp","swipeDown","doubleTap","tap","singleTap","longTap"].forEach(function(e){t.fn[e]=function(t){return this.on(e,t)}})}(Zepto),function(t){function r(e){return e=t(e),!(!e.width()&&!e.height())&&"none"!==e.css("display")}function f(t,e){t=t.replace(/=#\]/g,'="#"]');var n,i,r=s.exec(t);if(r&&r[2]in o&&(n=o[r[2]],i=r[3],t=r[1],i)){var a=Number(i);i=isNaN(a)?i.replace(/^["']|["']$/g,""):a}return e(t,n,i)}var e=t.zepto,n=e.qsa,i=e.matches,o=t.expr[":"]={visible:function(){return r(this)?this:void 0},hidden:function(){return r(this)?void 0:this},selected:function(){return this.selected?this:void 0},checked:function(){return this.checked?this:void 0},parent:function(){return this.parentNode},first:function(t){return 0===t?this:void 0},last:function(t,e){return t===e.length-1?this:void 0},eq:function(t,e,n){return t===n?this:void 0},contains:function(e,n,i){return t(this).text().indexOf(i)>-1?this:void 0},has:function(t,n,i){return e.qsa(this,i).length?this:void 0}},s=new RegExp("(.*):(\\w+)(?:\\(([^)]+)\\))?$\\s*"),a=/^\s*>/,u="Zepto"+ +new Date;e.qsa=function(i,r){return f(r,function(o,s,f){try{var c;!o&&s?o="*":a.test(o)&&(c=t(i).addClass(u),o="."+u+" "+o);var l=n(i,o)}catch(h){throw console.error("error performing selector: %o",r),h}finally{c&&c.removeClass(u)}return s?e.uniq(t.map(l,function(t,e){return s.call(t,e,l,f)})):l})},e.matches=function(t,e){return f(e,function(e,n,r){return!(e&&!i(t,e)||n&&n.call(t,null,r)!==t)})}}(Zepto),function(t){function l(t){return t._zid||(t._zid=e++)}function h(t,e,n,i){if(e=p(e),e.ns)var r=d(e.ns);return(s[l(t)]||[]).filter(function(t){return!(!t||e.e&&t.e!=e.e||e.ns&&!r.test(t.ns)||n&&l(t.fn)!==l(n)||i&&t.sel!=i)})}function p(t){var e=(""+t).split(".");return{e:e[0],ns:e.slice(1).sort().join(" ")}}function d(t){return new RegExp("(?:^| )"+t.replace(" "," .* ?")+"(?: |$)")}function m(t,e){return t.del&&!u&&t.e in f||!!e}function g(t){return c[t]||u&&f[t]||t}function v(e,i,r,o,a,u,f){var h=l(e),d=s[h]||(s[h]=[]);i.split(/\s/).forEach(function(i){if("ready"==i)return t(document).ready(r);var s=p(i);s.fn=r,s.sel=a,s.e in c&&(r=function(e){var n=e.relatedTarget;return!n||n!==this&&!t.contains(this,n)?s.fn.apply(this,arguments):void 0}),s.del=u;var l=u||r;s.proxy=function(t){if(t=E(t),!t.isImmediatePropagationStopped()){t.data=o;var i=l.apply(e,t._args==n?[t]:[t].concat(t._args));return i===!1&&(t.preventDefault(),t.stopPropagation()),i}},s.i=d.length,d.push(s),"addEventListener"in e&&e.addEventListener(g(s.e),s.proxy,m(s,f))})}function y(t,e,n,i,r){var o=l(t);(e||"").split(/\s/).forEach(function(e){h(t,e,n,i).forEach(function(e){delete s[o][e.i],"removeEventListener"in t&&t.removeEventListener(g(e.e),e.proxy,m(e,r))})})}function E(e,i){return(i||!e.isDefaultPrevented)&&(i||(i=e),t.each(T,function(t,n){var r=i[t];e[t]=function(){return this[n]=w,r&&r.apply(i,arguments)},e[n]=b}),(i.defaultPrevented!==n?i.defaultPrevented:"returnValue"in i?i.returnValue===!1:i.getPreventDefault&&i.getPreventDefault())&&(e.isDefaultPrevented=w)),e}function S(t){var e,i={originalEvent:t};for(e in t)x.test(e)||t[e]===n||(i[e]=t[e]);return E(i,t)}var n,e=1,i=Array.prototype.slice,r=t.isFunction,o=function(t){return"string"==typeof t},s={},a={},u="onfocusin"in window,f={focus:"focusin",blur:"focusout"},c={mouseenter:"mouseover",mouseleave:"mouseout"};a.click=a.mousedown=a.mouseup=a.mousemove="MouseEvents",t.event={add:v,remove:y},t.proxy=function(e,n){var s=2 in arguments&&i.call(arguments,2);if(r(e)){var a=function(){return e.apply(n,s?s.concat(i.call(arguments)):arguments)};return a._zid=l(e),a}if(o(n))return s?(s.unshift(e[n],e),t.proxy.apply(null,s)):t.proxy(e[n],e);throw new TypeError("expected function")},t.fn.bind=function(t,e,n){return this.on(t,e,n)},t.fn.unbind=function(t,e){return this.off(t,e)},t.fn.one=function(t,e,n,i){return this.on(t,e,n,i,1)};var w=function(){return!0},b=function(){return!1},x=/^([A-Z]|returnValue$|layer[XY]$)/,T={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};t.fn.delegate=function(t,e,n){return this.on(e,t,n)},t.fn.undelegate=function(t,e,n){return this.off(e,t,n)},t.fn.live=function(e,n){return t(document.body).delegate(this.selector,e,n),this},t.fn.die=function(e,n){return t(document.body).undelegate(this.selector,e,n),this},t.fn.on=function(e,s,a,u,f){var c,l,h=this;return e&&!o(e)?(t.each(e,function(t,e){h.on(t,s,a,e,f)}),h):(o(s)||r(u)||u===!1||(u=a,a=s,s=n),(r(a)||a===!1)&&(u=a,a=n),u===!1&&(u=b),h.each(function(n,r){f&&(c=function(t){return y(r,t.type,u),u.apply(this,arguments)}),s&&(l=function(e){var n,o=t(e.target).closest(s,r).get(0);return o&&o!==r?(n=t.extend(S(e),{currentTarget:o,liveFired:r}),(c||u).apply(o,[n].concat(i.call(arguments,1)))):void 0}),v(r,e,u,a,s,l||c)}))},t.fn.off=function(e,i,s){var a=this;return e&&!o(e)?(t.each(e,function(t,e){a.off(t,i,e)}),a):(o(i)||r(s)||s===!1||(s=i,i=n),s===!1&&(s=b),a.each(function(){y(this,e,s,i)}))},t.fn.trigger=function(e,n){return e=o(e)||t.isPlainObject(e)?t.Event(e):E(e),e._args=n,this.each(function(){e.type in f&&"function"==typeof this[e.type]?this[e.type]():"dispatchEvent"in this?this.dispatchEvent(e):t(this).triggerHandler(e,n)})},t.fn.triggerHandler=function(e,n){var i,r;return this.each(function(s,a){i=S(o(e)?t.Event(e):e),i._args=n,i.target=a,t.each(h(a,e.type||e),function(t,e){return r=e.proxy(i),i.isImmediatePropagationStopped()?!1:void 0})}),r},"focusin focusout focus blur load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(e){t.fn[e]=function(t){return 0 in arguments?this.bind(e,t):this.trigger(e)}}),t.Event=function(t,e){o(t)||(e=t,t=e.type);var n=document.createEvent(a[t]||"Events"),i=!0;if(e)for(var r in e)"bubbles"==r?i=!!e[r]:n[r]=e[r];return n.initEvent(t,i,!0),E(n)}}(Zepto),function(t){t.Callbacks=function(e){e=t.extend({},e);var n,i,r,o,s,a,u=[],f=!e.once&&[],c=function(t){for(n=e.memory&&t,i=!0,a=o||0,o=0,s=u.length,r=!0;u&&s>a;++a)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}r=!1,u&&(f?f.length&&c(f.shift()):n?u.length=0:l.disable())},l={add:function(){if(u){var i=u.length,a=function(n){t.each(n,function(t,n){"function"==typeof n?e.unique&&l.has(n)||u.push(n):n&&n.length&&"string"!=typeof n&&a(n)})};a(arguments),r?s=u.length:n&&(o=i,c(n))}return this},remove:function(){return u&&t.each(arguments,function(e,n){for(var i;(i=t.inArray(n,u,i))>-1;)u.splice(i,1),r&&(s>=i&&--s,a>=i&&--a)}),this
},has:function(e){return!(!u||!(e?t.inArray(e,u)>-1:u.length))},empty:function(){return s=u.length=0,this},disable:function(){return u=f=n=void 0,this},disabled:function(){return!u},lock:function(){return f=void 0,n||l.disable(),this},locked:function(){return!f},fireWith:function(t,e){return!u||i&&!f||(e=e||[],e=[t,e.slice?e.slice():e],r?f.push(e):c(e)),this},fire:function(){return l.fireWith(this,arguments)},fired:function(){return!!i}};return l}}(Zepto);
module.exports = Zepto;
},{}]},{},[3,1])
//# sourceMappingURL=clappr.map |
docs/pages/api-docs/dialog.js | lgollut/material-ui | import React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown';
const pageFilename = 'api/dialog';
const requireRaw = require.context('!raw-loader!./', false, /\/dialog\.md$/);
export default function Page({ docs }) {
return <MarkdownDocs docs={docs} />;
}
Page.getInitialProps = () => {
const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw });
return { demos, docs };
};
|
app/javascript/mastodon/features/ui/components/video_modal.js | abcang/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Video from 'mastodon/features/video';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Footer from 'mastodon/features/picture_in_picture/components/footer';
import { getAverageFromBlurhash } from 'mastodon/blurhash';
export default class VideoModal extends ImmutablePureComponent {
static propTypes = {
media: ImmutablePropTypes.map.isRequired,
statusId: PropTypes.string,
options: PropTypes.shape({
startTime: PropTypes.number,
autoPlay: PropTypes.bool,
defaultVolume: PropTypes.number,
}),
onClose: PropTypes.func.isRequired,
onChangeBackgroundColor: PropTypes.func.isRequired,
};
componentDidMount () {
const { media, onChangeBackgroundColor } = this.props;
const backgroundColor = getAverageFromBlurhash(media.get('blurhash'));
if (backgroundColor) {
onChangeBackgroundColor(backgroundColor);
}
}
render () {
const { media, statusId, onClose } = this.props;
const options = this.props.options || {};
return (
<div className='modal-root__modal video-modal'>
<div className='video-modal__container'>
<Video
preview={media.get('preview_url')}
frameRate={media.getIn(['meta', 'original', 'frame_rate'])}
blurhash={media.get('blurhash')}
src={media.get('url')}
currentTime={options.startTime}
autoPlay={options.autoPlay}
volume={options.defaultVolume}
onCloseVideo={onClose}
detailed
alt={media.get('description')}
/>
</div>
<div className='media-modal__overlay'>
{statusId && <Footer statusId={statusId} withOpenButton onClose={onClose} />}
</div>
</div>
);
}
}
|
src/parser/shared/modules/features/ManaTab/TabComponent/ManaUsageGraph.js | FaideWW/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import {Line} from 'react-chartjs-2';
import {formatThousands } from 'common/format';
import {formatDuration} from 'common/format';
import ManaStyles from 'interface/others/ManaStyles.js';
const baseConfig = {
responsive: true,
scales: {
yAxes: [{
gridLines: ManaStyles.gridLines,
ticks: {
callback: (percentage, index, values) => {
return formatThousands(percentage);
},
fontSize: 14,
},
}],
xAxes: [{
gridLines: ManaStyles.gridLines,
ticks: {
callback: (seconds, index, values) => {
if (seconds % 30 === 0) {
return formatDuration(seconds);
}
return null;
},
fontSize: 14,
},
}],
},
animation: {
duration: 0,
},
hover: {
animationDuration: 0,
},
responsiveAnimationDuration: 0,
tooltips: {
enabled: false,
},
legend: ManaStyles.legend,
};
class HealingDoneGraph extends React.PureComponent {
static propTypes = {
start: PropTypes.number.isRequired,
end: PropTypes.number.isRequired,
healingBySecond: PropTypes.object.isRequired,
manaUpdates: PropTypes.array.isRequired,
};
constructor() {
super();
this.state = {
interval: 5,
};
}
groupHealingBySeconds(healingBySecond, interval) {
return Object.keys(healingBySecond)
.reduce((obj, second) => {
const healing = healingBySecond[second];
const index = Math.floor(second / interval);
if (obj[index]) {
obj[index] = obj[index].add(healing.regular, healing.absorbed, healing.overheal);
} else {
obj[index] = healing;
}
return obj;
}, {});
}
render() {
const { start, end, healingBySecond, manaUpdates } = this.props;
const interval = this.state.interval;
const healingPerFrame = this.groupHealingBySeconds(healingBySecond, interval);
let max = 0;
Object.keys(healingPerFrame)
.map(k => healingPerFrame[k])
.forEach((healingDone) => {
const current = healingDone.effective;
if (current > max) {
max = current;
}
});
max /= interval;
const manaUsagePerFrame = {
0: 0,
};
const manaLevelPerFrame = {
0: 100,
};
manaUpdates.forEach((item) => {
const frame = Math.floor((item.timestamp - start) / 1000 / interval);
manaUsagePerFrame[frame] = (manaUsagePerFrame[frame] || 0) + item.used / item.max;
manaLevelPerFrame[frame] = item.current / item.max; // use the lowest value of the frame; likely to be more accurate
});
const fightDurationSec = Math.ceil((end - start) / 1000);
const labels = [];
for (let i = 0; i <= fightDurationSec / interval; i += 1) {
labels.push(i * interval);
healingPerFrame[i] = healingPerFrame[i] !== undefined ? healingPerFrame[i].effective : 0;
manaUsagePerFrame[i] = manaUsagePerFrame[i] !== undefined ? manaUsagePerFrame[i] : 0;
manaLevelPerFrame[i] = manaLevelPerFrame[i] !== undefined ? manaLevelPerFrame[i] : null;
}
const chartData = {
labels,
datasets: [
{
label: `Mana`,
...ManaStyles.Mana,
data: Object.keys(manaLevelPerFrame).map(key => manaLevelPerFrame[key] !== null ? manaLevelPerFrame[key] * max : null),
},
{
label: `HPS`,
...ManaStyles.HPS,
data: Object.keys(healingPerFrame).map(key => healingPerFrame[key] !== null ? healingPerFrame[key] / interval : null),
},
{
label: `Mana used`,
...ManaStyles.ManaUsed,
data: Object.keys(manaUsagePerFrame).map(key => manaUsagePerFrame[key] !== null ? manaUsagePerFrame[key] * max : null),
},
],
};
return (
<div>
<div className="flex">
<div className="flex-main">
This shows you your mana usage in correlation with your throughput. Big spikes in mana usage without increases in throughput may indicate poor mana usage. The scale for both mana lines is 0-100% where 100% is aligned with the max HPS throughput.
</div>
<div className="flex-sub form-inline">
<dfn data-tip="This groups events by the provided amount of seconds to smooth out the graph.">Smoothing</dfn>: <input type="number" min="1" max="30" value={interval} className="form-control" onChange={e => this.setState({ interval: Number(e.target.value) || 5 })} /> seconds
</div>
</div>
<div className="graph-container">
<Line
data={chartData}
options={baseConfig}
width={1100}
height={400}
/>
</div>
</div>
);
}
}
export default HealingDoneGraph;
|
src/index.js | hadynz/pact-testing-example | /* eslint-disable import/default */
import React from 'react';
import { render } from 'react-dom';
import { Router, hashHistory } from 'react-router';
import routes from './routes';
import './styles/styles.scss';
render(
<Router history={hashHistory} routes={routes} />, document.getElementById('app')
);
|
app/containers/CatKitDemo/index.js | mhoffman/CatAppBrowser | /*
*
* CatKitDemo
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import _ from 'lodash';
import { MdChevronLeft, MdChevronRight } from 'react-icons/lib/md';
import { isMobileOnly } from 'react-device-detect';
import Helmet from 'react-helmet';
import { withStyles } from 'material-ui/styles';
import Stepper, { Step, StepLabel } from 'material-ui/Stepper';
import Button from 'material-ui/Button';
import Paper from 'material-ui/Paper';
import Grid from 'material-ui/Grid';
import Slide from 'material-ui/transitions/Slide';
import * as snackbarActions from 'containers/AppSnackBar/actions';
import CatKitDemoHeader from './catKitDemoHeader';
import BulkInput from './BulkInput';
import { CalculationsView } from './CalculationsView';
import { BulkView } from './BulkView';
import SlabInput from './SlabInput';
import { SlabView } from './SlabView';
import AdsorbateInput from './SimpleAdsorbateInput';
import { AdsorbateView } from './AdsorbateView';
import DftInput from './DftInput';
import * as actions from './actions';
import { styles } from './styles';
function getSteps() {
return [
'Configure bulk structure',
'Configure surface slab',
'Add adsorbates',
];
}
function nextStepReady(step, props) {
switch (step) {
case 0:
return !_.isEmpty(props.bulkCif);
case 1:
return !_.isEmpty(props.images);
case 2:
return false;
case 3:
return false;
default:
return false;
}
}
function getStepContent(step, props) {
switch (step) {
case 0:
/* return 'Make choices for bulk cell'*/
return (
<Slide direction="left" in mountOnEnter unmountOnExit>
<div>
<BulkInput {...props} />
<BulkView {...props} />
</div>
</Slide>
);
case 1:
/* return 'Make choices for surface slab'*/
return (
<Slide direction="left" in mountOnEnter unmountOnExit>
<div>
<SlabInput {...props} />
<SlabView {...props} />
</div>
</Slide>
);
case 2:
/* return 'Add some adsorbates'*/
return (
<Slide direction="left" in mountOnEnter unmountOnExit>
<div>
<AdsorbateInput {...props} />
<AdsorbateView {...props} />
</div>
</Slide>
);
case 3:
/* return 'Configure calculator'*/
return (
<Slide direction="left" in mountOnEnter unmountOnExit>
<div>
<DftInput {...props} />
</div>
</Slide>
);
default:
return `Unkown step ${typeof activeStep}`;
}
}
export class CatKitDemo extends React.Component { // eslint-disable-line react/prefer-stateless-function
handleNext =() => {
this.props.stepperHandleNext();
}
handleReset = () => {
this.props.stepperHandleReset();
}
handleBack = () => {
this.props.stepperHandleBack();
}
render() {
const steps = getSteps();
const { activeStep } = this.props;
return (
<div>
<Helmet>
<title>CatKit Generator Demo</title>
<meta name="description" content="CatKit Generator Demo is a GUI which demonstrates show CatKit can be used to create slab geometries with adsorbates in high-symmetry sites." />
<meta name="keywords" content="catkit, adsorption, slab generator, surface slab, adsorbates, catalysis, miller index, high symmetry sites, constraints, adsorption energies, density functional theory, input files" />
</Helmet>
<div >
<div className={this.props.classes.header} >
<CatKitDemoHeader {...this.props} />
</div>
<Paper className={this.props.classes.paper}>
<Grid
container
justify="space-between"
direction="row"
className={this.props.classes.buttongrid}
>
<Grid item>
<Stepper activeStep={activeStep} className={this.props.classes.lightsandhill} orientation={isMobileOnly ? 'vertical' : 'horizontal'}>
{steps.map((label) => {
const props = {};
const labelProps = {};
return (
<Step key={label} {...props}>
<StepLabel {...labelProps}>{label}</StepLabel>
</Step>
);
})}
</Stepper>
</Grid>
<Grid item>
<Button
className={this.props.classes.button}
disabled={activeStep === 0 ||
(activeStep === 2 && _.isEmpty(this.props.slabParams))}
onClick={this.handleBack}
>
<MdChevronLeft /> Back
</Button><Button
raised
className={this.props.classes.button}
disabled={!nextStepReady(activeStep, this.props)}
color="primary"
onClick={this.handleNext}
>
Next <MdChevronRight />
</Button>
</Grid>
</Grid>
</Paper>
</div>
<Paper className={this.props.classes.paper} height={12}>
{getStepContent(activeStep, this.props)}
</Paper>
<CalculationsView {...this.props} />
</div>
);
}
}
CatKitDemo.propTypes = {
/* dispatch: PropTypes.func.isRequired,*/
classes: PropTypes.object,
activeStep: PropTypes.number,
stepperHandleNext: PropTypes.func,
stepperHandleBack: PropTypes.func,
stepperHandleReset: PropTypes.func,
slabParams: PropTypes.object,
};
const mapDispatchToProps = (dispatch) => ({
receiveBulkCif: (cif) => {
dispatch(actions.receiveBulkCif(cif));
},
receiveSlabCifs: (images) => {
dispatch(actions.receiveSlabCifs(images));
},
saveLatticeConstant: (latticeConstant) => {
dispatch(actions.saveLatticeConstant(latticeConstant));
},
saveBulkParams: (bulkParams) => {
dispatch(actions.saveBulkParams(bulkParams));
},
saveSlabParams: (slabParams) => {
dispatch(actions.saveSlabParams(slabParams));
},
saveCalculation: (params) => {
dispatch(actions.saveCalculation(params));
},
clearBulkParams: () => {
dispatch(actions.clearBulkParams());
},
clearSlabParams: () => {
dispatch(actions.clearSlabParams());
},
clearBulkCif: () => {
dispatch(actions.clearBulkCif());
},
clearSlabCifs: () => {
dispatch(actions.clearSlabCifs());
},
clearCalculations: () => {
dispatch(actions.clearCalculations());
},
setOpenCalculation: (n) => {
dispatch(actions.setOpenCalculation(n));
},
editCalculation: (n) => {
dispatch(actions.editCalculation(n));
},
copyCalculation: (n) => {
dispatch(actions.copyCalculation(n));
},
removeCalculation: (n) => {
dispatch(actions.removeCalculation(n));
},
saveAdsorptionSites: (adsorptionSites) => {
dispatch(actions.saveAdsorptionSites(adsorptionSites));
},
stepperHandleNext: () => {
dispatch(actions.stepperHandleNext());
},
stepperHandleBack: () => {
dispatch(actions.stepperHandleBack());
},
stepperHandleReset: () => {
dispatch(actions.stepperHandleReset());
},
saveAltLabels: (altLabels) => {
dispatch(actions.saveAltLabels(altLabels));
},
forgetCustomBulk: () => {
dispatch(actions.forgetCustomBulk());
},
forgetCustomSlab: () => {
dispatch(actions.forgetCustomSlab());
},
dropSlabInput: (file) => {
dispatch(actions.dropSlabInput(file));
},
dropBulkInput: (file) => {
dispatch(actions.dropBulkInput(file));
},
saveSiteOccupations: (siteOccupations) => {
dispatch(actions.saveSiteOccupations(siteOccupations));
},
clearSiteOccupations: () => {
dispatch(actions.clearSiteOccupations());
},
appendSiteOccupation: (siteOccupation) => {
dispatch(actions.appendSiteOccupation(siteOccupation));
},
openSnackbar: (message) => {
dispatch(snackbarActions.open(message));
},
saveAdsorbateParams: (adsorbateParams) => {
dispatch(actions.saveAdsorbateParams(adsorbateParams));
},
});
const mapStateToProps = (state) => ({
bulkCif: state.get('catKitDemoReducer').bulkCif,
images: state.get('catKitDemoReducer').images,
latticeConstant: state.get('catKitDemoReducer').latticeConstant,
bulkParams: state.get('catKitDemoReducer').bulkParams,
slabParams: state.get('catKitDemoReducer').slabParams,
calculations: state.get('catKitDemoReducer').calculations,
openCalculation: state.get('catKitDemoReducer').openCalculation,
adsorptionSites: state.get('catKitDemoReducer').adsorptionSites,
activeStep: state.get('catKitDemoReducer').activeStep,
altLabels: state.get('catKitDemoReducer').altLabels,
customBulkInput: state.get('catKitDemoReducer').customBulkInput,
customSlabInput: state.get('catKitDemoReducer').customSlabInput,
siteOccupations: state.get('catKitDemoReducer').siteOccupations,
adsorbateParams: state.get('catKitDemoReducer').adsorbateParams,
});
export default withStyles(styles, { withTheme: true })(
connect(mapStateToProps, mapDispatchToProps)(CatKitDemo)
);
|
Examples/UIExplorer/TabBarIOSExample.js | daveenguyen/react-native | /**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @flow
*/
'use strict';
var React = require('react-native');
var {
StyleSheet,
TabBarIOS,
Text,
View,
} = React;
var base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg==';
var TabBarExample = React.createClass({
statics: {
title: '<TabBarIOS>',
description: 'Tab-based navigation.',
},
displayName: 'TabBarExample',
getInitialState: function() {
return {
selectedTab: 'redTab',
notifCount: 0,
presses: 0,
};
},
_renderContent: function(color: string, pageText: string, num?: number) {
return (
<View style={[styles.tabContent, {backgroundColor: color}]}>
<Text style={styles.tabText}>{pageText}</Text>
<Text style={styles.tabText}>{num} re-renders of the {pageText}</Text>
</View>
);
},
render: function() {
return (
<TabBarIOS
tintColor="white"
barTintColor="darkslateblue">
<TabBarIOS.Item
title="Blue Tab"
icon={{uri: base64Icon, scale: 3}}
selected={this.state.selectedTab === 'blueTab'}
onPress={() => {
this.setState({
selectedTab: 'blueTab',
});
}}>
{this._renderContent('#414A8C', 'Blue Tab')}
</TabBarIOS.Item>
<TabBarIOS.Item
systemIcon="history"
badge={this.state.notifCount > 0 ? this.state.notifCount : undefined}
selected={this.state.selectedTab === 'redTab'}
onPress={() => {
this.setState({
selectedTab: 'redTab',
notifCount: this.state.notifCount + 1,
});
}}>
{this._renderContent('#783E33', 'Red Tab', this.state.notifCount)}
</TabBarIOS.Item>
<TabBarIOS.Item
systemIcon="more"
selected={this.state.selectedTab === 'greenTab'}
onPress={() => {
this.setState({
selectedTab: 'greenTab',
presses: this.state.presses + 1
});
}}>
{this._renderContent('#21551C', 'Green Tab', this.state.presses)}
</TabBarIOS.Item>
</TabBarIOS>
);
},
});
var styles = StyleSheet.create({
tabContent: {
flex: 1,
alignItems: 'center',
},
tabText: {
color: 'white',
margin: 50,
},
});
module.exports = TabBarExample;
|
docs/src/app/components/pages/components/LinearProgress/ExampleDeterminate.js | owencm/material-ui | import React from 'react';
import LinearProgress from 'material-ui/LinearProgress';
export default class LinearProgressExampleDeterminate extends React.Component {
constructor(props) {
super(props);
this.state = {
completed: 0,
};
}
componentDidMount() {
this.timer = setTimeout(() => this.progress(5), 1000);
}
componentWillUnmount() {
clearTimeout(this.timer);
}
progress(completed) {
if (completed > 100) {
this.setState({completed: 100});
} else {
this.setState({completed});
const diff = Math.random() * 10;
this.timer = setTimeout(() => this.progress(completed + diff), 1000);
}
}
render() {
return (
<LinearProgress mode="determinate" value={this.state.completed} />
);
}
}
|
backend/modules/content/src/test/browser/index.js | savantly-net/sprout-platform | import React from 'react';
import { Provider } from 'react-redux'
import { render} from 'react-dom';
import ContentModule from '../../main/browser';
import { BrowserRouter } from 'react-router-dom';
import { ConnectedRouter } from 'connected-react-router'
import store, { history } from '../../main/browser/store'
const App = () => (
<Provider store={store}>
<ConnectedRouter history={history}>
<ContentModule />
</ConnectedRouter>
</Provider>
);
render(<App />, document.getElementById("root")); |
src/elements/header.js | jessy1092/react-semantify |
import React from 'react';
import filter from '../filter';
import Unit from '../commons/unit';
const stateArray = ['disabled'];
const defaultClassName = 'ui header';
const componentName = 'Header';
const Header = new filter(Unit)
.typeFilter()
.colorFilter()
.stateFilter(stateArray)
.classGenerator(defaultClassName)
.getComposeComponent(componentName);
export default Header;
|
node_modules/reactify/node_modules/react-tools/src/browser/ui/dom/components/__tests__/ReactDOMButton-test.js | niole/super-simple-d3-barchart | /**
* 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';
/*jshint evil:true */
var mocks = require('mocks');
describe('ReactDOMButton', function() {
var React;
var ReactTestUtils;
var onClick = mocks.getMockFunction();
function expectClickThru(button) {
onClick.mockClear();
ReactTestUtils.Simulate.click(button.getDOMNode());
expect(onClick.mock.calls.length).toBe(1);
}
function expectNoClickThru(button) {
onClick.mockClear();
ReactTestUtils.Simulate.click(button.getDOMNode());
expect(onClick.mock.calls.length).toBe(0);
}
function mounted(button) {
button = ReactTestUtils.renderIntoDocument(button);
return button;
}
beforeEach(function() {
React = require('React');
ReactTestUtils = require('ReactTestUtils');
});
it('should forward clicks when it starts out not disabled', function() {
expectClickThru(mounted(<button onClick={onClick} />));
});
it('should not forward clicks when it starts out disabled', function() {
expectNoClickThru(
mounted(<button disabled={true} onClick={onClick} />)
);
});
it('should forward clicks when it becomes not disabled', function() {
var btn = mounted(<button disabled={true} onClick={onClick} />);
btn.setProps({disabled: false});
expectClickThru(btn);
});
it('should not forward clicks when it becomes disabled', function() {
var btn = mounted(<button onClick={onClick} />);
btn.setProps({disabled: true});
expectNoClickThru(btn);
});
it('should work correctly if the listener is changed', function() {
var btn = mounted(
<button disabled={true} onClick={function() {}} />
);
btn.setProps({
disabled: false,
onClick: onClick
});
expectClickThru(btn);
});
});
|
react-shrine-network-aware-code-splitting/src/components/NavBar/NavBar.js | GoogleChromeLabs/adaptive-loading | /*
* Copyright 2019 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import { withRouter } from 'react-router-dom';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import { categories } from '../../utils/links';
import { getCategoryById } from '../../utils/utilities';
import './nav-bar.css';
const NavBar = ({ history, selected }) => {
const navChangeHandler = (event, value) => {
const category = getCategoryById(value);
history.push(`/category/${category.name.toLowerCase()}`);
};
return (
<Tabs
className='nav-bar'
value={selected.id}
onChange={navChangeHandler}
scrollButtons='auto'>
{ categories.map(category => (
<Tab
key={category.id}
label={category.name}
value={category.id} />
)) }
</Tabs>
);
};
export default withRouter(NavBar);
|
ajax/libs/6to5/3.6.4/browser-polyfill.js | RizkyAdiSaputra/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){(function(global){"use strict";if(global._6to5Polyfill){throw new Error("only one instance of 6to5/polyfill is allowed")}global._6to5Polyfill=true;require("core-js/shim");require("regenerator-6to5/runtime")}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"core-js/shim":2,"regenerator-6to5/runtime":3}],2:[function(require,module,exports){!function(global,framework,undefined){"use strict";var OBJECT="Object",FUNCTION="Function",ARRAY="Array",STRING="String",NUMBER="Number",REGEXP="RegExp",DATE="Date",MAP="Map",SET="Set",WEAKMAP="WeakMap",WEAKSET="WeakSet",SYMBOL="Symbol",PROMISE="Promise",MATH="Math",ARGUMENTS="Arguments",PROTOTYPE="prototype",CONSTRUCTOR="constructor",TO_STRING="toString",TO_STRING_TAG=TO_STRING+"Tag",TO_LOCALE="toLocaleString",HAS_OWN="hasOwnProperty",FOR_EACH="forEach",ITERATOR="iterator",FF_ITERATOR="@@"+ITERATOR,PROCESS="process",CREATE_ELEMENT="createElement",Function=global[FUNCTION],Object=global[OBJECT],Array=global[ARRAY],String=global[STRING],Number=global[NUMBER],RegExp=global[REGEXP],Date=global[DATE],Map=global[MAP],Set=global[SET],WeakMap=global[WEAKMAP],WeakSet=global[WEAKSET],Symbol=global[SYMBOL],Math=global[MATH],TypeError=global.TypeError,setTimeout=global.setTimeout,setImmediate=global.setImmediate,clearImmediate=global.clearImmediate,parseInt=global.parseInt,isFinite=global.isFinite,process=global[PROCESS],nextTick=process&&process.nextTick,document=global.document,html=document&&document.documentElement,navigator=global.navigator,define=global.define,ArrayProto=Array[PROTOTYPE],ObjectProto=Object[PROTOTYPE],FunctionProto=Function[PROTOTYPE],Infinity=1/0,DOT=".",CONSOLE_METHODS="assert,clear,count,debug,dir,dirxml,error,exception,"+"group,groupCollapsed,groupEnd,info,isIndependentlyComposed,log,"+"markTimeline,profile,profileEnd,table,time,timeEnd,timeline,"+"timelineEnd,timeStamp,trace,warn";function isObject(it){return it!==null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}var isNative=ctx(/./.test,/\[native code\]\s*\}\s*$/,1);var toString=ObjectProto[TO_STRING];function setToStringTag(it,tag,stat){if(it&&!has(it=stat?it:it[PROTOTYPE],SYMBOL_TAG))hidden(it,SYMBOL_TAG,tag)}function cof(it){return toString.call(it).slice(8,-1)}function classof(it){var O,T;return it==undefined?it===undefined?"Undefined":"Null":typeof(T=(O=Object(it))[SYMBOL_TAG])=="string"?T:cof(O)}var call=FunctionProto.call,apply=FunctionProto.apply,REFERENCE_GET;function part(){var fn=assertFunction(this),length=arguments.length,args=Array(length),i=0,_=path._,holder=false;while(length>i)if((args[i]=arguments[i++])===_)holder=true;return function(){var that=this,_length=arguments.length,i=0,j=0,_args;if(!holder&&!_length)return invoke(fn,args,that);_args=args.slice();if(holder)for(;length>i;i++)if(_args[i]===_)_args[i]=arguments[j++];while(_length>j)_args.push(arguments[j++]);return invoke(fn,_args,that)}}function ctx(fn,that,length){assertFunction(fn);if(~length&&that===undefined)return fn;switch(length){case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}}function invoke(fn,args,that){var un=that===undefined;switch(args.length|0){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)}function construct(target,argumentsList){var proto=assertFunction(arguments.length<3?target:arguments[2])[PROTOTYPE],instance=create(isObject(proto)?proto:ObjectProto),result=apply.call(target,instance,argumentsList);return isObject(result)?result:instance}var create=Object.create,getPrototypeOf=Object.getPrototypeOf,setPrototypeOf=Object.setPrototypeOf,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,getOwnDescriptor=Object.getOwnPropertyDescriptor,getKeys=Object.keys,getNames=Object.getOwnPropertyNames,getSymbols=Object.getOwnPropertySymbols,isFrozen=Object.isFrozen,has=ctx(call,ObjectProto[HAS_OWN],2),ES5Object=Object,Dict;function toObject(it){return ES5Object(assertDefined(it))}function returnIt(it){return it}function returnThis(){return this}function get(object,key){if(has(object,key))return object[key]}function ownKeys(it){assertObject(it);return getSymbols?getNames(it).concat(getSymbols(it)):getNames(it)}var assign=Object.assign||function(target,source){var T=Object(assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=ES5Object(arguments[i++]),keys=getKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T};function keyOf(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}function array(it){return String(it).split(",")}var push=ArrayProto.push,unshift=ArrayProto.unshift,slice=ArrayProto.slice,splice=ArrayProto.splice,indexOf=ArrayProto.indexOf,forEach=ArrayProto[FOR_EACH];function createArrayMethod(type){var isMap=type==1,isFilter=type==2,isSome=type==3,isEvery=type==4,isFindIndex=type==6,noholes=type==5||isFindIndex;return function(callbackfn){var O=Object(assertDefined(this)),that=arguments[1],self=ES5Object(O),f=ctx(callbackfn,that,3),length=toLength(self.length),index=0,result=isMap?Array(length):isFilter?[]:undefined,val,res;for(;length>index;index++)if(noholes||index in self){val=self[index];res=f(val,index,O);if(type){if(isMap)result[index]=res;else if(res)switch(type){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(isEvery)return false}}return isFindIndex?-1:isSome||isEvery?isEvery:result}}function createArrayContains(isContains){return function(el){var O=toObject(this),length=toLength(O.length),index=toIndex(arguments[1],length);if(isContains&&el!=el){for(;length>index;index++)if(sameNaN(O[index]))return isContains||index}else for(;length>index;index++)if(isContains||index in O){if(O[index]===el)return isContains||index}return!isContains&&-1}}function generic(A,B){return typeof A=="function"?A:B}var MAX_SAFE_INTEGER=9007199254740991,pow=Math.pow,abs=Math.abs,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min,random=Math.random,trunc=Math.trunc||function(it){return(it>0?floor:ceil)(it)};function sameNaN(number){return number!=number}function toInteger(it){return isNaN(it)?0:trunc(it)}function toLength(it){return it>0?min(toInteger(it),MAX_SAFE_INTEGER):0}function toIndex(index,length){var index=toInteger(index);return index<0?max(index+length,0):min(index,length)}function createReplacer(regExp,replace,isStatic){var replacer=isObject(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}function createPointAt(toString){return function(pos){var s=String(assertDefined(this)),i=toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return toString?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?toString?s.charAt(i):a:toString?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}var REDUCE_ERROR="Reduce of empty object with no initial value";function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}function assertDefined(it){if(it==undefined)throw TypeError("Function called on null or undefined");return it}function assertFunction(it){assert(isFunction(it),it," is not a function!");return it}function assertObject(it){assert(isObject(it),it," is not an object!");return it}function assertInstance(it,Constructor,name){assert(it instanceof Constructor,name,": use the 'new' operator!")}function descriptor(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 defineProperty(object,key,descriptor(bitmap,value))}:simpleSet}function uid(key){return SYMBOL+"("+key+")_"+(++sid+random())[TO_STRING](36)}function getWellKnownSymbol(name,setter){return Symbol&&Symbol[name]||(setter?Symbol:safeSymbol)(SYMBOL+DOT+name)}var DESC=!!function(){try{return defineProperty({},"a",{get:function(){return 2}}).a==2}catch(e){}}(),sid=0,hidden=createDefiner(1),set=Symbol?simpleSet:hidden,safeSymbol=Symbol||uid;function assignHidden(target,src){for(var key in src)hidden(target,key,src[key]);return target}var SYMBOL_UNSCOPABLES=getWellKnownSymbol("unscopables"),ArrayUnscopables=ArrayProto[SYMBOL_UNSCOPABLES]||{},SYMBOL_SPECIES=getWellKnownSymbol("species");function setSpecies(C){if(framework||!isNative(C))defineProperty(C,SYMBOL_SPECIES,{configurable:true,get:returnThis})}var SYMBOL_ITERATOR=getWellKnownSymbol(ITERATOR),SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG),SUPPORT_FF_ITER=FF_ITERATOR in ArrayProto,ITER=safeSymbol("iter"),KEY=1,VALUE=2,Iterators={},IteratorPrototype={},NATIVE_ITERATORS=SYMBOL_ITERATOR in ArrayProto,BUGGY_ITERATORS="keys"in ArrayProto&&!("next"in[].keys());setIterator(IteratorPrototype,returnThis);function setIterator(O,value){hidden(O,SYMBOL_ITERATOR,value);SUPPORT_FF_ITER&&hidden(O,FF_ITERATOR,value)}function createIterator(Constructor,NAME,next,proto){Constructor[PROTOTYPE]=create(proto||IteratorPrototype,{next:descriptor(1,next)});setToStringTag(Constructor,NAME+" Iterator")}function defineIterator(Constructor,NAME,value,DEFAULT){var proto=Constructor[PROTOTYPE],iter=get(proto,SYMBOL_ITERATOR)||get(proto,FF_ITERATOR)||DEFAULT&&get(proto,DEFAULT)||value;if(framework){setIterator(proto,iter);if(iter!==value){var iterProto=getPrototypeOf(iter.call(new Constructor));setToStringTag(iterProto,NAME+" Iterator",true);has(proto,FF_ITERATOR)&&setIterator(iterProto,returnThis)}}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=returnThis;return iter}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT,IS_SET){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);var entries=createIter(KEY+VALUE),values=createIter(VALUE);if(DEFAULT==VALUE)values=defineIterator(Base,NAME,values,"values");else entries=defineIterator(Base,NAME,entries,"entries");if(DEFAULT){$define(PROTO+FORCED*BUGGY_ITERATORS,NAME,{entries:entries,keys:IS_SET?values:createIter(KEY),values:values})}}function iterResult(done,value){return{value:value,done:!!done}}function isIterable(it){var O=Object(it),Symbol=global[SYMBOL],hasExt=(Symbol&&Symbol[ITERATOR]||FF_ITERATOR)in O;return hasExt||SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){var Symbol=global[SYMBOL],ext=it[Symbol&&Symbol[ITERATOR]||FF_ITERATOR],getIter=ext||it[SYMBOL_ITERATOR]||Iterators[classof(it)];return assertObject(getIter.call(it))}function stepCall(fn,value,entries){return entries?invoke(fn,value):fn(value)}function forOf(iterable,entries,fn,that){var iterator=getIterator(iterable),f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done)if(stepCall(f,step.value,entries)===false)return}var NODE=cof(process)==PROCESS,core={},path=framework?global:core,old=global.core,exportGlobal,FORCED=1,GLOBAL=2,STATIC=4,PROTO=8,BIND=16,WRAP=32;function $define(type,name,source){var key,own,out,exp,isGlobal=type&GLOBAL,target=isGlobal?global:type&STATIC?global[name]:(global[name]||ObjectProto)[PROTOTYPE],exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&FORCED)&&target&&key in target&&(!isFunction(target[key])||isNative(target[key]));out=(own?target:source)[key];if(type&BIND&&own)exp=ctx(out,global);else if(type&WRAP&&!framework&&target[key]==out){exp=function(param){return this instanceof out?new out(param):out(param)};exp[PROTOTYPE]=out[PROTOTYPE]}else exp=type&PROTO&&isFunction(out)?ctx(call,out):out;if(exports[key]!=out)hidden(exports,key,exp);if(framework&&target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&hidden(target,key,out)}}}if(typeof module!="undefined"&&module.exports)module.exports=core;else if(isFunction(define)&&define.amd)define(function(){return core});else exportGlobal=true;if(exportGlobal||framework){core.noConflict=function(){global.core=old;return core};global.core=core}!function(TAG,SymbolRegistry,AllSymbols,setter){if(!isNative(Symbol)){Symbol=function(description){assert(!(this instanceof Symbol),SYMBOL+" is not a "+CONSTRUCTOR);var tag=uid(description),sym=set(create(Symbol[PROTOTYPE]),TAG,tag);AllSymbols[tag]=sym;DESC&&setter&&defineProperty(ObjectProto,tag,{configurable:true,set:function(value){hidden(this,tag,value)}});return sym};hidden(Symbol[PROTOTYPE],TO_STRING,function(){return this[TAG]})}$define(GLOBAL+WRAP,{Symbol:Symbol});var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},iterator:SYMBOL_ITERATOR,keyFor:part.call(keyOf,SymbolRegistry),species:SYMBOL_SPECIES,toStringTag:SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG,true),unscopables:SYMBOL_UNSCOPABLES,pure:safeSymbol,set:set,useSetter:function(){setter=true},useSimple:function(){setter=false}};forEach.call(array("hasInstance,isConcatSpreadable,match,replace,search,split,toPrimitive"),function(it){symbolStatics[it]=getWellKnownSymbol(it)});$define(STATIC,SYMBOL,symbolStatics);setToStringTag(Symbol,SYMBOL);$define(STATIC+FORCED*!isNative(Symbol),OBJECT,{getOwnPropertyNames:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])||result.push(key);return result},getOwnPropertySymbols:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])&&result.push(AllSymbols[key]);return result}})}(safeSymbol("tag"),{},{},true);!function(tmp){var objectStatic={assign:assign,is:function(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}};"__proto__"in ObjectProto&&function(buggy,set){try{set=ctx(call,getOwnDescriptor(ObjectProto,"__proto__").set,2);set({},ArrayProto)}catch(e){buggy=true}objectStatic.setPrototypeOf=setPrototypeOf=setPrototypeOf||function(O,proto){assertObject(O);assert(proto===null||isObject(proto),proto,": can't set as prototype!");if(buggy)O.__proto__=proto;else set(O,proto);return O}}();$define(STATIC,OBJECT,objectStatic);if(framework){tmp[SYMBOL_TAG]=DOT;if(cof(tmp)!=DOT)hidden(ObjectProto,TO_STRING,function(){return"[object "+classof(this)+"]"})}setToStringTag(Math,MATH,true);setToStringTag(global.JSON,"JSON",true)}({});!function(){function wrapObjectMethod(key,MODE){var fn=Object[key],exp=core[OBJECT][key],f=0,o={};if(!exp||isNative(exp)){o[key]=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(it,key){return fn(toObject(it),key)}:function(it){return fn(toObject(it))};try{fn(DOT)}catch(e){f=1}$define(STATIC+FORCED*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");wrapObjectMethod("keys");wrapObjectMethod("getOwnPropertyNames")}();!function(NAME){NAME in FunctionProto||defineProperty(FunctionProto,NAME,{configurable:true,get:function(){var match=String(this).match(/^\s*function ([^ (]*)/),name=match?match[1]:"";has(this,NAME)||defineProperty(this,NAME,descriptor(5,name));return name},set:function(value){has(this,NAME)||defineProperty(this,NAME,descriptor(0,value))}})}("name");!function(isInteger){$define(STATIC,NUMBER,{EPSILON:pow(2,-52),isFinite:function(it){return typeof it=="number"&&isFinite(it)},isInteger:isInteger,isNaN:sameNaN,isSafeInteger:function(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt})}(Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it});!function(){var E=Math.E,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,sign=Math.sign||function(x){return(x=+x)==0||x!=x?x:x<0?-1:1};function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}function expm1(x){return(x=+x)==0?x:x>-1e-6&&x<1e-6?x+x*x/2:exp(x)-1}$define(STATIC,MATH,{acosh:function(x){return(x=+x)<1?NaN:isFinite(x)?log(x/E+sqrt(x+1)*sqrt(x-1)/E)+1:x},asinh:asinh,atanh:function(x){return(x=+x)==0?x:log((1+x)/(1-x))/2},cbrt:function(x){return sign(x=+x)*pow(abs(x),1/3)},clz32:function(x){return(x>>>=0)?32-x[TO_STRING](2).length:32},cosh:function(x){return(exp(x=+x)+exp(-x))/2},expm1:expm1,fround:function(x){return new Float32Array([x])[0]},hypot:function(value1,value2){var sum=0,len1=arguments.length,len2=len1,args=Array(len1),larg=-Infinity,arg;while(len1--){arg=args[len1]=+arguments[len1];if(arg==Infinity||arg==-Infinity)return Infinity;if(arg>larg)larg=arg}larg=arg||1;while(len2--)sum+=pow(args[len2]/larg,2);return larg*sqrt(sum)},imul:function(x,y){var UInt16=65535,xn=+x,yn=+y,xl=UInt16&xn,yl=UInt16&yn;return 0|xl*yl+((UInt16&xn>>>16)*yl+xl*(UInt16&yn>>>16)<<16>>>0)},log1p:function(x){return(x=+x)>-1e-8&&x<1e-8?x-x*x/2:log(1+x)},log10:function(x){return log(x)/Math.LN10},log2:function(x){return log(x)/Math.LN2},sign:sign,sinh:function(x){return abs(x=+x)<1?(expm1(x)-expm1(-x))/2:(exp(x-1)-exp(-x-1))*(E/2)},tanh:function(x){var a=expm1(x=+x),b=expm1(-x);return a==Infinity?1:b==Infinity?-1:(a-b)/(exp(x)+exp(-x))},trunc:trunc})}();!function(RangeError,fromCharCode){function assertNotRegExp(it){if(cof(it)==REGEXP)throw TypeError()}$define(STATIC,STRING,{fromCodePoint:function(x){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fromCharCode(code):fromCharCode(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")},raw:function(callSite){var raw=toObject(callSite.raw),len=toLength(raw.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(raw[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}});$define(PROTO,STRING,{codePointAt:createPointAt(false),endsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),endPosition=arguments[1],len=toLength(that.length),end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return that.slice(end-searchString.length,end)===searchString},includes:function(searchString){assertNotRegExp(searchString);return!!~String(assertDefined(this)).indexOf(searchString,arguments[1])},repeat:function(count){var str=String(assertDefined(this)),res="",n=toInteger(count);if(0>n||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res},startsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),index=toLength(min(arguments[1],that.length));searchString+="";return that.slice(index,index+searchString.length)===searchString}})}(global.RangeError,String.fromCharCode);!function(){$define(STATIC,ARRAY,{from:function(arrayLike){var O=Object(assertDefined(arrayLike)),mapfn=arguments[1],mapping=mapfn!==undefined,f=mapping?ctx(mapfn,arguments[2],2):undefined,index=0,length,result,iter,step;if(isIterable(O))for(iter=getIterator(O),result=new(generic(this,Array));!(step=iter.next()).done;index++){result[index]=mapping?f(step.value,index):step.value}else for(result=new(generic(this,Array))(length=toLength(O.length));length>index;index++){result[index]=mapping?f(O[index],index):O[index]}result.length=index;return result},of:function(){var index=0,length=arguments.length,result=new(generic(this,Array))(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}});$define(PROTO,ARRAY,{copyWithin:function(target,start){var O=Object(assertDefined(this)),len=toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),end=arguments[2],fin=end===undefined?len:toIndex(end,len),count=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},fill:function(value){var O=Object(assertDefined(this)),length=toLength(O.length),index=toIndex(arguments[1],length),end=arguments[2],endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O},find:createArrayMethod(5),findIndex:createArrayMethod(6)});if(framework){forEach.call(array("find,findIndex,fill,copyWithin,entries,keys,values"),function(it){ArrayUnscopables[it]=true});SYMBOL_UNSCOPABLES in ArrayProto||hidden(ArrayProto,SYMBOL_UNSCOPABLES,ArrayUnscopables)}setSpecies(Array)}();!function(at){defineStdIterators(Array,ARRAY,function(iterated,kind){set(this,ITER,{o:toObject(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length){iter.o=undefined;return iterResult(1)}if(kind==KEY)return iterResult(0,index);if(kind==VALUE)return iterResult(0,O[index]);return iterResult(0,[index,O[index]])},VALUE);Iterators[ARGUMENTS]=Iterators[ARRAY];defineStdIterators(String,STRING,function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return iterResult(1);point=at.call(O,index);iter.i+=point.length;return iterResult(0,point)})}(createPointAt(true));!function(RegExpProto,_RegExp){function assertRegExpWrapper(fn){return function(){assert(cof(this)===REGEXP);return fn(this)}}if(DESC&&!function(){try{return RegExp(/a/g,"i")=="/a/i"}catch(e){}}()){RegExp=function RegExp(pattern,flags){return new _RegExp(cof(pattern)==REGEXP&&flags!==undefined?pattern.source:pattern,flags)};forEach.call(getNames(_RegExp),function(key){key in RegExp||defineProperty(RegExp,key,{configurable:true,get:function(){return _RegExp[key]},set:function(it){_RegExp[key]=it}})});RegExpProto[CONSTRUCTOR]=RegExp;RegExp[PROTOTYPE]=RegExpProto;hidden(global,REGEXP,RegExp)}if(/./g.flags!="g")defineProperty(RegExpProto,"flags",{configurable:true,get:assertRegExpWrapper(createReplacer(/^.*\/(\w*)$/,"$1",true))});forEach.call(array("sticky,unicode"),function(key){key in/./||defineProperty(RegExpProto,key,DESC?{configurable:true,get:assertRegExpWrapper(function(){return false})}:descriptor(5,false))});setSpecies(RegExp)}(RegExp[PROTOTYPE],RegExp);isFunction(setImmediate)&&isFunction(clearImmediate)||function(ONREADYSTATECHANGE){var postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},defer,channel,port;setImmediate=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};clearImmediate=function(id){delete queue[id]};function run(id){if(has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run(event.data)}if(NODE){defer=function(id){nextTick(part.call(run,id))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document[CREATE_ELEMENT]("script")){defer=function(id){html.appendChild(document[CREATE_ELEMENT]("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run(id)}}}else{defer=function(id){setTimeout(run,0,id)}}}("onreadystatechange");$define(GLOBAL+BIND,{setImmediate:setImmediate,clearImmediate:clearImmediate});!function(Promise,test){isFunction(Promise)&&isFunction(Promise.resolve)&&Promise.resolve(test=new Promise(function(){}))==test||function(asap,DEF){function isThenable(o){var then;if(isObject(o))then=o.then;return isFunction(then)?then:false}function notify(def){var chain=def.chain;chain.length&&asap(function(){var msg=def.msg,ok=def.state==1,i=0;while(chain.length>i)!function(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){ret=cb===true?msg:cb(msg);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(msg)}catch(err){react.rej(err)}}(chain[i++]);chain.length=0})}function resolve(msg){var def=this,then,wrapper;if(def.done)return;def.done=true;def=def.def||def;try{if(then=isThenable(msg)){wrapper={def:def,done:false};then.call(msg,ctx(resolve,wrapper,1),ctx(reject,wrapper,1))}else{def.msg=msg;def.state=1;notify(def)}}catch(err){reject.call(wrapper||{def:def,done:false},err)}}function reject(msg){var def=this;if(def.done)return;def.done=true;def=def.def||def;def.msg=msg;def.state=2;notify(def)}function getConstructor(C){var S=assertObject(C)[SYMBOL_SPECIES];return S!=undefined?S:C}Promise=function(executor){assertFunction(executor);assertInstance(this,Promise,PROMISE);var def={chain:[],state:0,done:false,msg:undefined};hidden(this,DEF,def);try{executor(ctx(resolve,def,1),ctx(reject,def,1))}catch(err){reject.call(def,err)}};assignHidden(Promise[PROTOTYPE],{then:function(onFulfilled,onRejected){var S=assertObject(assertObject(this)[CONSTRUCTOR])[SYMBOL_SPECIES];var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false},P=react.P=new(S!=undefined?S:Promise)(function(resolve,reject){react.res=assertFunction(resolve);react.rej=assertFunction(reject)}),def=this[DEF];def.chain.push(react);def.state&¬ify(def);return P},"catch":function(onRejected){return this.then(undefined,onRejected)}});assignHidden(Promise,{all:function(iterable){var Promise=getConstructor(this),values=[];return new Promise(function(resolve,reject){forOf(iterable,false,push,values);var remaining=values.length,results=Array(remaining);if(remaining)forEach.call(values,function(promise,index){Promise.resolve(promise).then(function(value){results[index]=value;--remaining||resolve(results)},reject)});else resolve(results)})},race:function(iterable){var Promise=getConstructor(this);return new Promise(function(resolve,reject){forOf(iterable,false,function(promise){Promise.resolve(promise).then(resolve,reject)})})},reject:function(r){return new(getConstructor(this))(function(resolve,reject){reject(r)})},resolve:function(x){return isObject(x)&&DEF in x&&getPrototypeOf(x)===this[PROTOTYPE]?x:new(getConstructor(this))(function(resolve,reject){resolve(x)})}})}(nextTick||setImmediate,safeSymbol("def"));setToStringTag(Promise,PROMISE);setSpecies(Promise);$define(GLOBAL+FORCED*!isNative(Promise),{Promise:Promise})}(global[PROMISE]);!function(){var UID=safeSymbol("uid"),O1=safeSymbol("O1"),WEAK=safeSymbol("weak"),LEAK=safeSymbol("leak"),LAST=safeSymbol("last"),FIRST=safeSymbol("first"),SIZE=DESC?safeSymbol("size"):"size",uid=0,tmp={};function getCollection(C,NAME,methods,commonMethods,isMap,isWeak){var ADDER=isMap?"set":"add",proto=C&&C[PROTOTYPE],O={};function initFromIterable(that,iterable){if(iterable!=undefined)forOf(iterable,isMap,that[ADDER],that);return that}function fixSVZ(key,chain){var method=proto[key];if(framework)proto[key]=function(a,b){var result=method.call(this,a===0?0:a,b);return chain?this:result}}if(!isNative(C)||!(isWeak||!BUGGY_ITERATORS&&has(proto,FOR_EACH)&&has(proto,"entries"))){C=isWeak?function(iterable){assertInstance(this,C,NAME);set(this,UID,uid++);initFromIterable(this,iterable)}:function(iterable){var that=this;assertInstance(that,C,NAME);set(that,O1,create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);initFromIterable(that,iterable)};assignHidden(assignHidden(C[PROTOTYPE],methods),commonMethods);isWeak||defineProperty(C[PROTOTYPE],"size",{get:function(){return assertDefined(this[SIZE])}})}else{var Native=C,inst=new C,chain=inst[ADDER](isWeak?{}:-0,1),buggyZero;if(!NATIVE_ITERATORS||!C.length){C=function(iterable){assertInstance(this,C,NAME);return initFromIterable(new Native,iterable)};C[PROTOTYPE]=proto;if(framework)proto[CONSTRUCTOR]=C}isWeak||inst[FOR_EACH](function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixSVZ("delete");fixSVZ("has");isMap&&fixSVZ("get")}if(buggyZero||chain!==inst)fixSVZ(ADDER,true)}setToStringTag(C,NAME);setSpecies(C);O[NAME]=C;$define(GLOBAL+WRAP+FORCED*!isNative(C),O);isWeak||defineStdIterators(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!iter.o||!(iter.l=entry=entry?entry.n:iter.o[FIRST])){iter.o=undefined;return iterResult(1)}if(kind==KEY)return iterResult(0,entry.k);if(kind==VALUE)return iterResult(0,entry.v);return iterResult(0,[entry.k,entry.v])},isMap?KEY+VALUE:VALUE,!isMap);return C}function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(isFrozen(it))return"F";if(!has(it,UID)){if(!create)return"E";hidden(it,UID,++uid)}return"O"+it[UID]}function getEntry(that,key){var index=fastKey(key),entry;if(index!="F")return that[O1][index];for(entry=that[FIRST];entry;entry=entry.n){if(entry.k==key)return entry}}function def(that,key,value){var entry=getEntry(that,key),prev,index;if(entry)entry.v=value;else{that[LAST]=entry={i:index=fastKey(key,true),k:key,v:value,p:prev=that[LAST],n:undefined,r:false};if(!that[FIRST])that[FIRST]=entry;if(prev)prev.n=entry;that[SIZE]++;if(index!="F")that[O1][index]=entry}return that}var collectionMethods={clear:function(){for(var that=this,data=that[O1],entry=that[FIRST];entry;entry=entry.n){entry.r=true;if(entry.p)entry.p=entry.p.n=undefined;delete data[entry.i]}that[FIRST]=that[LAST]=undefined;that[SIZE]=0},"delete":function(key){var that=this,entry=getEntry(that,key);if(entry){var next=entry.n,prev=entry.p;delete that[O1][entry.i];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}return!!entry},forEach:function(callbackfn){var f=ctx(callbackfn,arguments[1],3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function(key){return!!getEntry(this,key)}};Map=getCollection(Map,MAP,{get:function(key){var entry=getEntry(this,key);return entry&&entry.v},set:function(key,value){return def(this,key===0?0:key,value)}},collectionMethods,true);Set=getCollection(Set,SET,{add:function(value){return def(this,value=value===0?0:value,value)}},collectionMethods);function defWeak(that,key,value){if(isFrozen(assertObject(key)))leakStore(that).set(key,value);else{has(key,WEAK)||hidden(key,WEAK,{});key[WEAK][that[UID]]=value}return that}function leakStore(that){return that[LEAK]||hidden(that,LEAK,new Map)[LEAK]}var weakMethods={"delete":function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this)["delete"](key);return has(key,WEAK)&&has(key[WEAK],this[UID])&&delete key[WEAK][this[UID]]},has:function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this).has(key);
return has(key,WEAK)&&has(key[WEAK],this[UID])}};WeakMap=getCollection(WeakMap,WEAKMAP,{get:function(key){if(isObject(key)){if(isFrozen(key))return leakStore(this).get(key);if(has(key,WEAK))return key[WEAK][this[UID]]}},set:function(key,value){return defWeak(this,key,value)}},weakMethods,true,true);if(framework&&(new WeakMap).set(Object.freeze(tmp),7).get(tmp)!=7){forEach.call(array("delete,has,get,set"),function(key){var method=WeakMap[PROTOTYPE][key];WeakMap[PROTOTYPE][key]=function(a,b){if(isObject(a)&&isFrozen(a)){var result=leakStore(this)[key](a,b);return key=="set"?this:result}return method.call(this,a,b)}})}WeakSet=getCollection(WeakSet,WEAKSET,{add:function(value){return defWeak(this,value,true)}},weakMethods,false,true)}();!function(){function Enumerate(iterated){var keys=[],key;for(key in iterated)keys.push(key);set(this,ITER,{o:iterated,a:keys,i:0})}createIterator(Enumerate,OBJECT,function(){var iter=this[ITER],keys=iter.a,key;do{if(iter.i>=keys.length)return iterResult(1)}while(!((key=keys[iter.i++])in iter.o));return iterResult(0,key)});function wrap(fn){return function(it){assertObject(it);try{return fn.apply(undefined,arguments),true}catch(e){return false}}}function reflectGet(target,propertyKey){var receiver=arguments.length<3?target:arguments[2],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc)return has(desc,"value")?desc.value:desc.get===undefined?undefined:desc.get.call(receiver);return isObject(proto=getPrototypeOf(target))?reflectGet(proto,propertyKey,receiver):undefined}function reflectSet(target,propertyKey,V){var receiver=arguments.length<4?target:arguments[3],ownDesc=getOwnDescriptor(assertObject(target),propertyKey),existingDescriptor,proto;if(!ownDesc){if(isObject(proto=getPrototypeOf(target))){return reflectSet(proto,propertyKey,V,receiver)}ownDesc=descriptor(0)}if(has(ownDesc,"value")){if(ownDesc.writable===false||!isObject(receiver))return false;existingDescriptor=getOwnDescriptor(receiver,propertyKey)||descriptor(0);existingDescriptor.value=V;return defineProperty(receiver,propertyKey,existingDescriptor),true}return ownDesc.set===undefined?false:(ownDesc.set.call(receiver,V),true)}var isExtensible=Object.isExtensible||returnIt;var reflect={apply:ctx(call,apply,3),construct:construct,defineProperty:wrap(defineProperty),deleteProperty:function(target,propertyKey){var desc=getOwnDescriptor(assertObject(target),propertyKey);return desc&&!desc.configurable?false:delete target[propertyKey]},enumerate:function(target){return new Enumerate(assertObject(target))},get:reflectGet,getOwnPropertyDescriptor:function(target,propertyKey){return getOwnDescriptor(assertObject(target),propertyKey)},getPrototypeOf:function(target){return getPrototypeOf(assertObject(target))},has:function(target,propertyKey){return propertyKey in target},isExtensible:function(target){return!!isExtensible(assertObject(target))},ownKeys:ownKeys,preventExtensions:wrap(Object.preventExtensions||returnIt),set:reflectSet};if(setPrototypeOf)reflect.setPrototypeOf=function(target,proto){return setPrototypeOf(assertObject(target),proto),true};$define(GLOBAL,{Reflect:{}});$define(STATIC,"Reflect",reflect)}();!function(){$define(PROTO,ARRAY,{includes:createArrayContains(true)});$define(PROTO,STRING,{at:createPointAt(true)});function createObjectToArray(isEntries){return function(object){var O=toObject(object),keys=getKeys(object),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$define(STATIC,OBJECT,{values:createObjectToArray(false),entries:createObjectToArray(true)});$define(STATIC,REGEXP,{escape:createReplacer(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(REFERENCE){REFERENCE_GET=getWellKnownSymbol(REFERENCE+"Get",true);var REFERENCE_SET=getWellKnownSymbol(REFERENCE+SET,true),REFERENCE_DELETE=getWellKnownSymbol(REFERENCE+"Delete",true);$define(STATIC,SYMBOL,{referenceGet:REFERENCE_GET,referenceSet:REFERENCE_SET,referenceDelete:REFERENCE_DELETE});hidden(FunctionProto,REFERENCE_GET,returnThis);function setMapMethods(Constructor){if(Constructor){var MapProto=Constructor[PROTOTYPE];hidden(MapProto,REFERENCE_GET,MapProto.get);hidden(MapProto,REFERENCE_SET,MapProto.set);hidden(MapProto,REFERENCE_DELETE,MapProto["delete"])}}setMapMethods(Map);setMapMethods(WeakMap)}("reference");!function(arrayStatics){function setArrayStatics(keys,length){forEach.call(array(keys),function(key){if(key in ArrayProto)arrayStatics[key]=ctx(call,ArrayProto[key],length)})}setArrayStatics("pop,reverse,shift,keys,values,entries",1);setArrayStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setArrayStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn");$define(STATIC,ARRAY,arrayStatics)}({});!function(NodeList){if(framework&&NodeList&&!(SYMBOL_ITERATOR in NodeList[PROTOTYPE])){hidden(NodeList[PROTOTYPE],SYMBOL_ITERATOR,Iterators[ARRAY])}Iterators.NodeList=Iterators[ARRAY]}(global.NodeList)}(typeof self!="undefined"&&self.Math===Math?self:Function("return this")(),true)},{}],3:[function(require,module,exports){(function(global){!function(global){"use strict";var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var inModule=typeof module==="object";var runtime=global.regeneratorRuntime;if(runtime){if(inModule){module.exports=runtime}return}runtime=global.regeneratorRuntime=inModule?module.exports:{};function wrap(innerFn,outerFn,self,tryLocsList){return new Generator(innerFn,outerFn,self||null,tryLocsList||[])}runtime.wrap=wrap;function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryLocsList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryLocsList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){var record=tryCatch(this,null,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 Generator(innerFn,outerFn,self,tryLocsList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryLocsList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()}while(true){var delegate=context.delegate;if(delegate){var record=tryCatch(delegate.iterator[method],delegate.iterator,arg);if(record.type==="throw"){context.delegate=null;method="throw";arg=record.arg;continue}method="next";arg=undefined;var info=record.arg;if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===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;var record=tryCatch(innerFn,self,context);if(record.type==="normal"){state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:record.arg,done:context.done};if(record.arg===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}else if(record.type==="throw"){state=GenStateCompleted;if(method==="next"){context.dispatchException(record.arg)}else{arg=record.arg}}}}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(locs){var entry={tryLoc:locs[0]};if(1 in locs){entry.catchLoc=locs[1]}if(2 in locs){entry.finallyLoc=locs[2];entry.afterLoc=locs[3]}this.tryEntries.push(entry)}function resetTryEntry(entry){var record=entry.completion||{};record.type="normal";delete record.arg;entry.completion=record}function Context(tryLocsList){this.tryEntries=[{tryLoc:"root"}];tryLocsList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod){return iteratorMethod.call(iterable)}if(typeof iterable.next==="function"){return iterable}if(!isNaN(iterable.length)){var i=-1,next=function next(){while(++i<iterable.length){if(hasOwn.call(iterable,i)){next.value=iterable[i];next.done=false;return next}}next.value=undefined;next.done=true;return next};return next.next=next}}return{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_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,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){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion,entry.afterLoc)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}(typeof global==="object"?global:typeof window==="object"?window:this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}]},{},[1]); |
ajax/libs/primereact/6.5.0/avatargroup/avatargroup.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { classNames } from 'primereact/core';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var AvatarGroup = /*#__PURE__*/function (_Component) {
_inherits(AvatarGroup, _Component);
var _super = _createSuper(AvatarGroup);
function AvatarGroup() {
_classCallCheck(this, AvatarGroup);
return _super.apply(this, arguments);
}
_createClass(AvatarGroup, [{
key: "render",
value: function render() {
var containerClassName = classNames('p-avatar-group p-component', this.props.className);
return /*#__PURE__*/React.createElement("div", {
className: containerClassName,
style: this.props.style
}, this.props.children);
}
}]);
return AvatarGroup;
}(Component);
_defineProperty(AvatarGroup, "defaultProps", {
style: null,
className: null
});
export { AvatarGroup };
|
generators/app/templates/index.js | dothanhlam/generator-react-redux-es6-webpack | import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './stores';
import App from './app';
const store = configureStore();
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
); |
jquery-1.4.4-uncompressed.js | sourceexchange/drupal-devel | /*!
* jQuery JavaScript Library v1.4.4
* http://jquery.com/
*
* Copyright 2010, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2010, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Thu Nov 11 19:04:53 2010 -0500
*/
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// (both of which we optimize for)
quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,
// Is it a simple selector
isSimple = /^.[^:#\[\.,]*$/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
rwhite = /\s/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// Check for non-word characters
rnonword = /\W/,
// Check for digits
rdigit = /\d/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// Has the ready events already been bound?
readyBound = false,
// The functions to execute on DOM ready
readyList = [],
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = "body";
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
match = quickExpr.exec( selector );
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
doc = (context ? context.ownerDocument || context : document);
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $("TAG")
} else if ( !context && !rnonword.test( selector ) ) {
this.selector = selector;
this.context = document;
selector = document.getElementsByTagName( selector );
return jQuery.merge( this, selector );
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return jQuery( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.4.4",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + (this.selector ? " " : "") + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// If the DOM is already ready
if ( jQuery.isReady ) {
// Execute the function immediately
fn.call( document, jQuery );
// Otherwise, remember the function for later
} else if ( readyList ) {
// Add the function to the wait list
readyList.push( fn );
}
return this;
},
eq: function( i ) {
return i === -1 ?
this.slice( i ) :
this.slice( i, +i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || jQuery(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
window.$ = _$;
if ( deep ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Handle when the DOM is ready
ready: function( wait ) {
// A third-party is pushing the ready event forwards
if ( wait === true ) {
jQuery.readyWait--;
}
// Make sure that the DOM is not already loaded
if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
if ( readyList ) {
// Execute all of them
var fn,
i = 0,
ready = readyList;
// Reset the list of functions
readyList = null;
while ( (fn = ready[ i++ ]) ) {
fn.call( document, jQuery );
}
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).unbind( "ready" );
}
}
}
},
bindReady: function() {
if ( readyBound ) {
return;
}
readyBound = true;
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", DOMContentLoaded);
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
// A crude way of determining if an object is a window
isWindow: function( obj ) {
return obj && typeof obj === "object" && "setInterval" in obj;
},
isNaN: function( obj ) {
return obj == null || !rdigit.test( obj ) || isNaN( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw msg;
},
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test(data.replace(rvalidescape, "@")
.replace(rvalidtokens, "]")
.replace(rvalidbraces, "")) ) {
// Try to use the native JSON parser first
return window.JSON && window.JSON.parse ?
window.JSON.parse( data ) :
(new Function("return " + data))();
} else {
jQuery.error( "Invalid JSON: " + data );
}
},
noop: function() {},
// Evalulates a script in a global context
globalEval: function( data ) {
if ( data && rnotwhite.test(data) ) {
// Inspired by code by Andrea Giammarchi
// http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
var head = document.getElementsByTagName("head")[0] || document.documentElement,
script = document.createElement("script");
script.type = "text/javascript";
if ( jQuery.support.scriptEval ) {
script.appendChild( document.createTextNode( data ) );
} else {
script.text = data;
}
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709).
head.insertBefore( script, head.firstChild );
head.removeChild( script );
}
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction(object);
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
}
}
return object;
},
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// The extra typeof function check is to prevent crashes
// in Safari 2 (See: #3039)
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type(array);
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
},
inArray: function( elem, array ) {
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
},
merge: function( first, second ) {
var i = first.length,
j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var ret = [], value;
// Go through the array, translating each of the items to their
// new value (or values).
for ( var i = 0, length = elems.length; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
proxy: function( fn, proxy, thisObject ) {
if ( arguments.length === 2 ) {
if ( typeof proxy === "string" ) {
thisObject = fn;
fn = thisObject[ proxy ];
proxy = undefined;
} else if ( proxy && !jQuery.isFunction( proxy ) ) {
thisObject = proxy;
proxy = undefined;
}
}
if ( !proxy && fn ) {
proxy = function() {
return fn.apply( thisObject || this, arguments );
};
}
// Set the guid of unique handler to the same of original handler, so it can be removed
if ( fn ) {
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
}
// So proxy can be declared as an argument
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can be optionally by executed if its a function
access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
jQuery.access( elems, k, key[k], exec, fn, value );
}
return elems;
}
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
return elems;
}
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
},
now: function() {
return (new Date()).getTime();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
if ( indexOf ) {
jQuery.inArray = function( elem, array ) {
return indexOf.call( array, elem );
};
}
// Verify that \s matches non-breaking spaces
// (IE fails on this test)
if ( !rwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
// Expose jQuery to the global object
return (window.jQuery = window.$ = jQuery);
})();
(function() {
jQuery.support = {};
var root = document.documentElement,
script = document.createElement("script"),
div = document.createElement("div"),
id = "script" + jQuery.now();
div.style.display = "none";
div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
var all = div.getElementsByTagName("*"),
a = div.getElementsByTagName("a")[0],
select = document.createElement("select"),
opt = select.appendChild( document.createElement("option") );
// Can't get basic test support
if ( !all || !all.length || !a ) {
return;
}
jQuery.support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: div.firstChild.nodeType === 3,
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText insted)
style: /red/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: a.getAttribute("href") === "/a",
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.55$/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: div.getElementsByTagName("input")[0].value === "on",
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Will be defined later
deleteExpando: true,
optDisabled: false,
checkClone: false,
scriptEval: false,
noCloneEvent: true,
boxModel: null,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableHiddenOffsets: true
};
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as diabled)
select.disabled = true;
jQuery.support.optDisabled = !opt.disabled;
script.type = "text/javascript";
try {
script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
} catch(e) {}
root.insertBefore( script, root.firstChild );
// Make sure that the execution of code works by injecting a script
// tag with appendChild/createTextNode
// (IE doesn't support this, fails, and uses .text instead)
if ( window[ id ] ) {
jQuery.support.scriptEval = true;
delete window[ id ];
}
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete script.test;
} catch(e) {
jQuery.support.deleteExpando = false;
}
root.removeChild( script );
if ( div.attachEvent && div.fireEvent ) {
div.attachEvent("onclick", function click() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
jQuery.support.noCloneEvent = false;
div.detachEvent("onclick", click);
});
div.cloneNode(true).fireEvent("onclick");
}
div = document.createElement("div");
div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>";
var fragment = document.createDocumentFragment();
fragment.appendChild( div.firstChild );
// WebKit doesn't clone checked state correctly in fragments
jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked;
// Figure out if the W3C box model works as expected
// document.body must exist before we can do this
jQuery(function() {
var div = document.createElement("div");
div.style.width = div.style.paddingLeft = "1px";
document.body.appendChild( div );
jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
if ( "zoom" in div.style ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.style.display = "inline";
div.style.zoom = 1;
jQuery.support.inlineBlockNeedsLayout = div.offsetWidth === 2;
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "";
div.innerHTML = "<div style='width:4px;'></div>";
jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2;
}
div.innerHTML = "<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";
var tds = div.getElementsByTagName("td");
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
jQuery.support.reliableHiddenOffsets = tds[0].offsetHeight === 0;
tds[0].style.display = "";
tds[1].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE < 8 fail this test)
jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0;
div.innerHTML = "";
document.body.removeChild( div ).style.display = "none";
div = tds = null;
});
// Technique from Juriy Zaytsev
// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
var eventSupported = function( eventName ) {
var el = document.createElement("div");
eventName = "on" + eventName;
var isSupported = (eventName in el);
if ( !isSupported ) {
el.setAttribute(eventName, "return;");
isSupported = typeof el[eventName] === "function";
}
el = null;
return isSupported;
};
jQuery.support.submitBubbles = eventSupported("submit");
jQuery.support.changeBubbles = eventSupported("change");
// release memory in IE
root = script = div = all = a = null;
})();
var windowData = {},
rbrace = /^(?:\{.*\}|\[.*\])$/;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
expando: "jQuery" + jQuery.now(),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
data: function( elem, name, data ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
elem = elem == window ?
windowData :
elem;
var isNode = elem.nodeType,
id = isNode ? elem[ jQuery.expando ] : null,
cache = jQuery.cache, thisCache;
if ( isNode && !id && typeof name === "string" && data === undefined ) {
return;
}
// Get the data from the object directly
if ( !isNode ) {
cache = elem;
// Compute a unique ID for the element
} else if ( !id ) {
elem[ jQuery.expando ] = id = ++jQuery.uuid;
}
// Avoid generating a new cache unless none exists and we
// want to manipulate it.
if ( typeof name === "object" ) {
if ( isNode ) {
cache[ id ] = jQuery.extend(cache[ id ], name);
} else {
jQuery.extend( cache, name );
}
} else if ( isNode && !cache[ id ] ) {
cache[ id ] = {};
}
thisCache = isNode ? cache[ id ] : cache;
// Prevent overriding the named cache with undefined values
if ( data !== undefined ) {
thisCache[ name ] = data;
}
return typeof name === "string" ? thisCache[ name ] : thisCache;
},
removeData: function( elem, name ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
elem = elem == window ?
windowData :
elem;
var isNode = elem.nodeType,
id = isNode ? elem[ jQuery.expando ] : elem,
cache = jQuery.cache,
thisCache = isNode ? cache[ id ] : id;
// If we want to remove a specific section of the element's data
if ( name ) {
if ( thisCache ) {
// Remove the section of cache data
delete thisCache[ name ];
// If we've removed all the data, remove the element's cache
if ( isNode && jQuery.isEmptyObject(thisCache) ) {
jQuery.removeData( elem );
}
}
// Otherwise, we want to remove all of the element's data
} else {
if ( isNode && jQuery.support.deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
// Completely remove the data cache
} else if ( isNode ) {
delete cache[ id ];
// Remove all fields from the object
} else {
for ( var n in elem ) {
delete elem[ n ];
}
}
}
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var data = null;
if ( typeof key === "undefined" ) {
if ( this.length ) {
var attr = this[0].attributes, name;
data = jQuery.data( this[0] );
for ( var i = 0, l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = name.substr( 5 );
dataAttr( this[0], name, data[ name ] );
}
}
}
return data;
} else if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
var parts = key.split(".");
parts[1] = parts[1] ? "." + parts[1] : "";
if ( value === undefined ) {
data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
// Try to fetch any internally stored data first
if ( data === undefined && this.length ) {
data = jQuery.data( this[0], key );
data = dataAttr( this[0], key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
} else {
return this.each(function() {
var $this = jQuery( this ),
args = [ parts[0], value ];
$this.triggerHandler( "setData" + parts[1] + "!", args );
jQuery.data( this, key, value );
$this.triggerHandler( "changeData" + parts[1] + "!", args );
});
}
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
data = elem.getAttribute( "data-" + key );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
!jQuery.isNaN( data ) ? parseFloat( data ) :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
queue: function( elem, type, data ) {
if ( !elem ) {
return;
}
type = (type || "fx") + "queue";
var q = jQuery.data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( !data ) {
return q || [];
}
if ( !q || jQuery.isArray(data) ) {
q = jQuery.data( elem, type, jQuery.makeArray(data) );
} else {
q.push( data );
}
return q;
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift();
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift("inprogress");
}
fn.call(elem, function() {
jQuery.dequeue(elem, type);
});
}
}
});
jQuery.fn.extend({
queue: function( type, data ) {
if ( typeof type !== "string" ) {
data = type;
type = "fx";
}
if ( data === undefined ) {
return jQuery.queue( this[0], type );
}
return this.each(function( i ) {
var queue = jQuery.queue( this, type, data );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
return this.queue( type, function() {
var elem = this;
setTimeout(function() {
jQuery.dequeue( elem, type );
}, time );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
}
});
var rclass = /[\n\t]/g,
rspaces = /\s+/,
rreturn = /\r/g,
rspecialurl = /^(?:href|src|style)$/,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i,
rradiocheck = /^(?:radio|checkbox)$/i;
jQuery.props = {
"for": "htmlFor",
"class": "className",
readonly: "readOnly",
maxlength: "maxLength",
cellspacing: "cellSpacing",
rowspan: "rowSpan",
colspan: "colSpan",
tabindex: "tabIndex",
usemap: "useMap",
frameborder: "frameBorder"
};
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.attr );
},
removeAttr: function( name, fn ) {
return this.each(function(){
jQuery.attr( this, name, "" );
if ( this.nodeType === 1 ) {
this.removeAttribute( name );
}
});
},
addClass: function( value ) {
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
self.addClass( value.call(this, i, self.attr("class")) );
});
}
if ( value && typeof value === "string" ) {
var classNames = (value || "").split( rspaces );
for ( var i = 0, l = this.length; i < l; i++ ) {
var elem = this[i];
if ( elem.nodeType === 1 ) {
if ( !elem.className ) {
elem.className = value;
} else {
var className = " " + elem.className + " ",
setClass = elem.className;
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
setClass += " " + classNames[c];
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
self.removeClass( value.call(this, i, self.attr("class")) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
var classNames = (value || "").split( rspaces );
for ( var i = 0, l = this.length; i < l; i++ ) {
var elem = this[i];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
var className = (" " + elem.className + " ").replace(rclass, " ");
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[c] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this);
self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspaces );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery.data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ";
for ( var i = 0, l = this.length; i < l; i++ ) {
if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},
val: function( value ) {
if ( !arguments.length ) {
var elem = this[0];
if ( elem ) {
if ( jQuery.nodeName( elem, "option" ) ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
// We need to handle select boxes special
if ( jQuery.nodeName( elem, "select" ) ) {
var index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
var option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery(option).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
}
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) {
return elem.getAttribute("value") === null ? "on" : elem.value;
}
// Everything else, we just grab the value
return (elem.value || "").replace(rreturn, "");
}
return undefined;
}
var isFunction = jQuery.isFunction(value);
return this.each(function(i) {
var self = jQuery(this), val = value;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call(this, i, self.val());
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray(val) ) {
val = jQuery.map(val, function (value) {
return value == null ? "" : value + "";
});
}
if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) {
this.checked = jQuery.inArray( self.val(), val ) >= 0;
} else if ( jQuery.nodeName( this, "select" ) ) {
var values = jQuery.makeArray(val);
jQuery( "option", this ).each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
this.selectedIndex = -1;
}
} else {
this.value = val;
}
});
}
});
jQuery.extend({
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
attr: function( elem, name, value, pass ) {
// don't set attributes on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
return undefined;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery(elem)[name](value);
}
var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ),
// Whether we are setting (or getting)
set = value !== undefined;
// Try to normalize/fix the name
name = notxml && jQuery.props[ name ] || name;
// These attributes require special treatment
var special = rspecialurl.test( name );
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( name === "selected" && !jQuery.support.optSelected ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
// If applicable, access the attribute via the DOM 0 way
// 'in' checks fail in Blackberry 4.7 #6931
if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) {
if ( set ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
}
if ( value === null ) {
if ( elem.nodeType === 1 ) {
elem.removeAttribute( name );
}
} else {
elem[ name ] = value;
}
}
// browsers index elements by id/name on forms, give priority to attributes.
if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) {
return elem.getAttributeNode( name ).nodeValue;
}
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
if ( name === "tabIndex" ) {
var attributeNode = elem.getAttributeNode( "tabIndex" );
return attributeNode && attributeNode.specified ?
attributeNode.value :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
return elem[ name ];
}
if ( !jQuery.support.style && notxml && name === "style" ) {
if ( set ) {
elem.style.cssText = "" + value;
}
return elem.style.cssText;
}
if ( set ) {
// convert the value to a string (all browsers do this but IE) see #1070
elem.setAttribute( name, "" + value );
}
// Ensure that missing attributes return undefined
// Blackberry 4.7 returns "" from getAttribute #6938
if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) {
return undefined;
}
var attr = !jQuery.support.hrefNormalized && notxml && special ?
// Some attributes require a special call on IE
elem.getAttribute( name, 2 ) :
elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return attr === null ? undefined : attr;
}
});
var rnamespaces = /\.(.*)$/,
rformElems = /^(?:textarea|input|select)$/i,
rperiod = /\./g,
rspace = / /g,
rescape = /[^\w\s.|`]/g,
fcleanup = function( nm ) {
return nm.replace(rescape, "\\$&");
},
focusCounts = { focusin: 0, focusout: 0 };
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code originated from
* Dean Edwards' addEvent library.
*/
jQuery.event = {
// Bind an event to an element
// Original by Dean Edwards
add: function( elem, types, handler, data ) {
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// For whatever reason, IE has trouble passing the window object
// around, causing it to be cloned in the process
if ( jQuery.isWindow( elem ) && ( elem !== window && !elem.frameElement ) ) {
elem = window;
}
if ( handler === false ) {
handler = returnFalse;
} else if ( !handler ) {
// Fixes bug #7229. Fix recommended by jdalton
return;
}
var handleObjIn, handleObj;
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
}
// Make sure that the function being executed has a unique ID
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure
var elemData = jQuery.data( elem );
// If no elemData is found then we must be trying to bind to one of the
// banned noData elements
if ( !elemData ) {
return;
}
// Use a key less likely to result in collisions for plain JS objects.
// Fixes bug #7150.
var eventKey = elem.nodeType ? "events" : "__events__",
events = elemData[ eventKey ],
eventHandle = elemData.handle;
if ( typeof events === "function" ) {
// On plain objects events is a fn that holds the the data
// which prevents this data from being JSON serialized
// the function does not need to be called, it just contains the data
eventHandle = events.handle;
events = events.events;
} else if ( !events ) {
if ( !elem.nodeType ) {
// On plain objects, create a fn that acts as the holder
// of the values to avoid JSON serialization of event data
elemData[ eventKey ] = elemData = function(){};
}
elemData.events = events = {};
}
if ( !eventHandle ) {
elemData.handle = eventHandle = function() {
// Handle the second event of a trigger and when
// an event is called after a page has unloaded
return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
jQuery.event.handle.apply( eventHandle.elem, arguments ) :
undefined;
};
}
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native events in IE.
eventHandle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = types.split(" ");
var type, i = 0, namespaces;
while ( (type = types[ i++ ]) ) {
handleObj = handleObjIn ?
jQuery.extend({}, handleObjIn) :
{ handler: handler, data: data };
// Namespaced event handlers
if ( type.indexOf(".") > -1 ) {
namespaces = type.split(".");
type = namespaces.shift();
handleObj.namespace = namespaces.slice(0).sort().join(".");
} else {
namespaces = [];
handleObj.namespace = "";
}
handleObj.type = type;
if ( !handleObj.guid ) {
handleObj.guid = handler.guid;
}
// Get the current list of functions bound to this event
var handlers = events[ type ],
special = jQuery.event.special[ type ] || {};
// Init the event handler queue
if ( !handlers ) {
handlers = events[ type ] = [];
// Check for a special event handler
// Only use addEventListener/attachEvent if the special
// events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add the function to the element's handler list
handlers.push( handleObj );
// Keep track of which events have been used, for global triggering
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, pos ) {
// don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
if ( handler === false ) {
handler = returnFalse;
}
var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
eventKey = elem.nodeType ? "events" : "__events__",
elemData = jQuery.data( elem ),
events = elemData && elemData[ eventKey ];
if ( !elemData || !events ) {
return;
}
if ( typeof events === "function" ) {
elemData = events;
events = events.events;
}
// types is actually an event object here
if ( types && types.type ) {
handler = types.handler;
types = types.type;
}
// Unbind all events for the element
if ( !types || typeof types === "string" && types.charAt(0) === "." ) {
types = types || "";
for ( type in events ) {
jQuery.event.remove( elem, type + types );
}
return;
}
// Handle multiple events separated by a space
// jQuery(...).unbind("mouseover mouseout", fn);
types = types.split(" ");
while ( (type = types[ i++ ]) ) {
origType = type;
handleObj = null;
all = type.indexOf(".") < 0;
namespaces = [];
if ( !all ) {
// Namespaced event handlers
namespaces = type.split(".");
type = namespaces.shift();
namespace = new RegExp("(^|\\.)" +
jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
}
eventType = events[ type ];
if ( !eventType ) {
continue;
}
if ( !handler ) {
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( all || namespace.test( handleObj.namespace ) ) {
jQuery.event.remove( elem, origType, handleObj.handler, j );
eventType.splice( j--, 1 );
}
}
continue;
}
special = jQuery.event.special[ type ] || {};
for ( j = pos || 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( handler.guid === handleObj.guid ) {
// remove the given handler for the given type
if ( all || namespace.test( handleObj.namespace ) ) {
if ( pos == null ) {
eventType.splice( j--, 1 );
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
if ( pos != null ) {
break;
}
}
}
// remove generic event handler if no more handlers exist
if ( eventType.length === 0 || pos != null && eventType.length === 1 ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
ret = null;
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
var handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
delete elemData.events;
delete elemData.handle;
if ( typeof elemData === "function" ) {
jQuery.removeData( elem, eventKey );
} else if ( jQuery.isEmptyObject( elemData ) ) {
jQuery.removeData( elem );
}
}
},
// bubbling is internal
trigger: function( event, data, elem /*, bubbling */ ) {
// Event object or event type
var type = event.type || event,
bubbling = arguments[3];
if ( !bubbling ) {
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
jQuery.extend( jQuery.Event(type), event ) :
// Just the event type (string)
jQuery.Event(type);
if ( type.indexOf("!") >= 0 ) {
event.type = type = type.slice(0, -1);
event.exclusive = true;
}
// Handle a global trigger
if ( !elem ) {
// Don't bubble custom events when global (to avoid too much overhead)
event.stopPropagation();
// Only trigger if we've ever bound an event for it
if ( jQuery.event.global[ type ] ) {
jQuery.each( jQuery.cache, function() {
if ( this.events && this.events[type] ) {
jQuery.event.trigger( event, data, this.handle.elem );
}
});
}
}
// Handle triggering a single element
// don't do events on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
return undefined;
}
// Clean up in case it is reused
event.result = undefined;
event.target = elem;
// Clone the incoming data, if any
data = jQuery.makeArray( data );
data.unshift( event );
}
event.currentTarget = elem;
// Trigger the event, it is assumed that "handle" is a function
var handle = elem.nodeType ?
jQuery.data( elem, "handle" ) :
(jQuery.data( elem, "__events__" ) || {}).handle;
if ( handle ) {
handle.apply( elem, data );
}
var parent = elem.parentNode || elem.ownerDocument;
// Trigger an inline bound script
try {
if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) {
if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) {
event.result = false;
event.preventDefault();
}
}
// prevent IE from throwing an error for some elements with some event types, see #3533
} catch (inlineError) {}
if ( !event.isPropagationStopped() && parent ) {
jQuery.event.trigger( event, data, parent, true );
} else if ( !event.isDefaultPrevented() ) {
var old,
target = event.target,
targetType = type.replace( rnamespaces, "" ),
isClick = jQuery.nodeName( target, "a" ) && targetType === "click",
special = jQuery.event.special[ targetType ] || {};
if ( (!special._default || special._default.call( elem, event ) === false) &&
!isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) {
try {
if ( target[ targetType ] ) {
// Make sure that we don't accidentally re-trigger the onFOO events
old = target[ "on" + targetType ];
if ( old ) {
target[ "on" + targetType ] = null;
}
jQuery.event.triggered = true;
target[ targetType ]();
}
// prevent IE from throwing an error for some elements with some event types, see #3533
} catch (triggerError) {}
if ( old ) {
target[ "on" + targetType ] = old;
}
jQuery.event.triggered = false;
}
}
},
handle: function( event ) {
var all, handlers, namespaces, namespace_re, events,
namespace_sort = [],
args = jQuery.makeArray( arguments );
event = args[0] = jQuery.event.fix( event || window.event );
event.currentTarget = this;
// Namespaced event handlers
all = event.type.indexOf(".") < 0 && !event.exclusive;
if ( !all ) {
namespaces = event.type.split(".");
event.type = namespaces.shift();
namespace_sort = namespaces.slice(0).sort();
namespace_re = new RegExp("(^|\\.)" + namespace_sort.join("\\.(?:.*\\.)?") + "(\\.|$)");
}
event.namespace = event.namespace || namespace_sort.join(".");
events = jQuery.data(this, this.nodeType ? "events" : "__events__");
if ( typeof events === "function" ) {
events = events.events;
}
handlers = (events || {})[ event.type ];
if ( events && handlers ) {
// Clone the handlers to prevent manipulation
handlers = handlers.slice(0);
for ( var j = 0, l = handlers.length; j < l; j++ ) {
var handleObj = handlers[ j ];
// Filter the functions by class
if ( all || namespace_re.test( handleObj.namespace ) ) {
// Pass in a reference to the handler function itself
// So that we can later remove it
event.handler = handleObj.handler;
event.data = handleObj.data;
event.handleObj = handleObj;
var ret = handleObj.handler.apply( this, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
}
return event.result;
},
props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// store a copy of the original event object
// and "clone" to set read-only properties
var originalEvent = event;
event = jQuery.Event( originalEvent );
for ( var i = this.props.length, prop; i; ) {
prop = this.props[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary
if ( !event.target ) {
// Fixes #1925 where srcElement might not be defined either
event.target = event.srcElement || document;
}
// check if target is a textnode (safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && event.fromElement ) {
event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
}
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) {
var doc = document.documentElement,
body = document.body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
}
// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
event.which = event.charCode != null ? event.charCode : event.keyCode;
}
// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
if ( !event.metaKey && event.ctrlKey ) {
event.metaKey = event.ctrlKey;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}
return event;
},
// Deprecated, use jQuery.guid instead
guid: 1E8,
// Deprecated, use jQuery.proxy instead
proxy: jQuery.proxy,
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady,
teardown: jQuery.noop
},
live: {
add: function( handleObj ) {
jQuery.event.add( this,
liveConvert( handleObj.origType, handleObj.selector ),
jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
},
remove: function( handleObj ) {
jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj );
}
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
jQuery.Event = function( src ) {
// Allow instantiation without the 'new' keyword
if ( !this.preventDefault ) {
return new jQuery.Event( src );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Event type
} else {
this.type = src;
}
// timeStamp is buggy for some events on Firefox(#3843)
// So we won't rely on the native value
this.timeStamp = jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function( event ) {
// Check if mouse(over|out) are still within the same parent element
var parent = event.relatedTarget;
// Firefox sometimes assigns relatedTarget a XUL element
// which we cannot access the parentNode property of
try {
// Traverse up the tree
while ( parent && parent !== this ) {
parent = parent.parentNode;
}
if ( parent !== this ) {
// set the correct event type
event.type = event.data;
// handle event if we actually just moused on to a non sub-element
jQuery.event.handle.apply( this, arguments );
}
// assuming we've left the element since we most likely mousedover a xul element
} catch(e) { }
},
// In case of event delegation, we only need to rename the event.type,
// liveHandler will take care of the rest.
delegate = function( event ) {
event.type = event.data;
jQuery.event.handle.apply( this, arguments );
};
// Create mouseenter and mouseleave events
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
setup: function( data ) {
jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
},
teardown: function( data ) {
jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
}
};
});
// submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function( data, namespaces ) {
if ( this.nodeName.toLowerCase() !== "form" ) {
jQuery.event.add(this, "click.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
e.liveFired = undefined;
return trigger( "submit", this, arguments );
}
});
jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
e.liveFired = undefined;
return trigger( "submit", this, arguments );
}
});
} else {
return false;
}
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialSubmit" );
}
};
}
// change delegation, happens here so we have bind.
if ( !jQuery.support.changeBubbles ) {
var changeFilters,
getVal = function( elem ) {
var type = elem.type, val = elem.value;
if ( type === "radio" || type === "checkbox" ) {
val = elem.checked;
} else if ( type === "select-multiple" ) {
val = elem.selectedIndex > -1 ?
jQuery.map( elem.options, function( elem ) {
return elem.selected;
}).join("-") :
"";
} else if ( elem.nodeName.toLowerCase() === "select" ) {
val = elem.selectedIndex;
}
return val;
},
testChange = function testChange( e ) {
var elem = e.target, data, val;
if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) {
return;
}
data = jQuery.data( elem, "_change_data" );
val = getVal(elem);
// the current data will be also retrieved by beforeactivate
if ( e.type !== "focusout" || elem.type !== "radio" ) {
jQuery.data( elem, "_change_data", val );
}
if ( data === undefined || val === data ) {
return;
}
if ( data != null || val ) {
e.type = "change";
e.liveFired = undefined;
return jQuery.event.trigger( e, arguments[1], elem );
}
};
jQuery.event.special.change = {
filters: {
focusout: testChange,
beforedeactivate: testChange,
click: function( e ) {
var elem = e.target, type = elem.type;
if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) {
return testChange.call( this, e );
}
},
// Change has to be called before submit
// Keydown will be called before keypress, which is used in submit-event delegation
keydown: function( e ) {
var elem = e.target, type = elem.type;
if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") ||
(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
type === "select-multiple" ) {
return testChange.call( this, e );
}
},
// Beforeactivate happens also before the previous element is blurred
// with this event you can't trigger a change event, but you can store
// information
beforeactivate: function( e ) {
var elem = e.target;
jQuery.data( elem, "_change_data", getVal(elem) );
}
},
setup: function( data, namespaces ) {
if ( this.type === "file" ) {
return false;
}
for ( var type in changeFilters ) {
jQuery.event.add( this, type + ".specialChange", changeFilters[type] );
}
return rformElems.test( this.nodeName );
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialChange" );
return rformElems.test( this.nodeName );
}
};
changeFilters = jQuery.event.special.change.filters;
// Handle when the input is .focus()'d
changeFilters.focus = changeFilters.beforeactivate;
}
function trigger( type, elem, args ) {
args[0].type = type;
return jQuery.event.handle.apply( elem, args );
}
// Create "bubbling" focus and blur events
if ( document.addEventListener ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
jQuery.event.special[ fix ] = {
setup: function() {
if ( focusCounts[fix]++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --focusCounts[fix] === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
function handler( e ) {
e = jQuery.event.fix( e );
e.type = fix;
return jQuery.event.trigger( e, null, e.target );
}
});
}
jQuery.each(["bind", "one"], function( i, name ) {
jQuery.fn[ name ] = function( type, data, fn ) {
// Handle object literals
if ( typeof type === "object" ) {
for ( var key in type ) {
this[ name ](key, data, type[key], fn);
}
return this;
}
if ( jQuery.isFunction( data ) || data === false ) {
fn = data;
data = undefined;
}
var handler = name === "one" ? jQuery.proxy( fn, function( event ) {
jQuery( this ).unbind( event, handler );
return fn.apply( this, arguments );
}) : fn;
if ( type === "unload" && name !== "one" ) {
this.one( type, data, fn );
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.add( this[i], type, handler, data );
}
}
return this;
};
});
jQuery.fn.extend({
unbind: function( type, fn ) {
// Handle object literals
if ( typeof type === "object" && !type.preventDefault ) {
for ( var key in type ) {
this.unbind(key, type[key]);
}
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.remove( this[i], type, fn );
}
}
return this;
},
delegate: function( selector, types, data, fn ) {
return this.live( types, data, fn, selector );
},
undelegate: function( selector, types, fn ) {
if ( arguments.length === 0 ) {
return this.unbind( "live" );
} else {
return this.die( types, null, fn, selector );
}
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
var event = jQuery.Event( type );
event.preventDefault();
event.stopPropagation();
jQuery.event.trigger( event, data, this[0] );
return event.result;
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
i = 1;
// link all the functions, so any of them can unbind this click handler
while ( i < args.length ) {
jQuery.proxy( fn, args[ i++ ] );
}
return this.click( jQuery.proxy( fn, function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
}));
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
var liveMap = {
focus: "focusin",
blur: "focusout",
mouseenter: "mouseover",
mouseleave: "mouseout"
};
jQuery.each(["live", "die"], function( i, name ) {
jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
var type, i = 0, match, namespaces, preType,
selector = origSelector || this.selector,
context = origSelector ? this : jQuery( this.context );
if ( typeof types === "object" && !types.preventDefault ) {
for ( var key in types ) {
context[ name ]( key, data, types[key], selector );
}
return this;
}
if ( jQuery.isFunction( data ) ) {
fn = data;
data = undefined;
}
types = (types || "").split(" ");
while ( (type = types[ i++ ]) != null ) {
match = rnamespaces.exec( type );
namespaces = "";
if ( match ) {
namespaces = match[0];
type = type.replace( rnamespaces, "" );
}
if ( type === "hover" ) {
types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
continue;
}
preType = type;
if ( type === "focus" || type === "blur" ) {
types.push( liveMap[ type ] + namespaces );
type = type + namespaces;
} else {
type = (liveMap[ type ] || type) + namespaces;
}
if ( name === "live" ) {
// bind live handler
for ( var j = 0, l = context.length; j < l; j++ ) {
jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
{ data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
}
} else {
// unbind live handler
context.unbind( "live." + liveConvert( type, selector ), fn );
}
}
return this;
};
});
function liveHandler( event ) {
var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
elems = [],
selectors = [],
events = jQuery.data( this, this.nodeType ? "events" : "__events__" );
if ( typeof events === "function" ) {
events = events.events;
}
// Make sure we avoid non-left-click bubbling in Firefox (#3861)
if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) {
return;
}
if ( event.namespace ) {
namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
}
event.liveFired = this;
var live = events.live.slice(0);
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) {
selectors.push( handleObj.selector );
} else {
live.splice( j--, 1 );
}
}
match = jQuery( event.target ).closest( selectors, event.currentTarget );
for ( i = 0, l = match.length; i < l; i++ ) {
close = match[i];
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) ) {
elem = close.elem;
related = null;
// Those two events require additional checking
if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
event.type = handleObj.preType;
related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];
}
if ( !related || related !== elem ) {
elems.push({ elem: elem, handleObj: handleObj, level: close.level });
}
}
}
}
for ( i = 0, l = elems.length; i < l; i++ ) {
match = elems[i];
if ( maxLevel && match.level > maxLevel ) {
break;
}
event.currentTarget = match.elem;
event.data = match.handleObj.data;
event.handleObj = match.handleObj;
ret = match.handleObj.origHandler.apply( match.elem, arguments );
if ( ret === false || event.isPropagationStopped() ) {
maxLevel = match.level;
if ( ret === false ) {
stop = false;
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
return stop;
}
function liveConvert( type, selector ) {
return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspace, "&");
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
});
// Prevent memory leaks in IE
// Window isn't included so as not to unbind existing unload events
// More info:
// - http://isaacschlueter.com/2006/10/msie-memory-leaks/
if ( window.attachEvent && !window.addEventListener ) {
jQuery(window).bind("unload", function() {
for ( var id in jQuery.cache ) {
if ( jQuery.cache[ id ].handle ) {
// Try/Catch is to handle iframes being unloaded, see #4280
try {
jQuery.event.remove( jQuery.cache[ id ].handle.elem );
} catch(e) {}
}
}
});
}
/*!
* Sizzle CSS Selector Engine - v1.0
* Copyright 2009, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
Sizzle.matches = function( expr, set ) {
return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
var set;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var match,
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
var left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace(/\\/g, "");
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = context.getElementsByTagName( "*" );
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
var found, item,
filter = Expr.filter[ type ],
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var pass = not ^ !!found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw "Syntax error, unrecognized expression: " + msg;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !/\W/.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !/\W/.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !/\W/.test(part) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !/\W/.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
return context.getElementsByTagName( match[1] );
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace(/\\/g, "") + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace(/\\/g, "");
},
TAG: function( match, curLoop ) {
return match[1].toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1].replace(/\\/g, "");
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
elem.parentNode.selectedIndex;
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
return "text" === elem.type;
},
radio: function( elem ) {
return "radio" === elem.type;
},
checkbox: function( elem ) {
return "checkbox" === elem.type;
},
file: function( elem ) {
return "file" === elem.type;
},
password: function( elem ) {
return "password" === elem.type;
},
submit: function( elem ) {
return "submit" === elem.type;
},
image: function( elem ) {
return "image" === elem.type;
},
reset: function( elem ) {
return "reset" === elem.type;
},
button: function( elem ) {
return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
},
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( "Syntax error, unrecognized expression: " + name );
}
},
CHILD: function( elem, match ) {
var type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
var first = match[2],
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
var doneName = match[0],
parent = elem.parentNode;
if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
var count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent.sizcache = doneName;
}
var diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// If the nodes are siblings (or identical) we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += Sizzle.getText( elem.childNodes );
}
}
return ret;
};
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime(),
root = document.documentElement;
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ?
m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
};
Expr.filter.ID = function( elem, match ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
// release memory in IE
root = form = null;
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function( elem ) {
return elem.getAttribute( "href", 2 );
};
}
// release memory in IE
div = null;
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// Make sure that attribute selectors are quoted
query = query.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
if ( context.nodeType === 9 ) {
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var old = context.getAttribute( "id" ),
nid = old || id;
if ( !old ) {
context.setAttribute( "id", nid );
}
try {
return makeArray( context.querySelectorAll( "#" + nid + " " + query ), extra );
} catch(pseudoError) {
} finally {
if ( !old ) {
context.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector,
pseudoWorks = false;
try {
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
}
if ( matches ) {
Sizzle.matchesSelector = function( node, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
return matches.call( node, expr );
}
} catch(e) {}
}
return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
// release memory in IE
div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem.sizcache = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem.sizcache = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
return a !== b && (a.contains ? a.contains(b) : true);
};
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
return !!(a.compareDocumentPosition(b) & 16);
};
} else {
Sizzle.contains = function() {
return false;
};
}
Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})();
var runtil = /Until$/,
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
POS = jQuery.expr.match.POS;
jQuery.fn.extend({
find: function( selector ) {
var ret = this.pushStack( "", "find", selector ),
length = 0;
for ( var i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( var n = length; n < ret.length; n++ ) {
for ( var r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && jQuery.filter( selector, this ).length > 0;
},
closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];
if ( jQuery.isArray( selectors ) ) {
var match, selector,
matches = {},
level = 1;
if ( cur && selectors.length ) {
for ( i = 0, l = selectors.length; i < l; i++ ) {
selector = selectors[i];
if ( !matches[selector] ) {
matches[selector] = jQuery.expr.match.POS.test( selector ) ?
jQuery( selector, context || this.context ) :
selector;
}
}
while ( cur && cur.ownerDocument && cur !== context ) {
for ( selector in matches ) {
match = matches[selector];
if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) {
ret.push({ selector: selector, elem: cur, level: level });
}
}
cur = cur.parentNode;
level++;
}
}
return ret;
}
var pos = POS.test( selectors ) ?
jQuery( selectors, context || this.context ) : null;
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context ) {
break;
}
}
}
}
ret = ret.length > 1 ? jQuery.unique(ret) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
if ( !elem || typeof elem === "string" ) {
return jQuery.inArray( this[0],
// If it receives a string, the selector is used
// If it receives nothing, the siblings are used
elem ? jQuery( elem ) : this.parent().children() );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context || this.context ) :
jQuery.makeArray( selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
andSelf: function() {
return this.add( this.prevObject );
}
});
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return jQuery.nth( elem, 2, "nextSibling" );
},
prev: function( elem ) {
return jQuery.nth( elem, 2, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( elem.parentNode.firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, slice.call(arguments).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
nth: function( cur, result, dir, elem ) {
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
}
return cur;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return (elem === qualifier) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return (jQuery.inArray( elem, qualifier ) >= 0) === keep;
});
}
var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnocache = /<(?:script|object|embed|option|style)/i,
// checked="checked" or checked (html5)
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
raction = /\=([^="'>\s]+\/)>/g,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( text ) {
if ( jQuery.isFunction(text) ) {
return this.each(function(i) {
var self = jQuery( this );
self.text( text.call(this, i, self.text()) );
});
}
if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
return jQuery.text( this );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append(this);
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
return this.each(function() {
jQuery( this ).wrapAll( html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
} else if ( arguments.length ) {
var set = jQuery(arguments[0]);
set.push.apply( set, this.toArray() );
return this.pushStack( set, "before", arguments );
}
},
after: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
} else if ( arguments.length ) {
var set = this.pushStack( this, "after", arguments );
set.push.apply( set, jQuery(arguments[0]).toArray() );
return set;
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( events ) {
// Do the clone
var ret = this.map(function() {
if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
// IE copies events bound via attachEvent when
// using cloneNode. Calling detachEvent on the
// clone will also remove the events from the orignal
// In order to get around this, we use innerHTML.
// Unfortunately, this means some modifications to
// attributes in IE that are actually only stored
// as properties will not be copied (such as the
// the name attribute on an input).
var html = this.outerHTML,
ownerDocument = this.ownerDocument;
if ( !html ) {
var div = ownerDocument.createElement("div");
div.appendChild( this.cloneNode(true) );
html = div.innerHTML;
}
return jQuery.clean([html.replace(rinlinejQuery, "")
// Handle the case in IE 8 where action=/test/> self-closes a tag
.replace(raction, '="$1">')
.replace(rleadingWhitespace, "")], ownerDocument)[0];
} else {
return this.cloneNode(true);
}
});
// Copy the events from the original to the clone
if ( events === true ) {
cloneCopyEvent( this, ret );
cloneCopyEvent( this.find("*"), ret.find("*") );
}
// Return the cloned set
return ret;
},
html: function( value ) {
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !rnocache.test( value ) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for ( var i = 0, l = this.length; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
if ( this[i].nodeType === 1 ) {
jQuery.cleanData( this[i].getElementsByTagName("*") );
this[i].innerHTML = value;
}
}
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
} else if ( jQuery.isFunction( value ) ) {
this.each(function(i){
var self = jQuery( this );
self.html( value.call(this, i, self.html()) );
});
} else {
this.empty().append( value );
}
return this;
},
replaceWith: function( value ) {
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
}
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
i > 0 || results.cacheable || this.length > 1 ?
fragment.cloneNode(true) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, evalScript );
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent(orig, ret) {
var i = 0;
ret.each(function() {
if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) {
return;
}
var oldData = jQuery.data( orig[i++] ),
curData = jQuery.data( this, oldData ),
events = oldData && oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( var type in events ) {
for ( var handler in events[ type ] ) {
jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
}
}
}
});
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults,
doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
// Only cache "small" (1/2 KB) strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
!rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ args[0] ];
if ( cacheresults ) {
if ( cacheresults !== 1 ) {
fragment = cacheresults;
}
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
jQuery.extend({
clean: function( elems, context, fragment, scripts ) {
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
var ret = [];
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" && !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else if ( typeof elem === "string" ) {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div");
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( var j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
for ( i = 0; ret[i]; i++ ) {
if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
} else {
if ( ret[i].nodeType === 1 ) {
ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
}
fragment.appendChild( ret[i] );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id, cache = jQuery.cache,
special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
function evalScript( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rdashAlpha = /-([a-z])/ig,
rupper = /([A-Z])/g,
rnumpx = /^-?\d+(?:px)?$/i,
rnum = /^-?\d/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssWidth = [ "Left", "Right" ],
cssHeight = [ "Top", "Bottom" ],
curCSS,
getComputedStyle,
currentStyle,
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn.css = function( name, value ) {
// Setting 'undefined' is a no-op
if ( arguments.length === 2 && value === undefined ) {
return this;
}
return jQuery.access( this, name, value, true, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
});
};
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity", "opacity" );
return ret === "" ? "1" : ret;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"zIndex": true,
"fontWeight": true,
"opacity": true,
"zoom": true,
"lineHeight": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
// Make sure that NaN and null values aren't set. See: #7116
if ( typeof value === "number" && isNaN( value ) || value == null ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( typeof value === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra ) {
// Make sure that we're working with the right name
var ret, origName = jQuery.camelCase( name ),
hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name, origName );
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {};
// Remember the old values, and insert the new ones
for ( var name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
},
camelCase: function( string ) {
return string.replace( rdashAlpha, fcamelCase );
}
});
// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
jQuery.each(["height", "width"], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
var val;
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
val = getWH( elem, name, extra );
} else {
jQuery.swap( elem, cssShow, function() {
val = getWH( elem, name, extra );
});
}
if ( val <= 0 ) {
val = curCSS( elem, name, name );
if ( val === "0px" && currentStyle ) {
val = currentStyle( elem, name, name );
}
if ( val != null ) {
// Should return "auto" instead of 0, use 0 for
// temporary backwards-compat
return val === "" || val === "auto" ? "0px" : val;
}
}
if ( val < 0 || val == null ) {
val = elem.style[ name ];
// Should return "auto" instead of 0, use 0 for
// temporary backwards-compat
return val === "" || val === "auto" ? "0px" : val;
}
return typeof val === "string" ? val : val + "px";
}
},
set: function( elem, value ) {
if ( rnumpx.test( value ) ) {
// ignore negative width and height values #1599
value = parseFloat(value);
if ( value >= 0 ) {
return value + "px";
}
} else {
return value;
}
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ?
(parseFloat(RegExp.$1) / 100) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style;
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// Set the alpha filter to set the opacity
var opacity = jQuery.isNaN(value) ?
"" :
"alpha(opacity=" + value * 100 + ")",
filter = style.filter || "";
style.filter = ralpha.test(filter) ?
filter.replace(ralpha, opacity) :
style.filter + ' ' + opacity;
}
};
}
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, newName, name ) {
var ret, defaultView, computedStyle;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( !(defaultView = elem.ownerDocument.defaultView) ) {
return undefined;
}
if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle.left;
// Put in the new values to get a computed value out
elem.runtimeStyle.left = elem.currentStyle.left;
style.left = name === "fontSize" ? "1em" : (ret || 0);
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
elem.runtimeStyle.left = rsLeft;
}
return ret === "" ? "auto" : ret;
};
}
curCSS = getComputedStyle || currentStyle;
function getWH( elem, name, extra ) {
var which = name === "width" ? cssWidth : cssHeight,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight;
if ( extra === "border" ) {
return val;
}
jQuery.each( which, function() {
if ( !extra ) {
val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0;
}
if ( extra === "margin" ) {
val += parseFloat(jQuery.css( elem, "margin" + this )) || 0;
} else {
val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0;
}
});
return val;
}
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
var jsc = jQuery.now(),
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rnoContent = /^(?:GET|HEAD)$/,
rbracket = /\[\]$/,
jsre = /\=\?(&|$)/,
rquery = /\?/,
rts = /([?&])_=[^&]*/,
rurl = /^(\w+:)?\/\/([^\/?#]+)/,
r20 = /%20/g,
rhash = /#.*$/,
// Keep a copy of the old load method
_load = jQuery.fn.load;
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf(" ");
if ( off >= 0 ) {
var selector = url.slice(off, url.length);
url = url.slice(0, off);
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = null;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
complete: function( res, status ) {
// If successful, inject the HTML into all the matched elements
if ( status === "success" || status === "notmodified" ) {
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(res.responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
}
if ( callback ) {
self.each( callback, [res.responseText, status, res] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param(this.serializeArray());
},
serializeArray: function() {
return this.map(function() {
return this.elements ? jQuery.makeArray(this.elements) : this;
})
.filter(function() {
return this.name && !this.disabled &&
(this.checked || rselectTextarea.test(this.nodeName) ||
rinput.test(this.type));
})
.map(function( i, elem ) {
var val = jQuery(this).val();
return val == null ?
null :
jQuery.isArray(val) ?
jQuery.map( val, function( val, i ) {
return { name: elem.name, value: val };
}) :
{ name: elem.name, value: val };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) {
jQuery.fn[o] = function( f ) {
return this.bind(o, f);
};
});
jQuery.extend({
get: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = null;
}
return jQuery.ajax({
type: "GET",
url: url,
data: data,
success: callback,
dataType: type
});
},
getScript: function( url, callback ) {
return jQuery.get(url, null, callback, "script");
},
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},
post: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
},
ajaxSetup: function( settings ) {
jQuery.extend( jQuery.ajaxSettings, settings );
},
ajaxSettings: {
url: location.href,
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
/*
timeout: 0,
data: null,
username: null,
password: null,
traditional: false,
*/
// This function can be overriden by calling jQuery.ajaxSetup
xhr: function() {
return new window.XMLHttpRequest();
},
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
script: "text/javascript, application/javascript",
json: "application/json, text/javascript",
text: "text/plain",
_default: "*/*"
}
},
ajax: function( origSettings ) {
var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
jsonp, status, data, type = s.type.toUpperCase(), noContent = rnoContent.test(type);
s.url = s.url.replace( rhash, "" );
// Use original (not extended) context object if it was provided
s.context = origSettings && origSettings.context != null ? origSettings.context : s;
// convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Handle JSONP Parameter Callbacks
if ( s.dataType === "jsonp" ) {
if ( type === "GET" ) {
if ( !jsre.test( s.url ) ) {
s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
}
} else if ( !s.data || !jsre.test(s.data) ) {
s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
}
s.dataType = "json";
}
// Build temporary JSONP function
if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
jsonp = s.jsonpCallback || ("jsonp" + jsc++);
// Replace the =? sequence both in the query string and the data
if ( s.data ) {
s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
}
s.url = s.url.replace(jsre, "=" + jsonp + "$1");
// We need to make sure
// that a JSONP style response is executed properly
s.dataType = "script";
// Handle JSONP-style loading
var customJsonp = window[ jsonp ];
window[ jsonp ] = function( tmp ) {
if ( jQuery.isFunction( customJsonp ) ) {
customJsonp( tmp );
} else {
// Garbage collect
window[ jsonp ] = undefined;
try {
delete window[ jsonp ];
} catch( jsonpError ) {}
}
data = tmp;
jQuery.handleSuccess( s, xhr, status, data );
jQuery.handleComplete( s, xhr, status, data );
if ( head ) {
head.removeChild( script );
}
};
}
if ( s.dataType === "script" && s.cache === null ) {
s.cache = false;
}
if ( s.cache === false && noContent ) {
var ts = jQuery.now();
// try replacing _= if it is there
var ret = s.url.replace(rts, "$1_=" + ts);
// if nothing was replaced, add timestamp to the end
s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
}
// If data is available, append data to url for GET/HEAD requests
if ( s.data && noContent ) {
s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
}
// Watch for a new set of requests
if ( s.global && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// Matches an absolute URL, and saves the domain
var parts = rurl.exec( s.url ),
remote = parts && (parts[1] && parts[1].toLowerCase() !== location.protocol || parts[2].toLowerCase() !== location.host);
// If we're requesting a remote document
// and trying to load JSON or Script with a GET
if ( s.dataType === "script" && type === "GET" && remote ) {
var head = document.getElementsByTagName("head")[0] || document.documentElement;
var script = document.createElement("script");
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Handle Script loading
if ( !jsonp ) {
var done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if ( !done && (!this.readyState ||
this.readyState === "loaded" || this.readyState === "complete") ) {
done = true;
jQuery.handleSuccess( s, xhr, status, data );
jQuery.handleComplete( s, xhr, status, data );
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
if ( head && script.parentNode ) {
head.removeChild( script );
}
}
};
}
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
// We handle everything using the script element injection
return undefined;
}
var requestDone = false;
// Create the request object
var xhr = s.xhr();
if ( !xhr ) {
return;
}
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open(type, s.url, s.async, s.username, s.password);
} else {
xhr.open(type, s.url, s.async);
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
// Set content-type if data specified and content-body is valid for this type
if ( (s.data != null && !noContent) || (origSettings && origSettings.contentType) ) {
xhr.setRequestHeader("Content-Type", s.contentType);
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[s.url] ) {
xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
}
if ( jQuery.etag[s.url] ) {
xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
}
}
// Set header so the called script knows that it's an XMLHttpRequest
// Only send the header if it's not a remote XHR
if ( !remote ) {
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
// Set the Accepts header for the server, depending on the dataType
xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
s.accepts[ s.dataType ] + ", */*; q=0.01" :
s.accepts._default );
} catch( headerError ) {}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
// Handle the global AJAX counter
if ( s.global && jQuery.active-- === 1 ) {
jQuery.event.trigger( "ajaxStop" );
}
// close opended socket
xhr.abort();
return false;
}
if ( s.global ) {
jQuery.triggerGlobal( s, "ajaxSend", [xhr, s] );
}
// Wait for a response to come back
var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
// The request was aborted
if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
// Opera doesn't call onreadystatechange before this point
// so we simulate the call
if ( !requestDone ) {
jQuery.handleComplete( s, xhr, status, data );
}
requestDone = true;
if ( xhr ) {
xhr.onreadystatechange = jQuery.noop;
}
// The transfer is complete and the data is available, or the request timed out
} else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
requestDone = true;
xhr.onreadystatechange = jQuery.noop;
status = isTimeout === "timeout" ?
"timeout" :
!jQuery.httpSuccess( xhr ) ?
"error" :
s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
"notmodified" :
"success";
var errMsg;
if ( status === "success" ) {
// Watch for, and catch, XML document parse errors
try {
// process the data (runs the xml through httpData regardless of callback)
data = jQuery.httpData( xhr, s.dataType, s );
} catch( parserError ) {
status = "parsererror";
errMsg = parserError;
}
}
// Make sure that the request was successful or notmodified
if ( status === "success" || status === "notmodified" ) {
// JSONP handles its own success callback
if ( !jsonp ) {
jQuery.handleSuccess( s, xhr, status, data );
}
} else {
jQuery.handleError( s, xhr, status, errMsg );
}
// Fire the complete handlers
if ( !jsonp ) {
jQuery.handleComplete( s, xhr, status, data );
}
if ( isTimeout === "timeout" ) {
xhr.abort();
}
// Stop memory leaks
if ( s.async ) {
xhr = null;
}
}
};
// Override the abort handler, if we can (IE 6 doesn't allow it, but that's OK)
// Opera doesn't fire onreadystatechange at all on abort
try {
var oldAbort = xhr.abort;
xhr.abort = function() {
if ( xhr ) {
// oldAbort has no call property in IE7 so
// just do it this way, which works in all
// browsers
Function.prototype.call.call( oldAbort, xhr );
}
onreadystatechange( "abort" );
};
} catch( abortError ) {}
// Timeout checker
if ( s.async && s.timeout > 0 ) {
setTimeout(function() {
// Check to see if the request is still happening
if ( xhr && !requestDone ) {
onreadystatechange( "timeout" );
}
}, s.timeout);
}
// Send the data
try {
xhr.send( noContent || s.data == null ? null : s.data );
} catch( sendError ) {
jQuery.handleError( s, xhr, null, sendError );
// Fire the complete handlers
jQuery.handleComplete( s, xhr, status, data );
}
// firefox 1.5 doesn't fire statechange for sync requests
if ( !s.async ) {
onreadystatechange();
}
// return XMLHttpRequest to allow aborting the request etc.
return xhr;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction(value) ? value() : value;
s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray(a) || a.jquery ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[prefix], traditional, add );
}
}
// Return the resulting serialization
return s.join("&").replace(r20, "+");
}
});
function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray(obj) && obj.length ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && obj != null && typeof obj === "object" ) {
if ( jQuery.isEmptyObject( obj ) ) {
add( prefix, "" );
// Serialize object item.
} else {
jQuery.each( obj, function( k, v ) {
buildParams( prefix + "[" + k + "]", v, traditional, add );
});
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context, xhr, status, e );
}
// Fire the global callback
if ( s.global ) {
jQuery.triggerGlobal( s, "ajaxError", [xhr, s, e] );
}
},
handleSuccess: function( s, xhr, status, data ) {
// If a local callback was specified, fire it and pass it the data
if ( s.success ) {
s.success.call( s.context, data, status, xhr );
}
// Fire the global callback
if ( s.global ) {
jQuery.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
}
},
handleComplete: function( s, xhr, status ) {
// Process result
if ( s.complete ) {
s.complete.call( s.context, xhr, status );
}
// The request was completed
if ( s.global ) {
jQuery.triggerGlobal( s, "ajaxComplete", [xhr, s] );
}
// Handle the global AJAX counter
if ( s.global && jQuery.active-- === 1 ) {
jQuery.event.trigger( "ajaxStop" );
}
},
triggerGlobal: function( s, type, args ) {
(s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
},
// Determines if an XMLHttpRequest was successful or not
httpSuccess: function( xhr ) {
try {
// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
return !xhr.status && location.protocol === "file:" ||
xhr.status >= 200 && xhr.status < 300 ||
xhr.status === 304 || xhr.status === 1223;
} catch(e) {}
return false;
},
// Determines if an XMLHttpRequest returns NotModified
httpNotModified: function( xhr, url ) {
var lastModified = xhr.getResponseHeader("Last-Modified"),
etag = xhr.getResponseHeader("Etag");
if ( lastModified ) {
jQuery.lastModified[url] = lastModified;
}
if ( etag ) {
jQuery.etag[url] = etag;
}
return xhr.status === 304;
},
httpData: function( xhr, type, s ) {
var ct = xhr.getResponseHeader("content-type") || "",
xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if ( xml && data.documentElement.nodeName === "parsererror" ) {
jQuery.error( "parsererror" );
}
// Allow a pre-filtering function to sanitize the response
// s is checked to keep backwards compatibility
if ( s && s.dataFilter ) {
data = s.dataFilter( data, type );
}
// The filter can actually parse the response
if ( typeof data === "string" ) {
// Get the JavaScript object, if JSON is used.
if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
data = jQuery.parseJSON( data );
// If the type is "script", eval it in global context
} else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
jQuery.globalEval( data );
}
}
return data;
}
});
/*
* Create the request object; Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
if ( window.ActiveXObject ) {
jQuery.ajaxSettings.xhr = function() {
if ( window.location.protocol !== "file:" ) {
try {
return new window.XMLHttpRequest();
} catch(xhrError) {}
}
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch(activeError) {}
};
}
// Does this browser support XHR requests?
jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();
var elemdisplay = {},
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)(.*)$/,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
];
jQuery.fn.extend({
show: function( speed, easing, callback ) {
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[i];
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery.data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( display === "" && jQuery.css( elem, "display" ) === "none" ) {
jQuery.data(elem, "olddisplay", defaultDisplay(elem.nodeName));
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[i];
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery.data(elem, "olddisplay") || "";
}
}
return this;
}
},
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
var display = jQuery.css( this[i], "display" );
if ( display !== "none" ) {
jQuery.data( this[i], "olddisplay", display );
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
this[i].style.display = "none";
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2, callback ) {
var bool = typeof fn === "boolean";
if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
this._toggle.apply( this, arguments );
} else if ( fn == null || bool ) {
this.each(function() {
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
});
} else {
this.animate(genFx("toggle", 3), fn, fn2, callback);
}
return this;
},
fadeTo: function( speed, to, easing, callback ) {
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed(speed, easing, callback);
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete );
}
return this[ optall.queue === false ? "each" : "queue" ](function() {
// XXX 'this' does not always have a nodeName when running the
// test suite
var opt = jQuery.extend({}, optall), p,
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
self = this;
for ( p in prop ) {
var name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
p = name;
}
if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) {
return opt.complete.call(this);
}
if ( isElement && ( p === "height" || p === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height
// animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
if ( !jQuery.support.inlineBlockNeedsLayout ) {
this.style.display = "inline-block";
} else {
var display = defaultDisplay(this.nodeName);
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( display === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.display = "inline";
this.style.zoom = 1;
}
}
}
}
if ( jQuery.isArray( prop[p] ) ) {
// Create (if needed) and add to specialEasing
(opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1];
prop[p] = prop[p][0];
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
opt.curAnim = jQuery.extend({}, prop);
jQuery.each( prop, function( name, val ) {
var e = new jQuery.fx( self, opt, name );
if ( rfxtypes.test(val) ) {
e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop );
} else {
var parts = rfxnum.exec(val),
start = e.cur() || 0;
if ( parts ) {
var end = parseFloat( parts[2] ),
unit = parts[3] || "px";
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( self, name, (end || 1) + unit);
start = ((end || 1) / e.cur()) * start;
jQuery.style( self, name, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ((parts[1] === "-=" ? -1 : 1) * end) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
});
// For JS strict compliance
return true;
});
},
stop: function( clearQueue, gotoEnd ) {
var timers = jQuery.timers;
if ( clearQueue ) {
this.queue([]);
}
this.each(function() {
// go in reverse order so anything added to the queue during the loop is ignored
for ( var i = timers.length - 1; i >= 0; i-- ) {
if ( timers[i].elem === this ) {
if (gotoEnd) {
// force the next step to be the last
timers[i](true);
}
timers.splice(i, 1);
}
}
});
// start the next in the queue if the last step wasn't forced
if ( !gotoEnd ) {
this.dequeue();
}
return this;
}
});
function genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() {
obj[ this ] = type;
});
return obj;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show", 1),
slideUp: genFx("hide", 1),
slideToggle: genFx("toggle", 1),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.extend({
speed: function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( opt.queue !== false ) {
jQuery(this).dequeue();
}
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
};
return opt;
},
easing: {
linear: function( p, n, firstNum, diff ) {
return firstNum + diff * p;
},
swing: function( p, n, firstNum, diff ) {
return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
}
},
timers: [],
fx: function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
if ( !options.orig ) {
options.orig = {};
}
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
},
// Get the current size
cur: function() {
if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
return this.elem[ this.prop ];
}
var r = parseFloat( jQuery.css( this.elem, this.prop ) );
return r && r > -10000 ? r : 0;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx;
this.startTime = jQuery.now();
this.start = from;
this.end = to;
this.unit = unit || this.unit || "px";
this.now = this.start;
this.pos = this.state = 0;
function t( gotoEnd ) {
return self.step(gotoEnd);
}
t.elem = this.elem;
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval(fx.tick, fx.interval);
}
},
// Simple 'show' function
show: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any
// flash of content
this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur());
// Start by showing the element
jQuery( this.elem ).show();
},
// Simple 'hide' function
hide: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
this.options.hide = true;
// Begin the animation
this.custom(this.cur(), 0);
},
// Each step of an animation
step: function( gotoEnd ) {
var t = jQuery.now(), done = true;
if ( gotoEnd || t >= this.options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
this.options.curAnim[ this.prop ] = true;
for ( var i in this.options.curAnim ) {
if ( this.options.curAnim[i] !== true ) {
done = false;
}
}
if ( done ) {
// Reset the overflow
if ( this.options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
var elem = this.elem,
options = this.options;
jQuery.each( [ "", "X", "Y" ], function (index, value) {
elem.style[ "overflow" + value ] = options.overflow[index];
} );
}
// Hide the element if the "hide" operation was done
if ( this.options.hide ) {
jQuery(this.elem).hide();
}
// Reset the properties, if the item has been hidden or shown
if ( this.options.hide || this.options.show ) {
for ( var p in this.options.curAnim ) {
jQuery.style( this.elem, p, this.options.orig[p] );
}
}
// Execute the complete function
this.options.complete.call( this.elem );
}
return false;
} else {
var n = t - this.startTime;
this.state = n / this.options.duration;
// Perform the easing function, defaults to swing
var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop];
var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear");
this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration);
this.now = this.start + ((this.end - this.start) * this.pos);
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
tick: function() {
var timers = jQuery.timers;
for ( var i = 0; i < timers.length; i++ ) {
if ( !timers[i]() ) {
timers.splice(i--, 1);
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
},
interval: 13,
stop: function() {
clearInterval( timerId );
timerId = null;
},
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function( fx ) {
jQuery.style( fx.elem, "opacity", fx.now );
},
_default: function( fx ) {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) {
var elem = jQuery("<" + nodeName + ">").appendTo("body"),
display = elem.css("display");
elem.remove();
if ( display === "none" || display === "" ) {
display = "block";
}
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
var elem = this[0], box;
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
try {
box = elem.getBoundingClientRect();
} catch(e) {}
var doc = elem.ownerDocument,
docElem = doc.documentElement;
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box || { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow(doc),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = (win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ),
scrollLeft = (win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft),
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
} else {
jQuery.fn.offset = function( options ) {
var elem = this[0];
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
jQuery.offset.initialize();
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
doc = elem.ownerDocument,
docElem = doc.documentElement,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}
computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;
if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.offset = {
initialize: function() {
var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0,
html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } );
container.innerHTML = html;
body.insertBefore( container, body.firstChild );
innerDiv = container.firstChild;
checkDiv = innerDiv.firstChild;
td = innerDiv.nextSibling.firstChild.firstChild;
this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
checkDiv.style.position = "fixed";
checkDiv.style.top = "20px";
// safari subtracts parent border width here which is 5px
this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
checkDiv.style.position = checkDiv.style.top = "";
innerDiv.style.overflow = "hidden";
innerDiv.style.position = "relative";
this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop);
body.removeChild( container );
body = container = innerDiv = checkDiv = table = td = null;
jQuery.offset.initialize = jQuery.noop;
},
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
jQuery.offset.initialize();
if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = (position === "absolute" && jQuery.inArray('auto', [curCSSTop, curCSSLeft]) > -1),
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is absolute
if ( calculatePosition ) {
curPosition = curElem.position();
}
curTop = calculatePosition ? curPosition.top : parseInt( curCSSTop, 10 ) || 0;
curLeft = calculatePosition ? curPosition.left : parseInt( curCSSLeft, 10 ) || 0;
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if (options.top != null) {
props.top = (options.top - curOffset.top) + curTop;
}
if (options.left != null) {
props.left = (options.left - curOffset.left) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return null;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( ["Left", "Top"], function( i, name ) {
var method = "scroll" + name;
jQuery.fn[ method ] = function(val) {
var elem = this[0], win;
if ( !elem ) {
return null;
}
if ( val !== undefined ) {
// Set the scroll offset
return this.each(function() {
win = getWindow( this );
if ( win ) {
win.scrollTo(
!i ? val : jQuery(win).scrollLeft(),
i ? val : jQuery(win).scrollTop()
);
} else {
this[ method ] = val;
}
});
} else {
win = getWindow( elem );
// Return the scroll offset
return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function( i, name ) {
var type = name.toLowerCase();
// innerHeight and innerWidth
jQuery.fn["inner" + name] = function() {
return this[0] ?
parseFloat( jQuery.css( this[0], type, "padding" ) ) :
null;
};
// outerHeight and outerWidth
jQuery.fn["outer" + name] = function( margin ) {
return this[0] ?
parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) :
null;
};
jQuery.fn[ type ] = function( size ) {
// Get window width or height
var elem = this[0];
if ( !elem ) {
return size == null ? null : this;
}
if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
self[ type ]( size.call( this, i, self[ type ]() ) );
});
}
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
return elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] ||
elem.document.body[ "client" + name ];
// Get document width or height
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);
// Get or set width or height on the element
} else if ( size === undefined ) {
var orig = jQuery.css( elem, type ),
ret = parseFloat( orig );
return jQuery.isNaN( ret ) ? orig : ret;
// Set the width or height on the element (default to pixels if value is unitless)
} else {
return this.css( type, typeof size === "string" ? size : size + "px" );
}
};
});
})(window); |
fields/types/password/PasswordFilter.js | giovanniRodighiero/cms | import React from 'react';
import { SegmentedControl } from '../../../admin/client/App/elemental';
const EXISTS_OPTIONS = [
{ label: 'Is Set', value: true },
{ label: 'Is NOT Set', value: false },
];
function getDefaultValue () {
return {
exists: true,
};
}
var PasswordFilter = React.createClass({
propTypes: {
filter: React.PropTypes.shape({
exists: React.PropTypes.oneOf(EXISTS_OPTIONS.map(i => i.value)),
}),
},
statics: {
getDefaultValue: getDefaultValue,
},
getDefaultProps () {
return {
filter: getDefaultValue(),
};
},
toggleExists (value) {
this.props.onChange({ exists: value });
},
render () {
const { filter } = this.props;
return (
<SegmentedControl
equalWidthSegments
onChange={this.toggleExists}
options={EXISTS_OPTIONS}
value={filter.exists}
/>
);
},
});
module.exports = PasswordFilter;
|
src/React/Widgets/EqualizerWidget/index.js | Kitware/paraviewweb | import React from 'react';
import PropTypes from 'prop-types';
import equals from 'mout/src/array/equals';
import style from 'PVWStyle/ReactWidgets/EqualizerWidget.mcss';
import MouseHandler from '../../../Interaction/Core/MouseHandler';
import SizeHelper from '../../../Common/Misc/SizeHelper';
export default class EqualizerWidget extends React.Component {
constructor(props) {
super(props);
this.state = {
layers: props.layers,
width: props.width,
height: props.height,
};
// Bind callback
this.updateDimensions = this.updateDimensions.bind(this);
this.draw = this.draw.bind(this);
this.clicked = this.clicked.bind(this);
}
componentDidMount() {
// Listen to window resize
this.sizeSubscription = SizeHelper.onSizeChangeForElement(
this.rootContainer.parentNode,
this.updateDimensions
);
// Make sure we monitor window size if it is not already the case
SizeHelper.startListening();
this.updateDimensions();
this.draw();
this.mouseHandler = new MouseHandler(this.canvas);
this.mouseHandler.attach({
click: this.clicked,
drag: this.clicked,
});
}
componentWillReceiveProps(nextProps) {
const layers = nextProps.layers;
if (!equals(this.state.layers, layers)) {
this.setState({ layers });
}
}
componentDidUpdate(prevProps, prevState) {
this.draw();
}
componentWillUnmount() {
this.mouseHandler.destroy();
// Remove window listener
if (this.sizeSubscription) {
this.sizeSubscription.unsubscribe();
this.sizeSubscription = null;
}
}
updateDimensions() {
const el = this.rootContainer.parentNode;
const innerWidth = SizeHelper.getSize(el, true).clientWidth;
if (el && innerWidth && this.state.width !== innerWidth) {
this.setState({ width: innerWidth });
return true;
}
return false;
}
draw() {
const ctx = this.canvas.getContext('2d');
ctx.strokeStyle = this.props.stroke;
ctx.lineWidth = '1';
const array = this.state.layers;
const width = this.state.width;
const height = this.state.height;
const size = array.length;
const spacing = this.props.spacing;
const layerWidth = Math.floor((width - 5 * spacing) / size - spacing);
const maxLayerHeight = height - 4 * spacing;
const layerStep =
layerWidth +
(width - layerWidth * array.length - 2 * spacing) / (array.length + 1);
ctx.clearRect(0, 0, this.state.width, this.state.height);
ctx.beginPath();
ctx.rect(spacing, spacing, width - 2 * spacing, height - 2 * spacing);
ctx.stroke();
for (let i = 0; i < size; i++) {
const layerHeight = array[i] * maxLayerHeight;
ctx.fillStyle = this.props.colors[i % this.props.colors.length];
ctx.fillRect(
layerStep * i + 2 * spacing,
height - layerHeight - 2 * spacing,
layerWidth,
layerHeight
);
ctx.beginPath();
ctx.rect(
layerStep * i + 2 * spacing,
height - layerHeight - 2 * spacing,
layerWidth,
layerHeight
);
ctx.stroke();
}
// Draw Grid
// var yStep = maxLayerHeight / 10;
// ctx.fillStyle = '#ffffff';
// for(var i = 0; i < 9; i++) {
// ctx.beginPath();
// ctx.fillRect(spacing*1.5, (1+i)*yStep + 2 * spacing, width - 3.5 * spacing, 1);
// ctx.stroke();
// }
}
clicked(e) {
const rect = this.canvas.getClientRects()[0];
const x = e.pointers[0].clientX - rect.left - 2 * this.props.spacing;
const y = e.pointers[0].clientY - rect.top - 2 * this.props.spacing;
const effectiveHeight = rect.height - 4 * this.props.spacing;
const idx = Math.min(
this.state.layers.length - 1,
Math.floor(
(x / (rect.width - 4 * this.props.spacing)) * this.state.layers.length
)
);
let opacity = 1.0 - y / effectiveHeight;
const layers = [].concat(this.state.layers);
opacity = opacity > 1.0 ? 1.0 : opacity;
opacity = opacity < 0.0 ? 0.0 : opacity;
layers[idx] = opacity;
this.setState({ layers });
if (this.props.onChange) {
this.props.onChange(layers);
}
this.draw();
}
render() {
return (
<div
className={style.container}
ref={(c) => {
this.rootContainer = c;
}}
>
<canvas
className={style.canvas}
ref={(c) => {
this.canvas = c;
}}
width={this.state.width}
height={this.state.height}
/>
</div>
);
}
}
EqualizerWidget.propTypes = {
colors: PropTypes.array,
height: PropTypes.number,
layers: PropTypes.array,
onChange: PropTypes.func,
spacing: PropTypes.number,
stroke: PropTypes.string,
width: PropTypes.number,
};
EqualizerWidget.defaultProps = {
layers: [1, 1, 1, 1, 1, 1, 1],
colors: ['#0000ff', '#ffffff', '#ff0000'],
stroke: '#000000',
height: 120,
width: 300,
spacing: 2,
onChange: undefined,
};
|
node_modules/react-icons/ti/chevron-left-outline.js | bengimbel/Solstice-React-Contacts-Project |
import React from 'react'
import Icon from 'react-icon-base'
const TiChevronLeftOutline = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m21.7 33.3c-1.4 0-2.6-0.5-3.6-1.4l-11.8-11.9 11.8-11.9c1.9-1.9 5.2-1.9 7.1 0 0.9 1 1.5 2.2 1.5 3.6s-0.6 2.6-1.5 3.5l-4.8 4.8 4.8 4.8c0.9 0.9 1.5 2.2 1.5 3.5s-0.6 2.6-1.5 3.6c-0.9 0.9-2.2 1.4-3.5 1.4z m-10.7-13.3l9.5 9.5c0.6 0.6 1.7 0.6 2.3 0 0.4-0.3 0.5-0.7 0.5-1.2s-0.1-0.8-0.5-1.1l-7.1-7.2 7.1-7.2c0.4-0.3 0.5-0.7 0.5-1.1s-0.1-0.9-0.5-1.2c-0.6-0.6-1.7-0.6-2.3 0l-9.5 9.5z"/></g>
</Icon>
)
export default TiChevronLeftOutline
|
packages/material-ui-icons/src/NoteSharp.js | allanalexandre/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M22 10l-6-6H2v16h20V10zm-7-4.5l5.5 5.5H15V5.5z" /></React.Fragment>
, 'NoteSharp');
|
examples/basic/initializers/client/index.js | gavacho/react-lazy-load | import React from 'react';
import ReactDOM from 'react-dom';
import Application from 'components/Application';
ReactDOM.render(
<Application />,
document.getElementById('content')
); |
react/FlagMYIcon/FlagMYIcon.iconSketch.js | seekinternational/seek-asia-style-guide | import React from 'react';
import FlagMYIcon from './FlagMYIcon';
export const symbols = {
'FlagMYIcon': <FlagMYIcon />
};
|
app/javascript/mastodon/components/media_attachments.js | maa123/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { MediaGallery, Video, Audio } from 'mastodon/features/ui/util/async-components';
import Bundle from 'mastodon/features/ui/components/bundle';
import noop from 'lodash/noop';
export default class MediaAttachments extends ImmutablePureComponent {
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
height: PropTypes.number,
width: PropTypes.number,
};
static defaultProps = {
height: 110,
width: 239,
};
updateOnProps = [
'status',
];
renderLoadingMediaGallery = () => {
const { height, width } = this.props;
return (
<div className='media-gallery' style={{ height, width }} />
);
}
renderLoadingVideoPlayer = () => {
const { height, width } = this.props;
return (
<div className='video-player' style={{ height, width }} />
);
}
renderLoadingAudioPlayer = () => {
const { height, width } = this.props;
return (
<div className='audio-player' style={{ height, width }} />
);
}
render () {
const { status, width, height } = this.props;
const mediaAttachments = status.get('media_attachments');
if (mediaAttachments.size === 0) {
return null;
}
if (mediaAttachments.getIn([0, 'type']) === 'audio') {
const audio = mediaAttachments.get(0);
return (
<Bundle fetchComponent={Audio} loading={this.renderLoadingAudioPlayer} >
{Component => (
<Component
src={audio.get('url')}
alt={audio.get('description')}
width={width}
height={height}
poster={audio.get('preview_url') || status.getIn(['account', 'avatar_static'])}
backgroundColor={audio.getIn(['meta', 'colors', 'background'])}
foregroundColor={audio.getIn(['meta', 'colors', 'foreground'])}
accentColor={audio.getIn(['meta', 'colors', 'accent'])}
duration={audio.getIn(['meta', 'original', 'duration'], 0)}
/>
)}
</Bundle>
);
} else if (mediaAttachments.getIn([0, 'type']) === 'video') {
const video = mediaAttachments.get(0);
return (
<Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} >
{Component => (
<Component
preview={video.get('preview_url')}
frameRate={video.getIn(['meta', 'original', 'frame_rate'])}
blurhash={video.get('blurhash')}
src={video.get('url')}
alt={video.get('description')}
width={width}
height={height}
inline
sensitive={status.get('sensitive')}
onOpenVideo={noop}
/>
)}
</Bundle>
);
} else {
return (
<Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery} >
{Component => (
<Component
media={mediaAttachments}
sensitive={status.get('sensitive')}
defaultWidth={width}
height={height}
onOpenMedia={noop}
/>
)}
</Bundle>
);
}
}
}
|
core/modules/ckeditor/js/views/ControllerView.js | natem/tahoe-treetop | /**
* @file
* A Backbone View acting as a controller for CKEditor toolbar configuration.
*/
(function ($, Drupal, Backbone, CKEDITOR, _) {
'use strict';
Drupal.ckeditor.ControllerView = Backbone.View.extend(/** @lends Drupal.ckeditor.ControllerView# */{
/**
* @type {object}
*/
events: {},
/**
* Backbone View acting as a controller for CKEditor toolbar configuration.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.getCKEditorFeatures(this.model.get('hiddenEditorConfig'), this.disableFeaturesDisallowedByFilters.bind(this));
// Push the active editor configuration to the textarea.
this.model.listenTo(this.model, 'change:activeEditorConfig', this.model.sync);
this.listenTo(this.model, 'change:isDirty', this.parseEditorDOM);
},
/**
* Converts the active toolbar DOM structure to an object representation.
*
* @param {Drupal.ckeditor.ConfigurationModel} model
* The state model for the CKEditor configuration.
* @param {bool} isDirty
* Tracks whether the active toolbar DOM structure has been changed.
* isDirty is toggled back to false in this method.
* @param {object} options
* An object that includes:
* @param {bool} [options.broadcast]
* A flag that controls whether a CKEditorToolbarChanged event should be
* fired for configuration changes.
*
* @fires event:CKEditorToolbarChanged
*/
parseEditorDOM: function (model, isDirty, options) {
if (isDirty) {
var currentConfig = this.model.get('activeEditorConfig');
// Process the rows.
var rows = [];
this.$el
.find('.ckeditor-active-toolbar-configuration')
.children('.ckeditor-row').each(function () {
var groups = [];
// Process the button groups.
$(this).find('.ckeditor-toolbar-group').each(function () {
var $group = $(this);
var $buttons = $group.find('.ckeditor-button');
if ($buttons.length) {
var group = {
name: $group.attr('data-drupal-ckeditor-toolbar-group-name'),
items: []
};
$group.find('.ckeditor-button, .ckeditor-multiple-button').each(function () {
group.items.push($(this).attr('data-drupal-ckeditor-button-name'));
});
groups.push(group);
}
});
if (groups.length) {
rows.push(groups);
}
});
this.model.set('activeEditorConfig', rows);
// Mark the model as clean. Whether or not the sync to the textfield
// occurs depends on the activeEditorConfig attribute firing a change
// event. The DOM has at least been processed and posted, so as far as
// the model is concerned, it is clean.
this.model.set('isDirty', false);
// Determine whether we should trigger an event.
if (options.broadcast !== false) {
var prev = this.getButtonList(currentConfig);
var next = this.getButtonList(rows);
if (prev.length !== next.length) {
this.$el
.find('.ckeditor-toolbar-active')
.trigger('CKEditorToolbarChanged', [
(prev.length < next.length) ? 'added' : 'removed',
_.difference(_.union(prev, next), _.intersection(prev, next))[0]
]);
}
}
}
},
/**
* Asynchronously retrieve the metadata for all available CKEditor features.
*
* In order to get a list of all features needed by CKEditor, we create a
* hidden CKEditor instance, then check the CKEditor's "allowedContent"
* filter settings. Because creating an instance is expensive, a callback
* must be provided that will receive a hash of {@link Drupal.EditorFeature}
* features keyed by feature (button) name.
*
* @param {object} CKEditorConfig
* An object that represents the configuration settings for a CKEditor
* editor component.
* @param {function} callback
* A function to invoke when the instanceReady event is fired by the
* CKEditor object.
*/
getCKEditorFeatures: function (CKEditorConfig, callback) {
var getProperties = function (CKEPropertiesList) {
return (_.isObject(CKEPropertiesList)) ? _.keys(CKEPropertiesList) : [];
};
var convertCKERulesToEditorFeature = function (feature, CKEFeatureRules) {
for (var i = 0; i < CKEFeatureRules.length; i++) {
var CKERule = CKEFeatureRules[i];
var rule = new Drupal.EditorFeatureHTMLRule();
// Tags.
var tags = getProperties(CKERule.elements);
rule.required.tags = (CKERule.propertiesOnly) ? [] : tags;
rule.allowed.tags = tags;
// Attributes.
rule.required.attributes = getProperties(CKERule.requiredAttributes);
rule.allowed.attributes = getProperties(CKERule.attributes);
// Styles.
rule.required.styles = getProperties(CKERule.requiredStyles);
rule.allowed.styles = getProperties(CKERule.styles);
// Classes.
rule.required.classes = getProperties(CKERule.requiredClasses);
rule.allowed.classes = getProperties(CKERule.classes);
// Raw.
rule.raw = CKERule;
feature.addHTMLRule(rule);
}
};
// Create hidden CKEditor with all features enabled, retrieve metadata.
// @see \Drupal\ckeditor\Plugin\Editor\CKEditor::settingsForm.
var hiddenCKEditorID = 'ckeditor-hidden';
if (CKEDITOR.instances[hiddenCKEditorID]) {
CKEDITOR.instances[hiddenCKEditorID].destroy(true);
}
// Load external plugins, if any.
var hiddenEditorConfig = this.model.get('hiddenEditorConfig');
if (hiddenEditorConfig.drupalExternalPlugins) {
var externalPlugins = hiddenEditorConfig.drupalExternalPlugins;
for (var pluginName in externalPlugins) {
if (externalPlugins.hasOwnProperty(pluginName)) {
CKEDITOR.plugins.addExternal(pluginName, externalPlugins[pluginName], '');
}
}
}
CKEDITOR.inline($('#' + hiddenCKEditorID).get(0), CKEditorConfig);
// Once the instance is ready, retrieve the allowedContent filter rules
// and convert them to Drupal.EditorFeature objects.
CKEDITOR.once('instanceReady', function (e) {
if (e.editor.name === hiddenCKEditorID) {
// First collect all CKEditor allowedContent rules.
var CKEFeatureRulesMap = {};
var rules = e.editor.filter.allowedContent;
var rule;
var name;
for (var i = 0; i < rules.length; i++) {
rule = rules[i];
name = rule.featureName || ':(';
if (!CKEFeatureRulesMap[name]) {
CKEFeatureRulesMap[name] = [];
}
CKEFeatureRulesMap[name].push(rule);
}
// Now convert these to Drupal.EditorFeature objects. And track which
// buttons are mapped to which features.
// @see getFeatureForButton()
var features = {};
var buttonsToFeatures = {};
for (var featureName in CKEFeatureRulesMap) {
if (CKEFeatureRulesMap.hasOwnProperty(featureName)) {
var feature = new Drupal.EditorFeature(featureName);
convertCKERulesToEditorFeature(feature, CKEFeatureRulesMap[featureName]);
features[featureName] = feature;
var command = e.editor.getCommand(featureName);
if (command) {
buttonsToFeatures[command.uiItems[0].name] = featureName;
}
}
}
callback(features, buttonsToFeatures);
}
});
},
/**
* Retrieves the feature for a given button from featuresMetadata. Returns
* false if the given button is in fact a divider.
*
* @param {string} button
* The name of a CKEditor button.
*
* @return {object}
* The feature metadata object for a button.
*/
getFeatureForButton: function (button) {
// Return false if the button being added is a divider.
if (button === '-') {
return false;
}
// Get a Drupal.editorFeature object that contains all metadata for
// the feature that was just added or removed. Not every feature has
// such metadata.
var featureName = this.model.get('buttonsToFeatures')[button.toLowerCase()];
// Features without an associated command do not have a 'feature name' by
// default, so we use the lowercased button name instead.
if (!featureName) {
featureName = button.toLowerCase();
}
var featuresMetadata = this.model.get('featuresMetadata');
if (!featuresMetadata[featureName]) {
featuresMetadata[featureName] = new Drupal.EditorFeature(featureName);
this.model.set('featuresMetadata', featuresMetadata);
}
return featuresMetadata[featureName];
},
/**
* Checks buttons against filter settings; disables disallowed buttons.
*
* @param {object} features
* A map of {@link Drupal.EditorFeature} objects.
* @param {object} buttonsToFeatures
* Object containing the button-to-feature mapping.
*
* @see Drupal.ckeditor.ControllerView#getFeatureForButton
*/
disableFeaturesDisallowedByFilters: function (features, buttonsToFeatures) {
this.model.set('featuresMetadata', features);
// Store the button-to-feature mapping. Needs to happen only once, because
// the same buttons continue to have the same features; only the rules for
// specific features may change.
// @see getFeatureForButton()
this.model.set('buttonsToFeatures', buttonsToFeatures);
// Ensure that toolbar configuration changes are broadcast.
this.broadcastConfigurationChanges(this.$el);
// Initialization: not all of the default toolbar buttons may be allowed
// by the current filter settings. Remove any of the default toolbar
// buttons that require more permissive filter settings. The remaining
// default toolbar buttons are marked as "added".
var existingButtons = [];
// Loop through each button group after flattening the groups from the
// toolbar row arrays.
var buttonGroups = _.flatten(this.model.get('activeEditorConfig'));
for (var i = 0; i < buttonGroups.length; i++) {
// Pull the button names from each toolbar button group.
var buttons = buttonGroups[i].items;
for (var k = 0; k < buttons.length; k++) {
existingButtons.push(buttons[k]);
}
}
// Remove duplicate buttons.
existingButtons = _.unique(existingButtons);
// Prepare the active toolbar and available-button toolbars.
for (var n = 0; n < existingButtons.length; n++) {
var button = existingButtons[n];
var feature = this.getFeatureForButton(button);
// Skip dividers.
if (feature === false) {
continue;
}
if (Drupal.editorConfiguration.featureIsAllowedByFilters(feature)) {
// Existing toolbar buttons are in fact "added features".
this.$el.find('.ckeditor-toolbar-active').trigger('CKEditorToolbarChanged', ['added', existingButtons[n]]);
}
else {
// Move the button element from the active the active toolbar to the
// list of available buttons.
$('.ckeditor-toolbar-active li[data-drupal-ckeditor-button-name="' + button + '"]')
.detach()
.appendTo('.ckeditor-toolbar-disabled > .ckeditor-toolbar-available > ul');
// Update the toolbar value field.
this.model.set({isDirty: true}, {broadcast: false});
}
}
},
/**
* Sets up broadcasting of CKEditor toolbar configuration changes.
*
* @param {jQuery} $ckeditorToolbar
* The active toolbar DOM element wrapped in jQuery.
*/
broadcastConfigurationChanges: function ($ckeditorToolbar) {
var view = this;
var hiddenEditorConfig = this.model.get('hiddenEditorConfig');
var getFeatureForButton = this.getFeatureForButton.bind(this);
var getCKEditorFeatures = this.getCKEditorFeatures.bind(this);
$ckeditorToolbar
.find('.ckeditor-toolbar-active')
// Listen for CKEditor toolbar configuration changes. When a button is
// added/removed, call an appropriate Drupal.editorConfiguration method.
.on('CKEditorToolbarChanged.ckeditorAdmin', function (event, action, button) {
var feature = getFeatureForButton(button);
// Early-return if the button being added is a divider.
if (feature === false) {
return;
}
// Trigger a standardized text editor configuration event to indicate
// whether a feature was added or removed, so that filters can react.
var configEvent = (action === 'added') ? 'addedFeature' : 'removedFeature';
Drupal.editorConfiguration[configEvent](feature);
})
// Listen for CKEditor plugin settings changes. When a plugin setting is
// changed, rebuild the CKEditor features metadata.
.on('CKEditorPluginSettingsChanged.ckeditorAdmin', function (event, settingsChanges) {
// Update hidden CKEditor configuration.
for (var key in settingsChanges) {
if (settingsChanges.hasOwnProperty(key)) {
hiddenEditorConfig[key] = settingsChanges[key];
}
}
// Retrieve features for the updated hidden CKEditor configuration.
getCKEditorFeatures(hiddenEditorConfig, function (features) {
// Trigger a standardized text editor configuration event for each
// feature that was modified by the configuration changes.
var featuresMetadata = view.model.get('featuresMetadata');
for (var name in features) {
if (features.hasOwnProperty(name)) {
var feature = features[name];
if (featuresMetadata.hasOwnProperty(name) && !_.isEqual(featuresMetadata[name], feature)) {
Drupal.editorConfiguration.modifiedFeature(feature);
}
}
}
// Update the CKEditor features metadata.
view.model.set('featuresMetadata', features);
});
});
},
/**
* Returns the list of buttons from an editor configuration.
*
* @param {object} config
* A CKEditor configuration object.
*
* @return {Array}
* A list of buttons in the CKEditor configuration.
*/
getButtonList: function (config) {
var buttons = [];
// Remove the rows.
config = _.flatten(config);
// Loop through the button groups and pull out the buttons.
config.forEach(function (group) {
group.items.forEach(function (button) {
buttons.push(button);
});
});
// Remove the dividing elements if any.
return _.without(buttons, '-');
}
});
})(jQuery, Drupal, Backbone, CKEDITOR, _);
|
ajax/libs/mobx-react/4.1.5/native.min.js | jonobr1/cdnjs | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("mobx"),require("react"),require("react-native")):"function"==typeof define&&define.amd?define(["mobx","react","react-native"],t):"object"==typeof exports?exports.mobxReact=t(require("mobx"),require("react"),require("react-native")):e.mobxReact=t(e.mobx,e.React,e.ReactNative)}(this,function(e,t,r){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.PropTypes=t.propTypes=t.inject=t.Provider=t.useStaticRendering=t.trackComponents=t.componentByNodeRegistery=t.renderReporter=t.Observer=t.observer=void 0;var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a=r(1);Object.defineProperty(t,"observer",{enumerable:!0,get:function(){return a.observer}}),Object.defineProperty(t,"Observer",{enumerable:!0,get:function(){return a.Observer}}),Object.defineProperty(t,"renderReporter",{enumerable:!0,get:function(){return a.renderReporter}}),Object.defineProperty(t,"componentByNodeRegistery",{enumerable:!0,get:function(){return a.componentByNodeRegistery}}),Object.defineProperty(t,"trackComponents",{enumerable:!0,get:function(){return a.trackComponents}}),Object.defineProperty(t,"useStaticRendering",{enumerable:!0,get:function(){return a.useStaticRendering}});var s=r(8);Object.defineProperty(t,"Provider",{enumerable:!0,get:function(){return o(s).default}});var u=r(6);Object.defineProperty(t,"inject",{enumerable:!0,get:function(){return o(u).default}});var c=r(2),f=n(c),p=r(3),l=o(p),d=(r(4),r(9)),b=r(10),y=n(b),v=void 0;if(v="mobx-react/native",!f)throw new Error(v+" requires the MobX package");if(!l.default)throw new Error(v+" requires React to be available");"function"==typeof d.unstable_batchedUpdates&&f.extras.setReactionScheduler(d.unstable_batchedUpdates),t.propTypes=y,t.PropTypes=y,t.default=e.exports,"object"===("undefined"==typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__?"undefined":i(__MOBX_DEVTOOLS_GLOBAL_HOOK__))&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobxReact(e.exports,f)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){if(m.default)try{return m.default.findDOMNode(e)}catch(e){return null}return null}function i(e){var t=o(e);t&&P&&P.set(t,e),S.emit({event:"render",renderTime:e.__$mobRenderEnd-e.__$mobRenderStart,totalTime:Date.now()-e.__$mobRenderStart,component:e,node:t})}function a(){if("undefined"==typeof WeakMap)throw new Error("[mobx-react] tracking components is not supported in this browser.");x||(x=!0)}function s(e){_=e}function u(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=e[t],o=M[t],i=n?r===!0?function(){o.apply(this,arguments),n.apply(this,arguments)}:function(){n.apply(this,arguments),o.apply(this,arguments)}:o;Object.defineProperty(e,t,{writable:!1,configurable:!0,enumerable:!1,value:i})}function c(e,t){if(null==e||null==t||"object"!==("undefined"==typeof e?"undefined":l(e))||"object"!==("undefined"==typeof t?"undefined":l(t)))return e!==t;var r=Object.keys(e);if(r.length!==Object.keys(t).length)return!0;for(var n=void 0,o=r.length-1;n=r[o];o--)if(t[n]!==e[n])return!0;return!1}function f(e,t){if("string"==typeof e)throw new Error("Store names should be provided as array");if(Array.isArray(e))return w||(w=!0,console.warn('Mobx observer: Using observer to inject stores is deprecated since 4.0. Use `@inject("store1", "store2") @observer ComponentClass` or `inject("store1", "store2")(observer(componentClass))` instead of `@observer(["store1", "store2"]) ComponentClass`')),t?j.default.apply(null,e)(f(t)):function(t){return f(e,t)};var r=e;if(r.isMobxInjector===!0&&console.warn("Mobx observer: You are trying to use 'observer' on a component that already has 'inject'. Please apply 'observer' before applying 'inject'"),!("function"!=typeof r||r.prototype&&r.prototype.render||r.isReactClass||y.default.Component.isPrototypeOf(r)))return f(y.default.createClass({displayName:r.displayName||r.name,propTypes:r.propTypes,contextTypes:r.contextTypes,getDefaultProps:function(){return r.defaultProps},render:function(){return r.call(this,this.props,this.context)}}));if(!r)throw new Error("Please pass a valid component to 'observer'");var n=r.prototype||r;return p(n),r.isMobXReactObserver=!0,r}function p(e){u(e,"componentWillMount",!0),["componentDidMount","componentWillUnmount","componentDidUpdate"].forEach(function(t){u(e,t)}),e.shouldComponentUpdate||(e.shouldComponentUpdate=M.shouldComponentUpdate)}Object.defineProperty(t,"__esModule",{value:!0}),t.Observer=t.renderReporter=t.componentByNodeRegistery=void 0;var l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};t.trackComponents=a,t.useStaticRendering=s,t.observer=f;var d=r(2),b=r(3),y=n(b),v=r(4),m=n(v),h=r(5),O=n(h),g=r(6),j=n(g),x=!1,_=!1,w=!1,P=t.componentByNodeRegistery="undefined"!=typeof WeakMap?new WeakMap:void 0,S=t.renderReporter=new O.default,M={componentWillMount:function(){function e(e){var t=this[e],r=new d.Atom("reactive "+e);Object.defineProperty(this,e,{configurable:!0,enumerable:!0,get:function(){return r.reportObserved(),t},set:function(e){!i&&c(t,e)?(t=e,o=!0,r.reportChanged(),o=!1):t=e}})}var t=this;if(_!==!0){var r=this.displayName||this.name||this.constructor&&(this.constructor.displayName||this.constructor.name)||"<component>",n=this._reactInternalInstance&&this._reactInternalInstance._rootNodeID,o=!1,i=!1;e.call(this,"props"),e.call(this,"state");var a=this.render.bind(this),s=null,u=!1,f=function(){return s=new d.Reaction(r+"#"+n+".render()",function(){if(!u&&(u=!0,"function"==typeof t.componentWillReact&&t.componentWillReact(),t.__$mobxIsUnmounted!==!0)){var e=!0;try{i=!0,o||y.default.Component.prototype.forceUpdate.call(t),e=!1}finally{i=!1,e&&s.dispose()}}}),p.$mobx=s,t.render=p,p()},p=function(){u=!1;var e=void 0,r=void 0;if(s.track(function(){x&&(t.__$mobRenderStart=Date.now());try{r=d.extras.allowStateChanges(!1,a)}catch(t){e=t}x&&(t.__$mobRenderEnd=Date.now())}),e)throw e;return r};this.render=f}},componentWillUnmount:function(){if(_!==!0&&(this.render.$mobx&&this.render.$mobx.dispose(),this.__$mobxIsUnmounted=!0,x)){var e=o(this);e&&P&&P.delete(e),S.emit({event:"destroy",component:this,node:e})}},componentDidMount:function(){x&&i(this)},componentDidUpdate:function(){x&&i(this)},shouldComponentUpdate:function(e,t){return _&&console.warn("[mobx-react] It seems that a re-rendering of a React component is triggered while in static (server-side) mode. Please make sure components are rendered only once server-side."),this.state!==t||c(this.props,e)}},R=t.Observer=f(function(e){var t=e.children;return t()});R.propTypes={children:y.default.PropTypes.func.isRequired}},function(t,r){t.exports=e},function(e,r){e.exports=t},function(e,t){e.exports=null},function(e,t){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var n=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),o=function(){function e(){r(this,e),this.listeners=[]}return n(e,[{key:"on",value:function(e){var t=this;return this.listeners.push(e),function(){var r=t.listeners.indexOf(e);r!==-1&&t.listeners.splice(r,1)}}},{key:"emit",value:function(e){this.listeners.forEach(function(t){return t(e)})}}]),e}();t.default=o},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t,r){var n="inject-"+(t.displayName||t.name||t.constructor&&t.constructor.name||"Unknown");r&&(n+="-with-"+r);var o=c.default.createClass({displayName:n,storeRef:function(e){this.wrappedInstance=e},render:function(){var r={};for(var n in this.props)this.props.hasOwnProperty(n)&&(r[n]=this.props[n]);var o=e(this.context.mobxStores||{},r,this.context)||{};for(var i in o)r[i]=o[i];return r.ref=this.storeRef,c.default.createElement(t,r)}});return(0,p.default)(o,t),o.wrappedComponent=t,Object.defineProperties(o,b),o}function i(e){return function(t,r){return e.forEach(function(e){if(!(e in r)){if(!(e in t))throw new Error("MobX observer: Store '"+e+"' is not available! Make sure it is provided by some Provider");r[e]=t[e]}}),r}}function a(){var e=arguments,t=void 0;if("function"==typeof arguments[0])return t=arguments[0],function(e){var r=o(t,e);return r.isMobxInjector=!1,r=(0,l.observer)(r),r.isMobxInjector=!0,r};var r=function(){for(var r=[],n=0;n<e.length;n++)r[n]=e[n];return t=i(r),{v:function(e){return o(t,e,r.join("-"))}}}();return"object"===("undefined"==typeof r?"undefined":s(r))?r.v:void 0}Object.defineProperty(t,"__esModule",{value:!0});var s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};t.default=a;var u=r(3),c=n(u),f=r(7),p=n(f),l=r(1),d={mobxStores:u.PropTypes.object};Object.seal(d);var b={contextTypes:{get:function(){return d},set:function(e){console.warn("Mobx Injector: you are trying to attach `contextTypes` on an component decorated with `inject` (or `observer`) HOC. Please specify the contextTypes on the wrapped component instead. It is accessible through the `wrappedComponent`")},configurable:!0,enumerable:!1},isMobxInjector:{value:!0,writable:!0,configurable:!0,enumerable:!0}}},function(e,t){"use strict";var r={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},n={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0},o="function"==typeof Object.getOwnPropertySymbols;e.exports=function(e,t,i){if("string"!=typeof t){var a=Object.getOwnPropertyNames(t);o&&(a=a.concat(Object.getOwnPropertySymbols(t)));for(var s=0;s<a.length;++s)if(!(r[a[s]]||n[a[s]]||i&&i[a[s]]))try{e[a[s]]=t[a[s]]}catch(e){}}return e}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var s,u,c=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),f=r(3),p=n(f),l={children:!0,key:!0,ref:!0},d=(u=s=function(e){function t(){return o(this,t),i(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),c(t,[{key:"render",value:function(){return p.default.Children.only(this.props.children)}},{key:"getChildContext",value:function(){var e={},t=this.context.mobxStores;if(t)for(var r in t)e[r]=t[r];for(var n in this.props)l[n]||"suppressChangedStoreWarning"===n||(e[n]=this.props[n]);return{mobxStores:e}}},{key:"componentWillReceiveProps",value:function(e){if(Object.keys(e).length!==Object.keys(this.props).length&&console.warn("MobX Provider: The set of provided stores has changed. Please avoid changing stores as the change might not propagate to all children"),!e.suppressChangedStoreWarning)for(var t in e)l[t]||this.props[t]===e[t]||console.warn("MobX Provider: Provided store '"+t+"' has changed. Please avoid replacing stores as the change might not propagate to all children")}}]),t}(f.Component),s.contextTypes={mobxStores:f.PropTypes.object},s.childContextTypes={mobxStores:f.PropTypes.object.isRequired},u);t.default=d},function(e,t){e.exports=r},function(e,t,r){"use strict";function n(e){function t(t,r,n,o,i,a){for(var s=arguments.length,u=Array(s>6?s-6:0),c=6;c<s;c++)u[c-6]=arguments[c];return(0,f.untracked)(function(){if(o=o||"<<anonymous>>",a=a||n,null==r[n]){if(t){var s=null===r[n]?"null":"undefined";return new Error("The "+i+" `"+a+"` is marked as required in `"+o+"`, but its value is `"+s+"`.")}return null}return e.apply(void 0,[r,n,o,i,a].concat(u))})}var r=t.bind(null,!1);return r.isRequired=t.bind(null,!0),r}function o(e,t){return"symbol"===e||("Symbol"===t["@@toStringTag"]||"function"==typeof Symbol&&t instanceof Symbol)}function i(e){var t="undefined"==typeof e?"undefined":c(e);return Array.isArray(e)?"array":e instanceof RegExp?"object":o(t,e)?"symbol":t}function a(e){var t=i(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function s(e,t){return n(function(r,n,o,s,u){return(0,f.untracked)(function(){if(e&&i(r[n])===t.toLowerCase())return null;var s=void 0;switch(t){case"Array":s=f.isObservableArray;break;case"Object":s=f.isObservableObject;break;case"Map":s=f.isObservableMap;break;default:throw new Error("Unexpected mobxType: "+t)}var c=r[n];if(!s(c)){var p=a(c),l=e?" or javascript `"+t.toLowerCase()+"`":"";return new Error("Invalid prop `"+u+"` of type `"+p+"` supplied to `"+o+"`, expected `mobx.Observable"+t+"`"+l+".")}return null})})}function u(e,t){return n(function(r,n,o,i,a){for(var u=arguments.length,c=Array(u>5?u-5:0),p=5;p<u;p++)c[p-5]=arguments[p];return(0,f.untracked)(function(){if("function"!=typeof t)return new Error("Property `"+a+"` of component `"+o+"` has invalid PropType notation.");var u=s(e,"Array")(r,n,o);if(u instanceof Error)return u;for(var f=r[n],p=0;p<f.length;p++)if(u=t.apply(void 0,[f,p,o,i,a+"["+p+"]"].concat(c)),u instanceof Error)return u;return null})})}Object.defineProperty(t,"__esModule",{value:!0}),t.objectOrObservableObject=t.arrayOrObservableArrayOf=t.arrayOrObservableArray=t.observableObject=t.observableMap=t.observableArrayOf=t.observableArray=void 0;var c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},f=r(2);t.observableArray=s(!1,"Array"),t.observableArrayOf=u.bind(null,!1),t.observableMap=s(!1,"Map"),t.observableObject=s(!1,"Object"),t.arrayOrObservableArray=s(!0,"Array"),t.arrayOrObservableArrayOf=u.bind(null,!0),t.objectOrObservableObject=s(!0,"Object")}])});
//# sourceMappingURL=native.min.js.map |
sites/all/libraries/flexslider/bower_components/jquery/dist/jquery.js | newpalmyra/newpalmyra-drupal | /*!
* jQuery JavaScript Library v1.11.3
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2015-04-28T16:19Z
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper window is present,
// execute the factory and get jQuery
// For environments that do not inherently posses a window with a document
// (such as Node.js), expose a jQuery-making factory as module.exports
// This accentuates the need for the creation of a real window
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//
var deletedIds = [];
var slice = deletedIds.slice;
var concat = deletedIds.concat;
var push = deletedIds.push;
var indexOf = deletedIds.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var support = {};
var
version = "1.11.3",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android<4.1, IE<9
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num != null ?
// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: deletedIds.sort,
splice: deletedIds.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
// adding 1 corrects loss of precision from parseFloat (#15100)
return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
isPlainObject: function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( support.ownLast ) {
for ( key in obj ) {
return hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Support: Android<4.1, IE<9
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( indexOf ) {
return indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
while ( j < len ) {
first[ i++ ] = second[ j++ ];
}
// Support: IE<9
// Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
if ( len !== len ) {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: function() {
return +( new Date() );
},
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
// Support: iOS 8.2 (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = "length" in obj && obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.2.0-pre
* http://sizzlejs.com/
*
* Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-12-16
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + 1 * new Date(),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf as it's faster than native
// http://jsperf.com/thor-indexof-vs-for/5
indexOf = function( list, elem ) {
var i = 0,
len = list.length;
for ( ; i < len; i++ ) {
if ( list[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + characterEncoding + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = new RegExp( whitespace + "+", "g" ),
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
nodeType = context.nodeType;
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
if ( !seed && documentIsHTML ) {
// Try to shortcut find operations when possible (e.g., not under DocumentFragment)
if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document (jQuery #6963)
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType !== 1 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== "undefined" && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare, parent,
doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
parent = doc.defaultView;
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent !== parent.top ) {
// IE11 does not have attachEvent, so all must suffer
if ( parent.addEventListener ) {
parent.addEventListener( "unload", unloadHandler, false );
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", unloadHandler );
}
}
/* Support tests
---------------------------------------------------------------------- */
documentIsHTML = !isXML( doc );
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( doc.getElementsByClassName );
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [ m ] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( tag );
// DocumentFragment nodes don't have gEBTN
} else if ( support.qsa ) {
return context.querySelectorAll( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\f]' msallowcapture=''>" +
"<option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( div.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+
if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
rbuggyQSA.push("~=");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibing-combinator selector` fails
if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch (e) {}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
// Don't keep the element (issue #299)
input[0] = null;
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
text = text.replace( runescape, funescape );
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
};
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (oldCache = outerCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
outerCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
// Avoid hanging onto element (issue #299)
checkContext = null;
return ret;
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context !== document && context;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is no seed and only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.extend({
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
jQuery.fn.extend({
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
return this.pushStack(
jQuery.unique(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.unique( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
});
var rnotwhite = (/\S+/g);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !(--remaining) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.triggerHandler ) {
jQuery( document ).triggerHandler( "ready" );
jQuery( document ).off( "ready" );
}
}
});
/**
* Clean-up method for dom ready events
*/
function detach() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
}
/**
* The ready event handler and self cleanup method
*/
function completed() {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
var strundefined = typeof undefined;
// Support: IE<9
// Iteration over object's inherited properties before its own
var i;
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Note: most support tests are defined in their respective modules.
// false until the test is run
support.inlineBlockNeedsLayout = false;
// Execute ASAP in case we need to set body.style.zoom
jQuery(function() {
// Minified: var a,b,c,d
var val, div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Return for frameset docs that don't have a body
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
if ( typeof div.style.zoom !== strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";
support.inlineBlockNeedsLayout = val = div.offsetWidth === 3;
if ( val ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
});
(function() {
var div = document.createElement( "div" );
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( elem ) {
var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ],
nodeType = +elem.nodeType || 1;
// Do not set data on non-element DOM nodes because it will not be cleared (#8335).
return nodeType !== 1 && nodeType !== 9 ?
false :
// Nodes accept data unless otherwise specified; rejection can be conditional
!noData || noData !== true && elem.getAttribute("classid") === noData;
};
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function internalData( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( i-- ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
/* jshint eqeqeq: false */
} else if ( support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// The following elements (space-suffixed to avoid Object.prototype collisions)
// throw uncatchable exceptions if you attempt to set expando properties
noData: {
"applet ": true,
"embed ": true,
// ...but Flash objects (which have this classid) *can* handle expandos
"object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[0],
attrs = elem && elem.attributes;
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE11+
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return arguments.length > 1 ?
// Sets one value
this.each(function() {
jQuery.data( this, key, value );
}) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined;
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
// Minified: var a,b,c
var input = document.createElement( "input" ),
div = document.createElement( "div" ),
fragment = document.createDocumentFragment();
// Setup
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName( "tbody" ).length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName( "link" ).length;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone =
document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
input.type = "checkbox";
input.checked = true;
fragment.appendChild( input );
support.appendChecked = input.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE6-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
// #11217 - WebKit loses check when the name is after the checked attribute
fragment.appendChild( div );
div.innerHTML = "<input type='radio' checked='checked' name='t'/>";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
support.noCloneEvent = true;
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
})();
(function() {
var i, eventName,
div = document.createElement( "div" );
// Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event)
for ( i in { submit: true, change: true, focusin: true }) {
eventName = "on" + i;
if ( !(support[ i + "Bubbles" ] = eventName in window) ) {
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
div.setAttribute( eventName, "t" );
support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
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( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: IE < 9, Android < 4.0
src.returnValue === false ?
returnTrue :
returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && e.stopImmediatePropagation ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
jQuery._removeData( doc, fix );
} else {
jQuery._data( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
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>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!support.noCloneEvent || !support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
deletedIds.push( id );
}
}
}
}
}
});
jQuery.fn.extend({
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, self.html() );
}
self.domManip( args, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[i], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var style,
elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
// Use of this method is a temporary fix (more like optmization) until something better comes along,
// since it was removed from specification and supported only in FF
style.display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
(function() {
var shrinkWrapBlocksVal;
support.shrinkWrapBlocks = function() {
if ( shrinkWrapBlocksVal != null ) {
return shrinkWrapBlocksVal;
}
// Will be changed later if needed.
shrinkWrapBlocksVal = false;
// Minified: var b,c,d
var div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
// Support: IE6
// Check if elements with layout shrink-wrap their children
if ( typeof div.style.zoom !== strundefined ) {
// Reset CSS: box-sizing; display; margin; border
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-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";
div.appendChild( document.createElement( "div" ) ).style.width = "5px";
shrinkWrapBlocksVal = div.offsetWidth !== 3;
}
body.removeChild( container );
return shrinkWrapBlocksVal;
};
})();
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles, curCSS,
rposition = /^(top|right|bottom|left)$/;
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
// Support: IE<=11+, Firefox<=30+ (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
if ( elem.ownerDocument.defaultView.opener ) {
return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
}
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "";
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, computed ) {
var left, rs, rsLeft, ret,
style = elem.style;
computed = computed || getStyles( elem );
ret = computed ? computed[ name ] : undefined;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "" || "auto";
};
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
var condition = conditionFn();
if ( condition == null ) {
// The test was not ready at this point; screw the hook this time
// but check again when needed next time.
return;
}
if ( condition ) {
// Hook not needed (or it's not possible to use it due to missing dependency),
// remove it.
// Since there are no other hooks for marginRight, remove the whole object.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply( this, arguments );
}
};
}
(function() {
// Minified: var b,c,d,e,f,g, h,i
var div, style, a, pixelPositionVal, boxSizingReliableVal,
reliableHiddenOffsetsVal, reliableMarginRightVal;
// Setup
div = document.createElement( "div" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName( "a" )[ 0 ];
style = a && a.style;
// Finish early in limited (non-browser) environments
if ( !style ) {
return;
}
style.cssText = "float:left;opacity:.5";
// Support: IE<9
// Make sure that element opacity exists (as opposed to filter)
support.opacity = style.opacity === "0.5";
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!style.cssFloat;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" ||
style.WebkitBoxSizing === "";
jQuery.extend(support, {
reliableHiddenOffsets: function() {
if ( reliableHiddenOffsetsVal == null ) {
computeStyleTests();
}
return reliableHiddenOffsetsVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computeStyleTests();
}
return boxSizingReliableVal;
},
pixelPosition: function() {
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return pixelPositionVal;
},
// Support: Android 2.3
reliableMarginRight: function() {
if ( reliableMarginRightVal == null ) {
computeStyleTests();
}
return reliableMarginRightVal;
}
});
function computeStyleTests() {
// Minified: var b,c,d,j
var div, body, container, contents;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-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";
// Support: IE<9
// Assume reasonable values in the absence of getComputedStyle
pixelPositionVal = boxSizingReliableVal = false;
reliableMarginRightVal = true;
// Check for getComputedStyle so that this code is not run in IE<9.
if ( window.getComputedStyle ) {
pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
boxSizingReliableVal =
( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Support: Android 2.3
// Div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
contents = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
contents.style.cssText = div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
contents.style.marginRight = contents.style.width = "0";
div.style.width = "1px";
reliableMarginRightVal =
!parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight );
div.removeChild( contents );
}
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
contents = div.getElementsByTagName( "td" );
contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
if ( reliableHiddenOffsetsVal ) {
contents[ 0 ].style.display = "";
contents[ 1 ].style.display = "none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
}
body.removeChild( container );
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.swap = function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
};
var
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Support: IE
// Swallow errors from 'invalid' CSS values (#5509)
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
jQuery.fn.extend({
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
} ]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = jQuery._data( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css( elem, "display" );
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !support.shrinkWrapBlocks() ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
// Any non-fx value stops us from restoring the original display value
} else {
display = undefined;
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = jQuery._data( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
// If this is a noop like .hide().hide(), restore an overwritten display value
} else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
style.display = display;
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
};
(function() {
// Minified: var a,b,c,d,e
var input, div, select, a, opt;
// Setup
div = document.createElement( "div" );
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName("a")[ 0 ];
// First batch of tests.
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute("style") );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.hrefNormalized = a.getAttribute("href") === "/a";
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement("form").enctype;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE8 only
// Check if we can trust getAttribute("value")
input = document.createElement( "input" );
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
})();
var rreturn = /\r/g;
jQuery.fn.extend({
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE10-11+
// option.text throws exceptions (#14686, #14858)
jQuery.trim( jQuery.text( elem ) );
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) {
// Support: IE6
// When new option element is added to select box we need to
// force reflow of newly added node in order to workaround delay
// of initialization properties
try {
option.selected = optionSet = true;
} catch ( _ ) {
// Will be executed only in IE6
option.scrollHeight;
}
} else {
option.selected = false;
}
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return options;
}
}
}
});
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = support.getSetAttribute,
getSetInput = support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
jQuery.extend({
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hook for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
// Retrieve booleans specially
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
} :
function( elem, name, isXML ) {
if ( !isXML ) {
return elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
}
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
if ( name === "value" || value === elem.getAttribute( name ) ) {
return value;
}
}
};
// Some attributes are constructed with empty-string values when not defined
attrHandle.id = attrHandle.name = attrHandle.coords =
function( elem, name, isXML ) {
var ret;
if ( !isXML ) {
return (ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
}
};
// Fixing value retrieval on a button requires this module
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
if ( ret && ret.specified ) {
return ret.value;
}
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
if ( !support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
var rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
}
});
jQuery.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
// Support: Safari, IE9+
// mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( type === strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
}
});
// Return jQuery for attributes-only inclusion
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var nonce = jQuery.now();
var rquery = (/\?/);
var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;
jQuery.parseJSON = function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
// Support: Android 2.3
// Workaround failure to string-cast null input
return window.JSON.parse( data + "" );
}
var requireNonComma,
depth = null,
str = jQuery.trim( data + "" );
// Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
// after removing valid tokens
return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {
// Force termination if we see a misplaced comma
if ( requireNonComma && comma ) {
depth = 0;
}
// Perform no more replacements after returning to outermost depth
if ( depth === 0 ) {
return token;
}
// Commas must not follow "[", "{", or ","
requireNonComma = open || comma;
// Determine new depth
// array/object open ("[" or "{"): depth += true - false (increment)
// array/object close ("]" or "}"): depth += false - true (decrement)
// other cases ("," or primitive): depth += true - true (numeric cast)
depth += !close - !open;
// Remove this token
return "";
}) ) ?
( Function( "return " + str ) )() :
jQuery.error( "Invalid JSON: " + data );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType.charAt( 0 ) === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
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"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
fireGlobals = jQuery.event && s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
jQuery._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!support.reliableHiddenOffsets() &&
((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function() {
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
})
.map(function( i, elem ) {
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ?
// Support: IE6+
function() {
// XHR cannot access local files, always use ActiveX for that case
return !this.isLocal &&
// Support: IE7-8
// oldIE XHR does not support non-RFC2616 methods (#13240)
// See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx
// and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
// Although this check for six methods instead of eight
// since IE also does not support "trace" and "connect"
/^(get|post|head|put|delete|options)$/i.test( this.type ) &&
createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
var xhrId = 0,
xhrCallbacks = {},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE<10
// Open requests must be manually aborted on unload (#5280)
// See https://support.microsoft.com/kb/2856746 for more info
if ( window.attachEvent ) {
window.attachEvent( "onunload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
});
}
// Determine support properties
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( options ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !options.crossDomain || support.cors ) {
var callback;
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
// Open the socket
xhr.open( options.type, options.url, options.async, options.username, options.password );
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
// Support: IE<9
// IE's ActiveXObject throws a 'Type Mismatch' exception when setting
// request header to a null-value.
//
// To keep consistent with other XHR implementations, cast the value
// to string and ignore `undefined`.
if ( headers[ i ] !== undefined ) {
xhr.setRequestHeader( i, headers[ i ] + "" );
}
}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( options.hasContent && options.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, statusText, responses;
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Clean up
delete xhrCallbacks[ id ];
callback = undefined;
xhr.onreadystatechange = jQuery.noop;
// Abort manually if needed
if ( isAbort ) {
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
// Support: IE<10
// Accessing binary-data responseText throws an exception
// (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && options.isLocal && !options.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, xhr.getAllResponseHeaders() );
}
};
if ( !options.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
// Add to the list of active xhr callbacks
xhr.onreadystatechange = xhrCallbacks[ id ] = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = jQuery.trim( url.slice( off, url.length ) );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
});
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -1;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
offset: function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
|
app/javascript/mastodon/features/keyboard_shortcuts/index.js | gol-cha/mastodon | import React from 'react';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
heading: { id: 'keyboard_shortcuts.heading', defaultMessage: 'Keyboard Shortcuts' },
});
export default @injectIntl
class KeyboardShortcuts extends ImmutablePureComponent {
static propTypes = {
intl: PropTypes.object.isRequired,
multiColumn: PropTypes.bool,
};
render () {
const { intl, multiColumn } = this.props;
return (
<Column bindToDocument={!multiColumn} icon='question' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<div className='keyboard-shortcuts scrollable optionally-scrollable'>
<table>
<thead>
<tr>
<th><FormattedMessage id='keyboard_shortcuts.hotkey' defaultMessage='Hotkey' /></th>
<th><FormattedMessage id='keyboard_shortcuts.description' defaultMessage='Description' /></th>
</tr>
</thead>
<tbody>
<tr>
<td><kbd>r</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.reply' defaultMessage='to reply' /></td>
</tr>
<tr>
<td><kbd>m</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.mention' defaultMessage='to mention author' /></td>
</tr>
<tr>
<td><kbd>p</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.profile' defaultMessage="to open author's profile" /></td>
</tr>
<tr>
<td><kbd>f</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.favourite' defaultMessage='to favourite' /></td>
</tr>
<tr>
<td><kbd>b</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.boost' defaultMessage='to boost' /></td>
</tr>
<tr>
<td><kbd>enter</kbd>, <kbd>o</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.enter' defaultMessage='to open status' /></td>
</tr>
<tr>
<td><kbd>e</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.open_media' defaultMessage='to open media' /></td>
</tr>
<tr>
<td><kbd>x</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.toggle_hidden' defaultMessage='to show/hide text behind CW' /></td>
</tr>
<tr>
<td><kbd>h</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.toggle_sensitivity' defaultMessage='to show/hide media' /></td>
</tr>
<tr>
<td><kbd>up</kbd>, <kbd>k</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.up' defaultMessage='to move up in the list' /></td>
</tr>
<tr>
<td><kbd>down</kbd>, <kbd>j</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.down' defaultMessage='to move down in the list' /></td>
</tr>
<tr>
<td><kbd>1</kbd>-<kbd>9</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.column' defaultMessage='to focus a status in one of the columns' /></td>
</tr>
<tr>
<td><kbd>n</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.compose' defaultMessage='to focus the compose textarea' /></td>
</tr>
<tr>
<td><kbd>alt</kbd>+<kbd>n</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.toot' defaultMessage='to start a brand new toot' /></td>
</tr>
<tr>
<td><kbd>alt</kbd>+<kbd>x</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.spoilers' defaultMessage='to show/hide CW field' /></td>
</tr>
<tr>
<td><kbd>backspace</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.back' defaultMessage='to navigate back' /></td>
</tr>
<tr>
<td><kbd>s</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.search' defaultMessage='to focus search' /></td>
</tr>
<tr>
<td><kbd>esc</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.unfocus' defaultMessage='to un-focus compose textarea/search' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>h</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.home' defaultMessage='to open home timeline' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>n</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.notifications' defaultMessage='to open notifications column' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>l</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.local' defaultMessage='to open local timeline' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>t</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.federated' defaultMessage='to open federated timeline' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>d</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.direct' defaultMessage='to open direct messages column' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>s</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.start' defaultMessage='to open "get started" column' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>f</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.favourites' defaultMessage='to open favourites list' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>p</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.pinned' defaultMessage='to open pinned toots list' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>u</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.my_profile' defaultMessage='to open your profile' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>b</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.blocked' defaultMessage='to open blocked users list' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>m</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.muted' defaultMessage='to open muted users list' /></td>
</tr>
<tr>
<td><kbd>g</kbd>+<kbd>r</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.requests' defaultMessage='to open follow requests list' /></td>
</tr>
<tr>
<td><kbd>?</kbd></td>
<td><FormattedMessage id='keyboard_shortcuts.legend' defaultMessage='to display this legend' /></td>
</tr>
</tbody>
</table>
</div>
</Column>
);
}
}
|
packages/test-studio/src/components/CustomFontStringInput.js | VegaPublish/vega-studio | import React from 'react'
import PropTypes from 'prop-types'
import {PatchEvent, set} from 'part:@lyra/form-builder/patch-event'
import styles from './CustomFontStringInput.css'
export default class CustomStringInput extends React.Component {
static propTypes = {
value: PropTypes.string,
type: PropTypes.object,
onChange: PropTypes.func
}
handleChange = event => {
this.props.onChange(PatchEvent.from(set(event.target.value)))
}
render() {
const {value, type} = this.props
return (
<div>
<h3>{type.title}</h3>
<p>{type.description}</p>
<input
type="text"
className={styles.input}
placeholder={type.placeholder}
onChange={this.handleChange}
value={value}
/>
</div>
)
}
}
|
app/initializer/scripts/header-initializer.js | Hartorn/character-builder-dd5 | import React from 'react';
import dispatcher from 'focus-core/dispatcher';
import { translate } from 'focus-core/translation';
// import NotificationCenter from 'focus-notifications';
export default () => {
console.info('|--- HEADER');
//initialize account/notification
dispatcher.handleViewAction({
data: {
summaryComponent: {
component:
() => (<h3 className='custom-font website-title'>{translate('website.title')}</h3>)
}
// // barContentLeftComponent: { component: (props) => <div>Empty</div> },
// // barContentRightComponent: {
// // component: (props) => {
// // return <NotificationCenter config={{ rootURL: 'http://localhost:9999/x/notification' }} onSingleClick={url => console.log('navigate', url)} />
// // }
// // }
},
type: 'update'
});
}
|
src/components/Button.js | enzoborgfrantz/react-boiler | import React from 'react';
import styled from 'styled-components';
import { tangerine, iceGray } from '../styles/colors';
const ButtonStyle = styled.button`
height: 35px;
appearance: none;
background-color: ${tangerine};
border-radius: 4px;
box-sizing: border-box;
color: ${iceGray};
font-size: 12px;
font-weight: 300;
outline: none;
padding: 10px;
width: 100%;
border: 1px solid transparent;
transition: opacity 0.2s ease-in, transform 0.1s linear;
&:hover {
cursor: pointer;
opacity: 0.9;
}
&:active {
transform: translateX(5px);
}
`;
const Button = ({ children, ...props }) => (
<ButtonStyle {...props}>{children}</ButtonStyle>
);
export default Button;
|
app/screens/Home.js | rakasiwi23/currency-converter | import React, { Component } from 'react';
import { StatusBar, KeyboardAvoidingView } from 'react-native';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Container } from '../components/Container';
import { Logo } from '../components/Logo';
import { InputWithButton } from '../components/TextInput';
import { ClearButton } from '../components/Buttons';
import { LastConverted } from '../components/Text';
import { Header } from '../components/Header';
import { connectAlert } from '../components/Alert';
import { swapCurrency, changeCurrencyAmount, getInitialConversion } from '../actions/currencies';
class Home extends Component {
constructor(props) {
super(props);
this.handlePressBaseCurrency = this.handlePressBaseCurrency.bind(this);
this.handlePressQuoteCurrency = this.handlePressQuoteCurrency.bind(this);
this.handleOptionPress = this.handleOptionPress.bind(this);
this.handleTextChange = this.handleTextChange.bind(this);
this.handleSwapCurrency = this.handleSwapCurrency.bind(this);
}
componentWillMount() {
this.props.dispatch(getInitialConversion());
}
componentWillReceiveProps(nextProps) {
if (nextProps.currencyError && nextProps.currencyError !== this.props.currencyError) {
this.props.alertWithType('error', 'Error', nextProps.currencyError);
}
}
handlePressBaseCurrency() {
this.props.navigation.navigate('CurrencyList', { title: 'Base Currency', type: 'base' });
}
handlePressQuoteCurrency() {
this.props.navigation.navigate('CurrencyList', { title: 'Quote Currency', type: 'quote' });
}
handleTextChange(amount) {
this.props.dispatch(changeCurrencyAmount(amount));
}
handleSwapCurrency() {
this.props.dispatch(swapCurrency());
}
handleOptionPress() {
this.props.navigation.navigate('Options');
}
render() {
let quotePrice = (this.props.amount * this.props.conversionRate).toFixed(2);
if (this.props.isFetching) {
quotePrice = '...';
}
return (
<Container backgroundColor={this.props.primaryColor}>
<StatusBar translucent={false} barStyle="light-content" />
<Header onPress={this.handleOptionPress} />
<KeyboardAvoidingView behavior="padding">
<Logo tintColor={this.props.primaryColor} />
<InputWithButton
buttonText={this.props.baseCurrency}
onPress={this.handlePressBaseCurrency}
keyboardType="numeric"
defaultValue={this.props.amount.toString()}
onChangeText={this.handleTextChange}
textColor={this.props.primaryColor}
/>
<InputWithButton
buttonText={this.props.quoteCurrency}
onPress={this.handlePressQuoteCurrency}
editable={false}
defaultValue={quotePrice}
textColor={this.props.primaryColor}
/>
<LastConverted
base={this.props.baseCurrency}
quote={this.props.quoteCurrency}
date={this.props.lastConvertedDate}
conversionRate={this.props.conversionRate}
/>
<ClearButton
text="Reverse Currencies"
onPress={this.handleSwapCurrency}
/>
</KeyboardAvoidingView>
</Container>
);
}
}
Home.propTypes = {
navigation: PropTypes.oneOfType([
PropTypes.object,
]).isRequired,
lastConvertedDate: PropTypes.oneOfType([
PropTypes.object,
]).isRequired,
dispatch: PropTypes.func.isRequired,
baseCurrency: PropTypes.string.isRequired,
quoteCurrency: PropTypes.string.isRequired,
amount: PropTypes.number.isRequired,
conversionRate: PropTypes.number.isRequired,
isFetching: PropTypes.bool,
primaryColor: PropTypes.string.isRequired,
alertWithType: PropTypes.func.isRequired,
currencyError: PropTypes.string,
};
Home.defaultProps = {
isFetching: false,
currencyError: '',
};
Home.displayName = 'Home';
const mapStateToProps = (state) => {
const baseCurrency = state.currencies.baseCurrency;
const quoteCurrency = state.currencies.quoteCurrency;
const conversionSelector = state.currencies.conversions[baseCurrency] || {};
const rates = conversionSelector.rates || {};
return {
baseCurrency,
quoteCurrency,
amount: state.currencies.amount,
conversionRate: rates[quoteCurrency] || 0,
isFetching: conversionSelector.isFetching,
lastConvertedDate: conversionSelector.date ? new Date(conversionSelector.date) : new Date(),
primaryColor: state.theme.primaryColor,
currencyError: state.currencies.error,
};
};
export default connect(mapStateToProps)(connectAlert(Home ));
|
src/svg-icons/navigation/expand-less.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationExpandLess = (props) => (
<SvgIcon {...props}>
<path d="M12 8l-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14z"/>
</SvgIcon>
);
NavigationExpandLess = pure(NavigationExpandLess);
NavigationExpandLess.displayName = 'NavigationExpandLess';
NavigationExpandLess.muiName = 'SvgIcon';
export default NavigationExpandLess;
|
tests/App-test.js | RoyalIcing/gateau | import expect from 'expect'
import React from 'react'
import {render, unmountComponentAtNode} from 'react-dom'
import App from 'src/App'
describe('App component', () => {
let node
beforeEach(() => {
node = document.createElement('div')
})
afterEach(() => {
unmountComponentAtNode(node)
})
it('displays a welcome message', () => {
render(<App/>, node, () => {
expect(node.innerHTML).toContain('Welcome to React')
})
})
})
|
karma.config.js | ModanBrothers/modanterist | const argv = require('yargs').argv;
const path = require('path');
const webpack = require('webpack');
module.exports = function (config) {
config.set({
// only use PhantomJS for our 'test' browser
browsers: ['PhantomJS'],
// just run once by default unless --watch flag is passed
singleRun: !argv.watch,
// which karma frameworks do we want integrated
frameworks: ['mocha', 'chai'],
// displays tests in a nice readable format
reporters: ['spec'],
// include some polyfills for babel and phantomjs
files: [
'node_modules/babel-polyfill/dist/polyfill.js',
'./node_modules/phantomjs-polyfill/bind-polyfill.js',
'./test/**/*.js' // specify files to watch for tests
],
preprocessors: {
// these files we want to be precompiled with webpack
// also run tests throug sourcemap for easier debugging
['./test/**/*.js']: ['webpack', 'sourcemap']
},
// A lot of people will reuse the same webpack config that they use
// in development for karma but remove any production plugins like UglifyJS etc.
// I chose to just re-write the config so readers can see what it needs to have
webpack: {
devtool: 'inline-source-map',
resolve: {
// allow us to import components in tests like:
// import Example from 'components/Example';
root: path.resolve(__dirname, './src'),
// allow us to avoid including extension name
extensions: ['', '.js', '.jsx'],
// required for enzyme to work properly
alias: {
sinon: 'sinon/pkg/sinon'
}
},
module: {
// don't run babel-loader through the sinon module
noParse: [
/node_modules\/sinon\//
],
// run babel loader for our tests
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'stage-0', 'react']
}
},
{
test: /\.css$/,
loaders: ['style', 'css', 'postcss']
},
{
test: /\.scss$/,
loaders: ['style', 'css', 'postcss', 'sass']
},
{
test: /bootstrap[\/\\]dist[\/\\]js[\/\\]umd[\/\\]/,
loader: 'imports?jQuery=jquery'
}
],
},
// required for enzyme to work properly
externals: {
jsdom: 'window',
cheerio: 'window',
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': 'window'
},
},
webpackMiddleware: {
noInfo: true
},
// tell karma all the plugins we're going to be using to prevent warnings
plugins: [
'karma-mocha',
'karma-chai',
'karma-webpack',
'karma-phantomjs-launcher',
'karma-spec-reporter',
'karma-sourcemap-loader',
new webpack.ProvidePlugin({
'window.Tether': 'tether',
$: 'jquery'
})
]
});
};
|
src/routes/contact/index.js | agiron123/react-starter-kit-TDDOList | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Contact from './Contact';
export default {
path: '/contact',
action() {
return <Contact />;
},
};
|
example/__tests__/index.android.js | Pilloxa/react-native-nordic-dfu | import 'react-native';
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
src/components/common/Icon.js | mark4carter/react-hrtbus | import React from 'react'
import Radium from 'radium'
class Icon extends React.Component {
render() {
let height = this.props.height || '48px',
width = this.props.width || '48px',
source = this.props.source
return (
<img src={`${source}.png`} width={width} height={height} />
);
}
}
export default Icon
|
pages/demos/selection-controls.js | Kagami/material-ui | import 'docs/src/modules/components/bootstrap';
// --- Post bootstrap -----
import React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
const req = require.context('docs/src/pages/demos/selection-controls', false, /\.md|\.js$/);
const reqSource = require.context(
'!raw-loader!../../docs/src/pages/demos/selection-controls',
false,
/\.js$/,
);
const reqPrefix = 'pages/demos/selection-controls';
function Page() {
return <MarkdownDocs req={req} reqSource={reqSource} reqPrefix={reqPrefix} />;
}
export default Page;
|
files/rxjs/2.4.2/rx.js | abishekrsrikaanth/jsdelivr | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;}
Rx.config.longStackSupport = false;
var hasStacks = false;
try {
throw new Error();
} catch (e) {
hasStacks = !!e.stack;
}
// All code after this point will be filtered from stack traces reported by RxJS
var rStartingLine = captureLine(), rFileName;
var STACK_JUMP_SEPARATOR = "From previous event:";
function makeStackTraceLong(error, observable) {
// If possible, transform the error stack trace by removing Node and RxJS
// cruft, then concatenating with the stack trace of `observable`.
if (hasStacks &&
observable.stack &&
typeof error === "object" &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var o = observable; !!o; o = o.source) {
if (o.stack) {
stacks.unshift(o.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split("\n"),
desiredLines = [];
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join("\n");
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
return fileName === rFileName &&
lineNumber >= rStartingLine &&
lineNumber <= rEndingLine;
}
function isNodeFrame(stackLine) {
return stackLine.indexOf("(module.js:") !== -1 ||
stackLine.indexOf("(node.js:") !== -1;
}
function captureLine() {
if (!hasStacks) { return; }
try {
throw new Error();
} catch (e) {
var lines = e.stack.split("\n");
var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) { return; }
rFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: "at functionName (filename:lineNumber:columnNumber)"
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
// Anonymous functions: "at filename:lineNumber:columnNumber"
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
// Firefox style: "function@filename:lineNumber or @filename:lineNumber"
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
}
var EmptyError = Rx.EmptyError = function() {
this.message = 'Sequence contains no elements.';
Error.call(this);
};
EmptyError.prototype = Error.prototype;
var ObjectDisposedError = Rx.ObjectDisposedError = function() {
this.message = 'Object has been disposed';
Error.call(this);
};
ObjectDisposedError.prototype = Error.prototype;
var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {
this.message = 'Argument out of range';
Error.call(this);
};
ArgumentOutOfRangeError.prototype = Error.prototype;
var NotSupportedError = Rx.NotSupportedError = function (message) {
this.message = message || 'This operation is not supported';
Error.call(this);
};
NotSupportedError.prototype = Error.prototype;
var NotImplementedError = Rx.NotImplementedError = function (message) {
this.message = message || 'This operation is not implemented';
Error.call(this);
};
NotImplementedError.prototype = Error.prototype;
var notImplemented = Rx.helpers.notImplemented = function () {
throw new NotImplementedError();
};
var notSupported = Rx.helpers.notSupported = function () {
throw new NotSupportedError();
};
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
var isIterable = Rx.helpers.isIterable = function (o) {
return o[$iterator$] !== undefined;
}
var isArrayLike = Rx.helpers.isArrayLike = function (o) {
return o && o.length !== undefined;
}
Rx.helpers.iterator = $iterator$;
var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
if (typeof thisArg === 'undefined') { return func; }
switch(argCount) {
case 0:
return function() {
return func.call(thisArg)
};
case 1:
return function(arg) {
return func.call(thisArg, arg);
}
case 2:
return function(value, index) {
return func.call(thisArg, value, index);
};
case 3:
return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
}
return function() {
return func.apply(thisArg, arguments);
};
};
/** Used to determine if values are of the language type Object */
var dontEnums = ['toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'],
dontEnumsLength = dontEnums.length;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
supportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch (e) {
supportNodeClass = true;
}
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
var isObject = Rx.internals.isObject = function(value) {
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
};
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = dontEnumsLength;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = dontEnums[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
var isArguments = function(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a) ?
b != +b :
// but treat `-0` vs. `+0` as not equal
(a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
var result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var hasProp = {}.hasOwnProperty,
slice = Array.prototype.slice;
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
var addProperties = Rx.internals.addProperties = function (obj) {
for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
for (var idx = 0, ln = sources.length; idx < ln; idx++) {
var source = sources[idx];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
var errorObj = {e: {}};
var tryCatchTarget;
function tryCatcher() {
try {
return tryCatchTarget.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
tryCatchTarget = fn;
return tryCatcher;
}
function thrower(e) {
throw e;
}
// Collections
function IndexedItem(id, value) {
this.id = id;
this.value = value;
}
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
c === 0 && (c = this.id - other.id);
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) { return; }
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) { return; }
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
+index || (index = 0);
if (index >= this.length || index < 0) { return; }
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
this.items[this.length] = undefined;
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
var args = [], i, len;
if (Array.isArray(arguments[0])) {
args = arguments[0];
len = args.length;
} else {
len = arguments.length;
args = new Array(len);
for(i = 0; i < len; i++) { args[i] = arguments[i]; }
}
for(i = 0; i < len; i++) {
if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); }
}
this.disposables = args;
this.isDisposed = false;
this.length = args.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var len = this.disposables.length, currentDisposables = new Array(len);
for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }
this.disposables = [];
this.length = 0;
for (i = 0; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Provides a set of static methods for creating Disposables.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
/**
* Validates whether the given object is a disposable
* @param {Object} Object to test whether it has a dispose method
* @returns {Boolean} true if a disposable object, else false.
*/
var isDisposable = Disposable.isDisposable = function (d) {
return d && isFunction(d.dispose);
};
var checkDisposed = Disposable.checkDisposed = function (disposable) {
if (disposable.isDisposed) { throw new ObjectDisposedError(); }
};
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
var old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable;
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed && !this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed && !this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
function scheduleItem(s, self) {
if (!self.isDisposed) {
self.isDisposed = true;
self.disposable.dispose();
}
}
ScheduledDisposable.prototype.dispose = function () {
this.scheduler.scheduleWithState(this, scheduleItem);
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method](state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () { self(_action); }); });
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
var s = state;
var id = root.setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
root.clearInterval(id);
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
}(Scheduler.prototype));
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/** Gets a scheduler that schedules work immediately on the current thread. */
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline () {
while (queue.length > 0) {
var item = queue.dequeue();
if (!item.isCancelled()) {
!item.isCancelled() && item.invoke();
}
}
}
function scheduleNow(state, action) {
var si = new ScheduledItem(this, state, action, this.now());
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
var result = tryCatch(runTrampoline)();
queue = null;
if (result === errorObj) { return thrower(result.e); }
} else {
queue.enqueue(si);
}
return si.disposable;
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
currentScheduler.scheduleRequired = function () { return !queue; };
currentScheduler.ensureTrampoline = function (action) {
if (!queue) { this.schedule(action); } else { action(); }
};
return currentScheduler;
}());
var scheduleMethod, clearMethod = noop;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if ('WScript' in this) {
localSetTimeout = function (fn, time) {
WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new NotSupportedError();
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
var onGlobalPostMessage = function (event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return localSetTimeout(action, 0); };
clearMethod = localClearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
var CatchScheduler = (function (__super__) {
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, __super__);
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
__super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute);
}
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, value, exception, accept, acceptObservable, toString) {
this.kind = kind;
this.value = value;
this.exception = exception;
this._accept = accept;
this._acceptObservable = acceptObservable;
this.toString = toString;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var self = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithState(self, function (_, notification) {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept(onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString() { return 'OnNext(' + this.value + ')'; }
return function (value) {
return new Notification('N', value, null, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (e) {
return new Notification('E', null, e, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
return new Notification('C', null, null, _accept, _acceptObservable, toString);
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (o) {
var e = sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return o.onError(ex);
}
if (currentItem.done) {
return o.onCompleted();
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function(err) { o.onError(err); },
self)
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchError = function () {
var sources = this;
return new AnonymousObservable(function (o) {
var e = sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return observer.onError(ex);
}
if (currentItem.done) {
if (lastException !== null) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
self,
function() { o.onCompleted(); }));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchErrorWhen = function (notificationHandler) {
var sources = this;
return new AnonymousObservable(function (o) {
var exceptions = new Subject(),
notifier = new Subject(),
handled = notificationHandler(exceptions),
notificationDisposable = handled.subscribe(notifier);
var e = sources[$iterator$]();
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return o.onError(ex);
}
if (currentItem.done) {
if (lastException) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var outer = new SingleAssignmentDisposable();
var inner = new SingleAssignmentDisposable();
subscription.setDisposable(new CompositeDisposable(inner, outer));
outer.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function (exn) {
inner.setDisposable(notifier.subscribe(self, function(ex) {
o.onError(ex);
}, function() {
o.onCompleted();
}));
exceptions.onNext(exn);
},
function() { o.onCompleted(); }));
});
return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
if (selector) {
var selectorFn = bindCallback(selector, thisArg, 3);
}
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) { return n.accept(observer); };
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler, thisArg) {
return new AnonymousObserver(function (x) {
return handler.call(thisArg, notificationCreateOnNext(x));
}, function (e) {
return handler.call(thisArg, notificationCreateOnError(e));
}, function () {
return handler.call(thisArg, notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.prototype.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
Observer.prototype.makeSafe = function(disposable) {
return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
__super__.call(this);
}
// Must be implemented by other observers
AbstractObserver.prototype.next = notImplemented;
AbstractObserver.prototype.error = notImplemented;
AbstractObserver.prototype.completed = notImplemented;
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) { this.next(value); }
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (__super__) {
inherits(CheckedObserver, __super__);
function CheckedObserver(observer) {
__super__.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
var res = tryCatch(this._observer.onNext).call(this._observer, value);
this._state = 0;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
var res = tryCatch(this._observer.onError).call(this._observer, err);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
var res = tryCatch(this._observer.onCompleted).call(this._observer);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
inherits(ScheduledObserver, __super__);
function ScheduledObserver(scheduler, observer) {
__super__.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () { self.observer.onNext(value); });
};
ScheduledObserver.prototype.error = function (e) {
var self = this;
this.queue.push(function () { self.observer.onError(e); });
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () { self.observer.onCompleted(); });
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
var ObserveOnObserver = (function (__super__) {
inherits(ObserveOnObserver, __super__);
function ObserveOnObserver(scheduler, observer, cancel) {
__super__.call(this, scheduler, observer);
this._cancel = cancel;
}
ObserveOnObserver.prototype.next = function (value) {
__super__.prototype.next.call(this, value);
this.ensureActive();
};
ObserveOnObserver.prototype.error = function (e) {
__super__.prototype.error.call(this, e);
this.ensureActive();
};
ObserveOnObserver.prototype.completed = function () {
__super__.prototype.completed.call(this);
this.ensureActive();
};
ObserveOnObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this._cancel && this._cancel.dispose();
this._cancel = null;
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
if (Rx.config.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
this.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
var self = this;
this._subscribe = function (observer) {
var oldOnError = observer.onError.bind(observer);
observer.onError = function (err) {
makeStackTraceLong(err, self);
oldOnError(err);
};
return subscribe.call(self, observer);
};
} else {
this._subscribe = subscribe;
}
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
return this._subscribe(typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
var ObservableBase = Rx.ObservableBase = (function (__super__) {
inherits(ObservableBase, __super__);
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], self = state[1];
var sub = tryCatch(self.subscribeCore).call(self, ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function subscribe(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, this];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
function ObservableBase() {
__super__.call(this, subscribe);
}
ObservableBase.prototype.subscribeCore = notImplemented;
return ObservableBase;
}(Observable));
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
}, source);
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
}, source);
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return observableDefer(function () {
var subject = new Rx.AsyncSubject();
promise.then(
function (value) {
subject.onNext(value);
subject.onCompleted();
},
subject.onError.bind(subject));
return subject;
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
var ToArrayObservable = (function(__super__) {
inherits(ToArrayObservable, __super__);
function ToArrayObservable(source) {
this.source = source;
__super__.call(this);
}
ToArrayObservable.prototype.subscribeCore = function(observer) {
return this.source.subscribe(new ToArrayObserver(observer));
};
return ToArrayObservable;
}(ObservableBase));
function ToArrayObserver(observer) {
this.observer = observer;
this.a = [];
this.isStopped = false;
}
ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } };
ToArrayObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
}
};
ToArrayObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onNext(this.a);
this.observer.onCompleted();
}
};
ToArrayObserver.prototype.dispose = function () { this.isStopped = true; }
ToArrayObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Creates an array from an observable sequence.
* @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
return new ToArrayObservable(this);
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe, parent) {
return new AnonymousObservable(subscribe, parent);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
var FromObservable = (function(__super__) {
inherits(FromObservable, __super__);
function FromObservable(iterable, mapper, scheduler) {
this.iterable = iterable;
this.mapper = mapper;
this.scheduler = scheduler;
__super__.call(this);
}
FromObservable.prototype.subscribeCore = function (observer) {
var sink = new FromSink(observer, this);
return sink.run();
};
return FromObservable;
}(ObservableBase));
var FromSink = (function () {
function FromSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromSink.prototype.run = function () {
var list = Object(this.parent.iterable),
it = getIterable(list),
observer = this.observer,
mapper = this.parent.mapper;
function loopRecursive(i, recurse) {
try {
var next = it.next();
} catch (e) {
return observer.onError(e);
}
if (next.done) {
return observer.onCompleted();
}
var result = next.value;
if (mapper) {
try {
result = mapper(result, i);
} catch (e) {
return observer.onError(e);
}
}
observer.onNext(result);
recurse(i + 1);
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return FromSink;
}());
var maxSafeInteger = Math.pow(2, 53) - 1;
function StringIterable(str) {
this._s = s;
}
StringIterable.prototype[$iterator$] = function () {
return new StringIterator(this._s);
};
function StringIterator(str) {
this._s = s;
this._l = s.length;
this._i = 0;
}
StringIterator.prototype[$iterator$] = function () {
return this;
};
StringIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;
};
function ArrayIterable(a) {
this._a = a;
}
ArrayIterable.prototype[$iterator$] = function () {
return new ArrayIterator(this._a);
};
function ArrayIterator(a) {
this._a = a;
this._l = toLength(a);
this._i = 0;
}
ArrayIterator.prototype[$iterator$] = function () {
return this;
};
ArrayIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;
};
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function getIterable(o) {
var i = o[$iterator$], it;
if (!i && typeof o === 'string') {
it = new StringIterable(o);
return it[$iterator$]();
}
if (!i && o.length !== undefined) {
it = new ArrayIterable(o);
return it[$iterator$]();
}
if (!i) { throw new TypeError('Object is not iterable'); }
return o[$iterator$]();
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isFunction(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
if (mapFn) {
var mapper = bindCallback(mapFn, thisArg, 2);
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromObservable(iterable, mapper, scheduler);
}
var FromArrayObservable = (function(__super__) {
inherits(FromArrayObservable, __super__);
function FromArrayObservable(args, scheduler) {
this.args = args;
this.scheduler = scheduler;
__super__.call(this);
}
FromArrayObservable.prototype.subscribeCore = function (observer) {
var sink = new FromArraySink(observer, this);
return sink.run();
};
return FromArrayObservable;
}(ObservableBase));
function FromArraySink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromArraySink.prototype.run = function () {
var observer = this.observer, args = this.parent.args, len = args.length;
function loopRecursive(i, recurse) {
if (i < len) {
observer.onNext(args[i]);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
* @deprecated use Observable.from or Observable.of
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler)
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var first = true, state = initialState;
return scheduler.scheduleRecursive(function (self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
}
} catch (exception) {
observer.onError(exception);
return;
}
if (hasResult) {
observer.onNext(result);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler);
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new FromArrayObservable(args, currentThreadScheduler);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length, args = new Array(len - 1);
for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }
return new FromArrayObservable(args, scheduler);
};
/**
* Convert an object into an observable sequence of [key, value] pairs.
* @param {Object} obj The object to inspect.
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} An observable sequence of [key, value] pairs from the object.
*/
Observable.pairs = function (obj, scheduler) {
scheduler || (scheduler = Rx.Scheduler.currentThread);
return new AnonymousObservable(function (observer) {
var keys = Object.keys(obj), len = keys.length;
return scheduler.scheduleRecursiveWithState(0, function (idx, self) {
if (idx < len) {
var key = keys[idx];
observer.onNext([key, obj[key]]);
self(idx + 1);
} else {
observer.onCompleted();
}
});
});
};
var RangeObservable = (function(__super__) {
inherits(RangeObservable, __super__);
function RangeObservable(start, count, scheduler) {
this.start = start;
this.count = count;
this.scheduler = scheduler;
__super__.call(this);
}
RangeObservable.prototype.subscribeCore = function (observer) {
var sink = new RangeSink(observer, this);
return sink.run();
};
return RangeObservable;
}(ObservableBase));
var RangeSink = (function () {
function RangeSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RangeSink.prototype.run = function () {
var start = this.parent.start, count = this.parent.count, observer = this.observer;
function loopRecursive(i, recurse) {
if (i < count) {
observer.onNext(start + i);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return RangeSink;
}());
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RangeObservable(start, count, scheduler);
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just', and 'returnValue' for browsers <IE9.
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/** @deprecated use return or just */
Observable.returnValue = function () {
//deprecate('returnValue', 'return or just');
return observableReturn.apply(null, arguments);
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @param {Mixed} error An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwError = function (error, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(error);
});
});
};
/** @deprecated use #some instead */
Observable.throwException = function () {
//deprecate('throwException', 'throwError');
return Observable.throwError.apply(null, arguments);
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
resource && (disposable = resource);
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(), items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (o) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) {
try {
var result = handler(e);
} catch (ex) {
return o.onError(ex);
}
isPromise(result) && (result = observableFromPromise(result));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(o));
}, function (x) { o.onCompleted(x); }));
return subscription;
}, source);
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () {
var items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
return enumerableOf(items).catchError();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop();
Array.isArray(args[0]) && (args = args[0]);
return new AnonymousObservable(function (o) {
var n = args.length,
falseFactory = function () { return false; },
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
var res = resultSelector.apply(null, values);
} catch (e) {
return o.onError(e);
}
o.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
o.onCompleted();
}
}
function done (i) {
isDone[i] = true;
isDone.every(identity) && o.onCompleted();
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
},
function(e) { o.onError(e); },
function () { done(i); }
));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
}, this);
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
args.unshift(this);
return observableConcat.apply(null, args);
};
/**
* Concatenates all the observable sequences.
* @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
args = new Array(arguments.length);
for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; }
}
return enumerableOf(args).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatAll = observableProto.concatObservable = function () {
return this.merge(1);
};
var MergeObservable = (function (__super__) {
inherits(MergeObservable, __super__);
function MergeObservable(source, maxConcurrent) {
this.source = source;
this.maxConcurrent = maxConcurrent;
__super__.call(this);
}
MergeObservable.prototype.subscribeCore = function(observer) {
var g = new CompositeDisposable();
g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g)));
return g;
};
return MergeObservable;
}(ObservableBase));
var MergeObserver = (function () {
function MergeObserver(o, max, g) {
this.o = o;
this.max = max;
this.g = g;
this.done = false;
this.q = [];
this.activeCount = 0;
this.isStopped = false;
}
MergeObserver.prototype.handleSubscribe = function (xs) {
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(xs) && (xs = observableFromPromise(xs));
sad.setDisposable(xs.subscribe(new InnerObserver(this, sad)));
};
MergeObserver.prototype.onNext = function (innerSource) {
if (this.isStopped) { return; }
if(this.activeCount < this.max) {
this.activeCount++;
this.handleSubscribe(innerSource);
} else {
this.q.push(innerSource);
}
};
MergeObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.done = true;
this.activeCount === 0 && this.o.onCompleted();
}
};
MergeObserver.prototype.dispose = function() { this.isStopped = true; };
MergeObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, sad) {
this.parent = parent;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
var parent = this.parent;
parent.g.remove(this.sad);
if (parent.q.length > 0) {
parent.handleSubscribe(parent.q.shift());
} else {
parent.activeCount--;
parent.done && parent.activeCount === 0 && parent.o.onCompleted();
}
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeObserver;
}());
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
return typeof maxConcurrentOrOther !== 'number' ?
observableMerge(this, maxConcurrentOrOther) :
new MergeObservable(this, maxConcurrentOrOther);
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources = [], i, len = arguments.length;
if (!arguments[0]) {
scheduler = immediateScheduler;
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else if (isScheduler(arguments[0])) {
scheduler = arguments[0];
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else {
scheduler = immediateScheduler;
for(i = 0; i < len; i++) { sources.push(arguments[i]); }
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableOf(scheduler, sources).mergeAll();
};
var CompositeError = Rx.CompositeError = function(errors) {
this.name = "NotImplementedError";
this.innerErrors = errors;
this.message = 'This contains multiple errors. Check the innerErrors';
Error.call(this);
}
CompositeError.prototype = Error.prototype;
/**
* Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to
* receive all successfully emitted items from all of the source Observables without being interrupted by
* an error notification from one of them.
*
* This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an
* error via the Observer's onError, mergeDelayError will refrain from propagating that
* error notification until all of the merged Observables have finished emitting items.
* @param {Array | Arguments} args Arguments or an array to merge.
* @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable
*/
Observable.mergeDelayError = function() {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
var len = arguments.length;
args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
}
var source = observableOf(null, args);
return new AnonymousObservable(function (o) {
var group = new CompositeDisposable(),
m = new SingleAssignmentDisposable(),
isStopped = false,
errors = [];
function setCompletion() {
if (errors.length === 0) {
o.onCompleted();
} else if (errors.length === 1) {
o.onError(errors[0]);
} else {
o.onError(new CompositeError(errors));
}
}
group.add(m);
m.setDisposable(source.subscribe(
function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) { o.onNext(x); },
function (e) {
errors.push(e);
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
},
function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
}));
},
function (e) {
errors.push(e);
isStopped = true;
group.length === 1 && setCompletion();
},
function () {
isStopped = true;
group.length === 1 && setCompletion();
}));
return group;
});
};
var MergeAllObservable = (function (__super__) {
inherits(MergeAllObservable, __super__);
function MergeAllObservable(source) {
this.source = source;
__super__.call(this);
}
MergeAllObservable.prototype.subscribeCore = function (observer) {
var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();
g.add(m);
m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g)));
return g;
};
return MergeAllObservable;
}(ObservableBase));
var MergeAllObserver = (function() {
function MergeAllObserver(o, g) {
this.o = o;
this.g = g;
this.isStopped = false;
this.done = false;
}
MergeAllObserver.prototype.onNext = function(innerSource) {
if(this.isStopped) { return; }
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad)));
};
MergeAllObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeAllObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
this.done = true;
this.g.length === 1 && this.o.onCompleted();
}
};
MergeAllObserver.prototype.dispose = function() { this.isStopped = true; };
MergeAllObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, g, sad) {
this.parent = parent;
this.g = g;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
var parent = this.parent;
this.isStopped = true;
parent.g.remove(this.sad);
parent.done && parent.g.length === 1 && parent.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeAllObserver;
}());
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeAll = observableProto.mergeObservable = function () {
return new MergeAllObservable(this);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) { throw new Error('Second observable is required'); }
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = [];
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
}
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && o.onNext(left);
}, function (e) { o.onError(e); }, function () {
isOpen && o.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, function (e) { o.onError(e); }, function () {
rightSubscription.dispose();
}));
return disposables;
}, source);
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(
function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(
function (x) { latest === id && observer.onNext(x); },
function (e) { latest === id && observer.onError(e); },
function () {
if (latest === id) {
hasLatest = false;
isStopped && observer.onCompleted();
}
}));
},
function (e) { observer.onError(e); },
function () {
isStopped = true;
!hasLatest && observer.onCompleted();
});
return new CompositeDisposable(subscription, innerSubscription);
}, sources);
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(o),
other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop)
);
}, source);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
*
* @example
* 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = obs1.withLatestFrom([obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.withLatestFrom = function () {
var len = arguments.length, args = new Array(len)
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop(), source = this;
if (typeof source === 'undefined') {
throw new Error('Source observable not found for withLatestFrom().');
}
if (typeof resultSelector !== 'function') {
throw new Error('withLatestFrom() expects a resultSelector function.');
}
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
values = new Array(n);
var subscriptions = new Array(n + 1);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var other = args[i], sad = new SingleAssignmentDisposable();
isPromise(other) && (other = observableFromPromise(other));
sad.setDisposable(other.subscribe(function (x) {
values[i] = x;
hasValue[i] = true;
hasValueAll = hasValue.every(identity);
}, observer.onError.bind(observer), function () {}));
subscriptions[i] = sad;
}(idx));
}
var sad = new SingleAssignmentDisposable();
sad.setDisposable(source.subscribe(function (x) {
var res;
var allValues = [x].concat(values);
if (!hasValueAll) return;
try {
res = resultSelector.apply(null, allValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
}, observer.onError.bind(observer), function () {
observer.onCompleted();
}));
subscriptions[n] = sad;
return new CompositeDisposable(subscriptions);
}, this);
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
return observer.onError(e);
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, function (e) { observer.onError(e); }, function () { observer.onCompleted(); });
}, first);
}
function falseFactory() { return false; }
function emptyArrayFactory() { return []; }
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); }
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var parent = this, resultSelector = args.pop();
args.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = args.length,
queues = arrayInitialize(n, emptyArrayFactory),
isDone = arrayInitialize(n, falseFactory);
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
}, parent);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources;
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
var len = arguments.length;
sources = new Array(len);
for(var i = 0; i < len; i++) { sources[i] = arguments[i]; }
}
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (o) { return source.subscribe(o); }, this);
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var key = value;
if (keySelector) {
try {
key = keySelector(value);
} catch (e) {
o.onError(e);
return;
}
}
if (hasCurrentKey) {
try {
var comparerEquals = comparer(currentKey, key);
} catch (e) {
o.onError(e);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
o.onNext(value);
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
var source = this, tapObserver = typeof observerOrOnNext === 'function' || typeof observerOrOnNext === 'undefined'?
observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) :
observerOrOnNext;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
tapObserver.onNext(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
try {
tapObserver.onError(err);
} catch (e) {
observer.onError(e);
}
observer.onError(err);
}, function () {
try {
tapObserver.onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
});
}, this);
};
/**
* Invokes an action for each element in the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
};
/**
* Invokes an action upon exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
};
/**
* Invokes an action upon graceful termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.ensure = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
}, this);
};
/**
* @deprecated use #finally or #ensure instead.
*/
observableProto.finallyAction = function (action) {
//deprecate('finallyAction', 'finally or ensure');
return this.ensure(action);
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
}, source);
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchError();
};
/**
* Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates.
* if the notifier completes, the observable sequence completes.
*
* @example
* var timer = Observable.timer(500);
* var source = observable.retryWhen(timer);
* @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retryWhen = function (notifier) {
return enumerableRepeat(this).catchErrorWhen(notifier);
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
o.onError(e);
return;
}
o.onNext(accumulation);
},
function (e) { o.onError(e); },
function () {
!hasValue && hasSeed && o.onNext(seed);
o.onCompleted();
}
);
}, source);
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && o.onNext(q.shift());
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return enumerableOf([observableFromArray(args, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
while (q.length > 0) { o.onNext(q.shift()); }
o.onCompleted();
});
}, source);
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
o.onNext(q);
o.onCompleted();
});
}, source);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
+count || (count = 0);
Math.abs(count) === Infinity && (count = 0);
if (count <= 0) { throw new ArgumentOutOfRangeError(); }
skip == null && (skip = count);
+skip || (skip = 0);
Math.abs(skip) === Infinity && (skip = 0);
if (skip <= 0) { throw new ArgumentOutOfRangeError(); }
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [];
function createWindow () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
createWindow();
m.setDisposable(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
var c = n - count + 1;
c >= 0 && c % skip === 0 && q.shift().onCompleted();
++n % skip === 0 && createWindow();
},
function (e) {
while (q.length > 0) { q.shift().onError(e); }
observer.onError(e);
},
function () {
while (q.length > 0) { q.shift().onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
function concatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
});
}
return isFunction(selector) ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
var source = this,
onNextFunc = bindCallback(onNext, thisArg, 2),
onErrorFunc = bindCallback(onError, thisArg, 1),
onCompletedFunc = bindCallback(onCompleted, thisArg, 0);
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNextFunc(x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onErrorFunc(err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompletedFunc();
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, this).concatAll();
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
defaultValue === undefined && (defaultValue = null);
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
},
function (e) { observer.onError(e); },
function () {
!found && observer.onNext(defaultValue);
observer.onCompleted();
});
}, source);
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
o.onError(e);
return;
}
}
hashSet.push(key) && o.onNext(x);
},
function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
var MapObservable = (function (__super__) {
inherits(MapObservable, __super__);
function MapObservable(source, selector, thisArg) {
this.source = source;
this.selector = bindCallback(selector, thisArg, 3);
__super__.call(this);
}
MapObservable.prototype.internalMap = function (selector, thisArg) {
var self = this;
return new MapObservable(this.source, function (x, i, o) { return selector(self.selector(x, i, o), i, o); }, thisArg)
};
MapObservable.prototype.subscribeCore = function (observer) {
return this.source.subscribe(new MapObserver(observer, this.selector, this));
};
return MapObservable;
}(ObservableBase));
function MapObserver(observer, selector, source) {
this.observer = observer;
this.selector = selector;
this.source = source;
this.i = 0;
this.isStopped = false;
}
MapObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var result = tryCatch(this.selector).call(this, x, this.i++, this.source);
if (result === errorObj) {
return this.observer.onError(result.e);
}
this.observer.onNext(result);
/*try {
var result = this.selector(x, this.i++, this.source);
} catch (e) {
return this.observer.onError(e);
}
this.observer.onNext(result);*/
};
MapObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); }
};
MapObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); }
};
MapObserver.prototype.dispose = function() { this.isStopped = true; };
MapObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.map = observableProto.select = function (selector, thisArg) {
var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
return this instanceof MapObservable ?
this.internalMap(selectorFn, thisArg) :
new MapObservable(this, selectorFn, thisArg);
};
/**
* Retrieves the value of a specified nested property from all elements in
* the Observable sequence.
* @param {Arguments} arguments The nested properties to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function () {
var args = arguments, len = arguments.length;
if (len === 0) { throw new Error('List of properties cannot be empty.'); }
return this.map(function (x) {
var currentProp = x;
for (var i = 0; i < len; i++) {
var p = currentProp[args[i]];
if (typeof p !== 'undefined') {
currentProp = p;
} else {
return undefined;
}
}
return currentProp;
});
};
/**
* Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, source).mergeAll();
};
function flatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).mergeAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
}, thisArg);
}
return isFunction(selector) ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining <= 0) {
o.onNext(x);
} else {
remaining--;
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
}
running && o.onNext(x);
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
if (count === 0) { return observableEmpty(scheduler); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining-- > 0) {
o.onNext(x);
remaining === 0 && o.onCompleted();
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = true;
return source.subscribe(function (x) {
if (running) {
try {
running = callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
if (running) {
o.onNext(x);
} else {
o.onCompleted();
}
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
var FilterObservable = (function (__super__) {
inherits(FilterObservable, __super__);
function FilterObservable(source, predicate, thisArg) {
this.source = source;
this.predicate = bindCallback(predicate, thisArg, 3);
__super__.call(this);
}
FilterObservable.prototype.subscribeCore = function (observer) {
return this.source.subscribe(new FilterObserver(observer, this.predicate, this));
};
FilterObservable.prototype.internalFilter = function(predicate, thisArg) {
var self = this;
return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate(x, i, o); }, thisArg);
};
return FilterObservable;
}(ObservableBase));
function FilterObserver(observer, predicate, source) {
this.observer = observer;
this.predicate = predicate;
this.source = source;
this.i = 0;
this.isStopped = false;
}
FilterObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source);
if (shouldYield === errorObj) {
return this.observer.onError(shouldYield.e);
}
shouldYield && this.observer.onNext(x);
};
FilterObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); }
};
FilterObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); }
};
FilterObserver.prototype.dispose = function() { this.isStopped = true; };
FilterObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.filter = observableProto.where = function (predicate, thisArg) {
return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :
new FilterObservable(this, predicate, thisArg);
};
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(observer) {
return {
init: function() {
return observer;
},
step: function(obs, input) {
return obs.onNext(input);
},
result: function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(observer) {
var xform = transducer(transformForObserver(observer));
return source.subscribe(
function(v) {
try {
xform.step(observer, v);
} catch (e) {
observer.onError(e);
}
},
observer.onError.bind(observer),
function() { xform.result(observer); }
);
}, source);
};
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], subscribe = state[1];
var sub = tryCatch(subscribe)(ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function AnonymousObservable(subscribe, parent) {
this.source = parent;
function s(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, subscribe];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
var AutoDetachObserver = (function (__super__) {
inherits(AutoDetachObserver, __super__);
function AutoDetachObserver(observer) {
__super__.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var result = tryCatch(this.observer.onNext).call(this.observer, value);
if (result === errorObj) {
this.dispose();
thrower(result.e);
}
};
AutoDetachObserverPrototype.error = function (err) {
var result = tryCatch(this.observer.onError).call(this.observer, err);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.completed = function () {
var result = tryCatch(this.observer.onCompleted).call(this.observer);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
AutoDetachObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, __super__);
/**
* Creates a subject.
*/
function Subject() {
__super__.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
this.hasError = false;
}
addProperties(Subject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (!this.isStopped) {
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else if (this.hasValue) {
observer.onNext(this.value);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.hasValue = false;
this.observers = [];
this.hasError = false;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var i, len;
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
var os = cloneArray(this.observers), len = os.length;
if (this.hasValue) {
for (i = 0; i < len; i++) {
var o = os[i];
o.onNext(this.value);
o.onCompleted();
}
} else {
for (i = 0; i < len; i++) {
os[i].onCompleted();
}
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
this.hasValue = true;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, subscribe);
}
addProperties(AnonymousSubject.prototype, Observer.prototype, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (error) {
this.observer.onError(error);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
// All code before this point will be filtered from stack traces.
var rEndingLine = captureLine();
}.call(this));
|
Subsets and Splits